@spooky-sync/core 0.0.1-canary.97 → 1.0.0-beta.1

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 (261) hide show
  1. package/AGENTS.md +57 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2096 -929
  4. package/dist/index.js +18217 -5019
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/sqlite-open.js +392 -0
  11. package/dist/sqlite-worker.d.ts +1 -0
  12. package/dist/sqlite-worker.js +439 -0
  13. package/dist/sw.d.ts +207 -0
  14. package/dist/sw.js +393 -0
  15. package/dist/tabs-broker-worker.d.ts +8 -0
  16. package/dist/tabs-broker-worker.js +477 -0
  17. package/dist/types.d.ts +1968 -82
  18. package/dist/worker-edges.js +498 -0
  19. package/dist/worker-impersonation.js +60 -0
  20. package/dist/worker-ref-tables.d.ts +48 -0
  21. package/dist/worker-types.d.ts +112 -0
  22. package/dist/worker-types.js +73 -0
  23. package/package.json +34 -8
  24. package/scripts/check-broker-bundle.mjs +33 -0
  25. package/scripts/check-worker-entries.mjs +173 -0
  26. package/skills/sp00ky-core/SKILL.md +42 -8
  27. package/skills/sp00ky-core/references/config.md +8 -2
  28. package/src/boot/auth-flip.saga.test.ts +174 -0
  29. package/src/boot/auth-flip.saga.ts +77 -0
  30. package/src/boot/boot.saga.test.ts +203 -0
  31. package/src/boot/boot.saga.ts +146 -0
  32. package/src/boot/bucket-switch.saga.test.ts +191 -0
  33. package/src/boot/bucket-switch.saga.ts +151 -0
  34. package/src/boot/preload.saga.test.ts +96 -0
  35. package/src/boot/preload.saga.ts +45 -0
  36. package/src/bucket-blurhash.test.ts +148 -0
  37. package/src/client/bucket-handle.test.ts +195 -0
  38. package/src/client/bucket-handle.ts +352 -0
  39. package/src/client/router.test.ts +59 -0
  40. package/src/client/router.ts +104 -0
  41. package/src/client/runtime.test.ts +319 -0
  42. package/src/client/runtime.ts +307 -0
  43. package/src/client/services.test.ts +74 -0
  44. package/src/client/services.ts +437 -0
  45. package/src/client/sp00ky-client.test.ts +428 -0
  46. package/src/client/sp00ky-client.ts +737 -0
  47. package/src/index.ts +78 -0
  48. package/src/kernel/constants.test.ts +19 -0
  49. package/src/kernel/constants.ts +94 -0
  50. package/src/kernel/effects.test.ts +40 -0
  51. package/src/kernel/effects.ts +171 -0
  52. package/src/kernel/events.ts +60 -0
  53. package/src/kernel/interpreter.test.ts +116 -0
  54. package/src/kernel/interpreter.ts +148 -0
  55. package/src/kernel/saga.test.ts +89 -0
  56. package/src/kernel/saga.ts +73 -0
  57. package/src/live/index.test.ts +512 -0
  58. package/src/live/index.ts +1059 -0
  59. package/src/modules/app-release/index.test.ts +125 -0
  60. package/src/modules/app-release/index.ts +209 -0
  61. package/src/modules/auth/auth.local-first.test.ts +228 -0
  62. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  63. package/src/modules/auth/events/index.ts +7 -1
  64. package/src/modules/auth/impersonation-banner.ts +443 -0
  65. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  66. package/src/modules/auth/impersonation.test.ts +377 -0
  67. package/src/modules/auth/impersonation.ts +179 -0
  68. package/src/modules/auth/index.ts +516 -34
  69. package/src/modules/channel/channel.test.ts +752 -0
  70. package/src/modules/channel/index.ts +1153 -0
  71. package/src/modules/channel/webrtc.ts +472 -0
  72. package/src/modules/crdt/acceptance.ts +75 -0
  73. package/src/modules/crdt/bytes.ts +50 -0
  74. package/src/modules/crdt/crdt-field.ts +82 -238
  75. package/src/modules/crdt/crdt.test.ts +546 -0
  76. package/src/modules/crdt/hash.ts +103 -0
  77. package/src/modules/crdt/index.ts +740 -271
  78. package/src/modules/crdt/loro-loader.ts +25 -0
  79. package/src/modules/crdt/mirror.ts +37 -0
  80. package/src/modules/devtools/flags.ts +349 -0
  81. package/src/modules/devtools/index.ts +661 -99
  82. package/src/modules/devtools/mutations.test.ts +92 -0
  83. package/src/modules/devtools/mutations.ts +160 -0
  84. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  85. package/src/modules/devtools/state-shape.test.ts +263 -0
  86. package/src/modules/devtools/storage-info.test.ts +79 -0
  87. package/src/modules/devtools/storage-info.ts +168 -0
  88. package/src/modules/devtools/versions.ts +29 -0
  89. package/src/modules/feature-flag/index.test.ts +179 -1
  90. package/src/modules/feature-flag/index.ts +117 -10
  91. package/src/modules/ref-tables.test.ts +28 -1
  92. package/src/modules/ref-tables.ts +23 -1
  93. package/src/modules/web-push/index.test.ts +824 -0
  94. package/src/modules/web-push/index.ts +1027 -0
  95. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  96. package/src/mutation/jobs.test.ts +25 -0
  97. package/src/mutation/jobs.ts +41 -0
  98. package/src/mutation/mutation-id.test.ts +37 -0
  99. package/src/mutation/mutation-id.ts +35 -0
  100. package/src/mutation/pending-writes.integration.test.ts +175 -0
  101. package/src/mutation/push.saga.test.ts +361 -0
  102. package/src/mutation/push.saga.ts +245 -0
  103. package/src/mutation/rows.test.ts +278 -0
  104. package/src/mutation/rows.ts +515 -0
  105. package/src/mutation/tray.saga.test.ts +63 -0
  106. package/src/mutation/tray.saga.ts +48 -0
  107. package/src/mutation/write.saga.test.ts +436 -0
  108. package/src/mutation/write.saga.ts +384 -0
  109. package/src/pure.ts +66 -0
  110. package/src/push/types.ts +174 -0
  111. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  112. package/src/query/env.test.ts +23 -0
  113. package/src/query/env.ts +65 -0
  114. package/src/query/fetch.saga.test.ts +199 -0
  115. package/src/query/fetch.saga.ts +120 -0
  116. package/src/query/hash.test.ts +14 -0
  117. package/src/query/hash.ts +18 -0
  118. package/src/query/id-set-plan.test.ts +132 -0
  119. package/src/query/lifecycle.saga.test.ts +274 -0
  120. package/src/query/lifecycle.saga.ts +186 -0
  121. package/src/query/list-ref-live.integration.test.ts +203 -0
  122. package/src/query/materialize.saga.test.ts +200 -0
  123. package/src/query/materialize.saga.ts +102 -0
  124. package/src/query/materialize.test.ts +58 -0
  125. package/src/query/materialize.ts +57 -0
  126. package/src/query/membership.saga.test.ts +514 -0
  127. package/src/query/membership.saga.ts +339 -0
  128. package/src/query/membership.test.ts +151 -0
  129. package/src/query/membership.ts +234 -0
  130. package/src/query/register.saga.test.ts +369 -0
  131. package/src/query/register.saga.ts +293 -0
  132. package/src/query/render-set.test.ts +47 -0
  133. package/src/query/render-set.ts +71 -0
  134. package/src/query/session-guard.integration.test.ts +304 -0
  135. package/src/query/sql.test.ts +118 -0
  136. package/src/query/sql.ts +174 -0
  137. package/src/{modules/data → query}/window-query.test.ts +22 -4
  138. package/src/{modules/data → query}/window-query.ts +86 -8
  139. package/src/services/blobs/blob-cache.test.ts +359 -0
  140. package/src/services/blobs/blob-cache.ts +603 -0
  141. package/src/services/blobs/blob-manifest.ts +227 -0
  142. package/src/services/blobs/blob-store.test.ts +77 -0
  143. package/src/services/blobs/blob-store.ts +359 -0
  144. package/src/services/blobs/blob.fixture.ts +90 -0
  145. package/src/services/blobs/index.ts +70 -0
  146. package/src/services/database/cache-engine.ts +209 -0
  147. package/src/services/database/connection-supervisor.test.ts +318 -0
  148. package/src/services/database/connection-supervisor.ts +422 -0
  149. package/src/services/database/database.query-timeout.test.ts +140 -0
  150. package/src/services/database/database.responses.test.ts +43 -0
  151. package/src/services/database/database.ts +151 -56
  152. package/src/services/database/engine-factory.ts +33 -0
  153. package/src/services/database/errors.ts +34 -0
  154. package/src/services/database/index.ts +7 -0
  155. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  156. package/src/services/database/local-migrator.integration.test.ts +110 -0
  157. package/src/services/database/local-migrator.ts +54 -9
  158. package/src/services/database/local.test.ts +117 -0
  159. package/src/services/database/local.ts +364 -74
  160. package/src/services/database/plan-render.test.ts +159 -0
  161. package/src/services/database/plan-render.ts +108 -0
  162. package/src/services/database/relation-resolver.test.ts +484 -0
  163. package/src/services/database/relation-resolver.ts +0 -0
  164. package/src/services/database/remote.ts +283 -4
  165. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  166. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  167. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  168. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  169. package/src/services/database/sqlite-column-reset.ts +91 -0
  170. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  171. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  172. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  173. package/src/services/database/sqlite-lock-verify.ts +45 -0
  174. package/src/services/database/sqlite-open.test.ts +150 -0
  175. package/src/services/database/sqlite-open.ts +164 -0
  176. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  177. package/src/services/database/sqlite-plan-sql.ts +196 -0
  178. package/src/services/database/sqlite-projection.test.ts +121 -0
  179. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  180. package/src/services/database/sqlite-select.test.ts +261 -0
  181. package/src/services/database/sqlite-select.ts +131 -0
  182. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  183. package/src/services/database/sqlite-transport.ts +229 -0
  184. package/src/services/database/sqlite-worker.ts +437 -0
  185. package/src/services/database/surql-translate.ts +417 -0
  186. package/src/services/database/surreal-cache-engine.ts +163 -0
  187. package/src/services/logger/index.test.ts +132 -0
  188. package/src/services/logger/index.ts +187 -6
  189. package/src/services/persistence/surrealdb.ts +2 -2
  190. package/src/services/stream-processor/index.ts +621 -93
  191. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  192. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  193. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  194. package/src/services/stream-processor/wasm-types.ts +41 -1
  195. package/src/services/tabs/broker-client.ts +284 -0
  196. package/src/services/tabs/broker.test.ts +381 -0
  197. package/src/services/tabs/coordinator.test.ts +386 -0
  198. package/src/services/tabs/coordinator.ts +646 -0
  199. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  200. package/src/services/tabs/leader-locks.ts +75 -0
  201. package/src/services/tabs/protocol.ts +262 -0
  202. package/src/services/tabs/support.ts +36 -0
  203. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  204. package/src/sp00ky.ts +5 -648
  205. package/src/state/client-state.ts +231 -0
  206. package/src/state/lifecycle.test.ts +184 -0
  207. package/src/state/lifecycle.ts +127 -0
  208. package/src/state/reducers.test.ts +337 -0
  209. package/src/state/reducers.ts +571 -0
  210. package/src/state/selectors.test.ts +203 -0
  211. package/src/state/selectors.ts +264 -0
  212. package/src/sw/index.test.ts +582 -0
  213. package/src/sw/index.ts +607 -0
  214. package/src/sw/store.ts +96 -0
  215. package/src/sync/connection.saga.test.ts +97 -0
  216. package/src/sync/connection.saga.ts +89 -0
  217. package/src/sync/live.saga.test.ts +229 -0
  218. package/src/sync/live.saga.ts +116 -0
  219. package/src/sync/policy.health.test.ts +56 -0
  220. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  221. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  222. package/src/sync/poll.saga.test.ts +51 -0
  223. package/src/sync/poll.saga.ts +36 -0
  224. package/src/sync/tabs.saga.test.ts +78 -0
  225. package/src/sync/tabs.saga.ts +96 -0
  226. package/src/testing/adapters.ts +137 -0
  227. package/src/testing/build.ts +63 -0
  228. package/src/testing/fake-services.ts +63 -0
  229. package/src/testing/run-pure.test.ts +92 -0
  230. package/src/testing/run-pure.ts +128 -0
  231. package/src/testing/services.ts +17 -0
  232. package/src/types.ts +568 -25
  233. package/src/utils/blurhash.ts +90 -0
  234. package/src/utils/edges.ts +57 -0
  235. package/src/utils/error-classification.test.ts +116 -0
  236. package/src/utils/error-classification.ts +74 -0
  237. package/src/utils/index.ts +58 -3
  238. package/src/utils/parser.test.ts +67 -102
  239. package/src/utils/parser.ts +62 -1
  240. package/src/utils/semver.test.ts +32 -0
  241. package/src/utils/semver.ts +30 -0
  242. package/src/utils/sha256.ts +15 -0
  243. package/src/utils/surql.ts +17 -15
  244. package/src/utils/utils.test.ts +3 -2
  245. package/tsdown.config.ts +64 -4
  246. package/vitest.config.ts +48 -0
  247. package/src/modules/cache/index.ts +0 -253
  248. package/src/modules/cache/types.ts +0 -19
  249. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  250. package/src/modules/data/data.status.test.ts +0 -108
  251. package/src/modules/data/data.test.ts +0 -58
  252. package/src/modules/data/index.ts +0 -1491
  253. package/src/modules/sync/engine.ts +0 -227
  254. package/src/modules/sync/events/index.ts +0 -84
  255. package/src/modules/sync/index.ts +0 -3
  256. package/src/modules/sync/queue/index.ts +0 -2
  257. package/src/modules/sync/queue/queue-down.ts +0 -90
  258. package/src/modules/sync/queue/queue-up.ts +0 -224
  259. package/src/modules/sync/scheduler.ts +0 -121
  260. package/src/modules/sync/sync.ts +0 -1244
  261. package/src/sp00ky.auth-order.test.ts +0 -65
package/dist/types.d.ts CHANGED
@@ -1,7 +1,351 @@
1
- import { RecordId } from "surrealdb";
2
- import { RecordId as RecordId$1, SchemaStructure } from "@spooky-sync/query-builder";
1
+ import { AccessDefinition, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryPlan, QueryPlan as QueryPlan$1, RecordId, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap, WhereNode, WhereNode as WhereNode$1 } from "@spooky-sync/query-builder";
2
+ import { RecordId as RecordId$1, Surreal, SurrealEvents, SurrealTransaction } from "surrealdb";
3
3
  import { Level, Level as Level$1, Logger, LoggerOptions } from "pino";
4
4
 
5
+ //#region src/services/logger/index.d.ts
6
+ type Logger$1 = Logger;
7
+ /** One line the logger wrote, as the DevTools Logs tab and the MCP read it. */
8
+ interface CapturedLog {
9
+ /** Monotonic for the page's lifetime; a reader resumes after the last one it holds. */
10
+ seq: number;
11
+ time: number;
12
+ /** Pino's numeric level: 10 trace … 60 fatal. */
13
+ level: number;
14
+ msg: string;
15
+ /** The whole log object as JSON (what the console printed), capped at {@link LogTap.LINE_MAX}. */
16
+ line: string;
17
+ }
18
+ interface LogRead {
19
+ entries: CapturedLog[];
20
+ /** `seq` of the newest captured line; pass it back as `after` to resume. */
21
+ head: number;
22
+ /** Lines after `after` the ring overwrote before they were read (cleared ones excluded). */
23
+ dropped: number;
24
+ consoleLevel: Level;
25
+ captureLevel: Level;
26
+ }
27
+ /**
28
+ * JSON for a log object that can never throw into the call site: Errors keep
29
+ * their message and stack (plain `JSON.stringify` prints `{}`), bigints become
30
+ * strings, and a cycle prints `[Circular]` instead of throwing.
31
+ */
32
+
33
+ /**
34
+ * The page-side log buffer behind the DevTools Logs tab. Always on and
35
+ * bounded: a line costs the JSON the console write produces anyway, and a
36
+ * panel opened after boot still sees the boot.
37
+ *
38
+ * It also owns the logger's level. The console prints at the configured level
39
+ * only; `setCaptureLevel` changes what is RECORDED (debug without flooding the
40
+ * console), live on every child logger, and keeps it for this tab's session so
41
+ * a reload captures its boot at that level too.
42
+ */
43
+ declare class LogTap {
44
+ readonly consoleLevel: Level;
45
+ static readonly CAPACITY = 500;
46
+ static readonly LINE_MAX = 4000;
47
+ private readonly ring;
48
+ private seq;
49
+ /** `seq` at the last `clear()`: lines up to here are gone on purpose, not dropped. */
50
+ private clearedThrough;
51
+ private readonly listeners;
52
+ private readonly loggers;
53
+ private captureLevelValue;
54
+ constructor(consoleLevel: Level);
55
+ /** `seq` of the newest captured line. */
56
+ get head(): number;
57
+ get captureLevel(): Level;
58
+ /** What pino has to produce for both the console and the buffer. */
59
+ get effectiveLevel(): Level;
60
+ /** Whether the console prints a line at this numeric level. */
61
+ printsToConsole(level: number): boolean;
62
+ /** Remember a logger (the root and every child) so a level change reaches it. */
63
+ track(logger: Logger$1): void;
64
+ setCaptureLevel(level: Level): void;
65
+ record(o: Record<string, unknown>, line: string): void;
66
+ /** Lines after `after` (0 = everything still buffered), oldest first. */
67
+ read(after?: number, limit?: number): LogRead;
68
+ clear(): void;
69
+ /** Called synchronously inside the log call: keep it cheap, never log from it. */
70
+ subscribe(cb: () => void): () => void;
71
+ }
72
+ //#endregion
73
+ //#region src/modules/channel/index.d.ts
74
+ /**
75
+ * Peer to peer channels (`-- @channel` tables, `client.channel(query, peers)`).
76
+ *
77
+ * A channel is a filter (the `where` of one or more queries on `@channel`
78
+ * tables) plus the users it connects to. Writes to rows that match the
79
+ * filter reach the users' tabs straight over the transport (WebRTC by
80
+ * default), and their tabs fold them in before the database has seen them.
81
+ * The filter is evaluated here, in plain JS, against the row; the query is
82
+ * never registered. Optimistic writes, distributed:
83
+ *
84
+ * - Updates: persistent fields still go through the normal outbox. A peer
85
+ * shows the sent value until its own synced row catches up to it, or for
86
+ * `confirmTimeoutMs` at most, so a value the server rejected (or that a
87
+ * peer made up) falls back to the server's on its own.
88
+ * - `-- @ephemeral` fields never reach the database. They live in memory,
89
+ * last writer wins, and a peer's values vanish when it disconnects.
90
+ * - Creates go into the peer's store and circuit like its own optimistic
91
+ * create (minus the outbox); deletes hide the row. Both are undone unless
92
+ * the server confirms them (see the peer sagas in `mutation/write.saga.ts`).
93
+ *
94
+ * Nothing here enforces permissions beyond identity: the transport proves
95
+ * which user a peer is (the database stamps the signaling rows), a message
96
+ * is only taken from a user listed by an open channel whose filter the row
97
+ * matches, and fields must exist and fit their column type. Everything else
98
+ * is the app's call, through `channels.accept`.
99
+ *
100
+ * Update and ephemeral values are folded into subscription output only,
101
+ * never into the local store.
102
+ */
103
+ type Row$1 = Record<string, unknown>;
104
+ /** Hybrid logical clock: wall ms, counter, tab peer id. Orders every write. */
105
+ type Hlc = readonly [ms: number, counter: number, peer: string];
106
+ /** One tab of one user. */
107
+ interface PeerRef {
108
+ readonly user: string;
109
+ readonly peer: string;
110
+ }
111
+ /** What a message does to its row. */
112
+ type ChannelOpKind = 'update' | 'create' | 'delete';
113
+ /** The one message channels exchange: a write to one row. */
114
+ interface ChannelMessage {
115
+ readonly t: 'op';
116
+ /** Absent means `update` (a field patch). */
117
+ readonly kind?: ChannelOpKind;
118
+ readonly table: string;
119
+ readonly id: string;
120
+ /** Wire-encoded values (see `encodeValue`): the patch, the whole row for a create, `{}` for a delete. */
121
+ readonly patch: Record<string, unknown>;
122
+ readonly hlc: Hlc;
123
+ }
124
+ /** How a channel is doing, as `useChannel(...).status()` shows it. */
125
+ type ChannelStatus = 'idle' | 'connecting' | 'connected' | 'failed' | 'unsupported';
126
+ interface ChannelState {
127
+ readonly status: ChannelStatus;
128
+ /** Users with at least one tab connected. */
129
+ readonly peers: ReadonlyArray<string>;
130
+ }
131
+ /** What an `accept` rule decides on. */
132
+ interface ChannelOp {
133
+ readonly kind: ChannelOpKind;
134
+ /** The sending user, as the database proved it. */
135
+ readonly from: string;
136
+ readonly table: string;
137
+ readonly id: string;
138
+ /** The row as this client currently shows it, overlay included; undefined for a create. */
139
+ readonly row: Row$1 | undefined;
140
+ /** Decoded field values: the patch, the new row for a create, `{}` for a delete. */
141
+ readonly patch: Readonly<Row$1>;
142
+ }
143
+ type ChannelAcceptRule = (op: ChannelOp) => boolean;
144
+ interface TransportHooks {
145
+ /** This tab, or null while signed out. */
146
+ self(): PeerRef | null;
147
+ onMessage(from: PeerRef, message: unknown): void;
148
+ onPeer(peer: PeerRef, up: boolean): void;
149
+ /** Per user: an attempt is running, a tab is connected, or attempts failed. */
150
+ onStatus(user: string, status: 'connecting' | 'connected' | 'failed'): void;
151
+ }
152
+ /**
153
+ * Moves messages between tabs. WebRTC by default; an app that already has a
154
+ * room (LiveKit, its own relay) can plug that in. `send` is fire and forget.
155
+ */
156
+ interface ChannelTransport {
157
+ readonly supported: boolean;
158
+ /** Users this tab wants connections to: the union over open channels. */
159
+ want(users: ReadonlySet<string>): void;
160
+ send(to: PeerRef, message: ChannelMessage): void;
161
+ close(): void;
162
+ }
163
+ type ChannelTransportFactory = (hooks: TransportHooks) => ChannelTransport;
164
+ interface ChannelsConfig {
165
+ /**
166
+ * Per table: decide whether to apply a peer's update. Runs after the
167
+ * built-in checks (sender listed by an open channel carrying the table,
168
+ * fields exist and fit).
169
+ * Without a rule every such update is applied.
170
+ */
171
+ accept?: Record<string, ChannelAcceptRule>;
172
+ /** STUN/TURN servers for the default WebRTC transport. */
173
+ iceServers?: RTCIceServer[];
174
+ /** Replace the WebRTC transport. */
175
+ transport?: ChannelTransportFactory;
176
+ /** How long a peer's persistent value shows without the server confirming it. Default 5000. */
177
+ confirmTimeoutMs?: number;
178
+ }
179
+ /** `table:id` for a record id in any spelling, or null. */
180
+
181
+ /** What a channel carries: the rows of one `@channel` table its filter matches. */
182
+ interface ChannelScope {
183
+ readonly table: string;
184
+ readonly where: ReadonlyArray<WhereNode>;
185
+ }
186
+ /** Whether `row` passes a query's `where` (a conjunction of comparisons and `_or` groups). */
187
+ declare function matchesWhere(where: ReadonlyArray<WhereNode>, row: Row$1): boolean;
188
+ /**
189
+ * The parts of a channel query that do nothing there (a channel only reads
190
+ * the `where`). Not an error, worth a warning unless `.ignoreUnusedArgs()`.
191
+ */
192
+ declare function unusedArgs(plan: QueryPlan, isOne?: boolean): string[];
193
+ /**
194
+ * A query plan as a channel scope, or an error saying why it cannot be one:
195
+ * the table must be `@channel`, and the filter must be decidable from the
196
+ * row alone (its own fields, literal values, supported operators). Order,
197
+ * limit and projection do not matter to a channel and are ignored.
198
+ */
199
+
200
+ /** An open channel. `client.channel(...)` wraps it with scoped writes. */
201
+ interface ChannelHandle {
202
+ /** The tables its queries read. */
203
+ tables(): ReadonlyArray<string>;
204
+ state(): ChannelState;
205
+ /** Called at once with the current state, then on every change. */
206
+ subscribe(cb: (s: ChannelState) => void): () => void;
207
+ /** Replace who it connects to (your own id is skipped). */
208
+ setPeers(peers: Iterable<unknown>): void;
209
+ /** Replace what it carries (the queries' filters changed). */
210
+ setScopes(scopes: ReadonlyArray<ChannelScope>): void;
211
+ close(): void;
212
+ }
213
+ /** How peers' creates and deletes reach the store (the runtime's peer sagas). */
214
+ //#endregion
215
+ //#region src/modules/auth/impersonation.d.ts
216
+ /**
217
+ * Admin impersonation, client side.
218
+ *
219
+ * The server does the enforcing (see `impersonation_remote.surql` in the CLI):
220
+ * an admin calls `fn::_00_impersonate::start`, receives a token for the
221
+ * `_00_impersonate` access method, and authenticates with it, so `$auth.id` is
222
+ * the target user. Everything here is state and timers around that:
223
+ *
224
+ * - the admin's own token is kept under {@link ORIGIN_TOKEN_KEY} so Stop (and a
225
+ * reload in between) can return to it;
226
+ * - the impersonation state is derived from the token's claims, never stored
227
+ * separately, so it cannot disagree with the session actually in use;
228
+ * - the token is re-signed before it expires, and the session is polled so a
229
+ * stop or revocation made elsewhere reaches an open WebSocket quickly.
230
+ */
231
+ /** Access method impersonation tokens are issued for. */
232
+ declare const IMPERSONATION_ACCESS = "_00_impersonate";
233
+ /** Persistence key holding the admin's own token while impersonating. */
234
+ declare const ORIGIN_TOKEN_KEY = "sp00ky_auth_token_origin";
235
+ /** How often an active impersonation re-checks its session on the server. */
236
+ declare const SESSION_POLL_MS = 60000;
237
+ interface ImpersonationInfo {
238
+ /** `_00_impersonation:<id>` the session is bound to. */
239
+ session: string;
240
+ /** Record id being impersonated. */
241
+ target: string;
242
+ /** Record id of the admin. */
243
+ admin: string;
244
+ /** When the current token expires (it is renewed before then). */
245
+ tokenExpiresAt: Date | null;
246
+ }
247
+ interface TokenClaims {
248
+ access: string | null;
249
+ userId: string | null;
250
+ exp: number | null;
251
+ impersonation: {
252
+ session: string;
253
+ admin: string;
254
+ } | null;
255
+ }
256
+ /**
257
+ * Read the claims of a SurrealDB record-access JWT WITHOUT verifying it. The
258
+ * server still enforces the token on every request; this is only so the client
259
+ * can act on what it already holds before a round trip completes.
260
+ *
261
+ * Returns nulls on any malformed input.
262
+ */
263
+ declare function decodeTokenClaims(token: string): TokenClaims;
264
+ /** The impersonation a token represents, or null for a regular session. */
265
+ declare function impersonationFromToken(token: string | null): ImpersonationInfo | null;
266
+ /** Same impersonation, for change detection (renewals only move the expiry). */
267
+ declare function sameImpersonation(a: ImpersonationInfo | null, b: ImpersonationInfo | null): boolean;
268
+ /**
269
+ * When to renew a token expiring at `expSecs`: at 80% of its remaining life,
270
+ * never sooner than 5s from now, and immediately once it is inside that.
271
+ */
272
+ declare function renewDelayMs(expSecs: number, nowMs: number): number;
273
+ interface ImpersonationTimerHost {
274
+ /** Current impersonation, or null. */
275
+ current(): ImpersonationInfo | null;
276
+ /** Re-sign the token. Rejects when the session has ended. */
277
+ renew(): Promise<void>;
278
+ /** Whether the server still considers the session live. */
279
+ stillActive(): Promise<boolean>;
280
+ /** Leave the impersonation because the server ended it. */
281
+ endedRemotely(reason: string): Promise<void>;
282
+ /** Whether a failure was a reachability problem (retry) rather than an answer. */
283
+ isNetworkError(error: unknown): boolean;
284
+ }
285
+ /**
286
+ * The two timers an active impersonation needs. `sync()` is called whenever
287
+ * the auth state changes and arms or clears them to match.
288
+ */
289
+ declare class ImpersonationTimers {
290
+ private host;
291
+ private renewTimer;
292
+ private pollTimer;
293
+ private armedFor;
294
+ constructor(host: ImpersonationTimerHost);
295
+ sync(): void;
296
+ clear(): void;
297
+ private renew;
298
+ private poll;
299
+ }
300
+ //#endregion
301
+ //#region src/modules/auth/impersonation-banner.d.ts
302
+ /**
303
+ * Restyling of the built-in banner. Every field is optional; anything unset
304
+ * keeps the default. Colours are plain CSS values, so a project can pass its
305
+ * own tokens (`var(--brand-warning)`) as long as they resolve at the document
306
+ * level.
307
+ */
308
+ interface ImpersonationBannerTheme {
309
+ /** Height of the warning bar above the page. */
310
+ heightPx?: number;
311
+ /** Gutter left, right and below the page. `0` frames only from the top. */
312
+ insetPx?: number;
313
+ /** Radius of the framed page's corners. `0` squares them off. */
314
+ radiusPx?: number;
315
+ /** The backdrop behind the page. Any CSS `background` value. */
316
+ background?: string;
317
+ /** Colour of the warning text on the backdrop. */
318
+ text?: string;
319
+ /** Background of the Stop button. */
320
+ accent?: string;
321
+ /** Text colour of the Stop button. */
322
+ accentText?: string;
323
+ /** Label for the Stop button. Defaults to `Stop`. */
324
+ stopLabel?: string;
325
+ /** The warning sentence. Defaults to `Impersonating <target> as <admin>`.
326
+ * Wrap a run in `**` to emphasise it; the result is text, never markup. */
327
+ label?: (info: ImpersonationInfo) => string;
328
+ /** Keep the bar but leave the page's own layout completely alone. The CSS
329
+ * variable is still published, so the app can do its own offset. */
330
+ noPageShift?: boolean;
331
+ }
332
+ interface ImpersonationBannerConfig {
333
+ /**
334
+ * - `'default'` renders the built-in banner.
335
+ * - `'custom'` leaves the page alone so the app can render its own from
336
+ * `useImpersonation()` / `auth.subscribeImpersonation`. Acknowledge it
337
+ * with `client.acknowledgeImpersonationBanner()` while it is on screen;
338
+ * if nothing acknowledges within {@link CUSTOM_BANNER_GRACE_MS}, the
339
+ * built-in banner appears, on the assumption that the custom one failed
340
+ * to render rather than that nobody should be warned.
341
+ * - `'none'` renders nothing, ever. The app takes over responsibility for
342
+ * telling whoever is looking at the page that it is not their session.
343
+ */
344
+ mode?: 'default' | 'custom' | 'none';
345
+ /** Restyle the built-in banner (also used if `custom` falls back). */
346
+ theme?: ImpersonationBannerTheme;
347
+ }
348
+ //#endregion
5
349
  //#region src/events/index.d.ts
6
350
  /**
7
351
  * Utility type to define the payload structure of an event.
@@ -123,63 +467,1083 @@ declare class EventSystem<E extends EventTypeMap> {
123
467
  private broadcastEvent;
124
468
  }
125
469
  //#endregion
126
- //#region src/modules/sync/events/index.d.ts
127
- declare const SyncEventTypes: {
128
- readonly QueryUpdated: "SYNC_QUERY_UPDATED";
129
- readonly RemoteDataIngested: "SYNC_REMOTE_DATA_INGESTED";
130
- readonly MutationRolledBack: "SYNC_MUTATION_ROLLED_BACK";
131
- readonly SyncHealthChanged: "SYNC_HEALTH_CHANGED";
470
+ //#region src/utils/surql.d.ts
471
+ interface SealedQuery<T = void> {
472
+ readonly sql: string;
473
+ readonly extract: (results: unknown[]) => T;
474
+ }
475
+ //#endregion
476
+ //#region src/services/database/events/index.d.ts
477
+ declare const DatabaseEventTypes: {
478
+ readonly LocalQuery: "DATABASE_LOCAL_QUERY";
479
+ readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
132
480
  };
133
- type SyncEventTypeMap = {
134
- [SyncEventTypes.QueryUpdated]: EventDefinition<typeof SyncEventTypes.QueryUpdated, {
135
- queryId: any;
136
- localHash?: string;
137
- localArray?: RecordVersionArray;
138
- remoteHash?: string;
139
- remoteArray?: RecordVersionArray;
140
- records: Record<string, any>[];
141
- }>;
142
- [SyncEventTypes.RemoteDataIngested]: EventDefinition<typeof SyncEventTypes.RemoteDataIngested, {
143
- records: Record<string, any>[];
144
- }>;
145
- [SyncEventTypes.MutationRolledBack]: EventDefinition<typeof SyncEventTypes.MutationRolledBack, {
146
- eventType: string;
147
- recordId: string;
148
- error: string;
149
- }>;
150
- [SyncEventTypes.SyncHealthChanged]: EventDefinition<typeof SyncEventTypes.SyncHealthChanged, SyncHealth>;
481
+ interface DatabaseQueryEventPayload {
482
+ query: string;
483
+ vars?: Record<string, unknown>;
484
+ duration: number;
485
+ success: boolean;
486
+ error?: string;
487
+ timestamp: number;
488
+ }
489
+ type DatabaseEventTypeMap = {
490
+ [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
491
+ [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
151
492
  };
152
- type SyncEventSystem = EventSystem<SyncEventTypeMap>;
493
+ type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
153
494
  //#endregion
154
- //#region src/services/logger/index.d.ts
155
- type Logger$1 = Logger;
495
+ //#region src/modules/devtools/storage-info.d.ts
496
+ /** Engine-side numbers only the engine can produce (worker round-trips). */
497
+ interface EngineStorageDiagnostics {
498
+ engine: 'sqlite';
499
+ bucketId: string;
500
+ useOpfs: boolean;
501
+ workerSelectConfigured: boolean;
502
+ /** `false` while configured `true` means the runtime downgraded to the
503
+ * legacy multi-hop select (stale cached worker bundle). */
504
+ workerSelectEffective: boolean;
505
+ /** page_count * page_size. */
506
+ dbSizeBytes?: number;
507
+ /** freelist_count * page_size — reclaimable via VACUUM. */
508
+ freelistBytes?: number;
509
+ tableCounts?: {
510
+ table: string;
511
+ rows: number;
512
+ }[];
513
+ error?: string;
514
+ }
515
+ /**
516
+ * Shared-tabs coordination state. Reported ONLY when `sharedTabs: true` was
517
+ * configured (apps that never asked for it get `null`, so the panel shows
518
+ * nothing). `active: false` with a `reason` is itself the useful signal: the
519
+ * app asked to share one store and this tab is not, so it owns or contends for
520
+ * the OPFS pool alone.
521
+ */
156
522
  //#endregion
157
- //#region src/modules/sync/queue/queue-up.d.ts
158
- type CreateEvent = {
159
- type: 'create';
160
- mutation_id: RecordId;
161
- record_id: RecordId;
162
- data: Record<string, unknown>;
163
- record?: Record<string, unknown>;
164
- tableName?: string;
165
- options?: PushEventOptions;
523
+ //#region src/services/database/cache-engine.d.ts
524
+ /**
525
+ * A materialized row. Keys are field names; values are already decoded to the
526
+ * client's runtime shapes (RecordId stays a RecordId, bytes a Uint8Array, …) so
527
+ * every backend hands `DataModule` the same shape SurrealDB does today.
528
+ */
529
+ type Row = Record<string, unknown>;
530
+ /** A record identifier — a `RecordId` or its stable string form (`table:id`). */
531
+ type Id = unknown;
532
+ /** How an order clause is expressed everywhere in the engine layer. */
533
+ type OrderBy = [field: string, direction: 'asc' | 'desc'][];
534
+ /**
535
+ * Batched relation fetch: "give me every row of `table` whose `matchField` is
536
+ * one of `keys`, filtered by `where`, ordered by `orderBy`". This is the single
537
+ * primitive relation decomposition (§3) leans on — implemented as
538
+ * `SELECT … WHERE <matchField> IN (…)` on SQLite, `SELECT … FROM $keys` /
539
+ * `WHERE <matchField> IN $keys` on SurrealDB, or an index scan elsewhere. Order
540
+ * here is a hint; the resolver re-applies order+limit PER PARENT after grouping.
541
+ */
542
+ interface RelationFetch {
543
+ table: string;
544
+ matchField: string;
545
+ keys: Id[];
546
+ where?: WhereNode$1[];
547
+ orderBy?: OrderBy;
548
+ select?: string[];
549
+ }
550
+ /**
551
+ * The read side of an engine, minus relation resolution — the surface a
552
+ * {@link RelationResolver} needs. Kept separate so the resolver can be unit
553
+ * tested against an in-memory fake without a full engine.
554
+ */
555
+ interface RowFetcher {
556
+ /** Batched fan-out fetch. See {@link RelationFetch}. */
557
+ fetchRelation(req: RelationFetch): Promise<Row[]>;
558
+ }
559
+ /** A transaction handle — the same verbs as the engine, but atomic. */
560
+ interface EngineTx {
561
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
562
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
563
+ delete(table: string, id: Id): Promise<void>;
564
+ }
565
+ /**
566
+ * A pluggable local cache backend. SurrealDB (the default) and SQLite both
567
+ * implement this; the rest of the client talks verbs, never SurrealQL.
568
+ *
569
+ * Reactivity is NOT part of this contract: the local cache is passive. The SSP
570
+ * (remote) drives change; `DataModule` writes rows here and re-reads them. The
571
+ * `epoch` field preserves the existing bucket-switch fencing (see
572
+ * `LocalDatabaseService.epoch`): an async chain captures it at start and its
573
+ * write is dropped if the epoch moved (a bucket switch) in between.
574
+ */
575
+ interface LocalCacheEngine extends RowFetcher {
576
+ /** Monotonic store generation; bumped on every bucket switch. */
577
+ readonly epoch: number;
578
+ connect(bucketId: string): Promise<void>;
579
+ switchBucket(bucketId: string): Promise<void>;
580
+ close(): Promise<void>;
581
+ /** Run `fn` inside a single atomic transaction. */
582
+ transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
583
+ /**
584
+ * Materialize a query, including its `.related()` tree (via §3
585
+ * decomposition). Params bind `where` `paramRef`s and any windowing id-set.
586
+ */
587
+ select(plan: QueryPlan$1, params?: Record<string, unknown>): Promise<Row[]>;
588
+ /** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
589
+ selectByIds(table: string, ids: Id[], opts?: {
590
+ select?: string[];
591
+ orderBy?: OrderBy;
592
+ }): Promise<Row[]>;
593
+ /** Single-record read by primary id, or `null`. */
594
+ getById(table: string, id: Id): Promise<Row | null>;
595
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
596
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
597
+ delete(table: string, id: Id): Promise<void>;
598
+ }
599
+ /**
600
+ * The full surface the client's `this.local` field depends on: the
601
+ * engine-neutral {@link LocalCacheEngine} verbs PLUS the legacy
602
+ * SurrealQL/lifecycle methods the not-yet-migrated call sites still use.
603
+ * `SurrealCacheEngine` (subclass of `LocalDatabaseService`) and
604
+ * `SqliteCacheEngine` (via a SurrealQL-vocabulary shim) both satisfy this, so
605
+ * either can back `this.local`.
606
+ *
607
+ * `getClient()` returns the underlying SurrealDB `Surreal` handle where one
608
+ * exists (SurrealDB backend); backends without one (SQLite) throw — it is only
609
+ * used by advanced/DevTools paths, never on the hot path.
610
+ */
611
+ interface LocalStore extends LocalCacheEngine {
612
+ /**
613
+ * Whether this engine needs SurrealQL schema provisioning (`DEFINE TABLE`,
614
+ * `DEFINE FIELD`, …) run against it at init / bucket switch. SurrealDB → true;
615
+ * schemaless engines (SQLite creates tables lazily) → false, so the client
616
+ * skips the `LocalMigrator` entirely for them.
617
+ */
618
+ readonly usesSurqlSchema: boolean;
619
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>, opts?: {
620
+ epoch?: number;
621
+ }): Promise<T>;
622
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>, opts?: {
623
+ epoch?: number;
624
+ }): Promise<T>;
625
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
626
+ switchStore(bucketId: string): Promise<void>;
627
+ beginSwitch(): () => void;
628
+ getEvents(): DatabaseEventSystem;
629
+ getClient(): unknown;
630
+ getConfig(): Sp00kyConfig<any>['database'];
631
+ readonly currentBucketId: string;
632
+ /** Which built-in backend this is. OPTIONAL: absent (custom engines) is
633
+ * reported as `'custom'` by DevTools. More robust than `instanceof` for
634
+ * engines constructed outside this package. */
635
+ readonly engineKind?: 'surrealdb' | 'sqlite';
636
+ /** Engine-specific storage numbers for DevTools (DB file size, per-table
637
+ * row counts). OPTIONAL: only engines with something to report implement it. */
638
+ getStorageDiagnostics?(opts?: {
639
+ tableCounts?: boolean;
640
+ }): Promise<EngineStorageDiagnostics>;
641
+ /**
642
+ * Durability of this engine's local store. OPTIONAL: engines that don't
643
+ * report it (SurrealDB, custom engines) are treated as `'unknown'` by the
644
+ * client facade, so adding this needs no change on their side.
645
+ */
646
+ readonly storageHealth?: StorageHealth;
647
+ /**
648
+ * Delete a bucket's persisted store. Never the open one. OPTIONAL and
649
+ * best-effort: used to remove an impersonated user's data from the admin's
650
+ * device once the impersonation ends.
651
+ */
652
+ dropBucket?(bucketId: string): Promise<void>;
653
+ /** Fires immediately with the current snapshot, then on every change.
654
+ * Returns an unsubscribe function. */
655
+ subscribeToStorageHealth?(cb: (health: StorageHealth) => void): () => void;
656
+ /**
657
+ * Every cached row's `(id, _00_rv)` per table, ids in stable `table:id`
658
+ * form. The in-browser circuit primes and reconciles itself from this on
659
+ * boot instead of re-downloading the working set. OPTIONAL: an engine
660
+ * without it boots the circuit empty, as before.
661
+ */
662
+ scanVersions?(tables: string[]): Promise<Record<string, [string, number][]>>;
663
+ /**
664
+ * Reset the cached `_00_rv` of every table whose column set (`fingerprints`,
665
+ * see `columnFingerprints`) changed since the store last recorded it, except
666
+ * the rows in `keep`, and record the new sets. Returns the tables reset.
667
+ * For engines that keep bodies across schema changes: a body landed under an
668
+ * older schema lacks the columns it did not know, at the server's version,
669
+ * and would never be fetched again. OPTIONAL: an engine that rebuilds its
670
+ * store on a schema change (SurrealDB) does not need it.
671
+ */
672
+ resetChangedTables?(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]>;
673
+ /**
674
+ * Circuit snapshot storage, keyed. Lives in the same durable store as the
675
+ * rows (OPFS SQLite), so it is per-bucket by construction, atomic, and
676
+ * readable by follower tabs over the port transport. OPTIONAL: an engine
677
+ * without it primes from `scanVersions` alone.
678
+ */
679
+ getSnapshot?(key: string): Promise<StoredSnapshot | null>;
680
+ putSnapshot?(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void>;
681
+ deleteSnapshot?(key: string): Promise<void>;
682
+ }
683
+ /** Describes a stored circuit snapshot; what decides whether it is usable. */
684
+ interface SnapshotMeta {
685
+ /** Bump when the wire shape the circuit reads changes. */
686
+ formatVersion: number;
687
+ /** Hash of the schema the rows were projected under. */
688
+ schemaHash: string;
689
+ savedAt: number;
690
+ /** Highest `_00_rv` per table at save time (diagnostics). */
691
+ maxRv?: Record<string, number>;
692
+ [key: string]: unknown;
693
+ }
694
+ interface StoredSnapshot {
695
+ bytes: Uint8Array;
696
+ meta: SnapshotMeta;
697
+ }
698
+ /** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
699
+ type LocalEngineChoice = 'surrealdb' | 'sqlite' | LocalStore;
700
+ /** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
701
+ * a guard against a cyclic schema producing unbounded fan-out. */
702
+ //#endregion
703
+ //#region src/services/database/database.d.ts
704
+ declare abstract class AbstractDatabaseService {
705
+ protected client: Surreal;
706
+ protected logger: Logger$1;
707
+ protected events: DatabaseEventSystem;
708
+ /**
709
+ * Per-query deadline in ms; `0` disables. The remote service sets it from
710
+ * `queryTimeoutMs` (see `RemoteDatabaseService`), the local one from
711
+ * `localOpTimeoutMs` (see `LocalDatabaseService`): a local query can be
712
+ * legitimately slow, but it must never be endless - every query waits on the
713
+ * previous link of {@link query}'s chain, and one that never settled wedged
714
+ * every later local op behind it.
715
+ */
716
+ protected queryTimeoutMs: number;
717
+ /** The error a deadline expiry rejects with; the local service substitutes
718
+ * its typed `LocalOpTimeoutError`. "timed out" in the message is
719
+ * load-bearing either way: `classifySyncError` keys off it. */
720
+ protected timeoutError(_query: string): Error;
721
+ protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
722
+ constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
723
+ abstract connect(): Promise<void>;
724
+ getClient(): Surreal;
725
+ getEvents(): DatabaseEventSystem;
726
+ tx(): Promise<SurrealTransaction>;
727
+ /**
728
+ * How many statements may be in flight at once.
729
+ *
730
+ * `1` serializes every statement behind the previous one. The local engines
731
+ * need that: overlapping ops trip the WASM / SQLite transaction layer. The
732
+ * remote service raises it (`RemoteDatabaseService`): a SurrealDB socket
733
+ * multiplexes requests by id, and serializing them capped the client at one
734
+ * statement per round trip (~5/s at 170ms RTT), so the `_00_list_ref` poll
735
+ * alone could hold every registration behind it and one slow one-shot read
736
+ * stalled the whole client. The scheduler's `MAX_CONCURRENT_DOWN` only means
737
+ * something when this is above 1.
738
+ */
739
+ protected maxConcurrentQueries: number;
740
+ private inFlightQueries;
741
+ private queryWaiters;
742
+ /** FIFO slot acquisition, so `maxConcurrentQueries = 1` keeps strict order. */
743
+ private acquireQuerySlot;
744
+ private releaseQuerySlot;
745
+ /**
746
+ * Resolve once every statement issued before this call has settled: take
747
+ * every slot (FIFO, so earlier statements go first), then hand them back.
748
+ * Bounded by {@link queryTimeoutMs}, like the statements it waits on.
749
+ */
750
+ protected drainStatements(): Promise<void>;
751
+ /**
752
+ * Hook run right before a statement is sent, inside its slot. The remote
753
+ * service uses it to hold statements while a connect is in flight, so a
754
+ * query never runs on a socket that is open but has not had its namespace
755
+ * and token applied yet. The default does nothing.
756
+ */
757
+ protected beforeQuery(): Promise<void>;
758
+ /**
759
+ * Execute a statement under {@link maxConcurrentQueries}.
760
+ *
761
+ * A statement that never settles would hold its slot forever, and with a
762
+ * limit of 1 that blocks every later statement behind it. {@link
763
+ * queryTimeoutMs} bounds each one: on expiry this promise rejects and the
764
+ * slot is released, even though the underlying RPC is still parked in the
765
+ * SDK's pending map.
766
+ */
767
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
768
+ /**
769
+ * Like {@link query} but never rejects on a statement error: every
770
+ * statement answers on its own as `{ status: 'OK', result }` or
771
+ * `{ status: 'ERR', error }`. This is what lets a batched outbox push judge
772
+ * each mutation separately.
773
+ */
774
+ queryResponses(query: string, vars?: Record<string, unknown>): Promise<Array<{
775
+ status: 'OK';
776
+ result: unknown;
777
+ } | {
778
+ status: 'ERR';
779
+ error: string;
780
+ }>>;
781
+ private runStatement;
782
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
783
+ close(): Promise<void>;
784
+ }
785
+ //#endregion
786
+ //#region src/services/database/remote.d.ts
787
+ /** Transport events the SDK publishes, mapped 1:1 to {@link ConnectionState}. */
788
+ type RemoteConnectionEvent = ConnectionState | 'error';
789
+ declare class RemoteDatabaseService extends AbstractDatabaseService {
790
+ private config;
791
+ protected eventType: "DATABASE_REMOTE_QUERY";
792
+ private readonly reconnectConfig;
793
+ /**
794
+ * In-flight `connect()`, so concurrent callers (boot + supervisor revive +
795
+ * an `online` event landing at the same moment) share one attempt instead of
796
+ * racing two sockets. Cleared on settle, so a later call always reconnects.
797
+ */
798
+ private connecting;
799
+ /**
800
+ * The token to re-authenticate a freshly opened socket with, kept current by
801
+ * {@link setAuthToken}.
802
+ *
803
+ * `config.token` is fixed at construction and most apps never set it: they
804
+ * sign in later, which authenticates the socket that happens to be open at
805
+ * the time. That is enough for the SDK's OWN reconnects (it replays
806
+ * `version`/`use`/`authenticate` itself), but not for the supervisor's revive
807
+ * loop, which builds a socket from scratch. Without this the revived socket
808
+ * came back UNAUTHENTICATED and stayed that way for the life of the page,
809
+ * while the client's `currentUserId` — restored from local storage — kept
810
+ * reporting the user as signed in.
811
+ *
812
+ * The visible damage is silent and total: `fn::query::register` sends
813
+ * `<string>($auth.id OR '')`, so every view registered afterwards is stamped
814
+ * with an empty identity, and every `$auth.id` predicate in it resolves
815
+ * false. Public tables keep returning rows while everything owned by the user
816
+ * returns nothing, on a page that still looks signed in.
817
+ */
818
+ private authToken;
819
+ /**
820
+ * Every `session::id()` this page's sockets have had, oldest first.
821
+ *
822
+ * The server stamps a view's `subscribers` entry with the session that
823
+ * registered or heartbeated it, and every socket (an SDK reconnect, a
824
+ * supervisor revive) is a new session. The pagehide release goes over HTTP,
825
+ * whose own session id matches none of them, so it names these instead. Kept
826
+ * for the page, not the socket: a view registered before a reconnect still
827
+ * carries the old id until its next heartbeat.
828
+ *
829
+ * The anonymous LIVE filters on the same ids (see `listRefLive`): its edges
830
+ * name the socket that registered their view, which may be an earlier one.
831
+ * A reload hands its ids to the next page with the salt.
832
+ */
833
+ private sessionIdsSeen;
834
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
835
+ /** See {@link sessionIdsSeen}. */
836
+ sessionIds(): readonly string[];
837
+ /**
838
+ * Take on the session ids of the page this one reloaded from. It kept that
839
+ * page's salt, so the views it re-registers still carry edges stamped by
840
+ * those sockets. Older than anything this page has seen, so they go first.
841
+ */
842
+ adoptSessionIds(ids: ReadonlyArray<string>): void;
843
+ /**
844
+ * Ask the socket that just connected for its session id. Straight to the
845
+ * SDK: it needs no namespace or identity, so it need not wait behind an
846
+ * in-flight connect or take a slot from the query queue.
847
+ */
848
+ private recordSessionId;
849
+ getConfig(): Sp00kyConfig<any>['database'];
850
+ /**
851
+ * Send one SurrealQL statement so that it survives the page going away.
852
+ *
853
+ * A WebSocket `send()` during `pagehide` is not guaranteed to flush — the
854
+ * browser may tear the socket down first, and the frame is simply lost.
855
+ * Measured: an unload-time release over the live socket reached the server
856
+ * zero times out of one. `fetch` with `keepalive` is the primitive the
857
+ * platform actually guarantees here, so this goes over SurrealDB's HTTP
858
+ * `/sql` endpoint instead of the RPC socket.
859
+ *
860
+ * Best-effort by design: no await, no retry, errors swallowed. Every caller
861
+ * must have a server-side fallback that makes a lost beacon a non-event.
862
+ *
863
+ * The statement runs in a fresh HTTP session: `session::id()` there is a new
864
+ * id, not this page's socket's, so anything keyed on it must be passed the
865
+ * ids from {@link sessionIds} instead.
866
+ */
867
+ beaconSql(sql: string): void;
868
+ /**
869
+ * Record the token every future connect should authenticate with, or `null`
870
+ * on sign-out. See {@link authToken}.
871
+ *
872
+ * Does not touch the CURRENT socket: callers authenticate that themselves
873
+ * (sign-in and session restore both already do). This only makes the next
874
+ * from-scratch connect reproduce that state.
875
+ */
876
+ setAuthToken(token: string | null): void;
877
+ /** The token the session is signed in with (or the configured one), for
878
+ * calls that leave the socket: `r2` bucket files go to the SSP over HTTP. */
879
+ getAuthToken(): string | null;
880
+ /** Resolved reconnect tunables; the supervisor reads its own knobs here. */
881
+ getReconnectConfig(): Required<ReconnectConfig>;
882
+ /** Current transport state as reported by the SDK. */
883
+ getStatus(): ConnectionState;
884
+ /**
885
+ * Observe transport events. Thin passthrough so callers (the supervisor,
886
+ * sync, CRDT) don't have to reach through `getClient()`.
887
+ */
888
+ subscribeConnection<K extends RemoteConnectionEvent>(event: K, cb: (...payload: SurrealEvents[K]) => void): () => void;
889
+ /**
890
+ * Tear the socket down on purpose. Used by the heartbeat watchdog when a
891
+ * socket stops answering but never closes: `close()` makes the SDK publish
892
+ * `disconnected`, which is what drives the supervisor's revive loop.
893
+ */
894
+ forceClose(): Promise<void>;
895
+ /** Resolve once no connect is in flight, for calls that go to the SDK
896
+ * client directly (sign-in, sign-up) and so skip `beforeQuery`. */
897
+ whenConnected(): Promise<void>;
898
+ /**
899
+ * Hold statements while a connect is in flight.
900
+ *
901
+ * `connect()` opens the socket, then selects the namespace/database, then
902
+ * authenticates - three round trips. The SDK considers the connection ready
903
+ * after the first, so a query queued during the other two ran on a socket
904
+ * with no namespace ("Specify a namespace to use") or, worse, no identity.
905
+ * Seen 2026-09-06 after the supervisor rebuilt a socket: a collection
906
+ * recount failed with exactly that error. Waiting on the in-flight connect
907
+ * costs nothing when no connect is running; a failed connect is not
908
+ * swallowed here - the query then fails on its own, as before.
909
+ */
910
+ protected beforeQuery(): Promise<void>;
911
+ /**
912
+ * Open (or re-open) the remote connection.
913
+ *
914
+ * Safe to call repeatedly: concurrent calls share the in-flight attempt, and
915
+ * a call after a `disconnected` builds a fresh socket. `use()` and
916
+ * `authenticate()` are re-applied here for the cold path; the SDK also
917
+ * replays them itself on its own internal reconnects.
918
+ */
919
+ connect(): Promise<void>;
920
+ private doConnect;
921
+ signin(params: any): Promise<any>;
922
+ signup(params: any): Promise<any>;
923
+ authenticate(token: string): Promise<any>;
924
+ invalidate(): Promise<void>;
925
+ }
926
+ //#endregion
927
+ //#region src/modules/auth/events/index.d.ts
928
+ declare const AuthEventTypes: {
929
+ readonly AuthStateChanged: "AUTH_STATE_CHANGED";
930
+ readonly ImpersonationChanged: "IMPERSONATION_CHANGED";
166
931
  };
167
- type UpdateEvent = {
168
- type: 'update';
169
- mutation_id: RecordId;
170
- record_id: RecordId;
171
- data: Record<string, unknown>;
172
- record?: Record<string, unknown>;
173
- beforeRecord?: Record<string, unknown>;
174
- options?: PushEventOptions;
932
+ type AuthEventTypeMap = {
933
+ [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
934
+ [AuthEventTypes.ImpersonationChanged]: EventDefinition<typeof AuthEventTypes.ImpersonationChanged, ImpersonationInfo | null>;
175
935
  };
176
- type DeleteEvent = {
177
- type: 'delete';
178
- mutation_id: RecordId;
179
- record_id: RecordId;
180
- options?: PushEventOptions;
936
+ type AuthEventSystem = EventSystem<AuthEventTypeMap>;
937
+ declare function createAuthEventSystem(): AuthEventSystem;
938
+ //#endregion
939
+ //#region src/modules/auth/index.d.ts
940
+ /** What `fn::_00_impersonate::list_users` returns per row. */
941
+ interface ImpersonationCandidate {
942
+ id: string;
943
+ is_admin: boolean;
944
+ [field: string]: unknown;
945
+ }
946
+ /** An open session, as `fn::_00_impersonate::active` lists it. */
947
+ interface ActiveImpersonation {
948
+ session: string;
949
+ target: string;
950
+ admin: string;
951
+ reason: string;
952
+ started_at: unknown;
953
+ expires_at: unknown;
954
+ }
955
+ /** What a sign-out hook sees: the session that is about to end. */
956
+ interface SignOutContext {
957
+ /** `table:id` of the signed-in record, or null. */
958
+ userId: string | null;
959
+ token: string | null;
960
+ /** The session is an admin impersonation (its token is the target's). */
961
+ impersonating: boolean;
962
+ }
963
+ type SignOutHook = (ctx: SignOutContext) => Promise<void> | void;
964
+ /** Upper bound on the before-sign-out hooks, so a dead socket never holds a sign-out. */
965
+ declare const SIGN_OUT_HOOK_TIMEOUT_MS = 2000;
966
+ /**
967
+ * Floor between two session re-checks started by refused statements. A
968
+ * refused session fails every statement at once, and a check that keeps the
969
+ * session (the server was unreachable) must not be re-run by each of them.
970
+ */
971
+ declare const REFUSAL_RECHECK_MIN_MS = 30000;
972
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
973
+ type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
974
+ 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;
975
+ declare class AuthService<S extends SchemaStructure> {
976
+ private schema;
977
+ private remote;
978
+ private persistenceClient;
979
+ private logger;
980
+ token: string | null;
981
+ currentUser: any | null;
982
+ isAuthenticated: boolean;
983
+ /**
984
+ * The record-access method name for the current session (e.g. `"account"`),
985
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
986
+ * permission injection so `$access`-gated table predicates resolve locally,
987
+ * mirroring the server's `$access`. Null when logged out.
988
+ */
989
+ access: string | null;
990
+ isLoading: boolean;
991
+ private events;
992
+ private signOutHooks;
993
+ /** The impersonation last announced, for change detection. */
994
+ private announcedImpersonation;
995
+ /** Target of an impersonation that just ended, until the client purges its
996
+ * local bucket (see `consumeEndedImpersonation`). */
997
+ private endedImpersonationTarget;
998
+ /** The way back to the admin in flight. The Stop button, the session poll,
999
+ * a refused renewal and a rejected check can all end an impersonation, and
1000
+ * they share this one: a second stop running beside the first found the
1001
+ * admin token already taken and signed the admin out. */
1002
+ private stopping;
1003
+ /** A token renewal in flight, which a stop waits out (see `renewImpersonation`). */
1004
+ private renewing;
1005
+ /** The session re-check in flight (see `watchSession`), shared by every trigger. */
1006
+ private reverifying;
1007
+ /** When a refused statement last started a re-check. */
1008
+ private lastRefusalCheckAt;
1009
+ private watchingSession;
1010
+ private impersonationTimers;
1011
+ get eventSystem(): AuthEventSystem;
1012
+ constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
1013
+ init(): Promise<void>;
1014
+ /**
1015
+ * Check the session again whenever the socket comes back, and whenever the
1016
+ * server refuses a statement because of the session.
1017
+ *
1018
+ * The server judges a token only when a socket authenticates: the SDK
1019
+ * replays `authenticate` on its own reconnects, `RemoteDatabaseService` on a
1020
+ * socket it rebuilds. When the replay is refused (the app ended the session,
1021
+ * say with a password reset) the SDK drops to an anonymous session, and the
1022
+ * supervisor swallows the rebuild's error, so the socket reports `connected`
1023
+ * while this service still announces the user. Every view registered from
1024
+ * then on carried no identity: the page looked signed in and showed nothing
1025
+ * of the user's. `check()` applies the token again and signs out when the
1026
+ * server refuses it.
1027
+ *
1028
+ * A socket that never reconnects is ended by the app's session guard
1029
+ * (`fn::sp00ky::session_live`) instead: its heartbeats stop finding rows,
1030
+ * and the re-registration that follows is refused with "There was a problem
1031
+ * with authentication", which starts a check here too.
1032
+ */
1033
+ private watchSession;
1034
+ /** One `check()` for every trigger that lands while it runs. */
1035
+ private reverify;
1036
+ getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
1037
+ /**
1038
+ * Subscribe to auth state changes.
1039
+ * callback is called immediately with current value and whenever validation status changes.
1040
+ * `immediate: false` skips that first call: only changes are reported.
1041
+ */
1042
+ subscribe(cb: (userId: string | null) => void, opts?: {
1043
+ immediate?: boolean;
1044
+ }): () => void;
1045
+ /**
1046
+ * Run `hook` at the start of every sign-out, while the token and the socket
1047
+ * still belong to the leaving user (Web Push removes this device's
1048
+ * subscription here). Hooks are best-effort: they run in parallel, errors
1049
+ * are swallowed, and the sign-out goes on after
1050
+ * {@link SIGN_OUT_HOOK_TIMEOUT_MS} whatever they are doing. Returns a disposer.
1051
+ */
1052
+ onBeforeSignOut(hook: SignOutHook): () => void;
1053
+ private runSignOutHooks;
1054
+ /**
1055
+ * The signed-in user as subscribers see it: the raw `table:id` string, the
1056
+ * way the token's `ID` claim spells it. `currentUser.id` is that string while
1057
+ * the session is restored from the token and the server's `RecordId` once
1058
+ * `check()` has answered, and the two must announce as the same user: every
1059
+ * subscriber that compares ids (feature flags, app release) took the switch
1060
+ * for a new principal and reset, so flag-gated UI blinked off and back on a
1061
+ * few seconds into every reload. A `RecordId`'s own `toString()` will not do
1062
+ * either, as it escapes ids like `user:⟨5abc⟩` that the claim spells raw.
1063
+ */
1064
+ private announcedUserId;
1065
+ private notifyListeners;
1066
+ /**
1067
+ * The impersonation the current session is, or null. Derived from the
1068
+ * token in use, so it always describes the identity the server sees.
1069
+ */
1070
+ get impersonation(): ImpersonationInfo | null;
1071
+ /** Subscribe to impersonation changes; called immediately with the current value. */
1072
+ subscribeImpersonation(cb: (info: ImpersonationInfo | null) => void): () => void;
1073
+ /**
1074
+ * Act as `targetId` (a record id such as `user:abc`). Admins only, and only
1075
+ * when the project enabled `impersonation` in sp00ky.yml: the server refuses
1076
+ * everything else. `reason` is recorded in the audit log.
1077
+ *
1078
+ * The admin's session is kept aside and restored by
1079
+ * {@link stopImpersonating}. Local data switches to the target's bucket
1080
+ * exactly as on a sign-in, and that bucket is removed on stop.
1081
+ */
1082
+ impersonate(targetId: string, reason: string): Promise<ImpersonationInfo>;
1083
+ /**
1084
+ * Return to the admin session. Always leaves the impersonated identity,
1085
+ * even when the server cannot be reached: the admin token is restored
1086
+ * locally first and verified afterwards, and a rejected admin token ends in
1087
+ * a full sign-out rather than staying on the target.
1088
+ */
1089
+ stopImpersonating(opts?: {
1090
+ serverEnded?: boolean;
1091
+ }): Promise<void>;
1092
+ private leaveImpersonation;
1093
+ /** Re-sign the impersonation token before it expires. */
1094
+ renewImpersonation(): Promise<void>;
1095
+ private applyRenewal;
1096
+ /** Users an admin may pick from. Admin-only on the server. */
1097
+ searchImpersonationTargets(search: string): Promise<ImpersonationCandidate[]>;
1098
+ /** Open impersonation sessions. Admin-only on the server. */
1099
+ listActiveImpersonations(): Promise<ActiveImpersonation[]>;
1100
+ /**
1101
+ * The target of an impersonation that ended, once. The bucket switch calls
1102
+ * this after leaving a bucket so it can delete that user's local data.
1103
+ */
1104
+ consumeEndedImpersonation(): string | null;
1105
+ /**
1106
+ * Restore a session from the locally cached JWT, with NO network.
1107
+ *
1108
+ * This is what makes a warm boot paint instantly and what makes an offline
1109
+ * boot possible at all: the token is in local storage, and it already carries
1110
+ * both the access method and the `$auth.id` record id. Everything the client
1111
+ * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
1112
+ * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
1113
+ * available before a socket exists.
1114
+ *
1115
+ * The session is OPTIMISTIC: the token is unverified here. `check()` runs
1116
+ * afterwards in the background and downgrades to a real sign-out if the
1117
+ * server rejects it. Nothing is trusted that the server has not also seen -
1118
+ * the local store only ever holds rows the server previously sent.
1119
+ *
1120
+ * Returns the restored user id, or null when there is no usable token.
1121
+ */
1122
+ restoreSessionFromToken(): Promise<string | null>;
1123
+ /**
1124
+ * Check for existing session and validate
1125
+ */
1126
+ check(accessToken?: string): Promise<void>;
1127
+ /** Hold a session the server accepted without its user row: the id comes
1128
+ * from the token, as on a warm boot. A token naming no user is refused. */
1129
+ private keepAcceptedSession;
1130
+ /**
1131
+ * The server refused `token`. A refused impersonation token (stopped,
1132
+ * expired, or revoked) returns to the admin session instead of signing the
1133
+ * admin out; anything else signs out.
1134
+ */
1135
+ private rejectToken;
1136
+ /**
1137
+ * Sign out and clear session. While impersonating this ends the
1138
+ * impersonation and signs the admin out too.
1139
+ */
1140
+ signOut(): Promise<void>;
1141
+ private setSession;
1142
+ /** Fallback when the token carries no `AC` claim: if the schema defines
1143
+ * exactly one record-access method, assume the session used it. */
1144
+ private defaultAccessName;
1145
+ signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
1146
+ signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
1147
+ }
1148
+ //#endregion
1149
+ //#region src/push/types.d.ts
1150
+ /**
1151
+ * Web Push wire types shared by the page (`db.webPush`), the service worker
1152
+ * bridge (`@spooky-sync/core/sw`) and the live feed. Pure: types plus a few
1153
+ * dependency-free helpers, safe in any context.
1154
+ *
1155
+ * `PushPayload` mirrors `packages/push-core/src/config.rs` (`PushPayload`,
1156
+ * `PayloadKind`, `Op`, `NotificationTemplate`). Keep the two in step.
1157
+ */
1158
+ /** Payload format version this build understands. */
1159
+ declare const PUSH_PAYLOAD_VERSION = 1;
1160
+ type PushPayloadKind = 'rule' | 'message';
1161
+ type PushOp = 'create' | 'update' | 'delete';
1162
+ type PushUrgency = 'very-low' | 'low' | 'normal' | 'high';
1163
+ /** One button on a notification (`NotificationAction` plus a per-action `url`). */
1164
+ interface PushNotificationAction {
1165
+ action: string;
1166
+ title: string;
1167
+ icon?: string;
1168
+ /** Opened instead of the notification's `url` when this action is clicked. */
1169
+ url?: string;
1170
+ [key: string]: unknown;
1171
+ }
1172
+ /**
1173
+ * What a content push shows. Every key other than `title` and `url` is passed
1174
+ * to `showNotification` as is, unknown ones included (`vibrate`, `timestamp`,
1175
+ * whatever a browser adds later).
1176
+ */
1177
+ interface PushNotification {
1178
+ title?: string;
1179
+ body?: string;
1180
+ icon?: string;
1181
+ badge?: string;
1182
+ image?: string;
1183
+ lang?: string;
1184
+ dir?: string;
1185
+ /** Defaults to the push's `topic`. */
1186
+ tag?: string;
1187
+ /** Opened (or focused) on click. */
1188
+ url?: string;
1189
+ requireInteraction?: boolean;
1190
+ renotify?: boolean;
1191
+ silent?: boolean;
1192
+ actions?: PushNotificationAction[];
1193
+ /** Merged into the notification's `data` next to the bridge's own keys. */
1194
+ data?: Record<string, unknown>;
1195
+ [key: string]: unknown;
1196
+ }
1197
+ /**
1198
+ * The JSON every push carries (then RFC 8291 encrypted). `notification`
1199
+ * present: a content push the service worker shows as is. Absent: a
1200
+ * content-free nudge, the app renders from its own data.
1201
+ */
1202
+ interface PushPayload {
1203
+ v: number;
1204
+ kind: PushPayloadKind;
1205
+ /** Rule name (`kind: 'rule'`). */
1206
+ rule?: string;
1207
+ /** `_00_push_message` id (`kind: 'message'`). */
1208
+ message?: string;
1209
+ /** The row that fired the rule. */
1210
+ table?: string;
1211
+ id?: string;
1212
+ op?: PushOp;
1213
+ topic?: string;
1214
+ notification?: PushNotification;
1215
+ data?: Record<string, unknown>;
1216
+ /** Epoch ms when the engine built it. */
1217
+ ts: number;
1218
+ }
1219
+ /** Page -> service worker: the session to use for live rendering. */
1220
+ interface BridgeTokenMessage {
1221
+ type: 'sp00ky:token';
1222
+ token: string;
1223
+ userId: string;
1224
+ /** The SurrealDB endpoint (`wss://host/rpc`), not the push endpoint. */
1225
+ endpoint: string;
1226
+ namespace: string;
1227
+ database: string;
1228
+ /** VAPID public key (base64url) the page subscribed with, for `pushsubscriptionchange`. */
1229
+ publicKey?: string;
1230
+ /** This browser's push endpoint, when subscribed. */
1231
+ pushEndpoint?: string;
1232
+ }
1233
+ /** Page -> service worker: forget the session and close every notification. */
1234
+ interface BridgeSignOutMessage {
1235
+ type: 'sp00ky:signout';
1236
+ }
1237
+ /** Service worker -> page messages. */
1238
+ type WebPushClientMessage = /** A push arrived while this page was visible, so nothing was shown. */
1239
+ {
1240
+ type: 'sp00ky:push';
1241
+ payload: PushPayload;
1242
+ }
1243
+ /** A notification was clicked and the bridge was told to route in-app. */ | {
1244
+ type: 'sp00ky:navigate';
1245
+ url: string;
1246
+ payload?: PushPayload;
1247
+ action?: string;
1248
+ }
1249
+ /** The browser rotated the push subscription; the page should `sync()`. */ | {
1250
+ type: 'sp00ky:subscriptionchange';
1251
+ endpoint?: string;
181
1252
  };
182
- type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
1253
+ /** `urlBase64ToUint8Array`: the VAPID key as `applicationServerKey` wants it. */
1254
+
1255
+ /** A payload this build can act on (`v` known, `kind` set). */
1256
+ declare function isPushPayload(value: unknown): value is PushPayload;
1257
+ //#endregion
1258
+ //#region src/modules/web-push/index.d.ts
1259
+ /**
1260
+ * `db.webPush`: this browser's Web Push subscription, on the page.
1261
+ *
1262
+ * Every server call is a `fn::push::*` function over the client's remote
1263
+ * connection (see `apps/cli/src/push_tables.surql`). Nothing here touches a
1264
+ * browser API at import time, and every method answers "unsupported" instead
1265
+ * of throwing where there is no window, service worker or push manager
1266
+ * (SSR, Node, workers, iOS Safari outside a home-screen app).
1267
+ */
1268
+ interface WebPushConfig {
1269
+ /**
1270
+ * Registered with `navigator.serviceWorker.register(url)` when the page has
1271
+ * no service worker yet. Leave unset when the app (or vite-plugin-pwa)
1272
+ * registers its own.
1273
+ */
1274
+ serviceWorkerUrl?: string;
1275
+ /**
1276
+ * Reconcile this browser's subscription after sign-in (see `sync()`): a
1277
+ * rotated key, a browser that dropped the subscription or a server row that
1278
+ * went away are repaired without a prompt. Default `true`.
1279
+ */
1280
+ autoSync?: boolean;
1281
+ /**
1282
+ * Let `sync()` subscribe a signed-in user whenever notification permission
1283
+ * is already granted, even if they never subscribed on this browser.
1284
+ * Default `false`: only a user who called `subscribe()` here is restored.
1285
+ */
1286
+ autoResubscribe?: boolean;
1287
+ /**
1288
+ * Remove this device's subscription for the user on `signOut()` (before the
1289
+ * token is dropped, bounded by a short timeout). Default `true`.
1290
+ */
1291
+ unsubscribeOnSignOut?: boolean;
1292
+ /**
1293
+ * Post the session token to the app's service worker whenever it changes,
1294
+ * while notifications are allowed, so `@spooky-sync/core/sw` can render from
1295
+ * live data. Never posts an impersonation token. Default `true`.
1296
+ */
1297
+ bridge?: boolean;
1298
+ }
1299
+ type WebPushUnsupportedReason = 'no-window' | 'insecure-context' | 'no-service-worker' | 'no-push-manager' | 'no-notification' | 'ios-not-installed';
1300
+ interface WebPushSupport {
1301
+ supported: boolean;
1302
+ permission: NotificationPermission | 'unsupported';
1303
+ reason?: WebPushUnsupportedReason;
1304
+ }
1305
+ interface WebPushInfo {
1306
+ /** A host with push on has published its key. */
1307
+ enabled: boolean;
1308
+ /** VAPID public key (base64url), the browser's `applicationServerKey`. */
1309
+ publicKey?: string;
1310
+ /** Id of that key. */
1311
+ kid?: string;
1312
+ /**
1313
+ * Every kind of device the project reaches: `web` once a VAPID key is
1314
+ * published, `apns` / `fcm` when `push.apns` / `push.fcm` are configured.
1315
+ */
1316
+ providers?: PushDeviceKind[];
1317
+ }
1318
+ /** How a device is reached: a browser (Web Push), APNs or FCM. */
1319
+ type PushDeviceKind = 'web' | 'apns' | 'fcm';
1320
+ interface WebPushDevice {
1321
+ /** `_00_push_subscription:<id>` */
1322
+ id: string;
1323
+ /** Web: the push service URL. Native: `<kind>:<token>`. */
1324
+ endpoint: string;
1325
+ /** Rows the Flutter / native side registered are `apns` or `fcm`. */
1326
+ kind: PushDeviceKind;
1327
+ /** `web`, `ios`, `android` or `macos`. */
1328
+ platform?: string;
1329
+ /** Native: bundle id / package name. */
1330
+ appId?: string;
1331
+ /** APNs: `sandbox` or `production`. */
1332
+ environment?: string;
1333
+ /** Key id a web device subscribed under (empty for native ones). */
1334
+ kid: string;
1335
+ label?: string;
1336
+ userAgent?: string;
1337
+ /** Rule names this device receives; undefined = every rule. */
1338
+ rules?: string[];
1339
+ meta?: Record<string, unknown>;
1340
+ createdAt?: Date;
1341
+ updatedAt?: Date;
1342
+ lastOkAt?: Date;
1343
+ lastError?: string;
1344
+ failures: number;
1345
+ disabledAt?: Date;
1346
+ disabledReason?: string;
1347
+ /** Subscribed under the current key (pushes reach it). Undefined when unknown. */
1348
+ current?: boolean;
1349
+ /** This browser. */
1350
+ thisDevice: boolean;
1351
+ }
1352
+ interface WebPushSubscribeOptions {
1353
+ /** Defaults to the page's service worker registration (`serviceWorker.ready`). */
1354
+ registration?: ServiceWorkerRegistration;
1355
+ /** Shown in the device list ("Work laptop"). */
1356
+ label?: string;
1357
+ /** Rule names this device wants. Omitted or empty: every rule. */
1358
+ rules?: string[];
1359
+ /** Free-form app data about the device. */
1360
+ meta?: Record<string, unknown>;
1361
+ /** Ask for notification permission when it is still `default`. Default `true`. Call from a user gesture. */
1362
+ requestPermission?: boolean;
1363
+ }
1364
+ interface WebPushUnsubscribeOptions {
1365
+ /** Remove every device of the user, not only this one. */
1366
+ all?: boolean;
1367
+ /** Keep the browser's PushSubscription (only the server row goes). */
1368
+ keepBrowserSubscription?: boolean;
1369
+ }
1370
+ interface WebPushSyncOptions {
1371
+ registration?: ServiceWorkerRegistration;
1372
+ /** Overrides `webPush.autoResubscribe` for this call. */
1373
+ autoResubscribe?: boolean;
1374
+ }
1375
+ /**
1376
+ * What `sync()` did. `ok`: nothing to repair. `resubscribed`: the browser
1377
+ * subscription was (re)created. `registered`: the server row was re-created.
1378
+ * The rest say why nothing happened.
1379
+ */
1380
+ type WebPushSyncStatus = 'ok' | 'resubscribed' | 'registered' | 'unsupported' | 'signed-out' | 'impersonating' | 'permission-default' | 'permission-denied' | 'not-subscribed' | 'disabled' | 'no-registration' | 'error';
1381
+ interface WebPushUpdateOptions {
1382
+ label?: string;
1383
+ /** Rule names; `null` or `[]` resets the device to every rule. */
1384
+ rules?: string[] | null;
1385
+ meta?: Record<string, unknown>;
1386
+ }
1387
+ /** A push to yourself (`fn::push::notify`). */
1388
+ interface WebPushMessageInput {
1389
+ /** Omit for a content-free nudge. */
1390
+ notification?: PushNotification;
1391
+ data?: Record<string, unknown>;
1392
+ topic?: string;
1393
+ urgency?: PushUrgency;
1394
+ /** Push-service TTL, seconds. */
1395
+ ttl?: number;
1396
+ /** In the future: scheduled. */
1397
+ sendAt?: Date | string | number;
1398
+ }
1399
+ interface WebPushMessage {
1400
+ /** `_00_push_message:<id>` */
1401
+ id: string;
1402
+ status: string;
1403
+ sendAt?: Date;
1404
+ createdAt?: Date;
1405
+ }
1406
+ type WebPushErrorCode = 'unsupported' | 'signed-out' | 'impersonating' | 'disabled' | 'permission-denied' | 'permission-default' | 'no-registration' | 'not-subscribed' | 'subscribe-failed' | 'server';
1407
+ declare class WebPushError extends Error {
1408
+ readonly code: WebPushErrorCode;
1409
+ readonly cause?: unknown | undefined;
1410
+ constructor(code: WebPushErrorCode, message: string, cause?: unknown | undefined);
1411
+ }
1412
+ interface WebPushAuthPort {
1413
+ readonly token: string | null;
1414
+ readonly currentUser: {
1415
+ id?: unknown;
1416
+ } | null;
1417
+ readonly isAuthenticated: boolean;
1418
+ readonly impersonation: unknown;
1419
+ subscribe(cb: (userId: unknown) => void): () => void;
1420
+ onBeforeSignOut(hook: (ctx: SignOutContext) => Promise<void> | void): () => void;
1421
+ }
1422
+ interface WebPushRemotePort {
1423
+ query<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
1424
+ }
1425
+ /** Browser globals, read at call time. Injectable for tests. */
1426
+ interface WebPushGlobals {
1427
+ window?: unknown;
1428
+ navigator?: Navigator & {
1429
+ standalone?: boolean;
1430
+ };
1431
+ Notification?: {
1432
+ permission: NotificationPermission;
1433
+ requestPermission(cb?: (p: NotificationPermission) => void): Promise<NotificationPermission> | void;
1434
+ };
1435
+ isSecureContext?: boolean;
1436
+ matchMedia?: (query: string) => {
1437
+ matches: boolean;
1438
+ };
1439
+ PushManager?: unknown;
1440
+ }
1441
+ interface WebPushModuleDeps {
1442
+ remote: WebPushRemotePort;
1443
+ auth: WebPushAuthPort;
1444
+ persistence: PersistenceClient;
1445
+ logger: Logger$1;
1446
+ database: {
1447
+ endpoint?: string;
1448
+ namespace: string;
1449
+ database: string;
1450
+ };
1451
+ /** Transport state; auto-sync waits for `connected`. */
1452
+ connection?: {
1453
+ subscribe(cb: (state: string) => void): () => void;
1454
+ };
1455
+ config?: WebPushConfig;
1456
+ globals?: () => WebPushGlobals;
1457
+ }
1458
+ declare const PUSH_ENDPOINT_KEY = "sp00ky_push_endpoint";
1459
+ /** `table:id` of a record id value, without the SDK's escaping. */
1460
+
1461
+ /** Where Web Push can work, from the given globals. */
1462
+ declare function detectWebPushSupport(g: WebPushGlobals): WebPushSupport;
1463
+ declare class WebPushModule {
1464
+ private readonly deps;
1465
+ private readonly logger;
1466
+ private readonly config;
1467
+ private readonly globals;
1468
+ private infoCache;
1469
+ private lastInfo;
1470
+ private readonly bridges;
1471
+ private readonly disposers;
1472
+ private syncedFor;
1473
+ private syncTimer;
1474
+ private attached;
1475
+ constructor(deps: WebPushModuleDeps);
1476
+ /**
1477
+ * Wire sign-out, auto-sync and the token bridge. Called by the client once;
1478
+ * a no-op beyond the sign-out hook where push is unsupported.
1479
+ */
1480
+ attach(): () => void;
1481
+ dispose(): void;
1482
+ support(): WebPushSupport;
1483
+ /** Is push on for this deployment, and with which key. Cached; `refresh` re-reads. */
1484
+ info(options?: {
1485
+ refresh?: boolean;
1486
+ }): Promise<WebPushInfo>;
1487
+ /** This browser holds a push subscription registered for the signed-in user. No server round trip. */
1488
+ isSubscribed(): Promise<boolean>;
1489
+ /** The user's devices, this one marked. */
1490
+ devices(): Promise<WebPushDevice[]>;
1491
+ /**
1492
+ * Ask for permission (when still `default`), subscribe this browser with the
1493
+ * deployment's key and register it for the signed-in user. Call it from a
1494
+ * click handler: permission prompts need a user gesture.
1495
+ */
1496
+ subscribe(options?: WebPushSubscribeOptions): Promise<WebPushDevice>;
1497
+ /** Remove this device (or every device, `all`) for the signed-in user. Returns how many rows went. */
1498
+ unsubscribe(options?: WebPushUnsubscribeOptions): Promise<number>;
1499
+ /**
1500
+ * Reconcile after sign-in (runs by itself with `autoSync`). Needs granted
1501
+ * permission and a user who subscribed on this browser (or
1502
+ * `autoResubscribe`). Repairs a missing browser subscription, one made with
1503
+ * a rotated key, and a missing, disabled or stale server row. Never throws.
1504
+ */
1505
+ sync(options?: WebPushSyncOptions): Promise<WebPushSyncStatus>;
1506
+ /** Change this device's label, rule filter or meta. */
1507
+ update(options: WebPushUpdateOptions): Promise<WebPushDevice | null>;
1508
+ /** Push to yourself, now or at `sendAt` (reminders). Omit `notification` for a nudge. */
1509
+ notify(message: WebPushMessageInput): Promise<WebPushMessage>;
1510
+ /** Cancel a scheduled message. `true` when it was still pending. */
1511
+ cancel(id: string | RecordId$1): Promise<boolean>;
1512
+ /** A visible test notification to every device of the user. */
1513
+ test(options?: {
1514
+ title?: string;
1515
+ body?: string;
1516
+ }): Promise<WebPushMessage>;
1517
+ /**
1518
+ * Post the session to the service worker now and whenever the token
1519
+ * changes (`{ type: 'sp00ky:token', token, userId, endpoint, namespace,
1520
+ * database }`). Never posts an impersonation token. Returns a disposer.
1521
+ * With `webPush.bridge` (the default) this already runs while notification
1522
+ * permission is granted.
1523
+ */
1524
+ bridge(registration?: ServiceWorkerRegistration): () => void;
1525
+ /** Messages from the push service worker (`sp00ky:push` while visible, `sp00ky:navigate`, ...). */
1526
+ onMessage(cb: (message: WebPushClientMessage) => void): () => void;
1527
+ private userId;
1528
+ private assertSignedIn;
1529
+ private assertNotImpersonating;
1530
+ private call;
1531
+ private listRaw;
1532
+ private register;
1533
+ private readStored;
1534
+ private writeStored;
1535
+ /** The page's registration: given, existing, registered from config, or `ready` within `waitMs`. */
1536
+ private registration;
1537
+ /** This browser's subscription, without waiting for a worker. */
1538
+ private currentSubscription;
1539
+ private thisEndpoint;
1540
+ private postToWorker;
1541
+ private startBridge;
1542
+ private refreshBridges;
1543
+ private tokenMessage;
1544
+ /** Sign-out hook: tell the worker, and drop this device's row for the user. Bounded. */
1545
+ private beforeSignOut;
1546
+ }
183
1547
  //#endregion
184
1548
  //#region src/types.d.ts
185
1549
  /**
@@ -220,6 +1584,24 @@ interface PersistenceClient {
220
1584
  * Format: number + unit (m=minutes, h=hours, d=days).
221
1585
  */
222
1586
  type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
1587
+ /**
1588
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
1589
+ * The FIRST load (cold) always fetches + blocks regardless.
1590
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
1591
+ * real `useQuery` mounts and registers its live view. No network on load.
1592
+ * - `background`: return instantly, but kick a one-time silent refetch.
1593
+ * - `stale`: like `background`, but only if the cached copy is older than
1594
+ * `staleTime`.
1595
+ */
1596
+ type PreloadRefresh = 'onUse' | 'background' | 'stale';
1597
+ interface PreloadOptions {
1598
+ /** Abort a cold preload that is still waiting for the server. */
1599
+ signal?: AbortSignal;
1600
+ /** @deprecated Preload is a registered query now; a warm preload never refetches by itself. Ignored. */
1601
+ refresh?: PreloadRefresh;
1602
+ /** @deprecated Ignored. */
1603
+ staleTime?: QueryTimeToLive;
1604
+ }
223
1605
  /**
224
1606
  * Result object returned when a query is registered or executed.
225
1607
  */
@@ -231,6 +1613,29 @@ type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
231
1613
  interface EventSubscriptionOptions {
232
1614
  priority?: number;
233
1615
  }
1616
+ /**
1617
+ * Factories for the local store's web workers (`database.workers`). Each one
1618
+ * must start a MODULE worker (`{ type: 'module' }`) whose entry imports the
1619
+ * module named below, bundled by the app's own build:
1620
+ *
1621
+ * ```ts
1622
+ * // sp00ky-surreal.worker.ts
1623
+ * import '@surrealdb/wasm/worker';
1624
+ *
1625
+ * // config
1626
+ * workers: {
1627
+ * surreal: () => new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }),
1628
+ * }
1629
+ * ```
1630
+ *
1631
+ * A factory left out falls back to the built-in worker.
1632
+ */
1633
+ interface LocalWorkers {
1634
+ /** The default engine's worker (`localEngine: 'surrealdb'`): runs `@surrealdb/wasm/worker`. */
1635
+ surreal?: () => Worker;
1636
+ /** The SQLite engine's worker (`localEngine: 'sqlite'`): runs `@spooky-sync/core/sqlite-worker`. */
1637
+ sqlite?: () => Worker;
1638
+ }
234
1639
  /**
235
1640
  * Configuration options for the Sp00ky client.
236
1641
  * @template S The schema structure type.
@@ -248,6 +1653,46 @@ interface Sp00kyConfig<S extends SchemaStructure> {
248
1653
  store?: StoreType;
249
1654
  /** Authentication token. */
250
1655
  token?: string;
1656
+ /**
1657
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
1658
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
1659
+ * table/relation level. Defaults to true; set false to force the legacy
1660
+ * multi-hop path (escape hatch while the worker-side path beds in).
1661
+ */
1662
+ workerSelect?: boolean;
1663
+ /**
1664
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
1665
+ * keep the connection alive indefinitely without configuration. See
1666
+ * {@link ReconnectConfig}.
1667
+ */
1668
+ reconnect?: ReconnectConfig;
1669
+ /**
1670
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
1671
+ * a single promise chain, so one call that never settles (half-open socket:
1672
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
1673
+ * otherwise wedge ALL later remote traffic behind it — including the sync
1674
+ * poll's own health probe, leaving health pinned at `healthy` with no
1675
+ * banner and no self-heal. The deadline turns that into an ordinary network
1676
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
1677
+ */
1678
+ queryTimeoutMs?: number;
1679
+ /**
1680
+ * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
1681
+ * or a query on the in-process surrealdb engine). Local ops are serialized
1682
+ * too, and one that never answered - a worker starved behind a long select,
1683
+ * a lock verification with no clock - left every `db.create`/`db.update`
1684
+ * promise pending for the tab's lifetime. On expiry the call rejects with
1685
+ * `LocalOpTimeoutError` (the op itself keeps running in the engine and is
1686
+ * not retried). `0` disables. Defaults to `30_000`.
1687
+ */
1688
+ localOpTimeoutMs?: number;
1689
+ /**
1690
+ * Start the local store's web worker yourself. Only needed under a bundler
1691
+ * that does not bundle a worker started inside a dependency, which is the
1692
+ * Angular CLI; Vite, Rollup and webpack bundle the built-in workers on
1693
+ * their own, so leave it unset there. See {@link LocalWorkers}.
1694
+ */
1695
+ workers?: LocalWorkers;
251
1696
  };
252
1697
  /** The schema definition. */
253
1698
  schema: S;
@@ -260,24 +1705,129 @@ interface Sp00kyConfig<S extends SchemaStructure> {
260
1705
  * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
261
1706
  */
262
1707
  persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
1708
+ /**
1709
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
1710
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
1711
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
1712
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
1713
+ * this engine. See `services/database/cache-engine.ts`.
1714
+ */
1715
+ localEngine?: LocalEngineChoice;
1716
+ /**
1717
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
1718
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
1719
+ * how bucket reads behaved before it existed.
1720
+ *
1721
+ * Nothing in this cache expires on a timer — an image whose row is still in
1722
+ * the local store has to stay available offline. Bytes are only dropped when
1723
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
1724
+ * reconcile finds no file behind a row, or when the cache is over budget, in
1725
+ * which case the least-recently-used unpinned entries go first. See
1726
+ * `services/blobs/blob-cache.ts`.
1727
+ */
1728
+ blobCache?: {
1729
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
1730
+ enabled?: boolean;
1731
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
1732
+ * `navigator.storage.estimate()`. */
1733
+ maxBytes?: number;
1734
+ /**
1735
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
1736
+ * `false`, matching the local store: cached files are namespaced per local
1737
+ * bucket, so signing back in is warm and no user can read another's cache.
1738
+ * Turn on for shared devices.
1739
+ */
1740
+ clearOnSignOut?: boolean;
1741
+ };
1742
+ /**
1743
+ * Share ONE durable local store across all tabs of this origin (default
1744
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
1745
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
1746
+ * worker and the sync loop, and follower tabs read/write the same store over
1747
+ * MessagePorts, so every tab is durable instead of only the first one.
1748
+ *
1749
+ * Falls back to solo mode (exactly the flag-off behavior, including the
1750
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
1751
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
1752
+ * not sqlite, or the broker rejects the tab (mixed app versions).
1753
+ *
1754
+ * Failover: when the leader tab closes or freezes, a follower is promoted
1755
+ * within seconds; queries briefly refetch and mutations are never lost once
1756
+ * their local write resolved (the shared outbox survives in the store).
1757
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
1758
+ */
1759
+ sharedTabs?: boolean;
1760
+ /**
1761
+ * Persist the in-browser SSP circuit's store as a snapshot in the local
1762
+ * store, so a reload restores it and only steps in what changed since.
1763
+ * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
1764
+ * can hold the bytes) and `false` otherwise.
1765
+ *
1766
+ * Without a snapshot the circuit is primed by reading every cached row back
1767
+ * out of the local store; either way a reload never re-downloads the working
1768
+ * set, which is what an empty circuit used to force: every id in the
1769
+ * server's list_ref classified as missing.
1770
+ *
1771
+ * Snapshots are store-only (views are re-registered per session) and written
1772
+ * on a checkpoint interval ({@link circuitCheckpointMs}) and when the page
1773
+ * goes hidden, never per ingest or per query registration.
1774
+ */
1775
+ persistCircuit?: boolean;
1776
+ /**
1777
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
1778
+ * 30000. Ignored when `persistCircuit` is off.
1779
+ */
1780
+ circuitCheckpointMs?: number;
1781
+ /**
1782
+ * Keep only the fields registered queries evaluate (filter predicates, join
1783
+ * keys, sort keys, plus `id`/`_00_rv`) per row in the in-browser circuit.
1784
+ * Default `true`. The circuit only ever reads those fields; bodies are
1785
+ * rendered from the local store. Measured on 7700 rows with 20 KB bodies:
1786
+ * the wasm heap peak went from ~500 MB to ~24 MB and the snapshot from
1787
+ * 156 MB to 1.2 MB. A query that evaluates a field earlier rows were kept
1788
+ * without has that field merged in from the local store on registration.
1789
+ */
1790
+ circuitProjection?: boolean;
263
1791
  /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
264
1792
  otelTransmit?: PinoTransmit;
265
1793
  /**
266
- * Debounce time in milliseconds for stream updates (the client-side SSP
267
- * aggregation throttle — coalesces the in-browser StreamProcessor's
268
- * per-record updates per query before notifying readers).
269
- * Defaults to 50ms.
1794
+ * Minimum gap in milliseconds between two materializations of one query
1795
+ * (coalesces per-record updates before notifying readers). The first change
1796
+ * after a quiet spell is delivered on the next tick; later ones inside the
1797
+ * window fold into one update at its end. Defaults to 50ms.
270
1798
  */
271
1799
  streamDebounceTime?: number;
272
1800
  /**
273
- * Debounce time in milliseconds for syncing collaborative (CRDT) field
274
- * changes to the remote database. Local writes happen immediately on
275
- * every keystroke (so reload/offline works), but the remote UPSERT is
276
- * coalesced over this window. Lower = snappier remote propagation +
277
- * more network traffic; higher = less traffic + more lag for other
278
- * collaborators. Defaults to 500ms.
1801
+ * How long in milliseconds the first edit to a collaborative (CRDT) field
1802
+ * after a quiet spell waits before it goes out, so a burst of keystrokes
1803
+ * travels as one edit-log row. Local state is kept on every change (so
1804
+ * reload and offline work). Defaults to 50ms.
279
1805
  */
280
1806
  crdtDebounceMs?: number;
1807
+ /**
1808
+ * The shortest gap in milliseconds between two edit-log rows of one CRDT
1809
+ * field: while someone keeps typing, their edits go out on this cadence
1810
+ * instead of waiting for a pause. Lower = other collaborators see the text
1811
+ * sooner and more rows are written; higher = fewer rows and more lag.
1812
+ * Defaults to 200ms.
1813
+ */
1814
+ crdtSendIntervalMs?: number;
1815
+ /**
1816
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
1817
+ * preloaded at client startup (fetched as a separate chunk on page load) so
1818
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
1819
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
1820
+ * out of apps that don't use collaboration. Defaults to `false`.
1821
+ */
1822
+ crdt?: boolean;
1823
+ /**
1824
+ * Peer to peer channels for `-- @channel` tables (see `.channel(peers)` on
1825
+ * a query). `accept` holds the app's rules per table: which peer updates to
1826
+ * apply. `iceServers` configures the default WebRTC transport (a public
1827
+ * STUN server when omitted; add TURN for networks that block direct
1828
+ * connections), `transport` replaces it.
1829
+ */
1830
+ channels?: ChannelsConfig;
281
1831
  /**
282
1832
  * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
283
1833
  * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
@@ -286,15 +1836,39 @@ interface Sp00kyConfig<S extends SchemaStructure> {
286
1836
  */
287
1837
  refSyncIntervalMs?: number;
288
1838
  /**
289
- * Instant-hydrate cold queries: when a query is registered with no local
290
- * data yet, first run its surql directly on the remote (one-shot) and display
291
- * the result immediately, THEN do the full realtime registration in the
292
- * background. The hydrated rows are ingested with their versions so the
293
- * registration's `syncRecords` skips re-pulling unchanged bodies. Cuts cold
294
- * first-paint from ~one full registration round-trip to ~one query.
295
- * Defaults to `true`; set `false` to keep the old wait-for-registration path.
1839
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
1840
+ * registered with no server result yet, its surql also runs directly on the
1841
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
1842
+ * before the full register lifecycle completes. Hydrated rows carry their
1843
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
1844
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
1845
+ * paints from the local cache immediately — however the rows got there
1846
+ * (preload, prior sync). Default `false`: the register lifecycle
1847
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
1848
+ * freshness path and no duplicate one-shot fetches are made.
296
1849
  */
297
1850
  instantHydrate?: boolean;
1851
+ /**
1852
+ * Carry the changed row's body on the LIVE notification instead of going
1853
+ * back for it.
1854
+ *
1855
+ * The client holds exactly one live subscription, on its `_00_list_ref`
1856
+ * table. Without this, the notification names the row and the client then
1857
+ * pulls it with `SELECT * FROM $ids`. The edge
1858
+ * is a real graph edge, so `FETCH out` makes SurrealDB resolve the row into
1859
+ * the notification and the body fetch disappears.
1860
+ *
1861
+ * The push stays advisory: the body is landed exactly the way a fetched body
1862
+ * is (store write, circuit ingest, version recorded), so a notification the
1863
+ * server drops costs nothing but the old round trip. A row joining a live
1864
+ * view is committed to membership from the notification either way (no
1865
+ * re-read); with this on, the body fetch is saved as well.
1866
+ *
1867
+ * Default `false`. The cost is wire bytes: one edit bumps the edge in every
1868
+ * view holding the row, and under `FETCH` each of those notifications
1869
+ * carries its own full copy of the body.
1870
+ */
1871
+ liveInlineBodies?: boolean;
298
1872
  /**
299
1873
  * Enable realtime sync while signed out. When `true`, the client starts its
300
1874
  * `_00_list_ref` poll (and a LIVE subscription) against the shared
@@ -302,9 +1876,30 @@ interface Sp00kyConfig<S extends SchemaStructure> {
302
1876
  * page gets live `useQuery` updates over world-readable tables. Requires the
303
1877
  * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
304
1878
  * (this flag must match it). Defaults to `false`: anonymous clients can read
305
- * one-shot but never sync live.
1879
+ * one-shot but never sync live, and a `preload` made while signed out returns
1880
+ * at once rather than wait for membership that never comes.
306
1881
  */
307
1882
  enableAnonymousLiveQueries?: boolean;
1883
+ /**
1884
+ * Opt in to the raw remote escape hatches (`useRemote`, `remoteQuery`,
1885
+ * `queryRaw`) when the generated schema's `policy.queryAllowlist` is `warn`
1886
+ * or `enforce`. With the allowlist on, the server only accepts query shapes
1887
+ * that `spky generate` collected from the query builder, so a hand-written
1888
+ * SurrealQL string cannot be allowlisted and these methods throw unless this
1889
+ * flag is `true`. Defaults to `false`.
1890
+ */
1891
+ allowRawRemote?: boolean;
1892
+ /**
1893
+ * How the "you are impersonating" warning is shown while an admin acts as
1894
+ * another user. The built-in one (hazard stripes at the top, the page
1895
+ * shifted down onto them) needs no configuration; this is for restyling it,
1896
+ * or replacing it with the app's own.
1897
+ *
1898
+ * See `ImpersonationBannerConfig`. Replacing it does not mean "no warning":
1899
+ * if the app has not acknowledged its own banner shortly after impersonation
1900
+ * starts, the built-in one appears anyway.
1901
+ */
1902
+ impersonationBanner?: ImpersonationBannerConfig;
308
1903
  /**
309
1904
  * Surface sustained sync failures as a "degraded" health status that the app
310
1905
  * can observe via `subscribeToSyncHealth` (or the client-solid
@@ -318,6 +1913,57 @@ interface Sp00kyConfig<S extends SchemaStructure> {
318
1913
  * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
319
1914
  */
320
1915
  syncHealth?: SyncHealthConfig | false;
1916
+ /**
1917
+ * Automatic blurhash placeholders for bucket image uploads. On every
1918
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
1919
+ * the client computes a blurhash and stores it as a tiny sidecar object
1920
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
1921
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
1922
+ * helpers) to paint a placeholder until the image is decoded.
1923
+ *
1924
+ * `true` (the default) enables with 4x3 components; pass
1925
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
1926
+ * A per-call `put(path, content, { blurhash })` option overrides this.
1927
+ */
1928
+ blurhash?: boolean | {
1929
+ componentX?: number;
1930
+ componentY?: number;
1931
+ };
1932
+ /**
1933
+ * Buckets declared `BACKEND "r2"` keep their files with the SSP (R2 on
1934
+ * Cloudflare, a directory under `spky dev`) instead of in SurrealDB, which
1935
+ * on Surreal Cloud can only hold memory buckets. `endpoint` is the SSP's
1936
+ * URL: `spky dev` and `spky deploy` hand it to Vite as
1937
+ * `VITE_SPKY_FILES_ENDPOINT`.
1938
+ */
1939
+ files?: {
1940
+ endpoint?: string;
1941
+ };
1942
+ /**
1943
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
1944
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
1945
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
1946
+ * settles stops every later mutation for the session, with no retry and no
1947
+ * error. On expiry the push is treated as a network failure and re-queued.
1948
+ * `0` disables. Defaults to `30_000`.
1949
+ */
1950
+ pushTimeoutMs?: number;
1951
+ /**
1952
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
1953
+ * it is retried. Mirror of {@link pushTimeoutMs} for the read side.
1954
+ * Defaults to 30000; `0` disables the timeout.
1955
+ */
1956
+ downTimeoutMs?: number;
1957
+ /**
1958
+ * Web Push on this page (`client.webPush`, `db.webPush`). Everything is
1959
+ * optional and the defaults need no service worker configuration here:
1960
+ * `autoSync` (repair this browser's subscription after sign-in),
1961
+ * `unsubscribeOnSignOut` (drop this device's subscription on `signOut()`),
1962
+ * `bridge` (post the session to the service worker for live rendering) are
1963
+ * on; `serviceWorkerUrl` registers a worker when the app does not.
1964
+ * See the `push-notifications` docs page.
1965
+ */
1966
+ webPush?: WebPushConfig;
321
1967
  }
322
1968
  /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
323
1969
  interface SyncHealthConfig {
@@ -329,6 +1975,53 @@ interface SyncHealthConfig {
329
1975
  */
330
1976
  degradeAfterConsecutiveFailures?: number;
331
1977
  }
1978
+ /**
1979
+ * Tunables for WebSocket reconnect and liveness detection. See
1980
+ * {@link Sp00kyConfig.database.reconnect}.
1981
+ *
1982
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
1983
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
1984
+ * supervisor above it re-opens the connection from scratch whenever the SDK
1985
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
1986
+ * engine permanently in that case, so a supervisor is required, not optional.
1987
+ * The heartbeat covers the third case: a socket that never closes at all.
1988
+ */
1989
+ interface ReconnectConfig {
1990
+ /**
1991
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
1992
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
1993
+ * ~62s outage and then gives up for the life of the page).
1994
+ */
1995
+ attempts?: number;
1996
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
1997
+ retryDelayMax?: number;
1998
+ /**
1999
+ * Cadence of the application-level liveness probe (`RETURN true`) that
2000
+ * detects a half-open socket the transport never reports as closed.
2001
+ * `0` disables the heartbeat. Defaults to `20_000`.
2002
+ */
2003
+ heartbeatIntervalMs?: number;
2004
+ /**
2005
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
2006
+ * regardless of what its `readyState` claims, so the connection is torn down
2007
+ * and rebuilt. Defaults to `10_000`.
2008
+ */
2009
+ heartbeatTimeoutMs?: number;
2010
+ /**
2011
+ * Cap on the supervisor's own backoff between `connect()` retries once the
2012
+ * SDK has given up. Defaults to `15_000`.
2013
+ */
2014
+ superviseRetryDelayMaxMs?: number;
2015
+ }
2016
+ /**
2017
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
2018
+ *
2019
+ * These answer different questions: `connection` is about the socket,
2020
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
2021
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
2022
+ * usually still `healthy` for the first few seconds.
2023
+ */
2024
+ type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
332
2025
  type SyncHealthStatus = 'healthy' | 'degraded';
333
2026
  /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
334
2027
  interface SyncHealth {
@@ -340,8 +2033,76 @@ interface SyncHealth {
340
2033
  kind?: 'network' | 'application';
341
2034
  /** Message of the most recent failure (only set while `degraded`). */
342
2035
  error?: string;
2036
+ /**
2037
+ * `true` once at least one sync round has succeeded this session. Lets a UI
2038
+ * distinguish a first-time "connecting" phase (never reached the server yet,
2039
+ * so a cold-start failure run is expected) from a real lost connection after
2040
+ * a working session. Never resets back to `false` once set.
2041
+ */
2042
+ everConnected: boolean;
2043
+ /**
2044
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
2045
+ * one flips the instant the socket drops, whereas `status` only degrades
2046
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
2047
+ * immediately without waiting for the degrade threshold.
2048
+ */
2049
+ connection: ConnectionState;
2050
+ }
2051
+ type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
2052
+ /**
2053
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
2054
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
2055
+ * server, this one is about whether the local store survives a reload.
2056
+ *
2057
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
2058
+ * which only one client per bucket can hold open. When it can't be opened (a
2059
+ * second tab of the app already has it, an insecure context, a full pool) the
2060
+ * engine keeps working against an in-memory DB, which holds the whole dataset
2061
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
2062
+ * so a UI can warn about it.
2063
+ */
2064
+ interface StorageHealth {
2065
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
2066
+ status: StorageHealthStatus;
2067
+ /**
2068
+ * `true` only when durable storage was REQUESTED and could not be opened.
2069
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
2070
+ * is a choice rather than a failure, so a UI can key off this alone.
2071
+ */
2072
+ fallback: boolean;
2073
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
2074
+ error?: string;
2075
+ /**
2076
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
2077
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
2078
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
2079
+ * single-tab behavior. Absent entirely when the feature is off.
2080
+ */
2081
+ role?: 'leader' | 'follower' | 'solo';
343
2082
  }
344
2083
  type QueryHash = string;
2084
+ /**
2085
+ * One changed row delivered inline on a LIVE notification, when the
2086
+ * subscription was opened with the body joined on (see
2087
+ * {@link Sp00kyConfig.liveInlineBodies}). `version` is the edge's `version`,
2088
+ * i.e. the same number the membership read would have reported for this row.
2089
+ */
2090
+ interface InlineRow {
2091
+ id: string;
2092
+ version: number;
2093
+ record: Record<string, unknown>;
2094
+ }
2095
+ /**
2096
+ * A row that joined a query's view, or moved to a newer version, as one LIVE
2097
+ * notification on `_00_list_ref` reports it: the edge's `out` and `version`.
2098
+ * The client commits it to the query's membership straight away instead of
2099
+ * re-reading the edges (see `sync/live.saga.ts`).
2100
+ */
2101
+ interface EdgeDelta {
2102
+ hash: QueryHash;
2103
+ id: string;
2104
+ version: number;
2105
+ }
345
2106
  type RecordVersionArray = Array<[string, number]>;
346
2107
  /**
347
2108
  * Represents the difference between two record version sets.
@@ -350,16 +2111,16 @@ type RecordVersionArray = Array<[string, number]>;
350
2111
  interface RecordVersionDiff {
351
2112
  /** List of records added. */
352
2113
  added: Array<{
353
- id: RecordId$1<string>;
2114
+ id: RecordId<string>;
354
2115
  version: number;
355
2116
  }>;
356
2117
  /** List of records updated. */
357
2118
  updated: Array<{
358
- id: RecordId$1<string>;
2119
+ id: RecordId<string>;
359
2120
  version: number;
360
2121
  }>;
361
2122
  /** List of record IDs removed. */
362
- removed: RecordId$1<string>[];
2123
+ removed: RecordId<string>[];
363
2124
  }
364
2125
  /**
365
2126
  * Configuration for a specific query instance.
@@ -367,9 +2128,16 @@ interface RecordVersionDiff {
367
2128
  */
368
2129
  interface QueryConfig {
369
2130
  /** The unique ID of the query config record. */
370
- id: RecordId$1<string>;
2131
+ id: RecordId<string>;
371
2132
  /** The SURQL query string. */
372
2133
  surql: string;
2134
+ /**
2135
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
2136
+ * `_00_query`). Present when the query came from the query-builder. Non-
2137
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
2138
+ * instead of re-running `surql`, which they cannot parse.
2139
+ */
2140
+ plan?: QueryPlan;
373
2141
  /** Parameters used in the query. */
374
2142
  params: Record<string, any>;
375
2143
  /** The version array representing the local state of results. */
@@ -384,6 +2152,29 @@ interface QueryConfig {
384
2152
  * `rowCount` / `localArray`.
385
2153
  */
386
2154
  subqueryRemoteArray?: RecordVersionArray;
2155
+ /**
2156
+ * Whether authoritative membership (`remoteArray`) has ever been established
2157
+ * for this query — either fetched from `_00_list_ref` this session, or read
2158
+ * back from the durable `_00_view` row on a cold start.
2159
+ *
2160
+ * Tri-state matters: "known and empty" must render an empty list, while
2161
+ * "never established" has to fall back to a predicate scan of the local store
2162
+ * so a query first run on this device still paints offline. A
2163
+ * `remoteArray.length === 0` check cannot tell those apart.
2164
+ *
2165
+ * On a cold start it is seeded from the durable `_00_view` row when that
2166
+ * row is non-empty, or empty but `confirmed` (the server reported zero rows
2167
+ * for the query). An unconfirmed empty row is ignored, so a device poisoned
2168
+ * by an old client that mirrored unflushed reads still self-heals.
2169
+ */
2170
+ membershipKnown?: boolean;
2171
+ /**
2172
+ * Key of this query's durable `_00_view` membership row: a hash of
2173
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
2174
+ * survives a reload (which mints a new session id) and a bucket switch.
2175
+ * In-memory only.
2176
+ */
2177
+ membershipKey?: string;
387
2178
  /** Time-To-Live for this query. */
388
2179
  ttl: QueryTimeToLive;
389
2180
  /** Timestamp when the query was last accessed/active. */
@@ -396,12 +2187,37 @@ type QueryConfigRecord = QueryConfig & {
396
2187
  };
397
2188
  /**
398
2189
  * Runtime fetch status of a live query.
399
- * - `idle`: not currently fetching missing records.
400
- * - `fetching`: the sync engine is fetching/ingesting missing records for this
401
- * query. UI notifications are coalesced so the result lands as a single
402
- * update once fetching completes.
2190
+ * - `idle`: registered, initial sync completed, and not currently fetching
2191
+ * missing records — the materialized rows are authoritative (a windowed
2192
+ * query's short result really is the end of the list).
2193
+ * - `fetching`: the query is registering (a query is born `fetching` until its
2194
+ * initial remote sync completes) or the sync engine is fetching/ingesting
2195
+ * missing records for it. Any pending debounced result is flushed BEFORE the
2196
+ * flip back to `idle`, so idle status never races ahead of the rows.
403
2197
  */
404
2198
  type QueryStatus = 'idle' | 'fetching';
2199
+ /**
2200
+ * What the server's `_00_query` row says about a view, read alongside its
2201
+ * `_00_list_ref` edges (registration, the poll, a targeted re-read).
2202
+ *
2203
+ * - `present: false`: the row is not there (or not readable). The SSP no
2204
+ * longer has this view: a TTL sweep, an SSP reset, a scheduler wipe. An
2205
+ * empty edge set read at the same time is NOT "no rows", it is "no view".
2206
+ * - `state: 'materializing'`: the SSP has (re)computed the set and its edges
2207
+ * are in flight; an empty read is "not landed yet".
2208
+ * - `state: 'ready'`: the edges are committed (flipped in the same
2209
+ * transaction), so `rowCount === 0` with no edges is a real empty result.
2210
+ * - `state: null`: a server that predates the marker; only `rowCount` can be
2211
+ * used, with its `> 0` = flush window / `0` = empty ambiguity.
2212
+ */
2213
+ interface ServerViewMeta {
2214
+ present: boolean;
2215
+ /** `_00_query.rowCount`; `null` when unreadable. */
2216
+ rowCount: number | null;
2217
+ state: 'materializing' | 'ready' | null;
2218
+ }
2219
+ /** Outcome of handing a server id-set to `DataModule.updateQueryRemoteArray`. */
2220
+ type MembershipOutcome = 'applied' | 'ignored' | 'view-lost';
405
2221
  /**
406
2222
  * Internal state of a live query.
407
2223
  */
@@ -413,12 +2229,42 @@ interface QueryState {
413
2229
  /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
414
2230
  * path fires at most once per query (see DataModule.isCold/applyHydration). */
415
2231
  hydrated?: boolean;
2232
+ /** Set once a server-side membership set has been accepted this session
2233
+ * (`updateQueryRemoteArray`). The `register` down-event is enqueued before
2234
+ * the instant-hydrate, so a hydrate that finishes later must not prime
2235
+ * membership over the authoritative set. Ephemeral. */
2236
+ serverMembership?: boolean;
2237
+ /**
2238
+ * Set when the server's `_00_query` row for this query went missing while
2239
+ * we held membership (TTL sweep, SSP reset, scheduler wipe). The view is
2240
+ * being re-registered; until a readable row comes back, empty reads are
2241
+ * NOT the server's answer and nothing is dropped. Ephemeral.
2242
+ */
2243
+ viewLost?: boolean;
2244
+ /** Last `_00_query.state` read from the server, for DevTools. Ephemeral. */
2245
+ serverState?: 'materializing' | 'ready' | null;
2246
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
2247
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
2248
+ * always emits at least once even when its records are unchanged — otherwise
2249
+ * an empty re-registered window would never notify and stay "loading". */
2250
+ syncNotified?: boolean;
2251
+ /**
2252
+ * Subscribers hold the rows of a known membership (see `QueryLifecycle`'s
2253
+ * `answered`): what the authority channel and the bindings'
2254
+ * `isAuthoritative()` report. Ephemeral.
2255
+ */
2256
+ answered?: boolean;
416
2257
  /** Timer for TTL expiration. */
417
2258
  ttlTimer: NodeJS.Timeout | null;
418
2259
  /** TTL duration in milliseconds. */
419
2260
  ttlDurationMs: number;
2261
+ /** When the last TTL heartbeat for this query was sent (ms epoch); `undefined` before the first. */
2262
+ lastHeartbeatAt?: number;
420
2263
  /** Number of times the query has been updated. */
421
2264
  updateCount: number;
2265
+ /** Timestamp (ms) of the last user-visible update, or null before the first
2266
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
2267
+ lastUpdatedAt: number | null;
422
2268
  /**
423
2269
  * Rolling window of the most recent materialization-step latencies (ms).
424
2270
  * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
@@ -485,7 +2331,16 @@ interface QueryTimings {
485
2331
  }
486
2332
  type QueryUpdateCallback = (records: Record<string, any>[]) => void;
487
2333
  type QueryStatusCallback = (status: QueryStatus) => void;
488
- type MutationCallback = (mutations: UpEvent[]) => void;
2334
+ /**
2335
+ * Observer for a query's authority flips: `true` once subscribers hold the
2336
+ * rendered rows of a known membership (a server answer whose bodies are
2337
+ * local, or the durable membership of an earlier session), delivered after
2338
+ * the rows that vouch for it; `false` when it is reset (bucket switch). Knowing the set is
2339
+ * not enough: a `cached` re-seed or a just-applied server set has no rows
2340
+ * painted yet. What the bindings' `isAuthoritative()` mirrors.
2341
+ */
2342
+ type QueryAuthorityCallback = (known: boolean) => void;
2343
+ type MutationCallback = (mutations: MutationEvent[]) => void;
489
2344
  type MutationEventType = 'create' | 'update' | 'delete';
490
2345
  /**
491
2346
  * Represents a mutation event (create, update, delete) to be synchronized.
@@ -494,9 +2349,9 @@ interface MutationEvent {
494
2349
  /** Example: 'create', 'update', or 'delete'. */
495
2350
  type: MutationEventType;
496
2351
  /** unique id of the mutation */
497
- mutation_id: RecordId$1<string>;
2352
+ mutation_id: RecordId<string>;
498
2353
  /** The ID of the record being mutated. */
499
- record_id: RecordId$1<string>;
2354
+ record_id: RecordId<string>;
500
2355
  /** The data payload for create/update operations. */
501
2356
  data?: any;
502
2357
  /** The full record data (optional context). */
@@ -543,6 +2398,37 @@ interface DebounceOptions {
543
2398
  key?: 'recordId' | 'recordId_x_fields';
544
2399
  /** The debounce delay in milliseconds. */
545
2400
  delay?: number;
2401
+ /**
2402
+ * Keep the pending patch across a reload or a closed tab. Default `true`.
2403
+ *
2404
+ * Every call also writes the merged patch to `_00_pending_writes`, in the
2405
+ * same local transaction as the row itself. When the page is hidden (tab
2406
+ * switch, reload, close, app sent to the background) every pending patch is
2407
+ * moved into the outbox and pushed at once instead of waiting out `delay`.
2408
+ * A page that dies before that finishes leaves the patch in the store, and
2409
+ * the next boot moves it into the outbox.
2410
+ *
2411
+ * `false` keeps the patch in memory only, so whatever is still inside its
2412
+ * delay is lost on reload. Meant for throwaway state like a cursor position.
2413
+ */
2414
+ flushOnHide?: boolean;
2415
+ }
2416
+ /** A query a channel takes its filter from: a builder or a built query, on a `-- @channel` table. */
2417
+ type ChannelQuery<S extends SchemaStructure, T extends TableNames<S>> = QueryBuilder<S, T, any, any, any> | FinalQuery<S, T, any, any, any, any>;
2418
+ /**
2419
+ * An open peer to peer channel (`client.channel(queries, peers)`): its
2420
+ * state, plus writes that go to ITS peers only (when the row matches its
2421
+ * filter). Plain `create` / `update` / `delete` reach the peers of every
2422
+ * open channel whose filter the row matches.
2423
+ */
2424
+ interface Sp00kyChannel<S extends SchemaStructure, T extends string> extends Omit<ChannelHandle, 'tables' | 'setScopes'> {
2425
+ /** The tables its queries read. */
2426
+ tables(): ReadonlyArray<T>;
2427
+ /** Replace the queries (their filters changed). */
2428
+ setQueries(queries: ChannelQuery<S, T & TableNames<S>> | ReadonlyArray<ChannelQuery<S, T & TableNames<S>>>): void;
2429
+ update<N extends T>(table: N, id: string, data: Partial<TableModel<GetTable<S, N & TableNames<S>>>>, options?: UpdateOptions): Promise<Partial<TableModel<GetTable<S, N & TableNames<S>>>>>;
2430
+ create<N extends T>(id: `${N}:${string}`, data: Partial<TableModel<GetTable<S, N & TableNames<S>>>>): Promise<Partial<TableModel<GetTable<S, N & TableNames<S>>>>>;
2431
+ delete<N extends T>(table: N, id: string): Promise<void>;
546
2432
  }
547
2433
  //#endregion
548
- export { SyncHealthStatus as A, RunOptions as C, StoreType as D, Sp00kyQueryResultPromise as E, SyncEventSystem as F, EventDefinition as I, EventSystem as L, UpdateOptions as M, UpEvent as N, SyncHealth as O, Logger$1 as P, RegistrationTimings as S, Sp00kyQueryResult as T, QueryTimeToLive as _, MutationCallback as a, RecordVersionArray as b, PersistenceClient as c, QueryConfig as d, QueryConfigRecord as f, QueryStatusCallback as g, QueryStatus as h, MATERIALIZATION_SAMPLE_WINDOW as i, TimingPhase as j, SyncHealthConfig as k, PhaseStat as l, QueryState as m, EventSubscriptionOptions as n, MutationEvent as o, QueryHash as p, Level$1 as r, MutationEventType as s, DebounceOptions as t, PinoTransmit as u, QueryTimings as v, Sp00kyConfig as w, RecordVersionDiff as x, QueryUpdateCallback as y };
2434
+ export { WebPushInfo as $, ChannelScope as $t, RecordVersionArray as A, AuthEventTypeMap as At, StorageHealthStatus as B, ImpersonationTimerHost as Bt, QueryState as C, AuthService as Ct, QueryTimings as D, SignOutContext as Dt, QueryTimeToLive as E, SIGN_OUT_HOOK_TIMEOUT_MS as Et, Sp00kyChannel as F, SealedQuery as Ft, TimingPhase as G, decodeTokenClaims as Gt, SyncHealth as H, ORIGIN_TOKEN_KEY as Ht, Sp00kyConfig as I, EventDefinition as It, PushDeviceKind as J, sameImpersonation as Jt, UpdateOptions as K, impersonationFromToken as Kt, Sp00kyQueryResult as L, EventSystem as Lt, RegistrationTimings as M, createAuthEventSystem as Mt, RunOptions as N, RemoteDatabaseService as Nt, QueryUpdateCallback as O, SignOutHook as Ot, ServerViewMeta as P, LocalStore as Pt, WebPushErrorCode as Q, ChannelOp as Qt, Sp00kyQueryResultPromise as R, IMPERSONATION_ACCESS as Rt, QueryHash as S, ActiveImpersonation as St, QueryStatusCallback as T, REFUSAL_RECHECK_MIN_MS as Tt, SyncHealthConfig as U, SESSION_POLL_MS as Ut, StoreType as V, ImpersonationTimers as Vt, SyncHealthStatus as W, TokenClaims as Wt, WebPushDevice as X, ChannelHandle as Xt, WebPushConfig as Y, ChannelAcceptRule as Yt, WebPushError as Z, ChannelMessage as Zt, PreloadOptions as _, PushPayload as _t, EventSubscriptionOptions as a, PeerRef as an, WebPushSyncOptions as at, QueryConfig as b, WebPushClientMessage as bt, LocalWorkers as c, unusedArgs as cn, WebPushUnsupportedReason as ct, MutationCallback as d, BridgeSignOutMessage as dt, ChannelState as en, WebPushMessage as et, MutationEvent as f, BridgeTokenMessage as ft, PinoTransmit as g, PushOp as gt, PhaseStat as h, PushNotificationAction as ht, EdgeDelta as i, ChannelsConfig as in, WebPushSupport as it, RecordVersionDiff as j, AuthEventTypes as jt, ReconnectConfig as k, AuthEventSystem as kt, MATERIALIZATION_SAMPLE_WINDOW as l, LogTap as ln, WebPushUpdateOptions as lt, PersistenceClient as m, PushNotification as mt, ConnectionState as n, ChannelTransport as nn, WebPushModule as nt, InlineRow as o, TransportHooks as on, WebPushSyncStatus as ot, MutationEventType as p, PUSH_PAYLOAD_VERSION as pt, PUSH_ENDPOINT_KEY as q, renewDelayMs as qt, DebounceOptions as r, ChannelTransportFactory as rn, WebPushSubscribeOptions as rt, Level$1 as s, matchesWhere as sn, WebPushUnsubscribeOptions as st, ChannelQuery as t, ChannelStatus as tn, WebPushMessageInput as tt, MembershipOutcome as u, Logger$1 as un, detectWebPushSupport as ut, PreloadRefresh as v, PushPayloadKind as vt, QueryStatus as w, ImpersonationCandidate as wt, QueryConfigRecord as x, isPushPayload as xt, QueryAuthorityCallback as y, PushUrgency as yt, StorageHealth as z, ImpersonationInfo as zt };