@spooky-sync/core 0.0.1-canary.32 → 0.0.1-canary.320

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