@spooky-sync/core 0.0.1-canary.31 → 0.0.1-canary.311

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 (257) hide show
  1. package/AGENTS.md +81 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2026 -137
  4. package/dist/index.js +14956 -2434
  5. package/dist/live.d.ts +141 -0
  6. package/dist/live.js +709 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/otel/index.js +3 -3
  9. package/dist/pure.d.ts +329 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +358 -0
  12. package/dist/sqlite-worker.d.ts +1 -0
  13. package/dist/sqlite-worker.js +439 -0
  14. package/dist/sw.d.ts +207 -0
  15. package/dist/sw.js +393 -0
  16. package/dist/tabs-broker-worker.d.ts +8 -0
  17. package/dist/tabs-broker-worker.js +472 -0
  18. package/dist/types.d.ts +1765 -38
  19. package/dist/worker-edges.js +423 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +46 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +27 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +172 -0
  27. package/skills/sp00ky-core/SKILL.md +31 -6
  28. package/skills/sp00ky-core/references/config.md +6 -0
  29. package/src/boot/auth-flip.saga.test.ts +135 -0
  30. package/src/boot/auth-flip.saga.ts +77 -0
  31. package/src/boot/boot.saga.test.ts +158 -0
  32. package/src/boot/boot.saga.ts +131 -0
  33. package/src/boot/bucket-switch.saga.test.ts +187 -0
  34. package/src/boot/bucket-switch.saga.ts +133 -0
  35. package/src/boot/preload.saga.test.ts +51 -0
  36. package/src/boot/preload.saga.ts +31 -0
  37. package/src/bucket-blurhash.test.ts +148 -0
  38. package/src/build-globals.d.ts +12 -0
  39. package/src/client/bucket-handle.test.ts +117 -0
  40. package/src/client/bucket-handle.ts +227 -0
  41. package/src/client/router.test.ts +58 -0
  42. package/src/client/router.ts +100 -0
  43. package/src/client/runtime.test.ts +195 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.ts +370 -0
  46. package/src/client/sp00ky-client.test.ts +303 -0
  47. package/src/client/sp00ky-client.ts +586 -0
  48. package/src/events/events.test.ts +2 -1
  49. package/src/events/index.ts +3 -0
  50. package/src/index.ts +69 -1
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +80 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +161 -0
  55. package/src/kernel/events.ts +57 -0
  56. package/src/kernel/interpreter.test.ts +116 -0
  57. package/src/kernel/interpreter.ts +148 -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 +478 -0
  61. package/src/live/index.ts +1013 -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 +141 -0
  65. package/src/modules/auth/events/index.ts +9 -2
  66. package/src/modules/auth/impersonation-banner.ts +443 -0
  67. package/src/modules/auth/impersonation.test.ts +355 -0
  68. package/src/modules/auth/impersonation.ts +179 -0
  69. package/src/modules/auth/index.ts +386 -17
  70. package/src/modules/crdt/crdt-field.ts +294 -0
  71. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  72. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  73. package/src/modules/crdt/index.ts +463 -0
  74. package/src/modules/crdt/loro-loader.ts +25 -0
  75. package/src/modules/devtools/flags.ts +349 -0
  76. package/src/modules/devtools/index.ts +746 -95
  77. package/src/modules/devtools/mutations.test.ts +92 -0
  78. package/src/modules/devtools/mutations.ts +160 -0
  79. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  80. package/src/modules/devtools/state-shape.test.ts +263 -0
  81. package/src/modules/devtools/storage-info.test.ts +79 -0
  82. package/src/modules/devtools/storage-info.ts +168 -0
  83. package/src/modules/devtools/versions.test.ts +74 -0
  84. package/src/modules/devtools/versions.ts +110 -0
  85. package/src/modules/feature-flag/index.test.ts +251 -0
  86. package/src/modules/feature-flag/index.ts +316 -0
  87. package/src/modules/ref-tables.test.ts +91 -0
  88. package/src/modules/ref-tables.ts +88 -0
  89. package/src/modules/web-push/index.test.ts +824 -0
  90. package/src/modules/web-push/index.ts +1027 -0
  91. package/src/mutation/jobs.test.ts +25 -0
  92. package/src/mutation/jobs.ts +41 -0
  93. package/src/mutation/mutation-id.test.ts +37 -0
  94. package/src/mutation/mutation-id.ts +35 -0
  95. package/src/mutation/pending-writes.integration.test.ts +175 -0
  96. package/src/mutation/push.saga.test.ts +285 -0
  97. package/src/mutation/push.saga.ts +217 -0
  98. package/src/mutation/rows.test.ts +231 -0
  99. package/src/mutation/rows.ts +427 -0
  100. package/src/mutation/tray.saga.test.ts +63 -0
  101. package/src/mutation/tray.saga.ts +48 -0
  102. package/src/mutation/write.saga.test.ts +316 -0
  103. package/src/mutation/write.saga.ts +268 -0
  104. package/src/otel/index.ts +10 -7
  105. package/src/pure.ts +65 -0
  106. package/src/push/types.ts +174 -0
  107. package/src/query/env.test.ts +23 -0
  108. package/src/query/env.ts +56 -0
  109. package/src/query/fetch.saga.test.ts +199 -0
  110. package/src/query/fetch.saga.ts +120 -0
  111. package/src/query/hash.test.ts +14 -0
  112. package/src/query/hash.ts +18 -0
  113. package/src/query/id-set-plan.test.ts +132 -0
  114. package/src/query/lifecycle.saga.test.ts +274 -0
  115. package/src/query/lifecycle.saga.ts +159 -0
  116. package/src/query/materialize.saga.test.ts +115 -0
  117. package/src/query/materialize.saga.ts +84 -0
  118. package/src/query/materialize.test.ts +58 -0
  119. package/src/query/materialize.ts +57 -0
  120. package/src/query/membership.saga.test.ts +350 -0
  121. package/src/query/membership.saga.ts +278 -0
  122. package/src/query/membership.test.ts +118 -0
  123. package/src/query/membership.ts +201 -0
  124. package/src/query/register.saga.test.ts +293 -0
  125. package/src/query/register.saga.ts +226 -0
  126. package/src/query/render-set.test.ts +47 -0
  127. package/src/query/render-set.ts +71 -0
  128. package/src/query/sql.test.ts +63 -0
  129. package/src/query/sql.ts +93 -0
  130. package/src/query/window-query.test.ts +70 -0
  131. package/src/query/window-query.ts +195 -0
  132. package/src/services/blobs/blob-cache.test.ts +359 -0
  133. package/src/services/blobs/blob-cache.ts +603 -0
  134. package/src/services/blobs/blob-manifest.ts +227 -0
  135. package/src/services/blobs/blob-store.test.ts +77 -0
  136. package/src/services/blobs/blob-store.ts +359 -0
  137. package/src/services/blobs/blob.fixture.ts +90 -0
  138. package/src/services/blobs/index.ts +70 -0
  139. package/src/services/database/cache-engine.ts +199 -0
  140. package/src/services/database/connection-supervisor.test.ts +318 -0
  141. package/src/services/database/connection-supervisor.ts +422 -0
  142. package/src/services/database/database.query-timeout.test.ts +140 -0
  143. package/src/services/database/database.responses.test.ts +43 -0
  144. package/src/services/database/database.ts +146 -61
  145. package/src/services/database/engine-factory.ts +33 -0
  146. package/src/services/database/errors.ts +34 -0
  147. package/src/services/database/events/index.ts +2 -1
  148. package/src/services/database/index.ts +7 -0
  149. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  150. package/src/services/database/local-migrator.integration.test.ts +110 -0
  151. package/src/services/database/local-migrator.ts +59 -16
  152. package/src/services/database/local.test.ts +64 -0
  153. package/src/services/database/local.ts +487 -63
  154. package/src/services/database/plan-render.test.ts +159 -0
  155. package/src/services/database/plan-render.ts +108 -0
  156. package/src/services/database/relation-resolver.test.ts +467 -0
  157. package/src/services/database/relation-resolver.ts +0 -0
  158. package/src/services/database/remote.ts +213 -6
  159. package/src/services/database/sqlite-cache-engine.test.ts +617 -0
  160. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  161. package/src/services/database/sqlite-cache-engine.ts +1372 -0
  162. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  163. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  164. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  165. package/src/services/database/sqlite-lock-verify.ts +45 -0
  166. package/src/services/database/sqlite-open.test.ts +150 -0
  167. package/src/services/database/sqlite-open.ts +164 -0
  168. package/src/services/database/sqlite-plan-sql.test.ts +139 -0
  169. package/src/services/database/sqlite-plan-sql.ts +179 -0
  170. package/src/services/database/sqlite-projection.test.ts +121 -0
  171. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  172. package/src/services/database/sqlite-select.test.ts +246 -0
  173. package/src/services/database/sqlite-select.ts +131 -0
  174. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  175. package/src/services/database/sqlite-transport.ts +224 -0
  176. package/src/services/database/sqlite-worker.ts +437 -0
  177. package/src/services/database/surql-translate.ts +416 -0
  178. package/src/services/database/surreal-cache-engine.ts +161 -0
  179. package/src/services/logger/index.test.ts +132 -0
  180. package/src/services/logger/index.ts +189 -7
  181. package/src/services/persistence/localstorage.ts +2 -2
  182. package/src/services/persistence/resilient.ts +10 -3
  183. package/src/services/persistence/surrealdb.ts +4 -4
  184. package/src/services/stream-processor/index.ts +779 -67
  185. package/src/services/stream-processor/permissions.test.ts +47 -0
  186. package/src/services/stream-processor/permissions.ts +53 -0
  187. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  188. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  189. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  190. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  191. package/src/services/stream-processor/wasm-types.ts +58 -2
  192. package/src/services/tabs/broker-client.ts +283 -0
  193. package/src/services/tabs/broker.test.ts +327 -0
  194. package/src/services/tabs/coordinator.test.ts +386 -0
  195. package/src/services/tabs/coordinator.ts +638 -0
  196. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  197. package/src/services/tabs/leader-locks.ts +75 -0
  198. package/src/services/tabs/protocol.ts +262 -0
  199. package/src/services/tabs/support.ts +36 -0
  200. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  201. package/src/sp00ky.ts +5 -395
  202. package/src/state/client-state.ts +200 -0
  203. package/src/state/lifecycle.test.ts +118 -0
  204. package/src/state/lifecycle.ts +86 -0
  205. package/src/state/reducers.test.ts +304 -0
  206. package/src/state/reducers.ts +526 -0
  207. package/src/state/selectors.test.ts +167 -0
  208. package/src/state/selectors.ts +216 -0
  209. package/src/sw/index.test.ts +582 -0
  210. package/src/sw/index.ts +607 -0
  211. package/src/sw/store.ts +96 -0
  212. package/src/sync/connection.saga.test.ts +86 -0
  213. package/src/sync/connection.saga.ts +85 -0
  214. package/src/sync/live.saga.test.ts +178 -0
  215. package/src/sync/live.saga.ts +107 -0
  216. package/src/sync/policy.health.test.ts +56 -0
  217. package/src/sync/policy.test.ts +659 -0
  218. package/src/sync/policy.ts +502 -0
  219. package/src/sync/poll.saga.test.ts +51 -0
  220. package/src/sync/poll.saga.ts +36 -0
  221. package/src/sync/tabs.saga.test.ts +78 -0
  222. package/src/sync/tabs.saga.ts +96 -0
  223. package/src/testing/adapters.ts +133 -0
  224. package/src/testing/build.ts +63 -0
  225. package/src/testing/fake-services.ts +48 -0
  226. package/src/testing/run-pure.test.ts +92 -0
  227. package/src/testing/run-pure.ts +128 -0
  228. package/src/testing/services.ts +17 -0
  229. package/src/types.ts +624 -10
  230. package/src/utils/blurhash.ts +90 -0
  231. package/src/utils/edges.ts +39 -0
  232. package/src/utils/error-classification.test.ts +54 -0
  233. package/src/utils/error-classification.ts +25 -0
  234. package/src/utils/index.ts +78 -12
  235. package/src/utils/parser.test.ts +67 -102
  236. package/src/utils/parser.ts +64 -2
  237. package/src/utils/semver.test.ts +32 -0
  238. package/src/utils/semver.ts +30 -0
  239. package/src/utils/sha256.ts +15 -0
  240. package/src/utils/surql.ts +30 -18
  241. package/src/utils/utils.test.ts +3 -2
  242. package/tsdown.config.ts +117 -3
  243. package/vitest.config.ts +48 -0
  244. package/src/modules/cache/index.ts +0 -241
  245. package/src/modules/cache/types.ts +0 -19
  246. package/src/modules/data/data.test.ts +0 -58
  247. package/src/modules/data/index.ts +0 -879
  248. package/src/modules/sync/engine.ts +0 -173
  249. package/src/modules/sync/events/index.ts +0 -77
  250. package/src/modules/sync/index.ts +0 -3
  251. package/src/modules/sync/queue/index.ts +0 -2
  252. package/src/modules/sync/queue/queue-down.ts +0 -89
  253. package/src/modules/sync/queue/queue-up.ts +0 -223
  254. package/src/modules/sync/scheduler.ts +0 -84
  255. package/src/modules/sync/sync.ts +0 -421
  256. package/src/modules/sync/utils.test.ts +0 -311
  257. package/src/modules/sync/utils.ts +0 -167
package/dist/index.d.ts CHANGED
@@ -1,74 +1,218 @@
1
- import { C as Logger$1, S as UpdateOptions, T as EventSystem, _ as RunOptions, a as MutationEvent, b as Sp00kyQueryResultPromise, c as PinoTransmit, d as QueryHash, f as QueryState, g as RecordVersionDiff, h as RecordVersionArray, i as MutationCallback, l as QueryConfig, m as QueryUpdateCallback, n as EventSubscriptionOptions, o as MutationEventType, p as QueryTimeToLive, r as Level, s as PersistenceClient, t as DebounceOptions, u as QueryConfigRecord, v as Sp00kyConfig, w as EventDefinition, x as StoreType, y as Sp00kyQueryResult } from "./types.js";
1
+ import { $ as WebPushSubscribeOptions, A as RunOptions, At as Logger$1, B as SyncHealthStatus, Bt as SESSION_POLL_MS, C as QueryTimeToLive, Ct as SignOutHook, D as RecordVersionArray, Dt as createAuthEventSystem, E as ReconnectConfig, Et as AuthEventTypes, F as StorageHealth, Ft as IMPERSONATION_ACCESS, G as WebPushConfig, Gt as sameImpersonation, H as UpdateOptions, Ht as decodeTokenClaims, I as StorageHealthStatus, It as ImpersonationInfo, J as WebPushErrorCode, K as WebPushDevice, L as StoreType, Lt as ImpersonationTimerHost, M as Sp00kyConfig, Mt as SealedQuery, N as Sp00kyQueryResult, Nt as EventDefinition, O as RecordVersionDiff, Ot as RemoteDatabaseService, P as Sp00kyQueryResultPromise, Pt as EventSystem, Q as WebPushModule, R as SyncHealth, Rt as ImpersonationTimers, S as QueryStatusCallback, St as SignOutContext, T as QueryUpdateCallback, Tt as AuthEventTypeMap, U as PUSH_ENDPOINT_KEY, Ut as impersonationFromToken, V as TimingPhase, Vt as TokenClaims, W as PushDeviceKind, Wt as renewDelayMs, X as WebPushMessage, Y as WebPushInfo, Z as WebPushMessageInput, _ as QueryConfig, _t as isPushPayload, a as Level, at as WebPushUpdateOptions, b as QueryState, bt as ImpersonationCandidate, c as MutationCallback, ct as BridgeTokenMessage, d as PersistenceClient, dt as PushNotificationAction, et as WebPushSupport, f as PhaseStat, ft as PushOp, g as QueryAuthorityCallback, gt as WebPushClientMessage, h as PreloadRefresh, ht as PushUrgency, i as InlineRow, it as WebPushUnsupportedReason, j as ServerViewMeta, jt as LocalStore, k as RegistrationTimings, kt as LogTap, l as MutationEvent, lt as PUSH_PAYLOAD_VERSION, m as PreloadOptions, mt as PushPayloadKind, n as DebounceOptions, nt as WebPushSyncStatus, o as MATERIALIZATION_SAMPLE_WINDOW, ot as detectWebPushSupport, p as PinoTransmit, pt as PushPayload, q as WebPushError, r as EventSubscriptionOptions, rt as WebPushUnsubscribeOptions, s as MembershipOutcome, st as BridgeSignOutMessage, t as ConnectionState, tt as WebPushSyncOptions, u as MutationEventType, ut as PushNotification, v as QueryConfigRecord, vt as ActiveImpersonation, w as QueryTimings, wt as AuthEventSystem, x as QueryStatus, xt as SIGN_OUT_HOOK_TIMEOUT_MS, y as QueryHash, yt as AuthService, z as SyncHealthConfig, zt as ORIGIN_TOKEN_KEY } from "./types.js";
2
+ import { BackendNames, BackendRoutes, BucketNames, 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, 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";
7
+ import { LoroDoc } from "loro-crdt";
6
8
 
7
- //#region src/services/database/events/index.d.ts
8
- declare const DatabaseEventTypes: {
9
- readonly LocalQuery: "DATABASE_LOCAL_QUERY";
10
- readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
11
- };
12
- interface DatabaseQueryEventPayload {
13
- query: string;
14
- vars?: Record<string, unknown>;
15
- duration: number;
16
- success: boolean;
17
- error?: string;
18
- timestamp: number;
19
- }
20
- type DatabaseEventTypeMap = {
21
- [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
22
- [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
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[];
23
42
  };
24
- type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
25
- //#endregion
26
- //#region src/utils/surql.d.ts
27
- interface SealedQuery<T = void> {
28
- readonly sql: string;
29
- readonly extract: (results: unknown[]) => T;
43
+ type LeaderToFollowerMessage = {
44
+ type: 'db-ready';
45
+ leadershipId: number;
46
+ bucketId: string;
47
+ storageHealth: StorageHealth;
30
48
  }
31
- //#endregion
32
- //#region src/services/database/database.d.ts
33
- declare abstract class AbstractDatabaseService {
34
- protected client: Surreal;
35
- protected logger: Logger$1;
36
- protected events: DatabaseEventSystem;
37
- protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
38
- constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
39
- abstract connect(): Promise<void>;
40
- getClient(): Surreal;
41
- getEvents(): DatabaseEventSystem;
42
- tx(): Promise<SurrealTransaction>;
43
- private queryQueue;
44
- /**
45
- * Execute a query with serialized execution to prevent WASM transaction issues.
46
- */
47
- query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
48
- execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
49
- 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;
50
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[];
84
+ }
85
+ /** The failed-writes tray changed size on the shared store. */ | {
86
+ type: 'failed-mutations-changed';
87
+ count: number;
88
+ };
51
89
  //#endregion
52
- //#region src/services/database/local.d.ts
53
- declare class LocalDatabaseService extends AbstractDatabaseService {
54
- private config;
55
- protected eventType: "DATABASE_LOCAL_QUERY";
56
- constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
57
- getConfig(): Sp00kyConfig<any>['database'];
58
- connect(): Promise<void>;
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;
59
202
  }
60
203
  //#endregion
61
- //#region src/services/database/remote.d.ts
62
- declare class RemoteDatabaseService extends AbstractDatabaseService {
63
- private config;
64
- protected eventType: "DATABASE_REMOTE_QUERY";
65
- constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
66
- getConfig(): Sp00kyConfig<any>['database'];
67
- connect(): Promise<void>;
68
- signin(params: any): Promise<any>;
69
- signup(params: any): Promise<any>;
70
- authenticate(token: string): Promise<any>;
71
- 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;
72
216
  }
73
217
  //#endregion
74
218
  //#region src/services/stream-processor/wasm-types.d.ts
@@ -76,6 +220,12 @@ interface WasmStreamUpdate {
76
220
  query_id: string;
77
221
  result_hash: string;
78
222
  result_data: RecordVersionArray;
223
+ timing_store_apply_ms?: number;
224
+ timing_circuit_step_ms?: number;
225
+ timing_transform_ms?: number;
226
+ timing_parse_ms?: number;
227
+ timing_plan_ms?: number;
228
+ timing_snapshot_ms?: number;
79
229
  }
80
230
  //#endregion
81
231
  //#region src/services/stream-processor/index.d.ts
@@ -96,6 +246,33 @@ interface StreamUpdate {
96
246
  queryHash: string;
97
247
  localArray: RecordVersionArray;
98
248
  op?: 'CREATE' | 'UPDATE' | 'DELETE';
249
+ /**
250
+ * Client-internal: not from the circuit. A membership-only change that
251
+ * needed no fetch is re-materialized through this same path so it cannot
252
+ * race a real update (DataModule.scheduleRematerialize). Carries the last
253
+ * known `localArray`; consumers that describe an INGEST (persist, metrics,
254
+ * devtools events) skip it.
255
+ */
256
+ synthetic?: boolean;
257
+ /**
258
+ * End-to-end ingest latency for the WASM call that produced this update,
259
+ * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
260
+ * for the initial register_view snapshot.
261
+ */
262
+ materializationTimeMs?: number;
263
+ /** SSP internal sub-phase timings (ms) for this ingest, from the WASM binding. */
264
+ storeApplyMs?: number;
265
+ circuitStepMs?: number;
266
+ transformMs?: number;
267
+ /**
268
+ * One-shot registration timings (ms). Only set on the StreamUpdate returned
269
+ * by `registerQueryPlan` (the register_view snapshot), not on ingest updates.
270
+ */
271
+ registration?: {
272
+ parseMs: number;
273
+ planMs: number;
274
+ snapshotMs: number;
275
+ };
99
276
  }
100
277
  type StreamProcessorEvents = {
101
278
  stream_update: EventDefinition<'stream_update', StreamUpdate[]>;
@@ -107,34 +284,204 @@ type StreamProcessorEvents = {
107
284
  interface StreamUpdateReceiver {
108
285
  onStreamUpdate(update: StreamUpdate): void;
109
286
  }
287
+ /** One row change in the shape `ingestMany` consumes. */
288
+ interface IngestRecord {
289
+ table: string;
290
+ /** `MERGE` overlays the given fields on the stored row (projection widening). */
291
+ op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
292
+ id: string;
293
+ record: any;
294
+ }
295
+ /**
296
+ * What the boot-time prime needs from the client: which tables to walk, how
297
+ * to recognise a snapshot written under a different schema, and which rows'
298
+ * local `_00_rv` must not be reported as the server's.
299
+ */
300
+ interface CircuitPrimeContext {
301
+ tables: string[];
302
+ schemaHash: string;
303
+ /** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
304
+ * locally and may exceed the server's next version). */
305
+ pendingIds: Set<string>;
306
+ /** Receives every `(id, rv)` the prime put into the circuit, per table, so
307
+ * the sync layer can skip re-downloading bodies it already has. */
308
+ onVersions?: (table: string, entries: [string, number][]) => void;
309
+ }
310
+ /** Storage key of the circuit snapshot inside the local store. */
311
+
110
312
  declare class StreamProcessorService {
111
313
  events: EventSystem<StreamProcessorEvents>;
112
314
  private db;
113
- private persistenceClient;
114
315
  private logger;
115
316
  private processor;
116
317
  private isInitialized;
117
318
  private receivers;
118
- constructor(events: EventSystem<StreamProcessorEvents>, db: LocalDatabaseService, persistenceClient: PersistenceClient, logger: Logger);
319
+ private batching;
320
+ private batchBuffer;
321
+ private sessionAuth;
322
+ private stateGeneration;
323
+ private persistState;
324
+ private persistCircuit;
325
+ private checkpointMs;
326
+ private checkpointTimer;
327
+ private snapshotDirty;
328
+ private dirtyRows;
329
+ private hideHandler;
330
+ private checkpointInFlight;
331
+ private projection;
332
+ private primed;
333
+ private schemaHash;
334
+ private widenQueue;
335
+ private widenPending;
336
+ constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, logger: Logger);
119
337
  /**
120
338
  * Add a receiver for stream updates.
121
339
  * Multiple receivers can be registered (DataManager, DevTools, etc.)
122
340
  */
123
341
  addReceiver(receiver: StreamUpdateReceiver): void;
124
342
  private notifyUpdates;
343
+ private dispatchUpdates;
344
+ /**
345
+ * Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
346
+ * affected query once every record has been ingested. Use this whenever
347
+ * multiple records land at once (sync fetching N rows, the boot prime).
348
+ *
349
+ * The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
350
+ * circuit step per chunk (a step walks every registered view, so per-record
351
+ * ingest paid that fixed cost N times), but never the whole batch at once,
352
+ * because the wasm side has to hold every parsed row of a call at the same
353
+ * time and wasm32 dlmalloc never returns that peak.
354
+ *
355
+ * Returns the records that were ingested. A chunk that fails is reported
356
+ * and skipped, not retried (a retry would double-apply whatever the failed
357
+ * step already committed), and the remaining chunks still run.
358
+ */
359
+ ingestMany(records: IngestRecord[]): IngestRecord[];
360
+ /**
361
+ * Open a coalescing window. While open, the per-record stream updates
362
+ * emitted by `ingest` are buffered (one entry per queryHash) instead of
363
+ * dispatched. Always paired with `flushCoalescing()` in a try/finally by
364
+ * `ingestMany` so the window always closes — otherwise the processor stays
365
+ * stuck buffering forever.
366
+ *
367
+ * No-op if a window is already open (nested batches aren't expected here).
368
+ */
369
+ private beginCoalescing;
370
+ /**
371
+ * Close the coalescing window and flush: dispatch one coalesced
372
+ * `StreamUpdate` per buffered queryHash, then persist processor state once
373
+ * for the whole batch (instead of once per ingest).
374
+ */
375
+ private flushCoalescing;
125
376
  /**
126
377
  * Initialize the WASM module and processor.
127
378
  * This must be called before using other methods.
128
379
  */
129
380
  init(): Promise<void>;
130
- loadState(): Promise<void>;
131
- saveState(): Promise<void>;
381
+ /**
382
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
383
+ * local-bucket switches: the old circuit holds the previous user's rows AND
384
+ * views registered with the previous `$auth` context, so neither may survive.
385
+ * Deliberately loads nothing: the snapshot in the store being swapped away
386
+ * from belongs to the previous bucket; the caller primes the new bucket's
387
+ * circuit (`primeFromLocal`) once its store is open, and the DataModule
388
+ * rebind re-registers every live view against this fresh processor. Caller
389
+ * must re-seed `setPermissions` afterwards (a fresh circuit default-denies
390
+ * every table).
391
+ */
392
+ reset(): Promise<void>;
393
+ /**
394
+ * Release the wasm circuit and stop checkpointing. Call when the client is
395
+ * torn down; a recreated client (provider remount, HMR) would otherwise stack
396
+ * one full circuit per instance.
397
+ */
398
+ dispose(): void;
399
+ /**
400
+ * Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
401
+ * not expose `free`, and a double free must not take the app down.
402
+ */
403
+ private freeProcessor;
404
+ /** Toggle circuit-state persistence (shared-tabs follower/leader role). */
405
+ setPersistenceEnabled(enabled: boolean): void;
406
+ /**
407
+ * Snapshot persistence (`persistCircuit`). When on, the circuit's store is
408
+ * written to the local store on a checkpoint interval and when the page
409
+ * goes hidden, and restored by {@link primeFromLocal} on the next boot.
410
+ */
411
+ configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
412
+ /**
413
+ * Field projection (`circuitProjection`, default on). Takes effect on the
414
+ * next processor (`init`/`reset`) and on rows written after that.
415
+ */
416
+ configureProjection(enabled: boolean): void;
417
+ private applyProjection;
418
+ /** Resolves once the boot-time prime has finished (or was skipped). */
419
+ whenPrimed(): Promise<void>;
420
+ /**
421
+ * Fill the circuit from the LOCAL store, in the background.
422
+ *
423
+ * With a usable snapshot: install it under whatever views have registered
424
+ * meanwhile (`load_store_state` re-primes them), then `reconcile` each table
425
+ * against the store's `(id, rv)` list so rows deleted since the checkpoint
426
+ * are stepped out and only rows added or changed since are read back and
427
+ * ingested. Without one: read every row and ingest it, chunked.
428
+ *
429
+ * Either way the circuit ends up equal to the local store without touching
430
+ * the network, so the first sync diff is a real delta rather than "fetch
431
+ * everything". The returned promise never rejects; `whenPrimed` gates on it.
432
+ */
433
+ primeFromLocal(ctx: CircuitPrimeContext): Promise<void>;
434
+ private runPrime;
435
+ /** Publish wasm updates produced outside an ingest (restore, reconcile). */
436
+ private dispatchWasmUpdates;
437
+ /**
438
+ * Record that the circuit changed by `rows` rows. Cheap; the snapshot is
439
+ * deferred to the checkpoint timer and skipped entirely when `persistCircuit`
440
+ * is off.
441
+ */
442
+ private markSnapshotDirty;
443
+ private startCheckpoints;
444
+ /** Stop checkpointing and drop the visibility listeners. */
445
+ stopCheckpoints(): void;
446
+ /**
447
+ * Write the circuit's store to the local store as a snapshot. Compacts the
448
+ * row arena first when dead bytes outweigh live ones. Serialised: a second
449
+ * call while one is in flight joins it. No-op unless persistence is on, this
450
+ * tab owns the store, and the engine can hold a snapshot.
451
+ */
452
+ checkpoint(reason?: string): Promise<void>;
453
+ private runCheckpoint;
454
+ /**
455
+ * Projection widening: a newly registered view evaluates fields that rows
456
+ * already in the circuit were stored without. Merge just those fields in,
457
+ * table by table, from the local store. The view registered against what
458
+ * was present and converges as the merges step through.
459
+ */
460
+ private scheduleWiden;
461
+ private runWiden;
462
+ /**
463
+ * Seed per-table `select` permission predicates ({ [table]: whereText }).
464
+ * Must run after the processor exists and before any `register_view`, else
465
+ * non-`_00_` tables are default-denied and registration fails.
466
+ */
467
+ setPermissions(permissions: Record<string, string>): void;
468
+ /**
469
+ * Set the current session's auth identity for permission injection,
470
+ * mirroring the server's `fn::query::register`
471
+ * (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
472
+ * Stored as strings (empty when logged out) and applied to every
473
+ * `register_view` in {@link registerQueryPlan}. Must be set before a
474
+ * `$auth`-gated query registers (and re-set on auth state changes), or the
475
+ * in-browser SSP's `permission_inject` rejects it with
476
+ * "requires $auth but registration params lack it".
477
+ */
478
+ setSessionAuth(authId: string | null, access: string | null): void;
132
479
  /**
133
480
  * Ingest a record change into the processor.
134
481
  * Emits 'stream_update' event if materialized views are affected.
135
482
  * @param isOptimistic true = local mutation (increment versions), false = remote sync (keep versions)
136
483
  */
137
- ingest(table: string, op: 'CREATE' | 'UPDATE' | 'DELETE', id: string, record: any): WasmStreamUpdate[];
484
+ ingest(table: string, op: IngestRecord['op'], id: string, record: any): WasmStreamUpdate[];
138
485
  /**
139
486
  * Register a new query plan.
140
487
  * Emits 'stream_update' with the initial result.
@@ -147,60 +494,1491 @@ declare class StreamProcessorService {
147
494
  private normalizeValue;
148
495
  }
149
496
  //#endregion
150
- //#region src/modules/auth/events/index.d.ts
151
- declare const AuthEventTypes: {
152
- readonly AuthStateChanged: "AUTH_STATE_CHANGED";
153
- };
154
- type AuthEventTypeMap = {
155
- [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
156
- };
157
- type AuthEventSystem = EventSystem<AuthEventTypeMap>;
158
- declare function createAuthEventSystem(): AuthEventSystem;
497
+ //#region src/modules/crdt/crdt-field.d.ts
498
+ declare const CURSOR_COLORS: string[];
499
+ declare function cursorColorFromName(name: string): string;
500
+ declare class CrdtField {
501
+ private fieldName;
502
+ private doc;
503
+ private pushTimer;
504
+ private local;
505
+ private remote;
506
+ private recordId;
507
+ private sessionId;
508
+ private unsubscribe;
509
+ private lastPushTime;
510
+ private lastCursorPushTime;
511
+ private loadedFromCrdt;
512
+ private pushRetryCount;
513
+ private logger;
514
+ private cursorsEnabled;
515
+ /** Remote-push debounce. Local writes happen immediately on every Loro
516
+ * update; the remote UPSERT is coalesced over this window. Configured
517
+ * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
518
+ private remoteDebounceMs;
519
+ private _onCursorUpdate;
520
+ private pendingCursorUpdate;
521
+ /** Callback set by the editor to receive remote cursor updates.
522
+ * Any cursor data that arrived before this callback was set will be replayed. */
523
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
524
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
525
+ /**
526
+ * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
527
+ * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
528
+ * import graph so it only ships to apps that use CRDT fields.
529
+ */
530
+ constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
531
+ getDoc(): LoroDoc;
532
+ /** Whether the LoroDoc was loaded from saved CRDT state */
533
+ hasContent(): boolean;
534
+ startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
535
+ /**
536
+ * Stop syncing this field. Flushes one final remote push by default so the
537
+ * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
538
+ * the remote session already belongs to the NEXT user, and pushing this
539
+ * (previous user's) snapshot under it would clobber the record remotely.
540
+ */
541
+ stopSync(options?: {
542
+ flush?: boolean;
543
+ }): void;
544
+ importRemote(state: Uint8Array): void;
545
+ exportSnapshot(): Uint8Array;
546
+ /** Push this session's cursor blob into the parent row at
547
+ * `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
548
+ * field — the editor still calls this method optimistically, but
549
+ * without `@cursor` on the schema there's nowhere to store the blob.
550
+ * The UPDATE itself fires the parent table's LIVE feed, so other
551
+ * browsers receive the cursor change without a separate `_00_rv` bump. */
552
+ pushCursorState(encoded: Uint8Array): Promise<void>;
553
+ /** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
554
+ importRemoteCursor(base64State: string): void;
555
+ private scheduleRemotePush;
556
+ /** SET path inside a parent row for the current snapshot. `@crdt`-only
557
+ * fields hold the snapshot directly (`<field>`); `@crdt @cursor`
558
+ * fields hold a `{ state, cursors }` object so the snapshot lives at
559
+ * `<field>.state` next to per-session cursor blobs. */
560
+ private statePath;
561
+ /** Mirror the LoroDoc snapshot into the parent row locally. Runs on
562
+ * every local update and every remote import so reloads (online or
563
+ * offline) see the freshest content immediately. Failures are
564
+ * swallowed — a stale local write must never block user input. */
565
+ private persistLocal;
566
+ private pushToRemote;
567
+ }
159
568
  //#endregion
160
- //#region src/modules/auth/index.d.ts
161
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
162
- type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
163
- type ExtractAccessParams<S extends SchemaStructure, Name extends keyof S['access'], Method extends 'signIn' | 'signup'> = S['access'] extends undefined ? never : S['access'][Name] extends AccessDefinition ? Prettify<{ [K in keyof S['access'][Name][Method]['params']]: MapColumnType<S['access'][Name][Method]['params'][K]> }> : never;
164
- declare class AuthService<S extends SchemaStructure> {
569
+ //#region src/modules/crdt/index.d.ts
570
+ /**
571
+ * CrdtManager manages active CrdtField instances and their sync channels.
572
+ *
573
+ * Collaborative state lives in two dedicated tables (defined in
574
+ * `apps/cli/src/meta_tables_remote.surql`):
575
+ * - `_00_crdt` { record_id, field, state } — one row per (record, field)
576
+ * - `_00_cursor` { record_id, session_id, field, state } — one row per
577
+ * (record, session, field)
578
+ *
579
+ * Splitting them off the parent row is what makes offline edits mergeable:
580
+ * each (record, field) gets its own row, so concurrent offline writes don't
581
+ * collide on the parent's last-write-wins semantics.
582
+ *
583
+ * Cross-browser delivery still rides the parent table's existing LIVE feed
584
+ * to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
585
+ * (issues 3602, 4026). On every meta UPSERT the writer also bumps the
586
+ * parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
587
+ * feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
588
+ * via subquery. Permission inheritance happens server-side via
589
+ * `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
590
+ */
591
+ declare class CrdtManager {
165
592
  private schema;
593
+ private local;
166
594
  private remote;
167
- private persistenceClient;
595
+ private debounceMs;
596
+ private fields;
597
+ private liveByTable;
598
+ private pendingLive;
599
+ private staleTables;
600
+ private connectionGeneration;
601
+ private connectionUnsubscribes;
168
602
  private logger;
169
- token: string | null;
170
- currentUser: any | null;
171
- isAuthenticated: boolean;
172
- isLoading: boolean;
173
- private events;
174
- get eventSystem(): AuthEventSystem;
175
- constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
176
- init(): Promise<void>;
177
- getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
603
+ private sessionId;
604
+ constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
605
+ /**
606
+ * Re-establish table LIVEs after a socket drop.
607
+ *
608
+ * A LIVE subscription lives and dies with its WebSocket session, and
609
+ * `ensureTableSubscription` is memoized on `liveByTable` — so without this,
610
+ * the first reconnect leaves CRDT realtime permanently dead: the map still
611
+ * holds a uuid for a subscription the server has forgotten, so every later
612
+ * `open()` short-circuits and no LIVE is ever re-issued.
613
+ *
614
+ * Both drop events matter: the SDK publishes `reconnecting` (not
615
+ * `disconnected`) when it intends to recover on its own, and `disconnected`
616
+ * only once it has given up.
617
+ */
618
+ private subscribeToReconnect;
619
+ /** Stop observing transport events. Separate from {@link closeAll}, which also
620
+ * runs on a bucket switch where the manager keeps being used. */
621
+ dispose(): void;
622
+ private hasOpenFieldFor;
623
+ /** Set the session id that scopes this client's cursor entries. Must be
624
+ * called before `open()` for cursors to be pushed under a stable key.
625
+ * Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
626
+ * for the data-module salt). */
627
+ setSessionId(sessionId: string): void;
628
+ /**
629
+ * Open a CRDT field for collaborative editing.
630
+ *
631
+ * @param table - Table name
632
+ * @param recordId - Full record ID (e.g., "thread:abc")
633
+ * @param field - Field name (e.g., "title", "content")
634
+ * @param fallbackText - Current plain text from the record, used to seed the
635
+ * LoroDoc if no CRDT state exists yet (migration path)
636
+ */
637
+ open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
638
+ close(table: string, recordId: string, field: string): void;
639
+ /**
640
+ * Close every open field + table LIVE. Fields flush a final remote push by
641
+ * default; pass `{ flush: false }` on a bucket switch, where that flush
642
+ * would push the previous user's snapshot under the next user's session.
643
+ */
644
+ closeAll(options?: {
645
+ flush?: boolean;
646
+ }): void;
647
+ /** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
648
+ * every open CrdtField on `table`. */
649
+ private ensureTableSubscription;
650
+ /** Apply a parent-row payload from a non-LIVE source (e.g. the
651
+ * list_ref-driven sync engine, when the cross-user LIVE on the
652
+ * parent table is filtered out by the SurrealDB cross-session
653
+ * permission gap). Same semantics as the internal `dispatchRow`. */
654
+ applyRow(table: string, row: Record<string, unknown>): void;
655
+ /** Dispatch a parent-row LIVE event to every open CrdtField on that
656
+ * record. Each open field reads its slice of the row directly — the
657
+ * CRDT snapshot is a column on the parent now, so there is no
658
+ * follow-up subquery. */
659
+ private dispatchRow;
660
+ /** One-shot remote fetch for a row whose CRDT field hasn't synced
661
+ * locally yet (fresh device, memory-backed local DB after reload, …).
662
+ * Used by `open()` when the local read came up empty. Subsequent
663
+ * cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
664
+ private fetchAndDispatchRow;
665
+ /** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
666
+ * Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
667
+ private fieldHasCursor;
668
+ /** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
669
+ * the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
670
+ * `{ state, cursors }` where `state` carries the snapshot bytes. */
671
+ private extractSnapshot;
672
+ private killTableSubscription;
673
+ private makeKey;
674
+ /**
675
+ * Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
676
+ * typos, removed annotations, and stale schema codegen at the call site instead
677
+ * of silently producing a non-CRDT writer.
678
+ */
679
+ private assertCrdtField;
680
+ }
681
+ //#endregion
682
+ //#region src/modules/feature-flag/index.d.ts
683
+ interface FeatureFlagSnapshot {
684
+ variant: string | undefined;
685
+ payload: unknown | undefined;
686
+ }
687
+ interface FeatureFlagOptions {
688
+ fallback?: string;
689
+ ttl?: QueryTimeToLive;
690
+ }
691
+ /**
692
+ * A locally forced variant. Applies to THIS browser only and is never sent to
693
+ * the server — the assignment in `_00_user_feature` is untouched, so clearing
694
+ * the override restores whatever the server says.
695
+ */
696
+ interface FeatureFlagOverride {
697
+ variant: string;
698
+ payload?: unknown;
699
+ }
700
+ declare class FeatureFlagHandle {
701
+ readonly key: string;
702
+ readonly fallback: string | undefined;
703
+ private latest;
704
+ private listeners;
705
+ private unsubscribeFn;
706
+ private onCloseFn;
707
+ private closed;
708
+ constructor(key: string, fallback: string | undefined);
709
+ attach(unsubscribe: () => void): void;
710
+ detach(): void;
711
+ set(snapshot: FeatureFlagSnapshot): void;
712
+ variant(): string | undefined;
713
+ payload<T = unknown>(): T | undefined;
714
+ enabled(): boolean;
715
+ subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void;
716
+ onClose(cb: () => void): void;
717
+ close(): void;
718
+ }
719
+ /** The slice of the query engine this module drives: register a live query
720
+ * locally, ask for its remote registration, subscribe to its rows. */
721
+ interface LiveQueryPort$1 {
722
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
723
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
724
+ immediate?: boolean;
725
+ }): () => void;
726
+ }
727
+ interface RemoteRegisterPort$1 {
728
+ enqueueDownEvent(event: {
729
+ type: 'register';
730
+ payload: {
731
+ hash: string;
732
+ };
733
+ }): void;
734
+ }
735
+ interface FeatureFlagModuleDeps<S extends SchemaStructure> {
736
+ dataModule: LiveQueryPort$1;
737
+ sync: RemoteRegisterPort$1;
738
+ auth: Pick<AuthService<S>, 'subscribe'>;
739
+ logger: Logger$1;
740
+ }
741
+ declare class FeatureFlagModule<S extends SchemaStructure> {
742
+ private deps;
743
+ private logger;
744
+ private handles;
745
+ private authUnsubscribe;
746
+ private lastUserId;
747
+ private querySubscription;
748
+ private starting;
749
+ private ttl;
750
+ private snapshots;
751
+ private loaded;
752
+ private overrides;
753
+ constructor(deps: FeatureFlagModuleDeps<S>);
754
+ init(): void;
755
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
756
+ closeAll(): Promise<void>;
757
+ /** Auth changed: drop the old user's query/snapshots and re-observe. */
758
+ private refresh;
759
+ private teardownQuery;
760
+ /** Start the single shared live query (idempotent; no-op with no handles). */
761
+ private ensureStarted;
762
+ /** Live query result → per-key snapshots → push to every active handle. */
763
+ private applyRecords;
764
+ /**
765
+ * Force `key` to `variant` in THIS browser. Pass `null` to clear.
766
+ *
767
+ * Nothing is written to the server: the `_00_user_feature` assignment is
768
+ * untouched, so clearing restores whatever the server says. Persisted to
769
+ * localStorage on the page origin, so it survives a reload.
770
+ */
771
+ setLocalOverride(key: string, variant: string | null, payload?: unknown): void;
772
+ clearLocalOverrides(): void;
773
+ getLocalOverrides(): Record<string, FeatureFlagOverride>;
774
+ /** The assignment for `key`, with any local override taking precedence. */
775
+ private resolve;
776
+ private pushAll;
777
+ private loadOverrides;
778
+ private persistOverrides;
779
+ }
780
+ //#endregion
781
+ //#region src/modules/app-release/index.d.ts
782
+ interface AppReleaseSnapshot {
783
+ /** Latest announced version for the app, or undefined when no row exists. */
784
+ version: string | undefined;
785
+ /** Clients should clear SW/caches when reloading onto this version. */
786
+ cacheBust: boolean;
787
+ /** Clients should reload/update immediately instead of asking. */
788
+ mandatory: boolean;
789
+ releasedAt: string | undefined;
790
+ }
791
+ interface AppReleaseOptions {
792
+ ttl?: QueryTimeToLive;
793
+ }
794
+ declare class AppReleaseHandle {
795
+ readonly app: string;
796
+ private latest;
797
+ private listeners;
798
+ private onCloseFn;
799
+ private closed;
800
+ constructor(app: string);
801
+ set(snapshot: AppReleaseSnapshot): void;
802
+ snapshot(): AppReleaseSnapshot;
803
+ version(): string | undefined;
804
+ /** True when the announced version is semver-newer than `currentVersion`. */
805
+ updateAvailable(currentVersion: string): boolean;
806
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
807
+ onClose(cb: () => void): void;
808
+ close(): void;
809
+ }
810
+ /** The slice of the query engine this module drives: register a live query
811
+ * locally, ask for its remote registration, subscribe to its rows. */
812
+ interface LiveQueryPort {
813
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
814
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
815
+ immediate?: boolean;
816
+ }): () => void;
817
+ }
818
+ interface RemoteRegisterPort {
819
+ enqueueDownEvent(event: {
820
+ type: 'register';
821
+ payload: {
822
+ hash: string;
823
+ };
824
+ }): void;
825
+ }
826
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
827
+ dataModule: LiveQueryPort;
828
+ sync: RemoteRegisterPort;
829
+ auth: Pick<AuthService<S>, 'subscribe'>;
830
+ logger: Logger$1;
831
+ }
832
+ declare class AppReleaseModule<S extends SchemaStructure> {
833
+ private deps;
834
+ private logger;
835
+ private handles;
836
+ private authUnsubscribe;
837
+ private lastUserId;
838
+ private querySubscription;
839
+ private starting;
840
+ private ttl;
841
+ private snapshots;
842
+ private loaded;
843
+ constructor(deps: AppReleaseModuleDeps<S>);
844
+ init(): void;
845
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
846
+ closeAll(): Promise<void>;
847
+ private refresh;
848
+ private teardownQuery;
849
+ private ensureStarted;
850
+ private applyRecords;
851
+ }
852
+ //#endregion
853
+ //#region src/kernel/events.d.ts
854
+ /**
855
+ * Inbound events. Everything that can start a saga arrives as one of these
856
+ * through the runtime router: public API calls, adapter callbacks, timers,
857
+ * and `dispatch` effects from other sagas.
858
+ */
859
+ type RuntimeEvent = {
860
+ type: 'EnsureRegistered';
861
+ requireAuth?: boolean;
862
+ attempt?: number;
863
+ } | {
864
+ type: 'RegisterRemote';
865
+ hash: QueryHash;
866
+ retry?: boolean;
867
+ } | {
868
+ type: 'SyncOutcome';
869
+ ok: boolean;
870
+ error?: unknown;
871
+ } | {
872
+ type: 'AckPrune';
873
+ } | {
874
+ type: 'ReadDirtyMembership';
875
+ } | {
876
+ type: 'RecoverLostView';
877
+ hash: QueryHash;
878
+ } | {
879
+ type: 'ReadMembership';
880
+ hashes: QueryHash[];
881
+ } | {
882
+ type: 'FetchRows';
883
+ } | {
884
+ type: 'Materialize';
885
+ hash: QueryHash;
886
+ } | {
887
+ type: 'MaterializeDirty';
888
+ } | {
889
+ type: 'LifecycleTick';
890
+ } | {
891
+ type: 'GcTick';
892
+ } | {
893
+ type: 'Drain';
894
+ } | {
895
+ type: 'FlushWrite';
896
+ key: string;
897
+ } | {
898
+ type: 'FlushPendingWrites';
899
+ } | {
900
+ type: 'AdoptPendingWrites';
901
+ } | {
902
+ type: 'PollTick';
903
+ } | {
904
+ type: 'SelfHealTick';
905
+ } | {
906
+ type: 'HeartbeatNow';
907
+ } | {
908
+ type: 'StartRemote';
909
+ } | {
910
+ type: 'PrimeCircuit';
911
+ } | {
912
+ type: 'VersionsPrimed';
913
+ entries: Array<readonly [string, number]>;
914
+ } | {
915
+ type: 'WarmBlobs';
916
+ } | {
917
+ type: 'AuthFlip';
918
+ userId: string | null;
919
+ } | {
920
+ type: 'BucketSwitch';
921
+ target: string;
922
+ } | {
923
+ type: 'PageHide';
924
+ } | {
925
+ type: 'ConnectionChanged';
926
+ state: ConnectionState;
927
+ } | {
928
+ type: 'StreamUpdate';
929
+ update: StreamUpdate;
930
+ } | {
931
+ type: 'LiveStart';
932
+ } | {
933
+ type: 'LiveChange';
934
+ hashes: QueryHash[];
935
+ rows?: InlineRow[];
936
+ } | {
937
+ type: 'TabRole';
938
+ role: 'solo' | 'leader' | 'follower';
939
+ } | {
940
+ type: 'TabMessage';
941
+ message: unknown;
942
+ };
943
+ type OutEvent = {
944
+ type: 'query:records';
945
+ hash: QueryHash;
946
+ records: ReadonlyArray<Record<string, unknown>>;
947
+ } | {
948
+ type: 'query:status';
949
+ hash: QueryHash;
950
+ status: QueryStatus;
951
+ } | {
952
+ type: 'query:authority';
953
+ hash: QueryHash;
954
+ known: boolean;
955
+ } | {
956
+ type: 'query:view-lost';
957
+ hash: QueryHash;
958
+ } | {
959
+ type: 'query:evicted';
960
+ hash: QueryHash;
961
+ } | {
962
+ type: 'mutation:event';
963
+ event: unknown;
964
+ } | {
965
+ type: 'mutation:settled';
966
+ mutationId: string;
967
+ recordId: string;
968
+ eventType: string;
969
+ } | {
970
+ type: 'mutation:rolled-back';
971
+ mutationId: string;
972
+ recordId: string;
973
+ eventType: string;
974
+ error: string;
975
+ } | {
976
+ type: 'tray:changed';
977
+ count: number;
978
+ } | {
979
+ type: 'health:changed';
980
+ health: SyncHealth;
981
+ } | {
982
+ type: 'activity:changed';
983
+ fetching: number;
984
+ pending: number;
985
+ } | {
986
+ type: 'tabs:broadcast';
987
+ message: unknown;
988
+ } | {
989
+ type: 'tabs:sendTo';
990
+ tabId: string;
991
+ message: unknown;
992
+ } | {
993
+ type: 'log';
994
+ level: 'debug' | 'info' | 'warn' | 'error';
995
+ message: string;
996
+ data?: unknown;
997
+ };
998
+ //#endregion
999
+ //#region src/state/lifecycle.d.ts
1000
+ /**
1001
+ * The query lifecycle as one explicit machine.
1002
+ *
1003
+ * `phase` answers "where do this query's rows come from":
1004
+ * - `cold` never resolved on this device: rows come from a local
1005
+ * predicate scan (or the SSP local window), bindings show a loader.
1006
+ * - `cached` a durable `_00_view` row was found: rows come from that id-set.
1007
+ * - `live` a server membership set was accepted this session.
1008
+ * - `view-lost` the server's `_00_query` row vanished while we held
1009
+ * membership; rows are kept, a re-registration is under way.
1010
+ *
1011
+ * `remote` tracks the server-side registration, `fetchDepth` is the refcount
1012
+ * behind `status: 'fetching'`, `notified` says whether subscribers received
1013
+ * at least one materialization this registration.
1014
+ */
1015
+ type QueryPhase = 'cold' | 'cached' | 'live' | 'view-lost';
1016
+ type RemotePhase = 'unregistered' | 'registering' | 'registered' | 'failed';
1017
+ interface QueryLifecycle {
1018
+ readonly phase: QueryPhase;
1019
+ readonly remote: RemotePhase;
1020
+ readonly fetchDepth: number;
1021
+ readonly notified: boolean;
1022
+ }
1023
+ //#endregion
1024
+ //#region src/kernel/effects.d.ts
1025
+ type Vars = Record<string, unknown>;
1026
+ /** What the in-browser SSP needs to build a local view. */
1027
+ interface RegisterPlan {
1028
+ queryHash: string;
1029
+ surql: string;
1030
+ params: Vars;
1031
+ ttl: string;
1032
+ tableName: string;
1033
+ involvedTables?: string[];
1034
+ }
1035
+ /** One statement's outcome of a multi-statement remote request. */
1036
+ type StatementResult = {
1037
+ status: 'OK';
1038
+ result: unknown;
1039
+ } | {
1040
+ status: 'ERR';
1041
+ error: string;
1042
+ };
1043
+ /** One entry of an `all` fan-out result (allSettled semantics). */
1044
+
1045
+ /**
1046
+ * Effects are data. A saga yields one and gets its result back on the next
1047
+ * `next()`; the interpreter (client/runtime) is the only place they execute.
1048
+ */
1049
+ type Effect = {
1050
+ kind: 'local.query';
1051
+ sql: string;
1052
+ vars?: Vars;
1053
+ epoch?: number;
1054
+ } | {
1055
+ kind: 'local.select';
1056
+ plan: QueryPlan;
1057
+ params?: Vars;
1058
+ } | {
1059
+ kind: 'local.execute';
1060
+ query: SealedQuery<unknown>;
1061
+ vars?: Vars;
1062
+ epoch?: number;
1063
+ } | {
1064
+ kind: 'local.getById';
1065
+ table: string;
1066
+ id: unknown;
1067
+ } | {
1068
+ kind: 'local.upsert';
1069
+ table: string;
1070
+ id: unknown;
1071
+ data: Record<string, unknown>;
1072
+ mode: 'replace' | 'merge';
1073
+ } | {
1074
+ kind: 'local.delete';
1075
+ table: string;
1076
+ id: unknown;
1077
+ } | {
1078
+ kind: 'local.epoch';
1079
+ } | {
1080
+ kind: 'remote.query';
1081
+ sql: string;
1082
+ vars?: Vars;
1083
+ timeoutMs?: number;
1084
+ } | {
1085
+ kind: 'remote.live';
1086
+ table: string;
1087
+ } | {
1088
+ kind: 'remote.kill';
1089
+ uuid: string;
1090
+ } | {
1091
+ kind: 'ssp.register';
1092
+ plan: RegisterPlan;
1093
+ } | {
1094
+ kind: 'ssp.unregister';
1095
+ hash: string;
1096
+ } | {
1097
+ kind: 'ssp.ingest';
1098
+ records: IngestRecord[];
1099
+ } | {
1100
+ kind: 'timer.set';
1101
+ key: string;
1102
+ ms: number;
1103
+ event: RuntimeEvent;
1104
+ } | {
1105
+ kind: 'timer.clear';
1106
+ key: string;
1107
+ } | {
1108
+ kind: 'state.read';
1109
+ select: (s: ClientState) => unknown;
1110
+ } | {
1111
+ kind: 'state.update';
1112
+ fn: (s: ClientState) => ClientState;
1113
+ } | {
1114
+ kind: 'state.wait';
1115
+ until: (s: ClientState) => boolean;
1116
+ } | {
1117
+ kind: 'now';
1118
+ } | {
1119
+ kind: 'id';
1120
+ scope: 'mutation' | 'salt';
1121
+ } | {
1122
+ kind: 'hash';
1123
+ input: string;
1124
+ } | {
1125
+ kind: 'emit';
1126
+ event: OutEvent;
1127
+ } | {
1128
+ kind: 'dispatch';
1129
+ event: RuntimeEvent;
1130
+ } | {
1131
+ kind: 'all';
1132
+ effects: Effect[];
1133
+ } | {
1134
+ kind: 'service';
1135
+ name: ServiceName;
1136
+ args: unknown[];
1137
+ };
1138
+ /**
1139
+ * Calls into the legacy services that are adapters, not state: auth, tabs,
1140
+ * blobs, migrator, crdt, persistence, the SSP lifecycle, the remote socket.
1141
+ * A saga names the call; the runtime binds it to the real service.
1142
+ */
1143
+ interface ServiceCalls {
1144
+ 'hint.read': () => string | null;
1145
+ 'hint.write': (bucketId: string) => void;
1146
+ 'local.connect': (bucketId: string) => Promise<void>;
1147
+ 'local.switchStore': (bucketId: string) => Promise<void>;
1148
+ 'local.beginSwitch': () => () => void;
1149
+ 'local.currentBucketId': () => string;
1150
+ 'local.usesSurqlSchema': () => boolean;
1151
+ 'local.dropBucket': (bucketId: string) => Promise<void>;
1152
+ 'migrator.provision': () => Promise<void>;
1153
+ 'blobs.start': (bucketId: string) => Promise<void>;
1154
+ 'blobs.setNamespace': (bucketId: string) => Promise<void>;
1155
+ 'blobs.clear': () => Promise<void>;
1156
+ 'ssp.init': () => Promise<void>;
1157
+ 'ssp.setPermissions': () => void;
1158
+ 'ssp.setSessionAuth': (authId: string | null, access: string | null) => void;
1159
+ 'ssp.prime': (pendingIds: string[]) => Promise<void>;
1160
+ 'ssp.reset': () => Promise<void>;
1161
+ 'ssp.setPersistence': (enabled: boolean) => void;
1162
+ 'auth.restoreSession': () => Promise<string | null>;
1163
+ 'auth.init': () => Promise<void>;
1164
+ 'auth.sessionAuthId': () => string | null;
1165
+ 'auth.access': () => string | null;
1166
+ 'auth.token': () => string | null;
1167
+ 'auth.currentUser': () => Record<string, unknown> | null;
1168
+ 'auth.consumeEndedImpersonation': () => string | null;
1169
+ 'remote.connect': () => Promise<void>;
1170
+ 'remote.releaseViews': (ids: unknown[]) => void;
1171
+ 'supervisor.start': () => void;
1172
+ 'tabs.start': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
1173
+ 'tabs.moveToBucket': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
1174
+ 'crdt.setSessionId': (sessionId: string) => void;
1175
+ 'crdt.closeAll': (flush: boolean) => void;
1176
+ 'persistence.set': (key: string, value: unknown) => Promise<void>;
1177
+ 'features.init': () => void;
1178
+ 'releases.init': () => void;
1179
+ 'window.attach': () => void;
1180
+ }
1181
+ type ServiceName = keyof ServiceCalls;
1182
+ /** Typed constructors. Each is one line so the saga reads like the plan. */
1183
+ //#endregion
1184
+ //#region src/kernel/saga.d.ts
1185
+ /**
1186
+ * A saga is a generator that yields effects and receives their results. It
1187
+ * holds no references to adapters or state, so it can be driven by the real
1188
+ * interpreter or by `testing/run-pure` with canned results.
1189
+ */
1190
+ type Saga<R> = Generator<Effect, R, any>;
1191
+ /**
1192
+ * Lanes bound concurrency without a queue object per lane:
1193
+ * - `serial`: runs strictly one at a time per key, in arrival order.
1194
+ * - `dedupe`: a request while one run is active joins that run instead of
1195
+ * starting another.
1196
+ * The bookkeeping is a pure value so the policy is unit-testable; the runtime
1197
+ * owns the promises.
1198
+ */
1199
+ type Lane = {
1200
+ kind: 'serial';
1201
+ key: string;
1202
+ } | {
1203
+ kind: 'dedupe';
1204
+ key: string;
1205
+ };
1206
+ interface LaneState {
1207
+ readonly running: ReadonlySet<string>;
1208
+ readonly waiting: ReadonlyMap<string, number>;
1209
+ }
1210
+ //#endregion
1211
+ //#region src/state/client-state.d.ts
1212
+ type Row = Record<string, unknown>;
1213
+ /** Everything a query is, minus anything that changes after registration. */
1214
+ interface QueryDefinition {
1215
+ /** Session-salted `_00_query:<hash>` record id: the remote view id. */
1216
+ readonly id: RecordId<string>;
1217
+ readonly hash: QueryHash;
1218
+ /** Unsalted `sha256({surql, params})`: key of the durable `_00_view` row. */
1219
+ readonly viewKey: string;
1220
+ readonly surql: string;
1221
+ readonly params: Readonly<Record<string, unknown>>;
1222
+ readonly plan?: QueryPlan;
1223
+ readonly ttl: QueryTimeToLive;
1224
+ readonly ttlMs: number;
1225
+ readonly tableName: string;
1226
+ readonly createdAt: number;
1227
+ }
1228
+ type ServerViewState = 'materializing' | 'ready' | null;
1229
+ interface QueryTelemetry {
1230
+ readonly updateCount: number;
1231
+ readonly errorCount: number;
1232
+ readonly lastUpdatedAt: number | null;
1233
+ readonly materializationSamples: ReadonlyArray<number>;
1234
+ readonly lastIngestLatencyMs: number | null;
1235
+ readonly phaseSamples: Readonly<Record<string, ReadonlyArray<number>>>;
1236
+ readonly phaseLast: Readonly<Record<string, number | null>>;
1237
+ readonly registrationTimings: RegistrationTimings;
1238
+ }
1239
+ interface QueryEntry {
1240
+ readonly def: QueryDefinition;
1241
+ readonly lifecycle: QueryLifecycle;
1242
+ /** Server membership (ids + versions) or the durable seed. */
1243
+ readonly remoteArray: RecordVersionArray;
1244
+ /** The in-browser SSP view's id-set: local truth for "does this row match". */
1245
+ readonly localArray: RecordVersionArray;
1246
+ readonly subqueryRemoteArray: RecordVersionArray;
1247
+ readonly records: ReadonlyArray<Row>;
1248
+ readonly serverState: ServerViewState;
1249
+ readonly subscribers: number;
1250
+ readonly lastSubscriberLeftAt: number | null;
1251
+ readonly lastHeartbeatAt: number | null;
1252
+ readonly lastPolledAt: number | null;
1253
+ readonly registerAttempts: number;
178
1254
  /**
179
- * Subscribe to auth state changes.
180
- * callback is called immediately with current value and whenever validation status changes.
1255
+ * Re-registrations issued because the `_00_query` row read as gone, since
1256
+ * the row was last seen. Paces the next one (see `applyMembership`).
181
1257
  */
182
- subscribe(cb: (userId: string | null) => void): () => void;
183
- private notifyListeners;
1258
+ readonly viewLostCount: number;
1259
+ /** When the paced re-registration is due; null when none is pending. */
1260
+ readonly viewLostRetryAt: number | null;
1261
+ readonly telemetry: QueryTelemetry;
1262
+ }
1263
+ type OutboxStatus = 'pending' | 'acked';
1264
+ /** In-memory mirror of one `_00_pending_mutations` row plus its push progress. */
1265
+ interface OutboxItem {
1266
+ readonly id: string;
1267
+ readonly type: MutationEventType;
1268
+ readonly recordId: string;
1269
+ readonly table: string;
1270
+ readonly status: OutboxStatus;
1271
+ readonly ackedAt: number | null;
1272
+ readonly attempts: number;
1273
+ }
1274
+ type TabRole = 'solo' | 'leader' | 'follower';
1275
+ /** A debounced update accumulating locally until its flush writes the outbox row. */
1276
+ interface PendingWrite {
1277
+ readonly key: string;
1278
+ readonly table: string;
1279
+ readonly recordId: string;
1280
+ readonly data: Readonly<Record<string, unknown>>;
1281
+ readonly before: Readonly<Record<string, unknown>> | null;
1282
+ readonly firstAt: number;
1283
+ /** Its durable copy in `_00_pending_writes`; null when `flushOnHide` is off. */
1284
+ readonly mirrorId: string | null;
1285
+ }
1286
+ interface SyncSlice {
1287
+ readonly health: SyncHealth;
1288
+ readonly consecutiveFailures: number;
1289
+ readonly hasSyncedOnce: boolean;
1290
+ readonly selfHealAttempts: number;
1291
+ readonly pollIdleStreak: number;
1292
+ readonly lastReconnectRefetchAt: number | null;
1293
+ readonly needsResubscribe: boolean;
1294
+ readonly fetchAttempts: number;
1295
+ readonly liveUuid: string | null;
1296
+ readonly liveTable: string | null;
1297
+ readonly lanes: LaneState;
1298
+ }
1299
+ interface ClientState {
1300
+ readonly sessionId: string | null;
1301
+ readonly userId: string | null;
1302
+ /** The principal the current session salt was minted for. */
1303
+ readonly saltUserId: string | null;
1304
+ /** Latest bucket-switch target; an older switch that wakes up to a newer target skips. */
1305
+ readonly pendingBucket: string | null;
1306
+ readonly tabId: string;
1307
+ readonly tabRole: TabRole;
1308
+ readonly bucketId: string | null;
1309
+ readonly localReady: boolean;
1310
+ readonly primed: boolean;
1311
+ readonly queries: ReadonlyMap<QueryHash, QueryEntry>;
1312
+ /** Hashes whose local registration is in flight (dedupes concurrent `query()` calls). */
1313
+ readonly registering: ReadonlySet<QueryHash>;
1314
+ /** Re-read attempts per hash while the server reports a view as `materializing`. */
1315
+ readonly membershipReread: ReadonlyMap<QueryHash, number>;
1316
+ /** Local body versions (`_00_rv`) by encoded record id. */
1317
+ readonly versions: ReadonlyMap<string, number>;
184
1318
  /**
185
- * Check for existing session and validate
1319
+ * What each durable `_00_view` row vouches for, by view key: its members
1320
+ * and subquery children. A body no row names is an orphan: it never paints
1321
+ * before the server answers and the GC deletes it.
186
1322
  */
187
- check(accessToken?: string): Promise<void>;
1323
+ readonly views: ReadonlyMap<string, ReadonlyArray<string>>;
1324
+ readonly outbox: ReadonlyArray<OutboxItem>;
1325
+ readonly pendingWrites: ReadonlyMap<string, PendingWrite>;
1326
+ readonly failedCount: number;
1327
+ /** Queries whose render inputs changed since their last materialization. */
1328
+ readonly dirty: ReadonlySet<QueryHash>;
1329
+ /** Queries whose server membership must be re-read. */
1330
+ readonly membershipDirty: ReadonlySet<QueryHash>;
1331
+ readonly sync: SyncSlice;
1332
+ }
1333
+ //#endregion
1334
+ //#region src/modules/ref-tables.d.ts
1335
+ type RefMode = 'single' | 'dedicated';
1336
+ /**
1337
+ * Sentinel user id for unauthenticated clients when anonymous live queries are
1338
+ * enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
1339
+ * so it can never collide with a real user id (those arrive as `user:<id>`);
1340
+ * both sides resolve it to the shared `_00_list_ref_anon` table.
1341
+ */
1342
+ //#endregion
1343
+ //#region src/query/env.d.ts
1344
+ /**
1345
+ * Static configuration the sagas read. Plain data, built once by the runtime
1346
+ * from `Sp00kyConfig`; sagas never see the config object itself.
1347
+ */
1348
+ interface SagaEnv {
1349
+ readonly schema: SchemaStructure;
1350
+ readonly refMode: RefMode;
1351
+ readonly anonLive: boolean;
1352
+ readonly remoteTimeoutMs: number;
1353
+ readonly pushTimeoutMs: number;
1354
+ readonly outboxBatchSize: number;
1355
+ readonly degradeAfter: number;
1356
+ readonly materializeDebounceMs: number;
1357
+ readonly pollBaseMs: number;
1358
+ readonly defaultTtlMs: number;
1359
+ }
1360
+ //#endregion
1361
+ //#region src/mutation/rows.d.ts
1362
+ interface FailedMutationRow {
1363
+ id: string;
1364
+ mutationType: MutationEventType;
1365
+ recordId: string;
1366
+ tableName: string;
1367
+ data?: Record<string, unknown>;
1368
+ beforeRecord?: Record<string, unknown> | null;
1369
+ error: {
1370
+ message: string;
1371
+ kind: 'application' | 'unreplayable';
1372
+ };
1373
+ attempts: number;
1374
+ createdAt: number;
1375
+ failedAt: number;
1376
+ revert: 'full' | 'partial' | 'none';
1377
+ }
1378
+ /**
1379
+ * Parse a record id READ BACK FROM THE STORE, stripping SurrealDB's `⟨⟩`
1380
+ * escaping (outbox ids contain `_`, so they come back escaped).
1381
+ */
1382
+ //#endregion
1383
+ //#region src/kernel/interpreter.d.ts
1384
+ /** The five adapters plus the pure ports, as the interpreter sees them. */
1385
+ interface Adapters {
1386
+ local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'getById' | 'upsert' | 'delete'> & {
1387
+ readonly epoch: number;
1388
+ };
1389
+ remote: {
1390
+ queryResponses(sql: string, vars?: Record<string, unknown>): Promise<StatementResult[]>;
1391
+ /**
1392
+ * Subscribe to `LIVE SELECT * FROM <table>`; the callback receives the
1393
+ * changed query hashes, plus the changed rows themselves when the
1394
+ * subscription was opened with the body joined on (`liveInlineBodies`).
1395
+ */
1396
+ live(table: string, onChange: (hashes: string[], rows?: InlineRow[]) => void): Promise<string>;
1397
+ kill(uuid: string): Promise<void>;
1398
+ };
1399
+ ssp: {
1400
+ registerQueryPlan(plan: {
1401
+ queryHash: string;
1402
+ surql: string;
1403
+ params: Record<string, unknown>;
1404
+ ttl: Duration;
1405
+ lastActiveAt: Date;
1406
+ localArray: [];
1407
+ remoteArray: [];
1408
+ meta: {
1409
+ tableName: string;
1410
+ involvedTables?: string[];
1411
+ };
1412
+ }): StreamUpdate | undefined;
1413
+ unregisterQueryPlan(hash: string): void;
1414
+ ingestMany(records: IngestRecord[]): unknown;
1415
+ };
1416
+ timers: {
1417
+ set(key: string, ms: number, fire: () => void): void;
1418
+ clear(key: string): void;
1419
+ };
1420
+ clock: {
1421
+ now(): number;
1422
+ };
1423
+ ids: {
1424
+ mutation(): string;
1425
+ salt(): string;
1426
+ };
1427
+ hash(input: string): Promise<string>;
1428
+ services: ServiceCalls;
1429
+ }
1430
+ /** What the interpreter needs from the runtime: state, waiting, emitting, dispatching. */
1431
+ //#endregion
1432
+ //#region src/client/runtime.d.ts
1433
+ interface RuntimeOptions {
1434
+ env: SagaEnv;
1435
+ adapters: Adapters;
1436
+ logger: Logger$1;
1437
+ tabId: string;
1438
+ initialState?: ClientState;
1439
+ }
1440
+ /**
1441
+ * The one effectful object of the engine: holds the state, runs sagas on
1442
+ * lanes, fires timers, fans events out to subscribers and schedules
1443
+ * materialization for dirty queries. No decision logic lives here.
1444
+ */
1445
+ declare class Runtime {
1446
+ private stateValue;
1447
+ private readonly interpret;
1448
+ private readonly env;
1449
+ private readonly adapters;
1450
+ private readonly logger;
1451
+ private readonly serialLanes;
1452
+ private readonly dedupeLanes;
1453
+ private readonly waiters;
1454
+ private readonly recordSubs;
1455
+ private readonly statusSubs;
1456
+ private readonly authoritySubs;
1457
+ private readonly lastStatus;
1458
+ private readonly listeners;
1459
+ private readonly scheduledMaterialize;
1460
+ private readonly timerKeys;
1461
+ private lastActivity;
1462
+ private lastHealth;
1463
+ private disposed;
1464
+ constructor(opts: RuntimeOptions);
1465
+ get state(): ClientState;
1466
+ /** Run a saga, optionally on a lane. Rejections propagate to the caller. */
1467
+ run<R>(saga: Saga<R>, opts?: {
1468
+ lane?: Lane;
1469
+ signal?: AbortSignal;
1470
+ }): Promise<R>;
1471
+ /** Route an event to its saga. Never rejects: failures are logged. */
1472
+ dispatch(event: RuntimeEvent): Promise<void>;
1473
+ private setState;
1474
+ waitFor(until: (s: ClientState) => boolean, signal?: AbortSignal): Promise<void>;
1475
+ /** Deliver an outbound event to its subscribers and listeners. */
1476
+ emit(event: OutEvent): void;
1477
+ private notify;
1478
+ private safely;
1479
+ /** Observe outbound events by type (`'*'` for all). */
1480
+ on(type: OutEvent['type'] | '*', cb: (event: OutEvent) => void): () => void;
1481
+ subscribe(hash: QueryHash, cb: QueryUpdateCallback, options?: {
1482
+ immediate?: boolean;
1483
+ }): () => void;
1484
+ subscribeStatus(hash: QueryHash, cb: QueryStatusCallback, options?: {
1485
+ immediate?: boolean;
1486
+ }): () => void;
1487
+ subscribeAuthority(hash: QueryHash, cb: QueryAuthorityCallback, options?: {
1488
+ immediate?: boolean;
1489
+ }): () => void;
1490
+ /** Apply a reducer outside a saga (facade conveniences such as timing reports). */
1491
+ update(reducer: (s: ClientState) => ClientState): void;
1492
+ dispose(): void;
1493
+ }
1494
+ //#endregion
1495
+ //#region src/services/tabs/coordinator.d.ts
1496
+ interface CoordinatorHooks {
1497
+ /** Become the store owner: spawn the worker, open the pool under the given
1498
+ * per-leadership lock. Returns the resulting health for db-ready relays.
1499
+ * `resumeHeld` = keep the existing live worker (broker-restart path). */
1500
+ adoptOwner(bucketId: string, opts: {
1501
+ workerLockName: string;
1502
+ allowMemoryFallback: boolean;
1503
+ forceTakeover: boolean;
1504
+ resumeHeld: boolean;
1505
+ }): Promise<StorageHealth>;
1506
+ /** Attach to a leader's worker through `dbPort`. */
1507
+ adoptAttached(dbPort: MessagePort, snapshot: {
1508
+ bucketId: string;
1509
+ storageHealth: StorageHealth;
1510
+ leadershipId: number;
1511
+ }): Promise<void>;
1512
+ /** We were leader and got demoted (zombie thaw / stale promotion): tear the
1513
+ * owned worker down so its SAH handles free up. */
1514
+ releaseOwnership(): Promise<void>;
1515
+ /** The leader (or its port) is gone; queue/park ops until a new role lands. */
1516
+ onLeaderLost(reason: string): void;
1517
+ /** Leader side: forward a follower's dbPort into the owned worker. */
1518
+ exposeClientPort(clientId: string, port: MessagePort): Promise<void>;
1519
+ removeClientPort(clientId: string): Promise<void>;
1520
+ /** Sync layer role changes (implemented in the sync module). */
1521
+ /** Synchronous leader WIRING. Must not block: the role is published and
1522
+ * `leader-ready` is sent right after it returns. */
1523
+ becomeSyncLeader(hub: LeaderSyncHub): void;
1524
+ /** The blocking half of the leader handover (outbox drain, LIVE restart),
1525
+ * run in the background once the tab is already a working leader. */
1526
+ resumeSyncLeaderDuties(): Promise<void>;
1527
+ becomeSyncFollower(forwarder: SyncForwarder): void;
1528
+ becomeSyncSolo(): void;
1529
+ /** Current storage health, for db-ready sent to late-joining followers. */
1530
+ currentStorageHealth(): StorageHealth;
1531
+ }
1532
+ /** Leader-side fan-out surface handed to the sync layer. The sync router
1533
+ * (modules/sync/tab-router.ts) registers itself as the message handler. */
1534
+ declare class LeaderSyncHub {
1535
+ readonly leadershipId: number;
1536
+ private logger;
1537
+ private followers;
1538
+ private seq;
1539
+ onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
1540
+ onFollowerDetached: ((tabId: TabId) => void) | null;
1541
+ constructor(leadershipId: number, logger: Logger$1);
1542
+ attach(tabId: TabId, port: MessagePort): void;
1543
+ detach(tabId: TabId): void;
1544
+ detachAll(): void;
1545
+ sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
1546
+ broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
1547
+ /** Stamped ingest relay; seq lets followers detect gaps. */
1548
+ relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
1549
+ get followerCount(): number;
1550
+ get relayedBatches(): number;
1551
+ }
1552
+ /** Follower half of the syncPort. Queues while detached (leaderless window)
1553
+ * and flushes on rebind; a lost-in-flight mutation notify is additionally
1554
+ * backstopped by the new leader reloading the shared outbox from the store. */
1555
+ declare class SyncForwarder {
1556
+ private tabId;
1557
+ private port;
1558
+ private queued;
1559
+ onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
1560
+ constructor(tabId: TabId);
1561
+ rebind(port: MessagePort): void;
1562
+ unbind(): void;
1563
+ private post;
1564
+ mutationEnqueued(mutationId: string): void;
1565
+ /** An optimistic write this tab just ingested. Deliberately NOT queued while
1566
+ * detached: a new leader primes its circuit from the shared store, which
1567
+ * already holds the row, and replaying a stale tuple at it later would put
1568
+ * an older `_00_rv` in its version memo. */
1569
+ ingest(tuples: IngestTuple[]): void;
1570
+ requestPoll(): void;
1571
+ }
1572
+ declare class TabsCoordinator {
1573
+ private deps;
1574
+ role: TabRole$1;
1575
+ leadershipId: number;
1576
+ leaderTabId: TabId | null;
1577
+ brokerRole: 'pending' | TabRole$1;
1578
+ /** Wall time from `become-leader` to `leader-ready` on the last promotion.
1579
+ * Reported in the DevTools role-change event: a slow store adopt (OPFS pool
1580
+ * contention after the previous leader died) shows up here as seconds. */
1581
+ lastPromotionMs: number | null;
1582
+ private fingerprint;
1583
+ private bucketId;
1584
+ private broker;
1585
+ private hub;
1586
+ private forwarder;
1587
+ private roleListeners;
1588
+ private startResolve;
1589
+ private startReject;
1590
+ /** Ports received before start() resolves or between roles. */
1591
+ private promotionChain;
1592
+ private closed;
1593
+ constructor(deps: {
1594
+ tabId: TabId;
1595
+ fingerprint: string;
1596
+ hooks: CoordinatorHooks;
1597
+ logger: Logger$1;
1598
+ /** Fired on pagehide while this tab leads: last-chance OPFS release. */
1599
+ onLeaderPageHide?: () => void;
1600
+ });
1601
+ /** Serialize role transitions; each is small but async (worker opens). */
1602
+ private enqueue;
1603
+ onRoleChange(cb: (role: TabRole$1) => void): () => void;
1604
+ private setRole;
1605
+ /** Connect the broker and resolve once this tab has a usable store role.
1606
+ * Rejects when no role lands in time; the caller then boots solo. */
1607
+ start(bucketId: string): Promise<TabRole$1>;
1608
+ /** Bucket switch: leave the old namespace, join the new one. Resolves when
1609
+ * a role lands in the new namespace. */
1610
+ moveToBucket(bucketId: string): Promise<TabRole$1>;
1611
+ private promote;
1612
+ private demote;
1613
+ private tabLock;
1614
+ private teardownLeader;
1615
+ private teardownFollower;
1616
+ private serveFollower;
1617
+ private attachToLeader;
1618
+ private handleLeaderGone;
1619
+ private fallbackToSolo;
1620
+ get syncHub(): LeaderSyncHub | null;
1621
+ get syncForwarder(): SyncForwarder | null;
1622
+ get tabId(): TabId;
1623
+ stop(): Promise<void>;
1624
+ }
1625
+ //#endregion
1626
+ //#region src/services/blobs/blob-store.d.ts
1627
+ /**
1628
+ * Byte storage for cached bucket files.
1629
+ *
1630
+ * The default implementation is OPFS. Bucket files never arrive over HTTP in
1631
+ * this client — `BucketHandle.get()` is a SurrealQL RPC on the sync socket — so
1632
+ * neither the browser's HTTP cache nor the Cache API can hold them. We persist
1633
+ * the bytes ourselves, and OPFS is the cheapest place to put them: a read is
1634
+ * `getFile()` → a disk-backed lazy `File` that `URL.createObjectURL` can serve
1635
+ * without ever moving the bytes through the JS heap.
1636
+ *
1637
+ * Layout is real nested directories rather than one hashed filename:
1638
+ *
1639
+ * sp00ky-blobs/<namespace>/<bucket>/<...path segments>
1640
+ *
1641
+ * That costs a `getDirectoryHandle` per segment on write, and buys the property
1642
+ * the whole orphan story rests on: the full `(bucket, path)` key is recoverable
1643
+ * from a directory walk alone. The `_00_blob` manifest can therefore be wiped
1644
+ * (memory fallback, SQLite pool wipe, IndexedDB corruption recovery) and be
1645
+ * rebuilt from disk instead of taking the cached bytes down with it.
1646
+ */
1647
+ /** Identifies one cached file: the bucket it lives in and its path within. */
1648
+ interface BlobKey {
1649
+ bucket: string;
1650
+ path: string;
1651
+ }
1652
+ /** What a directory walk can tell us about a stored file, with no manifest. */
1653
+ interface BlobStat {
1654
+ key: BlobKey;
1655
+ size: number;
1656
+ /** File mtime. Seeds `lastAccess` when a manifest row has to be rebuilt. */
1657
+ mtime: number;
1658
+ }
1659
+ interface BlobStore {
1660
+ /** False for {@link MemoryBlobStore} and for OPFS-less environments: the
1661
+ * cache still dedupes and serves within a tab, but nothing survives reload. */
1662
+ readonly persistent: boolean;
1663
+ /** Namespace (the local bucketId) all keys are resolved under. */
1664
+ readonly namespace: string;
1665
+ read(key: BlobKey): Promise<Blob | null>;
1666
+ /** Returns the number of bytes written. Throws on quota exhaustion. */
1667
+ write(key: BlobKey, bytes: Blob): Promise<number>;
1668
+ remove(key: BlobKey): Promise<void>;
1669
+ /** Every committed file under the current namespace. Sweeps torn writes. */
1670
+ list(): Promise<BlobStat[]>;
1671
+ /** Drop the whole namespace (sign-out with `clearOnSignOut`, or a reset). */
1672
+ clear(): Promise<void>;
1673
+ /** Point at another namespace. Does not touch the bytes of the old one. */
1674
+ setNamespace(namespace: string): void;
1675
+ }
1676
+ //#endregion
1677
+ //#region src/services/blobs/blob-manifest.d.ts
1678
+ interface BlobEntry {
1679
+ /** `${bucket}/${path}` — also the `_00_blob` row id. */
1680
+ id: string;
1681
+ bucket: string;
1682
+ path: string;
1683
+ size: number;
1684
+ contentType: string;
1685
+ createdAt: number;
1686
+ lastAccess: number;
1687
+ hits: number;
1688
+ /** Exempt from pressure eviction. Never expires on its own. */
1689
+ pinned: boolean;
1690
+ }
1691
+ declare class BlobManifest {
1692
+ private local;
1693
+ private entries;
1694
+ /** Ids whose in-memory state has not been written back yet. */
1695
+ private dirty;
1696
+ private removed;
1697
+ private flushing;
1698
+ constructor(local: LocalStore);
188
1699
  /**
189
- * Sign out and clear session
1700
+ * Hydrate from the rows matching `keys`. Ids come from the OPFS listing, so
1701
+ * this never needs a full-table scan (and therefore never needs a QueryPlan).
1702
+ * Any read failure yields an empty manifest: reconcile then rebuilds every
1703
+ * row from disk, which is exactly the desired degradation.
190
1704
  */
191
- signOut(): Promise<void>;
192
- private setSession;
193
- signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
194
- signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
1705
+ load(ids: string[]): Promise<void>;
1706
+ get(key: BlobKey): BlobEntry | undefined;
1707
+ getById(id: string): BlobEntry | undefined;
1708
+ all(): BlobEntry[];
1709
+ totalBytes(): number;
1710
+ pinnedBytes(): number;
1711
+ put(entry: BlobEntry): void;
1712
+ touch(id: string, now: number): void;
1713
+ setPinned(id: string, pinned: boolean): boolean;
1714
+ remove(id: string): void;
1715
+ /** Forget everything without scheduling deletes — for a bucket switch, where
1716
+ * the rows belong to the store we are leaving and must stay put. */
1717
+ reset(): void;
1718
+ hasPendingWrites(): boolean;
1719
+ /**
1720
+ * Write back pending changes. Serialized: a second concurrent flush awaits
1721
+ * the first rather than racing it into the same rows. Failures are swallowed
1722
+ * on purpose — a lost metadata write costs an LRU timestamp, and the entry is
1723
+ * rebuilt from disk on the next reconcile.
1724
+ */
1725
+ flush(): Promise<void>;
1726
+ private doFlush;
195
1727
  }
196
1728
  //#endregion
197
- //#region src/sp00ky.d.ts
1729
+ //#region src/services/blobs/blob-cache.d.ts
1730
+ interface BlobUrlLease {
1731
+ url: string;
1732
+ release(): void;
1733
+ }
1734
+ interface BlobReadOptions {
1735
+ /** Write through to L1 on a miss. Default true. */
1736
+ persist?: boolean;
1737
+ /** Mark the entry exempt from pressure eviction. */
1738
+ pin?: boolean;
1739
+ /**
1740
+ * Default `'never'`: a bucket path is treated as immutable, which is how the
1741
+ * client writes them (`crypto.randomUUID() + ext`). `'head'` spends a remote
1742
+ * `head()` to compare sizes before trusting L1.
1743
+ */
1744
+ revalidate?: 'never' | 'head';
1745
+ /** Skip L0/L1 entirely and refill from remote. Backs `refetch()`. */
1746
+ reload?: boolean;
1747
+ }
1748
+ interface BlobCacheStats {
1749
+ entries: number;
1750
+ totalBytes: number;
1751
+ budgetBytes: number;
1752
+ pinnedBytes: number;
1753
+ evictedEntries: number;
1754
+ evictedBytes: number;
1755
+ reconciledEntries: number;
1756
+ hits: number;
1757
+ misses: number;
1758
+ persistent: boolean;
1759
+ /** True when pinned bytes alone exceed the budget: new entries stop being
1760
+ * written rather than pinned ones being thrown away. */
1761
+ persistPaused: boolean;
1762
+ }
1763
+ interface BlobCacheOptions {
1764
+ store: BlobStore;
1765
+ manifest: BlobManifest;
1766
+ /** L2 read. Resolves to null when the file does not exist remotely. */
1767
+ fetchRemote(key: BlobKey): Promise<Blob | null>;
1768
+ /** L2 metadata, for `revalidate: 'head'`. */
1769
+ headRemote?(key: BlobKey): Promise<Record<string, unknown> | null>;
1770
+ logger: Logger$1;
1771
+ maxBytes: number;
1772
+ now?: () => number;
1773
+ /** Injected so the URL layer is exercisable off a DOM (node tests). */
1774
+ urls?: {
1775
+ create(blob: Blob): string;
1776
+ revoke(url: string): void;
1777
+ };
1778
+ }
1779
+ declare class BlobCache {
1780
+ private readonly store;
1781
+ private readonly manifest;
1782
+ private readonly fetchRemote;
1783
+ private readonly headRemote?;
1784
+ private readonly logger;
1785
+ private readonly now;
1786
+ private readonly urlFactory;
1787
+ private maxBytes;
1788
+ private persistPaused;
1789
+ /** Set after a quota failure survives one forced eviction. */
1790
+ private persistDisabled;
1791
+ private readonly urls;
1792
+ /** Ids at zero references, oldest first — the hot-URL window. */
1793
+ private idleUrls;
1794
+ private readonly inflight;
1795
+ private flushTimer;
1796
+ private readonly onPageHide;
1797
+ /**
1798
+ * Resolves once the manifest has been reconciled against disk. Reads await
1799
+ * it, so `start()` does NOT have to be awaited on the boot path — blocking
1800
+ * boot on an OPFS directory walk delayed the WebSocket connect (and with it
1801
+ * the connection supervisor) for no benefit.
1802
+ */
1803
+ private ready;
1804
+ private hits;
1805
+ private misses;
1806
+ private evictedEntries;
1807
+ private evictedBytes;
1808
+ private reconciledEntries;
1809
+ constructor(opts: BlobCacheOptions);
1810
+ /** Coalesce manifest write-back. Metadata only, so losing the tail costs an
1811
+ * LRU timestamp that reconcile reseeds from the file mtime. */
1812
+ private scheduleFlush;
1813
+ /**
1814
+ * Resolve the bytes for `key`, filling L1 on the way when `persist` is on.
1815
+ * Returns null when the file does not exist remotely and is not cached.
1816
+ */
1817
+ read(key: BlobKey, options?: BlobReadOptions): Promise<Blob | null>;
1818
+ /**
1819
+ * An object URL for `key`, refcounted. Callers MUST `release()`; the URL is
1820
+ * revoked once the last holder lets go and it falls out of the hot window.
1821
+ */
1822
+ acquireUrl(key: BlobKey, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
1823
+ private lease;
1824
+ private releaseUrl;
1825
+ private revokeUrl;
1826
+ /** L1 lookup with the size check that catches torn and cross-tab writes. */
1827
+ private readLocal;
1828
+ /** True when the remote agrees with the cached size, or cannot be reached. */
1829
+ private headMatches;
1830
+ private fetchDeduped;
1831
+ private persist;
1832
+ private writeThrough;
1833
+ /** Forget one path everywhere. Called on `bucket.put()`/`bucket.delete()`. */
1834
+ invalidate(key: BlobKey): Promise<void>;
1835
+ private dropLocal;
1836
+ setPinned(key: BlobKey, pinned: boolean): void;
1837
+ /**
1838
+ * Bring total bytes under budget by dropping the least recently used
1839
+ * entries. Pinned entries and anything with a live object URL are skipped —
1840
+ * evicting bytes that a mounted `<img>` is displaying would blank it.
1841
+ */
1842
+ private enforceBudget;
1843
+ /** Evict LRU-first until at or below `target`. Returns the resulting total. */
1844
+ private evictTo;
1845
+ /**
1846
+ * Rebuild the manifest from what is actually on disk. OPFS wins on existence
1847
+ * in both directions: files with no row get a row (seeded from mtime), rows
1848
+ * are only loaded for files that exist, and torn `.part-` writes are swept by
1849
+ * the walk itself.
1850
+ *
1851
+ * Rows whose file vanished outside our control (a browser origin eviction)
1852
+ * are left in `_00_blob`. They are inert — `load()` only ever asks for ids it
1853
+ * found on disk — and are overwritten if that path is cached again.
1854
+ */
1855
+ reconcile(): Promise<void>;
1856
+ /** Warm the cache for offline use. Skips anything already cached. */
1857
+ prefetch(keys: BlobKey[]): Promise<void>;
1858
+ /** Bind to the boot bucket and hydrate the manifest from disk. Separate from
1859
+ * {@link setNamespace} because boot must reconcile even when the namespace
1860
+ * it lands on is the one the store was constructed with. */
1861
+ start(namespace: string): Promise<void>;
1862
+ /** Repoint at another local bucket. The bytes of the old one stay on disk so
1863
+ * switching back (or signing back in) is still warm. */
1864
+ setNamespace(namespace: string): Promise<void>;
1865
+ setMaxBytes(maxBytes: number): void;
1866
+ /** Delete every cached byte in the current namespace. */
1867
+ clear(): Promise<void>;
1868
+ flush(): Promise<void>;
1869
+ /** Flush metadata and drop every object URL. Must run before the local store
1870
+ * closes — the flush writes through it. */
1871
+ close(): Promise<void>;
1872
+ stats(): BlobCacheStats;
1873
+ }
1874
+ //#endregion
1875
+ //#region src/client/services.d.ts
1876
+ /** Everything the facade talks to besides the runtime. */
1877
+ interface Services<S extends SchemaStructure> {
1878
+ logger: Logger$1;
1879
+ /** What the logger wrote, for the DevTools Logs tab. Absent in test fakes. */
1880
+ logTap?: LogTap;
1881
+ local: LocalStore;
1882
+ remote: RemoteDatabaseService;
1883
+ connectionSupervisor: ConnectionSupervisor;
1884
+ blobs: BlobCache;
1885
+ persistence: PersistenceClient;
1886
+ streamProcessor: StreamProcessorService;
1887
+ migrator: LocalMigrator;
1888
+ crdt: CrdtManager;
1889
+ auth: AuthService<S>;
1890
+ tabs: TabsCoordinator | null;
1891
+ tabsUnsupportedReason: string | undefined;
1892
+ tabId: string;
1893
+ }
1894
+ /** What the services need back from the runtime once it exists. */
1895
+ //#endregion
1896
+ //#region src/utils/blurhash.d.ts
1897
+ /**
1898
+ * Blurhash generation settings. `true` enables with the defaults below, `false`
1899
+ * disables. Resolution order for a put: per-call option > client config >
1900
+ * default ON. See {@link Sp00kyConfig.blurhash}.
1901
+ */
1902
+ type BlurhashSetting = boolean | BlurhashEncodeOptions;
1903
+ interface BlurhashEncodeOptions {
1904
+ /** Horizontal detail components, 1-9. Defaults to 4. */
1905
+ componentX?: number;
1906
+ /** Vertical detail components, 1-9. Defaults to 3. */
1907
+ componentY?: number;
1908
+ }
1909
+ /**
1910
+ * Where an image's blurhash lives: a tiny sidecar object in the same bucket.
1911
+ * Buckets have no per-object metadata channel (`put` is just `.put($content)`),
1912
+ * so the hash for `covers/x_t.webp` is the text object `covers/x_t.webp.bh`.
1913
+ */
1914
+ declare function blurhashSidecarPath(path: string): string;
1915
+ /** Extensions `bucket.put` treats as images worth hashing. */
1916
+ declare const BLURHASH_IMAGE_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif", "avif", "bmp"];
1917
+ declare function isImagePath(path: string): boolean;
1918
+ /**
1919
+ * Decode `content` as an image and compute its blurhash. Browser-only: returns
1920
+ * null (never throws) when image decoding is unavailable (node, workers without
1921
+ * canvas), when the bytes are not a decodable image, or on any other failure —
1922
+ * a missing hash must never break the upload that triggered it.
1923
+ */
1924
+ declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
1925
+ //#endregion
1926
+ //#region src/client/bucket-handle.d.ts
1927
+ /** Coerce whatever the `.get()` RPC hands back into a Blob. */
1928
+ declare function bucketContentToBlob(content: unknown): Blob | null;
1929
+ interface BucketPutOptions {
1930
+ /** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
1931
+ blurhash?: BlurhashSetting;
1932
+ }
1933
+ interface BucketPutResult {
1934
+ /** The computed blurhash when the content was a hashable image; else null. */
1935
+ blurhash: string | null;
1936
+ }
1937
+ interface BucketHandleSettings {
1938
+ blurhash?: BlurhashSetting;
1939
+ logger?: {
1940
+ warn: (obj: unknown, msg?: string) => void;
1941
+ };
1942
+ }
198
1943
  declare class BucketHandle {
199
1944
  private bucketName;
200
1945
  private remote;
201
- constructor(bucketName: string, remote: RemoteDatabaseService);
202
- put(path: string, content: string | Uint8Array | Blob): Promise<void>;
1946
+ /** Absent on the raw handle the cache itself reads through. */
1947
+ private blobs?;
1948
+ private settings?;
1949
+ constructor(bucketName: string, remote: RemoteDatabaseService, /** Absent on the raw handle the cache itself reads through. */
1950
+ blobs?: (BlobCache | null) | undefined, settings?: BucketHandleSettings | undefined);
1951
+ /** Effective blurhash setting: per-call option > client config > default ON. */
1952
+ private resolveBlurhash;
1953
+ put(path: string, content: string | Uint8Array | Blob, options?: BucketPutOptions): Promise<BucketPutResult>;
1954
+ /**
1955
+ * The blurhash stored alongside an uploaded image (see
1956
+ * {@link blurhashSidecarPath}), or null when there is none. Reads through the
1957
+ * blob cache, so a warm client answers from OPFS without a network hop, and
1958
+ * misses are remembered per tab so a hashless image costs at most one
1959
+ * serialized remote read per session.
1960
+ */
1961
+ blurhash(path: string): Promise<string | null>;
203
1962
  get(path: string): Promise<unknown>;
1963
+ /**
1964
+ * Read through the local blob cache: OPFS first, the bucket second. Unlike
1965
+ * {@link get} this survives a reload and works offline. Returns null when the
1966
+ * file exists in neither place.
1967
+ */
1968
+ read(path: string, options?: BlobReadOptions): Promise<Blob | null>;
1969
+ /**
1970
+ * A refcounted object URL for `path`, suitable for `<img src>`. The caller
1971
+ * MUST call `release()` when the URL goes off screen. Returns null when the
1972
+ * file does not exist, or when object URLs are unavailable (non-browser).
1973
+ */
1974
+ url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
1975
+ /** Exempt `path` from pressure eviction. Pinned bytes never expire. */
1976
+ pin(path: string): void;
1977
+ unpin(path: string): void;
1978
+ /** Drop `path` from the local cache without touching the remote file. */
1979
+ evict(path: string): Promise<void>;
1980
+ /** Warm the cache for offline use. Already-cached paths are skipped. */
1981
+ prefetch(paths: string[]): Promise<void>;
204
1982
  delete(path: string): Promise<void>;
205
1983
  exists(path: string): Promise<boolean>;
206
1984
  head(path: string): Promise<Record<string, unknown>>;
@@ -208,55 +1986,166 @@ declare class BucketHandle {
208
1986
  rename(sourcePath: string, targetPath: string): Promise<void>;
209
1987
  list(prefix?: string): Promise<string[]>;
210
1988
  }
1989
+ //#endregion
1990
+ //#region src/client/sp00ky-client.d.ts
1991
+ interface Sp00kyClientDeps<S extends SchemaStructure> {
1992
+ services?: Services<S>;
1993
+ runtime?: Runtime;
1994
+ env?: Partial<SagaEnv>;
1995
+ }
1996
+ /**
1997
+ * The public client. Every method is a thin translation into a saga run, a
1998
+ * state read, or a subscription on the runtime; the engine's behaviour lives
1999
+ * in the sagas.
2000
+ */
211
2001
  declare class Sp00kyClient<S extends SchemaStructure> {
212
- private config;
213
- private local;
214
- private remote;
215
- private persistenceClient;
216
- private migrator;
217
- private cache;
218
- private dataModule;
219
- private sync;
220
- private devTools;
221
- private logger;
222
- auth: AuthService<S>;
223
- streamProcessor: StreamProcessorService;
224
- get remoteClient(): Surreal;
225
- get localClient(): Surreal;
226
- get pendingMutationCount(): number;
227
- subscribeToPendingMutations(cb: (count: number) => void): () => void;
228
- constructor(config: Sp00kyConfig<S>);
229
- /**
230
- * Setup direct callbacks instead of event subscriptions
231
- */
232
- private setupCallbacks;
2002
+ private readonly config;
2003
+ readonly auth: AuthService<S>;
2004
+ readonly streamProcessor: StreamProcessorService;
2005
+ /** Web Push for this browser: subscribe, devices, self-pushes, service worker bridge. */
2006
+ readonly webPush: WebPushModule;
2007
+ private readonly services;
2008
+ private readonly env;
2009
+ private readonly runtime;
2010
+ private readonly featureFlags;
2011
+ private readonly appReleases;
2012
+ /** Teardown for subscriptions the client itself owns. */
2013
+ private readonly disposers;
2014
+ /** Assigned in `wireAdapters`, which the constructor always runs. */
2015
+ private impersonationBanner;
2016
+ private readonly devTools;
2017
+ private hub;
2018
+ private forwarder;
2019
+ private detachWindow;
2020
+ private sharedActive;
2021
+ constructor(config: Sp00kyConfig<S>, deps?: Sp00kyClientDeps<S>);
2022
+ /** Adapter callbacks become runtime events; runtime events reach the legacy services. */
2023
+ private wireAdapters;
2024
+ /** Runtime events the DevTools panel follows; query transitions also go to the log. */
2025
+ private forwardToDevTools;
233
2026
  init(): Promise<void>;
234
2027
  close(): Promise<void>;
235
- authenticate(token: string): Promise<surrealdb0.Tokens>;
236
- deauthenticate(): Promise<void>;
2028
+ isLocalReady(): boolean;
237
2029
  query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
2030
+ private registerInput;
238
2031
  private initQuery;
2032
+ /**
2033
+ * The raw remote escape hatches bypass the query builder, so their shapes
2034
+ * can never be on the server's query allowlist. When the generated schema
2035
+ * says the allowlist is on, refuse them unless the app opted in explicitly.
2036
+ */
2037
+ private assertRawRemoteAllowed;
239
2038
  queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
2039
+ /**
2040
+ * Preload = register a query nobody subscribes to. Resolved before on this
2041
+ * device: returns at once. Never resolved: resolves when the server's
2042
+ * membership and every body are local. `signal` aborts the wait.
2043
+ */
2044
+ preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
240
2045
  subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
241
2046
  immediate?: boolean;
242
2047
  }): Promise<() => void>;
2048
+ deregisterQuery(queryHash: string): void;
2049
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
2050
+ immediate?: boolean;
2051
+ }): () => void;
2052
+ subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
2053
+ immediate?: boolean;
2054
+ }): () => void;
2055
+ reportFrontendTiming(queryHash: string, ms: number): void;
2056
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
2057
+ update<T extends Record<string, unknown>>(_table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
2058
+ delete(_table: string, id: string): Promise<void>;
243
2059
  run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
244
- bucket<B extends BucketNames<S>>(name: B): BucketHandle;
245
- create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
246
- update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
247
- [x: string]: /*elided*/any;
248
- }>;
249
- delete(table: string, id: string): Promise<void>;
2060
+ get failedMutationCount(): number;
2061
+ subscribeToFailedMutations(cb: (count: number) => void): () => void;
2062
+ listFailedMutations(): Promise<FailedMutationRow[]>;
2063
+ retryFailedMutation(mutationId: string): Promise<boolean>;
2064
+ discardFailedMutation(mutationId: string): Promise<boolean>;
2065
+ get tabRole(): TabRole$1 | null;
2066
+ get remoteClient(): Surreal;
2067
+ get localClient(): unknown;
2068
+ get pendingMutationCount(): number;
2069
+ /** Kept for the e2e suite; the saga core has no LIVE retry ladder. */
2070
+ get liveRetryCount(): number;
2071
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
2072
+ get fetchingQueryCount(): number;
2073
+ subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
2074
+ get syncHealth(): SyncHealth;
2075
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
2076
+ get storageHealth(): StorageHealth;
2077
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
2078
+ /** The engine state, read-only. For tests and DevTools. */
2079
+ get state(): ClientState;
2080
+ /** Feed an event into the engine. For adapters, tests and DevTools. */
2081
+ dispatch(event: RuntimeEvent): Promise<void>;
2082
+ authenticate(token: string): Promise<surrealdb0.Tokens>;
2083
+ deauthenticate(): Promise<void>;
250
2084
  useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
251
- private persistClientId;
252
- private loadOrGenerateClientId;
2085
+ remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
2086
+ /**
2087
+ * Tell the client that the app's own impersonation banner is on screen.
2088
+ * Only meaningful with `impersonationBanner: { mode: 'custom' }`, where it
2089
+ * cancels the fallback that would otherwise show the built-in banner. Call
2090
+ * it while the custom banner is rendered (the Solid `useImpersonation`
2091
+ * hook does it for you with `rendersBanner: true`).
2092
+ */
2093
+ acknowledgeImpersonationBanner(): void;
2094
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2095
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
2096
+ clearFeatureOverrides(): void;
2097
+ getFeatureOverrides(): Record<string, FeatureFlagOverride>;
2098
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2099
+ openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2100
+ closeCrdtField(table: string, recordId: string, field: string): void;
2101
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle;
2102
+ getBlobCacheStats(): BlobCacheStats;
2103
+ }
2104
+ //#endregion
2105
+ //#region src/utils/semver.d.ts
2106
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
2107
+ declare function semverGt(a: unknown, b: unknown): boolean;
2108
+ //#endregion
2109
+ //#region src/services/database/errors.d.ts
2110
+ /**
2111
+ * A local-store operation that did not answer within its deadline.
2112
+ *
2113
+ * The local write path (`db.create` / `db.update` / `db.delete`, every local
2114
+ * query behind them) used to have no deadline anywhere: the SQLite worker
2115
+ * transport parks a call until the worker replies, the surrealdb engine's
2116
+ * query chain waits on the previous link, and `withRetry` retries without a
2117
+ * clock. One op that never settled (a worker starved behind a long select, a
2118
+ * lock verification awaiting `navigator.locks.query()` forever) left the
2119
+ * caller's promise pending for the tab's lifetime - a chat composer that never
2120
+ * re-enabled, a call that never got past "Connecting".
2121
+ *
2122
+ * The message says "timed out" on purpose: `classifySyncError` keys off it and
2123
+ * treats the failure as transient (re-queue), never as an application error
2124
+ * that rolls the mutation back. `retryable: false` keeps `withRetry` from
2125
+ * spinning on it: the op is still running in the engine, retrying queues a
2126
+ * second copy behind it.
2127
+ */
2128
+ declare class LocalOpTimeoutError extends Error {
2129
+ readonly name = "LocalOpTimeoutError";
2130
+ readonly retryable = false;
2131
+ readonly op: string;
2132
+ readonly timeoutMs: number;
2133
+ constructor(op: string, timeoutMs: number);
253
2134
  }
2135
+ /** Default deadline for one local-store operation. Generous: a cold 4k-row
2136
+ * select on a throttled tab is seconds, not tens of seconds. */
2137
+ declare const DEFAULT_LOCAL_OP_TIMEOUT_MS = 30000;
254
2138
  //#endregion
255
2139
  //#region src/utils/index.d.ts
256
2140
  declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
2141
+ /**
2142
+ * Convert plain text to simple HTML paragraphs.
2143
+ * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
2144
+ */
2145
+ declare function textToHtml(text: string): string;
257
2146
  /**
258
2147
  * Helper for retrying DB operations with exponential backoff
259
2148
  */
260
2149
 
261
2150
  //#endregion
262
- export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, DebounceOptions, EventSubscriptionOptions, Level, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PinoTransmit, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryTimeToLive, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StoreType, UpdateOptions, createAuthEventSystem, fileToUint8Array };
2151
+ 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, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EventSubscriptionOptions, type FailedMutationRow as FailedMutation, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, IMPERSONATION_ACCESS, ImpersonationCandidate, ImpersonationInfo, ImpersonationTimerHost, ImpersonationTimers, InlineRow, Level, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, ORIGIN_TOKEN_KEY, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, 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, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, ServerViewMeta, SignOutContext, SignOutHook, Sp00kyClient, Sp00kyClientDeps, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, TokenClaims, 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, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, renewDelayMs, sameImpersonation, semverGt, textToHtml };