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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -0,0 +1,875 @@
1
+ import type { Surreal } from 'surrealdb';
2
+ import type {
3
+ BackendNames,
4
+ BackendRoutes,
5
+ FinalQuery,
6
+ GetTable,
7
+ InnerQuery,
8
+ QueryOptions,
9
+ RoutePayload,
10
+ SchemaStructure,
11
+ TableModel,
12
+ TableNames,
13
+ BucketNames,
14
+ ChannelPeer,
15
+ ChannelTableNames,
16
+ } from '@spooky-sync/query-builder';
17
+ import type { ChannelQuery } from '../types';
18
+ import { QueryBuilder } from '@spooky-sync/query-builder';
19
+ import type {
20
+ PreloadOptions,
21
+ QueryAuthorityCallback,
22
+ QueryStatusCallback,
23
+ QueryTimeToLive,
24
+ RunOptions,
25
+ Sp00kyChannel,
26
+ Sp00kyConfig,
27
+ Sp00kyQueryResultPromise,
28
+ StorageHealth,
29
+ SyncHealth,
30
+ UpdateOptions,
31
+ } from '../types';
32
+ import type { TabRole } from '../services/tabs/protocol';
33
+ import { StreamProcessorService } from '../services/stream-processor/index';
34
+ import type { StreamUpdateReceiver } from '../services/stream-processor/index';
35
+ import { AuthService } from '../modules/auth/index';
36
+ import { CrdtField } from '../modules/crdt/index';
37
+ import { FeatureFlagModule, FeatureFlagHandle } from '../modules/feature-flag/index';
38
+ import type { FeatureFlagOptions, FeatureFlagOverride } from '../modules/feature-flag/index';
39
+ import { AppReleaseModule, AppReleaseHandle } from '../modules/app-release/index';
40
+ import type { AppReleaseOptions } from '../modules/app-release/index';
41
+ import { WebPushModule } from '../modules/web-push/index';
42
+ import { ChannelManager, type ChannelHandle, type ChannelState, type ChannelTransportFactory } from '../modules/channel/index';
43
+ import { surrealSignal, webrtcTransport } from '../modules/channel/webrtc';
44
+ import { roomLink, splitTransport } from '../modules/channel/room';
45
+ import { hubTransport } from '../modules/channel/hub';
46
+ import { DevToolsService } from '../modules/devtools/index';
47
+ import type { DevToolsQuerySource } from '../modules/devtools/index';
48
+ import { parseQueryParams, generateId } from '../utils/index';
49
+ import type { OutEvent, RuntimeEvent } from '../kernel/events';
50
+ import type { ClientState } from '../state/client-state';
51
+ import * as R from '../state/reducers';
52
+ import { pendingMutationCount, fetchingQueryCount, phaseTimings, toQueryState } from '../state/selectors';
53
+ import { defaultEnv, type SagaEnv } from '../query/env';
54
+ import { registerLocal, type RegisterInput } from '../query/register.saga';
55
+ import { evictQuery } from '../query/lifecycle.saga';
56
+ import { peerCreate, peerDelete, readRow, write } from '../mutation/write.saga';
57
+ import { discardFailed, listFailed, retryFailed } from '../mutation/tray.saga';
58
+ import type { FailedMutationRow } from '../mutation/rows';
59
+ import { buildJobRecord } from '../mutation/jobs';
60
+ import { boot } from '../boot/boot.saga';
61
+ import { preload } from '../boot/preload.saga';
62
+ import { DEGRADE_AFTER_FAILURES, OUTBOX_BATCH_SIZE, PUSH_TIMEOUT_MS } from '../kernel/constants';
63
+ import { Runtime } from './runtime';
64
+ import { createAdapters, createServices, createTabsCoordinator, readBootBucketHint, type ServiceHost, type Services } from './services';
65
+ import { ANON_USER_ID } from '../modules/ref-tables';
66
+ import { paintKeyOf } from '../query/materialize';
67
+ import { BucketHandle, bucketSettings } from './bucket-handle';
68
+ import { ImpersonationBanner } from '../modules/auth/impersonation-banner';
69
+ import type { LeaderSyncHub, SyncForwarder } from '../services/tabs/coordinator';
70
+
71
+ const UNKNOWN_STORAGE_HEALTH: StorageHealth = Object.freeze({ status: 'unknown', fallback: false });
72
+ /** Longest SurrealQL a statement log line shows as its message. */
73
+ const STATEMENT_MSG_MAX = 160;
74
+
75
+ export interface Sp00kyClientDeps<S extends SchemaStructure> {
76
+ services?: Services<S>;
77
+ runtime?: Runtime;
78
+ env?: Partial<SagaEnv>;
79
+ }
80
+
81
+ /**
82
+ * The public client. Every method is a thin translation into a saga run, a
83
+ * state read, or a subscription on the runtime; the engine's behaviour lives
84
+ * in the sagas.
85
+ */
86
+ /** A promise and the two ways to settle it; settling twice does nothing. */
87
+ function deferred(): { promise: Promise<void>; resolve: () => void; reject: (error: unknown) => void } {
88
+ let resolve!: () => void;
89
+ let reject!: (error: unknown) => void;
90
+ const promise = new Promise<void>((res, rej) => {
91
+ resolve = res;
92
+ reject = rej;
93
+ });
94
+ return { promise, resolve, reject };
95
+ }
96
+
97
+ export class Sp00kyClient<S extends SchemaStructure> {
98
+ public readonly auth: AuthService<S>;
99
+ public readonly streamProcessor: StreamProcessorService;
100
+ /** Web Push for this browser: subscribe, devices, self-pushes, service worker bridge. */
101
+ public readonly webPush: WebPushModule;
102
+ /** Peer to peer channels of `-- @channel` tables. */
103
+ private readonly channels: ChannelManager;
104
+
105
+ private readonly services: Services<S>;
106
+ private readonly env: SagaEnv;
107
+ private readonly runtime: Runtime;
108
+ private readonly featureFlags: FeatureFlagModule<S>;
109
+ private readonly appReleases: AppReleaseModule<S>;
110
+ /** Teardown for subscriptions the client itself owns. */
111
+ private readonly disposers: Array<() => void> = [];
112
+ /** Assigned in `wireAdapters`, which the constructor always runs. */
113
+ private impersonationBanner!: ImpersonationBanner;
114
+ private readonly devTools: DevToolsService;
115
+ private hub: LeaderSyncHub | null = null;
116
+ private forwarder: SyncForwarder | null = null;
117
+ private detachWindow: (() => void) | null = null;
118
+ private sharedActive = false;
119
+
120
+ constructor(
121
+ private readonly config: Sp00kyConfig<S>,
122
+ deps: Sp00kyClientDeps<S> = {}
123
+ ) {
124
+ this.services = deps.services ?? createServices(config);
125
+ const s = this.services;
126
+ this.env = defaultEnv(config.schema, {
127
+ anonLive: config.enableAnonymousLiveQueries === true,
128
+ remoteTimeoutMs: Math.max(0, config.database.queryTimeoutMs ?? 60_000),
129
+ pushTimeoutMs: config.pushTimeoutMs ?? PUSH_TIMEOUT_MS,
130
+ outboxBatchSize: OUTBOX_BATCH_SIZE,
131
+ degradeAfter: config.syncHealth === false ? 0 : (config.syncHealth?.degradeAfterConsecutiveFailures ?? DEGRADE_AFTER_FAILURES),
132
+ materializeDebounceMs: config.streamDebounceTime ?? 50,
133
+ pollBaseMs: config.refSyncIntervalMs && config.refSyncIntervalMs > 0 ? config.refSyncIntervalMs : 500,
134
+ ...deps.env,
135
+ });
136
+ const host: ServiceHost = {
137
+ dispatch: (event) => void this.runtime.dispatch(event),
138
+ setTabsChannel: ({ hub, forwarder }) => {
139
+ this.hub = hub;
140
+ this.forwarder = forwarder;
141
+ this.sharedActive = hub !== null || forwarder !== null;
142
+ },
143
+ initModules: () => undefined,
144
+ detachWindow: () => this.detachWindow?.(),
145
+ setDetachWindow: (fn) => (this.detachWindow = fn),
146
+ };
147
+ if (!deps.runtime && s.tabs === null && s.tabsUnsupportedReason === undefined) {
148
+ s.tabs = createTabsCoordinator(config, s, host);
149
+ }
150
+ this.runtime =
151
+ deps.runtime ??
152
+ new Runtime({
153
+ env: this.env,
154
+ adapters: createAdapters(config, s, host, () => [this.featureFlags, this.appReleases]),
155
+ logger: s.logger,
156
+ tabId: s.tabId,
157
+ });
158
+ this.auth = s.auth;
159
+ this.streamProcessor = s.streamProcessor;
160
+
161
+ const liveQueryPort = {
162
+ // Feature flags and app releases register here, from boot (which has a
163
+ // session by the time it asks) and from hooks. A hook on a client that
164
+ // is not open yet has no session to register under: it waits, where it
165
+ // used to fail and only be tried again at the next sign-in.
166
+ query: async (table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive) => {
167
+ if (this.runtime.state.sessionId === null) await this.ready.promise;
168
+ return this.runtime.run(registerLocal(this.env, { tableName: table, surql, params, ttl }));
169
+ },
170
+ subscribe: (hash: string, cb: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }) =>
171
+ this.runtime.subscribe(hash, cb, options),
172
+ };
173
+ const remoteRegisterPort = { enqueueDownEvent: () => void this.runtime.dispatch({ type: 'EnsureRegistered' }) };
174
+ // CRDT edit logs ride ordinary queries and the ordinary outbox.
175
+ s.crdt.attach({
176
+ watch: async (table, where, onRows) => {
177
+ const { hash } = await (this.query as any)(table, {}).where(where).build().run();
178
+ const stopRows = this.runtime.subscribe(hash, onRows, { immediate: true });
179
+ let known = false;
180
+ let idle = false;
181
+ let done!: () => void;
182
+ const settled = new Promise<void>((resolve) => (done = resolve));
183
+ const check = () => known && idle && done();
184
+ const stopAuthority = this.runtime.subscribeAuthority(hash, (k) => ((known = k), check()), { immediate: true });
185
+ const stopStatus = this.runtime.subscribeStatus(hash, (st) => ((idle = st === 'idle'), check()), { immediate: true });
186
+ return {
187
+ stop: () => {
188
+ stopRows();
189
+ stopAuthority();
190
+ stopStatus();
191
+ },
192
+ settled,
193
+ };
194
+ },
195
+ create: (id, data) => this.create(id, data),
196
+ });
197
+ this.featureFlags = new FeatureFlagModule<S>({ dataModule: liveQueryPort, sync: remoteRegisterPort, auth: s.auth, logger: s.logger });
198
+ this.appReleases = new AppReleaseModule<S>({ dataModule: liveQueryPort, sync: remoteRegisterPort, auth: s.auth, logger: s.logger });
199
+ this.webPush = new WebPushModule({
200
+ remote: s.remote,
201
+ auth: s.auth,
202
+ persistence: s.persistence,
203
+ logger: s.logger,
204
+ database: config.database,
205
+ connection: s.connectionSupervisor,
206
+ config: config.webPush,
207
+ });
208
+ this.disposers.push(this.webPush.attach());
209
+
210
+ const channelsConfig = config.channels;
211
+ const relay = typeof channelsConfig?.relay === 'string' ? { url: channelsConfig.relay } : channelsConfig?.relay;
212
+ // Between users: a WebRTC link per pair of tabs, signaled through the database.
213
+ const mesh: ChannelTransportFactory = (hooks) =>
214
+ webrtcTransport(hooks, {
215
+ signal: surrealSignal(s.remote, s.connectionSupervisor, s.logger),
216
+ iceServers: channelsConfig?.iceServers,
217
+ logger: s.logger,
218
+ });
219
+ // Between the user's own devices: one link per browser to their room on the relay.
220
+ const room: ChannelTransportFactory | null = relay
221
+ ? (hooks) =>
222
+ hubTransport(hooks, {
223
+ scope: (user) => `${config.database.namespace}/${config.database.database}/${user}`,
224
+ link: (linkHooks) =>
225
+ roomLink(linkHooks, {
226
+ url: relay.url,
227
+ direct: relay.direct,
228
+ token: () => s.remote.getAuthToken(),
229
+ iceServers: channelsConfig?.iceServers,
230
+ logger: s.logger,
231
+ }),
232
+ logger: s.logger,
233
+ })
234
+ : null;
235
+ this.channels = new ChannelManager(config.schema, {
236
+ config: channelsConfig,
237
+ logger: s.logger,
238
+ rows: {
239
+ create: (_table, id, row, ttlMs) => this.runtime.run(peerCreate(this.env, { recordId: id, data: row, ttlMs })),
240
+ delete: (_table, id, ttlMs) => this.runtime.run(peerDelete(this.env, { recordId: id, ttlMs })),
241
+ read: (id) => this.runtime.run(readRow(id)),
242
+ },
243
+ transport: channelsConfig?.transport ?? splitTransport(room, mesh),
244
+ });
245
+ if (this.channels.sharing && !relay && !channelsConfig?.transport) {
246
+ s.logger.warn(
247
+ { Category: 'sp00ky-client::channel' },
248
+ 'channels.share is set without channels.relay: nothing reaches your other devices until a relay address is given'
249
+ );
250
+ }
251
+ if (this.channels.enabled) this.disposers.push(s.auth.subscribe((userId) => this.channels.setUser(userId)));
252
+
253
+ const querySource: DevToolsQuerySource = {
254
+ getActiveQueries: () => [...this.runtime.state.queries.values()].map(toQueryState),
255
+ getQueryById: (id) => {
256
+ const entry = [...this.runtime.state.queries.values()].find((e) => String(e.def.id) === String(id));
257
+ return entry ? toQueryState(entry) : undefined;
258
+ },
259
+ phaseTimings: (q) => {
260
+ const entry = this.runtime.state.queries.get(q.config.id.id as string) ?? [...this.runtime.state.queries.values()].find((e) => String(e.def.id) === String(q.config.id));
261
+ return entry ? phaseTimings(entry) : ({} as never);
262
+ },
263
+ };
264
+ this.devTools = new DevToolsService(s.local, s.remote, s.logger, config.schema, s.auth, querySource);
265
+ this.devTools.setFeatureFlagOverrides(this.featureFlags);
266
+ s.streamProcessor.addReceiver(this.devTools);
267
+ this.devTools.setBlobInfoProvider(() => s.blobs.stats());
268
+ this.devTools.setMutationSource({
269
+ state: () => this.runtime.state,
270
+ listFailed: () => this.listFailedMutations(),
271
+ retryFailed: (id) => this.retryFailedMutation(id),
272
+ discardFailed: (id) => this.discardFailedMutation(id),
273
+ });
274
+ if (s.logTap) this.devTools.setLogTap(s.logTap);
275
+ if (config.sharedTabs) {
276
+ this.devTools.setTabsInfoProvider(() => {
277
+ const c = s.tabs;
278
+ if (!this.sharedActive || !c) return { active: false, reason: s.tabsUnsupportedReason ?? 'fell-back' };
279
+ return {
280
+ active: true,
281
+ role: c.role,
282
+ tabId: c.tabId,
283
+ leadershipId: c.leadershipId,
284
+ leaderTabId: c.role === 'leader' ? c.tabId : c.leaderTabId,
285
+ ...(this.hub ? { followers: this.hub.followerCount, relayedBatches: this.hub.relayedBatches } : {}),
286
+ };
287
+ });
288
+ }
289
+ this.wireAdapters();
290
+ // Unobserved, a failed boot must not also be an unhandled rejection.
291
+ this.ready.promise.catch(() => {});
292
+ // The bucket `boot` is about to open, so the store can paint from it now
293
+ // (`peekQuery`). Alone in the store only: see `LocalStore.expectBucket`.
294
+ if (!s.tabs) s.local.expectBucket?.(readBootBucketHint() ?? ANON_USER_ID);
295
+ }
296
+
297
+ /** Adapter callbacks become runtime events; runtime events reach the legacy services. */
298
+ private wireAdapters(): void {
299
+ const s = this.services;
300
+ const receiver: StreamUpdateReceiver = { onStreamUpdate: (update) => void this.runtime.dispatch({ type: 'StreamUpdate', update }) };
301
+ s.streamProcessor.addReceiver(receiver);
302
+ s.connectionSupervisor.subscribe((state) => void this.runtime.dispatch({ type: 'ConnectionChanged', state }));
303
+ // Changes only. The immediate answer here is always "signed out" (nothing
304
+ // is restored before `init()`), and boot owns the first identity: it opens
305
+ // the bucket the hint names and announces the restored session itself. As
306
+ // a flip, that answer switched to the anon bucket while boot was still
307
+ // opening the user's, so two clients provisioned at once, boot failed, and
308
+ // a persistent store never got past the provider's fallback on reload.
309
+ s.auth.subscribe((userId) => void this.runtime.dispatch({ type: 'AuthFlip', userId }), { immediate: false });
310
+ // Whoever is looking at the page should be able to tell, and leave. The
311
+ // app can restyle this, replace it (`mode: 'custom'`, with a fallback if
312
+ // its own never renders) or take the job over entirely (`mode: 'none'`).
313
+ this.impersonationBanner = new ImpersonationBanner(
314
+ () => s.auth.stopImpersonating(),
315
+ this.config.impersonationBanner
316
+ );
317
+ const banner = this.impersonationBanner;
318
+ this.disposers.push(
319
+ s.auth.subscribeImpersonation((info) => banner.update(info)),
320
+ () => banner.unmount()
321
+ );
322
+ this.runtime.on('tabs:broadcast', (e) => {
323
+ if (e.type !== 'tabs:broadcast') return;
324
+ const msg = e.message as { type: string; records?: unknown[]; mutationId?: string };
325
+ if (this.hub) {
326
+ if (msg.type === 'ingest') this.hub.relayIngest(msg.records as never);
327
+ else this.hub.broadcast(msg as never);
328
+ } else if (this.forwarder) {
329
+ if (msg.type === 'ingest') this.forwarder.ingest(msg.records as never);
330
+ else if (msg.type === 'outbox-changed' && msg.mutationId) this.forwarder.mutationEnqueued(msg.mutationId);
331
+ }
332
+ });
333
+ this.runtime.on('tabs:sendTo', (e) => {
334
+ if (e.type === 'tabs:sendTo' && this.hub) this.hub.sendTo(e.tabId, e.message as never);
335
+ });
336
+ this.runtime.on('*', (e) => this.forwardToDevTools(e));
337
+ // One debug line per finished statement, for both stores and every engine
338
+ // (the SQLite engine logs none of its own). Guarded: this is the hottest
339
+ // path there is, and at the default `info` the line is never written.
340
+ // The message is the SurrealQL itself, so the Logs tab reads like a query
341
+ // trail; a long statement is cut there and kept whole in `query`.
342
+ const logStatement = (store: 'local' | 'remote') => (event: any) => {
343
+ if (!s.logger.isLevelEnabled('debug')) return;
344
+ const q = event.payload ?? {};
345
+ const sql = String(q.query ?? '').replace(/\s+/g, ' ').trim();
346
+ const cut = sql.length > STATEMENT_MSG_MAX;
347
+ s.logger.debug(
348
+ {
349
+ store,
350
+ ...(cut ? { query: q.query } : {}),
351
+ vars: q.vars,
352
+ ms: Math.round((q.duration ?? 0) * 10) / 10,
353
+ ok: q.success !== false,
354
+ error: q.error,
355
+ Category: `sp00ky-client::${store}`,
356
+ },
357
+ cut ? `${sql.slice(0, STATEMENT_MSG_MAX)}…` : sql
358
+ );
359
+ };
360
+ s.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', logStatement('local'));
361
+ s.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', logStatement('remote'));
362
+ }
363
+
364
+ /** Runtime events the DevTools panel follows; query transitions also go to the log. */
365
+ private forwardToDevTools(e: OutEvent): void {
366
+ const log = this.services.logger;
367
+ switch (e.type) {
368
+ case 'query:status':
369
+ log.debug({ hash: e.hash, status: e.status, Category: 'sp00ky-client::query' }, 'Query status');
370
+ this.devTools.onStateChanged();
371
+ break;
372
+ case 'query:authority':
373
+ log.debug({ hash: e.hash, known: e.known, Category: 'sp00ky-client::query' }, e.known ? 'Query membership known' : 'Query membership unknown');
374
+ this.devTools.onStateChanged();
375
+ break;
376
+ case 'query:view-lost':
377
+ log.info({ hash: e.hash, Category: 'sp00ky-client::query' }, 'Query view lost on the server; re-registering');
378
+ this.devTools.onStateChanged();
379
+ break;
380
+ case 'mutation:event':
381
+ this.devTools.onMutation([e.event]);
382
+ break;
383
+ case 'mutation:settled':
384
+ this.devTools.onMutationOutcome({ mutationId: e.mutationId, recordId: e.recordId, eventType: e.eventType, status: 'synced' });
385
+ break;
386
+ case 'mutation:rolled-back':
387
+ this.devTools.onMutationOutcome({ mutationId: e.mutationId, recordId: e.recordId, eventType: e.eventType, status: 'rolled-back', error: e.error });
388
+ break;
389
+ case 'tray:changed':
390
+ case 'health:changed':
391
+ case 'activity:changed':
392
+ this.devTools.onStateChanged();
393
+ break;
394
+ default:
395
+ break;
396
+ }
397
+ }
398
+
399
+ // ---- lifecycle ---------------------------------------------------------------
400
+
401
+ /** Settled by `init`: what a call made before the client is open waits on. */
402
+ private ready = deferred();
403
+
404
+ async init(): Promise<void> {
405
+ try {
406
+ await this.runtime.run(boot(this.env, { sharedTabs: this.services.tabs !== null }));
407
+ this.ready.resolve();
408
+ } catch (error) {
409
+ this.ready.reject(error);
410
+ throw error;
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Resolves once `init()` has finished, and rejects with its error if it
416
+ * fails. A page that renders before the client is open (a provider's
417
+ * `eager` mode) awaits this for whatever must not run earlier.
418
+ */
419
+ whenReady(): Promise<void> {
420
+ return this.ready.promise;
421
+ }
422
+
423
+ /**
424
+ * Queries and writes need the open client: its store, its session. Asked
425
+ * for earlier, they wait for `init()` to finish, so a component may register
426
+ * a query on its first render and need not know whether the client is open.
427
+ */
428
+ private opened(): Promise<void> | undefined {
429
+ return this.runtime.state.localReady ? undefined : this.ready.promise;
430
+ }
431
+
432
+ async close(): Promise<void> {
433
+ this.ready.reject(new Error('Sp00kyClient: closed before it was ready'));
434
+ const s = this.services;
435
+ s.connectionSupervisor.dispose();
436
+ for (const dispose of this.disposers.splice(0)) dispose();
437
+ this.channels.close();
438
+ this.runtime.dispose();
439
+ await this.featureFlags.closeAll();
440
+ await this.appReleases.closeAll();
441
+ s.crdt.closeAll();
442
+ s.crdt.dispose();
443
+ await s.blobs.close().catch(() => {});
444
+ await s.streamProcessor.checkpoint('close').catch(() => {});
445
+ if (s.tabs) await s.tabs.stop();
446
+ this.detachWindow?.();
447
+ this.detachWindow = null;
448
+ await s.local.close();
449
+ await s.remote.close();
450
+ s.streamProcessor.dispose();
451
+ }
452
+
453
+ isLocalReady(): boolean {
454
+ return this.runtime.state.localReady;
455
+ }
456
+
457
+ // ---- queries -----------------------------------------------------------------
458
+
459
+ query<Table extends TableNames<S>>(
460
+ table: Table,
461
+ options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
462
+ ttl: QueryTimeToLive = '10m'
463
+ ): QueryBuilder<S, Table, Sp00kyQueryResultPromise> {
464
+ return new QueryBuilder<S, Table, Sp00kyQueryResultPromise>(
465
+ this.config.schema,
466
+ table,
467
+ async (q) => ({ hash: await this.initQuery(table, q, ttl) }),
468
+ options
469
+ );
470
+ }
471
+
472
+ private registerInput(table: string, q: InnerQuery<any, any, any>, ttl: QueryTimeToLive): RegisterInput {
473
+ const tableSchema = this.config.schema.tables.find((t) => t.name === table);
474
+ if (!tableSchema) throw new Error(`Table ${table} not found`);
475
+ return {
476
+ tableName: table,
477
+ surql: q.selectQuery.query,
478
+ params: parseQueryParams(tableSchema.columns, q.selectQuery.vars ?? {}),
479
+ ttl,
480
+ plan: q.selectQuery.plan,
481
+ };
482
+ }
483
+
484
+ private async initQuery(table: string, q: InnerQuery<any, any, any>, ttl: QueryTimeToLive): Promise<string> {
485
+ await this.opened();
486
+ return this.runtime.run(registerLocal(this.env, this.registerInput(table, q, ttl)));
487
+ }
488
+
489
+ /**
490
+ * The rows this query rendered the last time this browser had the app open,
491
+ * handed back at once and with no need for `init()` to have run: something
492
+ * for a component to render on its first pass, where it would have rendered
493
+ * an empty list. `null` when the local store keeps no such copy (only
494
+ * `localEngine: 'rows'` with its paint cache does, and not with shared
495
+ * tabs), or has none for this query.
496
+ *
497
+ * They are rows to paint from, not a result. The query still has to be run
498
+ * and subscribed to; what that delivers is the answer, and it replaces these
499
+ * rows when it differs.
500
+ */
501
+ peekQuery(finalQuery: FinalQuery<S, any, any, any, any, any>): Record<string, any>[] | null {
502
+ try {
503
+ const q = finalQuery.innerQuery;
504
+ const input = this.registerInput(q.tableName, q, '10m');
505
+ if (!input.plan) return null;
506
+ // The membership render's rows only: a cold scan's are filtered by state the closed client does not have.
507
+ return this.services.local.peekSelect?.(input.plan, input.params, { paintKey: paintKeyOf(input, []) }) ?? null;
508
+ } catch {
509
+ return null;
510
+ }
511
+ }
512
+
513
+ /**
514
+ * The raw remote escape hatches bypass the query builder, so their shapes
515
+ * can never be on the server's query allowlist. When the generated schema
516
+ * says the allowlist is on, refuse them unless the app opted in explicitly.
517
+ */
518
+ private assertRawRemoteAllowed(method: string): void {
519
+ const mode = this.config.schema.policy?.queryAllowlist;
520
+ if ((mode === 'warn' || mode === 'enforce') && !this.config.allowRawRemote) {
521
+ throw new Error(
522
+ `sp00ky: ${method} is disabled because sync.queryAllowlist is on for this schema; pass allowRawRemote: true in the client config to opt in`
523
+ );
524
+ }
525
+ }
526
+
527
+ async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string> {
528
+ this.assertRawRemoteAllowed('queryRaw');
529
+ await this.opened();
530
+ const tableName = sql.split('FROM ')[1]?.split(' ')[0] ?? '';
531
+ return this.runtime.run(registerLocal(this.env, { tableName, surql: sql, params, ttl }));
532
+ }
533
+
534
+ /**
535
+ * Preload = register a query nobody subscribes to. Resolved before on this
536
+ * device: returns at once. Never resolved: resolves when the server's
537
+ * membership and every body are local. `signal` aborts the wait.
538
+ */
539
+ async preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void> {
540
+ const q = finalQuery.innerQuery;
541
+ await this.opened();
542
+ await this.runtime.run(preload(this.env, this.registerInput(q.tableName, q, '10m')), { signal: options?.signal });
543
+ }
544
+
545
+ async subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }): Promise<() => void> {
546
+ if (!this.channels.enabled) return this.runtime.subscribe(queryHash, callback, options);
547
+ // Channel values (peer updates, ephemeral fields) are folded into what
548
+ // subscribers see, never into the store.
549
+ // With `channels.share`, the user's other devices are told what this
550
+ // query can show, and only send what it has a use for.
551
+ const def = this.channels.sharing ? this.runtime.state.queries.get(queryHash)?.def : undefined;
552
+ const tap = this.channels.tap(callback, def ? this.channels.interestOf(def.plan, def.params) : null);
553
+ const stop = this.runtime.subscribe(queryHash, tap.feed, options);
554
+ return () => {
555
+ stop();
556
+ tap.stop();
557
+ };
558
+ }
559
+
560
+ /**
561
+ * Open a peer to peer channel to `peers` (your own id is skipped; a
562
+ * connection forms only when both sides list each other) for the rows
563
+ * `queries` match, each a query on a `-- @channel` table. Only its `where`
564
+ * counts, evaluated against each row; the query is never registered. Writes
565
+ * to matching rows (plain or the channel's own) reach the peers. Close it
566
+ * when done.
567
+ */
568
+ channel<T extends ChannelTableNames<S>>(
569
+ queries: ChannelQuery<S, T> | ReadonlyArray<ChannelQuery<S, T>>,
570
+ peers: Iterable<ChannelPeer>
571
+ ): Sp00kyChannel<S, T> {
572
+ const handle = this.channels.open(this.channelScopes(queries), peers);
573
+ const scoped = (table: string) => {
574
+ this.channels.assertCarries(handle, table);
575
+ return handle;
576
+ };
577
+ return {
578
+ tables: handle.tables as () => ReadonlyArray<T>,
579
+ state: handle.state,
580
+ subscribe: handle.subscribe,
581
+ setPeers: handle.setPeers,
582
+ setQueries: (next) => handle.setScopes(this.channelScopes(next)),
583
+ close: handle.close,
584
+ // Like every write, these wait for a client that is not open yet. A
585
+ // table the channel does not carry is still refused at once, in the call.
586
+ update: ((table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) => {
587
+ const scope = scoped(table);
588
+ return Promise.resolve(this.opened()).then(() => this.writeUpdate(table, id, data, options, scope));
589
+ }) as never,
590
+ create: ((id: string, data: Record<string, unknown>) => {
591
+ const scope = scoped(id.slice(0, id.indexOf(':')));
592
+ return Promise.resolve(this.opened()).then(() => this.writeCreate(id, data, scope));
593
+ }) as never,
594
+ delete: (table, id) => {
595
+ const scope = scoped(table);
596
+ return Promise.resolve(this.opened()).then(() => this.writeDelete(table, id, scope));
597
+ },
598
+ };
599
+ }
600
+
601
+ /**
602
+ * The link to this user's other devices (`channels.share`): `connected`
603
+ * with the user's id in `peers` while at least one other tab of theirs, in
604
+ * another browser, is in the room. `idle` when nothing is shared or nobody
605
+ * is signed in.
606
+ */
607
+ shareState(): ChannelState {
608
+ return this.channels.ownState();
609
+ }
610
+
611
+ /** Called at once with `shareState()`, then on every change. */
612
+ subscribeShareState(callback: (state: ChannelState) => void): () => void {
613
+ return this.channels.subscribeOwn(callback);
614
+ }
615
+
616
+ private channelScopes(queries: ChannelQuery<S, any> | ReadonlyArray<ChannelQuery<S, any>>) {
617
+ const list = (Array.isArray(queries) ? queries : [queries]) as ReadonlyArray<ChannelQuery<S, any>>;
618
+ return list.map((q) => {
619
+ const final = 'build' in q && typeof q.build === 'function' ? q.build() : (q as FinalQuery<S, any, any, any, any, any>);
620
+ const plan = final.innerQuery?.selectQuery?.plan;
621
+ if (!plan) throw new Error('channel(): pass a query, e.g. db.query(\'message\').where({ conversation })');
622
+ return this.channels.scope(plan, { isOne: final.isOne, ignoreUnused: final.ignoresUnusedArgs });
623
+ });
624
+ }
625
+
626
+ deregisterQuery(queryHash: string): void {
627
+ const entry = this.runtime.state.queries.get(queryHash);
628
+ if (!entry || entry.subscribers > 0) return;
629
+ void this.runtime.run(evictQuery(queryHash), { lane: { kind: 'serial', key: `mat:${queryHash}` } });
630
+ }
631
+
632
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: { immediate?: boolean }): () => void {
633
+ return this.runtime.subscribeStatus(queryHash, callback, options);
634
+ }
635
+
636
+ subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: { immediate?: boolean }): () => void {
637
+ return this.runtime.subscribeAuthority(queryHash, callback, options);
638
+ }
639
+
640
+ reportFrontendTiming(queryHash: string, ms: number): void {
641
+ if (Number.isFinite(ms)) this.runtime.update(R.recordPhase(queryHash, 'frontend', ms));
642
+ }
643
+
644
+ // ---- mutations ---------------------------------------------------------------
645
+
646
+ async create<T extends Record<string, unknown>>(id: string, data: T): Promise<T> {
647
+ await this.opened();
648
+ return (await this.writeCreate(id, data)) as T;
649
+ }
650
+
651
+ async update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T> {
652
+ await this.opened();
653
+ return (await this.writeUpdate(table, id, data as Record<string, unknown>, options)) as T;
654
+ }
655
+
656
+ async delete(table: string, id: string): Promise<void> {
657
+ await this.opened();
658
+ await this.writeDelete(table, id);
659
+ }
660
+
661
+ // Peers go first in all three: the local write costs a transaction they need
662
+ // not wait for. `@ephemeral` fields never reach the database.
663
+
664
+ private async writeCreate(id: string, data: Record<string, unknown>, scope?: ChannelHandle): Promise<Record<string, unknown>> {
665
+ const table = id.slice(0, id.indexOf(':'));
666
+ const { persistent, ephemeral } = this.channels.split(table, data);
667
+ this.channels.localCreate(table, id, data, scope);
668
+ const out = await this.runtime.run(write(this.env, { kind: 'create', recordId: id, data: persistent }));
669
+ return { ...(out.record ?? persistent), ...(ephemeral ?? {}) };
670
+ }
671
+
672
+ private async writeUpdate(
673
+ table: string,
674
+ id: string,
675
+ data: Record<string, unknown>,
676
+ options?: UpdateOptions,
677
+ scope?: ChannelHandle
678
+ ): Promise<Record<string, unknown>> {
679
+ const tableName = table || id.slice(0, id.indexOf(':'));
680
+ const { persistent, ephemeral } = this.channels.split(tableName, data);
681
+ this.channels.local(tableName, id, persistent, ephemeral, scope);
682
+ if (ephemeral && Object.keys(persistent).length === 0) return data;
683
+ const out = await this.runtime.run(write(this.env, { kind: 'update', recordId: id, data: persistent, options }));
684
+ return { ...(out.record ?? persistent), ...(ephemeral ?? {}) };
685
+ }
686
+
687
+ private async writeDelete(table: string, id: string, scope?: ChannelHandle): Promise<void> {
688
+ // Awaited: the filter is checked against the row, which the delete removes.
689
+ await this.channels.localDelete(table || id.slice(0, id.indexOf(':')), id, scope);
690
+ await this.runtime.run(write(this.env, { kind: 'delete', recordId: id }));
691
+ }
692
+
693
+ async run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void> {
694
+ const { tableName, record } = buildJobRecord(this.config.schema, String(backend), String(path), payload as Record<string, unknown>, options);
695
+ await this.create(`${tableName}:${generateId()}`, record);
696
+ }
697
+
698
+ // ---- failed-writes tray -------------------------------------------------------
699
+
700
+ get failedMutationCount(): number {
701
+ return this.runtime.state.failedCount;
702
+ }
703
+
704
+ subscribeToFailedMutations(cb: (count: number) => void): () => void {
705
+ cb(this.runtime.state.failedCount);
706
+ return this.runtime.on('tray:changed', (e) => {
707
+ if (e.type === 'tray:changed') cb(e.count);
708
+ });
709
+ }
710
+
711
+ listFailedMutations(): Promise<FailedMutationRow[]> {
712
+ return this.runtime.run(listFailed());
713
+ }
714
+
715
+ async retryFailedMutation(mutationId: string): Promise<boolean> {
716
+ return this.runtime.run(retryFailed(this.env, mutationId), { lane: { kind: 'serial', key: 'tray' } });
717
+ }
718
+
719
+ async discardFailedMutation(mutationId: string): Promise<boolean> {
720
+ return this.runtime.run(discardFailed(mutationId), { lane: { kind: 'serial', key: 'tray' } });
721
+ }
722
+
723
+ // ---- observability -----------------------------------------------------------
724
+
725
+ get tabRole(): TabRole | null {
726
+ return this.sharedActive && this.services.tabs ? this.services.tabs.role : null;
727
+ }
728
+
729
+ get remoteClient(): Surreal {
730
+ return this.services.remote.getClient();
731
+ }
732
+
733
+ get localClient(): unknown {
734
+ return this.services.local.getClient();
735
+ }
736
+
737
+ get pendingMutationCount(): number {
738
+ return pendingMutationCount(this.runtime.state);
739
+ }
740
+
741
+ /** Kept for the e2e suite; the saga core has no LIVE retry ladder. */
742
+ get liveRetryCount(): number {
743
+ return 0;
744
+ }
745
+
746
+ subscribeToPendingMutations(cb: (count: number) => void): () => void {
747
+ cb(this.pendingMutationCount);
748
+ return this.runtime.on('activity:changed', (e) => {
749
+ if (e.type === 'activity:changed') cb(e.pending);
750
+ });
751
+ }
752
+
753
+ get fetchingQueryCount(): number {
754
+ return fetchingQueryCount(this.runtime.state);
755
+ }
756
+
757
+ subscribeToFetchActivity(cb: (fetching: number) => void): () => void {
758
+ cb(this.fetchingQueryCount);
759
+ return this.runtime.on('activity:changed', (e) => {
760
+ if (e.type === 'activity:changed') cb(e.fetching);
761
+ });
762
+ }
763
+
764
+ get syncHealth(): SyncHealth {
765
+ return this.runtime.state.sync.health;
766
+ }
767
+
768
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {
769
+ cb(this.syncHealth);
770
+ return this.runtime.on('health:changed', (e) => {
771
+ if (e.type === 'health:changed') cb(e.health);
772
+ });
773
+ }
774
+
775
+ get storageHealth(): StorageHealth {
776
+ return this.services.local.storageHealth ?? UNKNOWN_STORAGE_HEALTH;
777
+ }
778
+
779
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void {
780
+ if (this.services.local.subscribeToStorageHealth) return this.services.local.subscribeToStorageHealth(cb);
781
+ cb(UNKNOWN_STORAGE_HEALTH);
782
+ return () => {};
783
+ }
784
+
785
+ /** The engine state, read-only. For tests and DevTools. */
786
+ get state(): ClientState {
787
+ return this.runtime.state;
788
+ }
789
+
790
+ /** Feed an event into the engine. For adapters, tests and DevTools. */
791
+ dispatch(event: RuntimeEvent): Promise<void> {
792
+ return this.runtime.dispatch(event);
793
+ }
794
+
795
+ // ---- auth / remote / crdt / flags / buckets ------------------------------------
796
+
797
+ authenticate(token: string) {
798
+ this.services.remote.setAuthToken(token);
799
+ return this.services.remote.getClient().authenticate(token);
800
+ }
801
+
802
+ deauthenticate() {
803
+ return this.services.remote.getClient().invalidate();
804
+ }
805
+
806
+ async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
807
+ this.assertRawRemoteAllowed('useRemote');
808
+ return fn(this.services.remote.getClient());
809
+ }
810
+
811
+ async remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T> {
812
+ this.assertRawRemoteAllowed('remoteQuery');
813
+ return this.services.remote.query<T>(sql, vars);
814
+ }
815
+
816
+ /**
817
+ * Tell the client that the app's own impersonation banner is on screen.
818
+ * Only meaningful with `impersonationBanner: { mode: 'custom' }`, where it
819
+ * cancels the fallback that would otherwise show the built-in banner. Call
820
+ * it while the custom banner is rendered (the Solid `useImpersonation`
821
+ * hook does it for you with `rendersBanner: true`).
822
+ */
823
+ acknowledgeImpersonationBanner(): void {
824
+ this.impersonationBanner.acknowledge();
825
+ }
826
+
827
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle {
828
+ return this.featureFlags.feature(key, options);
829
+ }
830
+
831
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void {
832
+ this.featureFlags.setLocalOverride(key, variant, payload);
833
+ }
834
+
835
+ clearFeatureOverrides(): void {
836
+ this.featureFlags.clearLocalOverrides();
837
+ }
838
+
839
+ getFeatureOverrides(): Record<string, FeatureFlagOverride> {
840
+ return this.featureFlags.getLocalOverrides();
841
+ }
842
+
843
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle {
844
+ return this.appReleases.release(app, options);
845
+ }
846
+
847
+ /** Open a `@crdt` field for editing. `draft` (from {@link createCrdtDraft})
848
+ * hands over edits made before the record existed. */
849
+ async openCrdtField(table: string, recordId: string, field: string, draft?: CrdtField): Promise<CrdtField> {
850
+ // Opening reads this device's unsent edits from the store: it has to be open.
851
+ await this.opened();
852
+ return this.services.crdt.open(table, recordId, field, draft);
853
+ }
854
+
855
+ /** A detached `@crdt` document for a record not created yet; see
856
+ * {@link openCrdtField}. */
857
+ async createCrdtDraft(table: string, field: string): Promise<CrdtField> {
858
+ return this.services.crdt.createDraft(table, field);
859
+ }
860
+
861
+ /** Close a `@crdt` field. The last close resolves once its unsent edits
862
+ * are queued in the outbox; offline, once they are saved on the device. */
863
+ closeCrdtField(table: string, recordId: string, field: string): Promise<void> {
864
+ return this.services.crdt.close(table, recordId, field);
865
+ }
866
+
867
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle {
868
+ return new BucketHandle(name, this.services.remote, this.services.blobs, bucketSettings(this.config, name, this.services.logger), () => this.opened());
869
+ }
870
+
871
+ getBlobCacheStats() {
872
+ return this.services.blobs.stats();
873
+ }
874
+ }
875
+