@spooky-sync/core 0.0.1-canary.15 → 0.0.1-canary.151

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 (101) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +1192 -372
  3. package/dist/index.js +5772 -1270
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/sqlite-plan-sql.js +194 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +202 -0
  9. package/dist/types.d.ts +755 -0
  10. package/package.json +40 -8
  11. package/skills/sp00ky-core/SKILL.md +258 -0
  12. package/skills/sp00ky-core/references/auth.md +98 -0
  13. package/skills/sp00ky-core/references/config.md +76 -0
  14. package/src/build-globals.d.ts +12 -0
  15. package/src/events/events.test.ts +2 -1
  16. package/src/events/index.ts +3 -0
  17. package/src/index.ts +16 -2
  18. package/src/modules/app-release/index.test.ts +125 -0
  19. package/src/modules/app-release/index.ts +201 -0
  20. package/src/modules/auth/events/index.ts +2 -1
  21. package/src/modules/auth/index.ts +59 -20
  22. package/src/modules/cache/index.ts +77 -32
  23. package/src/modules/cache/types.ts +2 -2
  24. package/src/modules/crdt/crdt-field.ts +294 -0
  25. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  26. package/src/modules/crdt/index.ts +361 -0
  27. package/src/modules/crdt/loro-loader.ts +25 -0
  28. package/src/modules/data/data.hydration.test.ts +142 -0
  29. package/src/modules/data/data.rebind.test.ts +147 -0
  30. package/src/modules/data/data.run.test.ts +113 -0
  31. package/src/modules/data/data.status.test.ts +249 -0
  32. package/src/modules/data/index.ts +1134 -128
  33. package/src/modules/data/window-query.test.ts +52 -0
  34. package/src/modules/data/window-query.ts +154 -0
  35. package/src/modules/devtools/index.ts +191 -30
  36. package/src/modules/devtools/versions.test.ts +74 -0
  37. package/src/modules/devtools/versions.ts +81 -0
  38. package/src/modules/feature-flag/index.test.ts +120 -0
  39. package/src/modules/feature-flag/index.ts +209 -0
  40. package/src/modules/ref-tables.test.ts +91 -0
  41. package/src/modules/ref-tables.ts +88 -0
  42. package/src/modules/sync/engine.ts +101 -37
  43. package/src/modules/sync/events/index.ts +9 -2
  44. package/src/modules/sync/queue/queue-down.ts +12 -5
  45. package/src/modules/sync/queue/queue-up.ts +29 -14
  46. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  47. package/src/modules/sync/scheduler.ts +73 -7
  48. package/src/modules/sync/sync.health.test.ts +149 -0
  49. package/src/modules/sync/sync.subquery.test.ts +82 -0
  50. package/src/modules/sync/sync.ts +1017 -62
  51. package/src/modules/sync/utils.test.ts +269 -2
  52. package/src/modules/sync/utils.ts +182 -17
  53. package/src/otel/index.ts +127 -0
  54. package/src/services/database/cache-engine.ts +143 -0
  55. package/src/services/database/database.ts +11 -11
  56. package/src/services/database/engine-factory.ts +32 -0
  57. package/src/services/database/events/index.ts +2 -1
  58. package/src/services/database/index.ts +6 -0
  59. package/src/services/database/local-migrator.ts +28 -27
  60. package/src/services/database/local.test.ts +64 -0
  61. package/src/services/database/local.ts +478 -67
  62. package/src/services/database/plan-render.test.ts +159 -0
  63. package/src/services/database/plan-render.ts +108 -0
  64. package/src/services/database/relation-resolver.test.ts +413 -0
  65. package/src/services/database/relation-resolver.ts +0 -0
  66. package/src/services/database/remote.ts +13 -13
  67. package/src/services/database/sqlite-cache-engine.test.ts +215 -0
  68. package/src/services/database/sqlite-cache-engine.ts +829 -0
  69. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  70. package/src/services/database/sqlite-plan-sql.ts +106 -0
  71. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  72. package/src/services/database/sqlite-select.test.ts +279 -0
  73. package/src/services/database/sqlite-select.ts +113 -0
  74. package/src/services/database/sqlite-worker.ts +160 -0
  75. package/src/services/database/surql-translate.ts +291 -0
  76. package/src/services/database/surreal-cache-engine.ts +139 -0
  77. package/src/services/logger/index.ts +6 -101
  78. package/src/services/persistence/localstorage.ts +2 -2
  79. package/src/services/persistence/resilient.ts +11 -4
  80. package/src/services/persistence/surrealdb.ts +10 -10
  81. package/src/services/stream-processor/index.ts +295 -38
  82. package/src/services/stream-processor/permissions.test.ts +47 -0
  83. package/src/services/stream-processor/permissions.ts +53 -0
  84. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  85. package/src/services/stream-processor/stream-processor.reset.test.ts +104 -0
  86. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  87. package/src/services/stream-processor/wasm-types.ts +18 -2
  88. package/src/sp00ky.auth-order.test.ts +92 -0
  89. package/src/sp00ky.init-query.test.ts +183 -0
  90. package/src/sp00ky.ts +1000 -0
  91. package/src/types.ts +267 -15
  92. package/src/utils/error-classification.test.ts +44 -0
  93. package/src/utils/error-classification.ts +7 -0
  94. package/src/utils/index.ts +35 -13
  95. package/src/utils/parser.ts +3 -2
  96. package/src/utils/semver.test.ts +32 -0
  97. package/src/utils/semver.ts +30 -0
  98. package/src/utils/surql.ts +24 -15
  99. package/src/utils/withRetry.test.ts +1 -1
  100. package/tsdown.config.ts +77 -1
  101. package/src/spooky.ts +0 -395
package/dist/index.d.ts CHANGED
@@ -1,166 +1,19 @@
1
+ import { A as SyncHealth, B as Logger$1, C as RecordVersionDiff, D as Sp00kyQueryResult, E as Sp00kyConfig, F as UpEvent, H as EventDefinition, I as LocalStore, L as SealedQuery, M as SyncHealthStatus, N as TimingPhase, O as Sp00kyQueryResultPromise, P as UpdateOptions, R as DatabaseEventSystem, S as RecordVersionArray, T as RunOptions, U as EventSystem, V as SyncEventSystem, _ as QueryStatus, a as MutationCallback, b as QueryTimings, c as PersistenceClient, d as PreloadOptions, f as PreloadRefresh, g as QueryState, h as QueryHash, i as MATERIALIZATION_SAMPLE_WINDOW, j as SyncHealthConfig, k as StoreType, l as PhaseStat, m as QueryConfigRecord, n as EventSubscriptionOptions, o as MutationEvent, p as QueryConfig, r as Level, s as MutationEventType, t as DebounceOptions, u as PinoTransmit, v as QueryStatusCallback, w as RegistrationTimings, x as QueryUpdateCallback, y as QueryTimeToLive, z as DatabaseEventTypes } from "./types.js";
1
2
  import * as surrealdb0 from "surrealdb";
2
- import { Duration, RecordId, Surreal, SurrealTransaction } from "surrealdb";
3
- import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RecordId as RecordId$1, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
4
- import { Level, Level as Level$1, Logger } from "pino";
3
+ import { Duration, RecordId, Surreal as Surreal$1, SurrealTransaction } from "surrealdb";
4
+ import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
5
+ import { Logger } from "pino";
6
+ import { LoroDoc } from "loro-crdt";
5
7
 
6
- //#region src/events/index.d.ts
7
- /**
8
- * Utility type to define the payload structure of an event.
9
- * If the payload type P is never, it defines payload as undefined.
10
- */
11
- type EventPayloadDefinition<P> = [P] extends [never] ? {
12
- payload: undefined;
13
- } : {
14
- payload: P;
15
- };
16
- /**
17
- * Defines the structure of an event with a specific type and payload.
18
- * @template T The string literal type of the event.
19
- * @template P The type of the event payload.
20
- */
21
- type EventDefinition<T extends string, P> = {
22
- type: T;
23
- } & EventPayloadDefinition<P>;
24
- /**
25
- * A map of event types to their definitions.
26
- * Keys are event names, values are EventDefinitions.
27
- */
28
- type EventTypeMap = Record<string, EventDefinition<any, unknown> | EventDefinition<any, never>>;
29
- /**
30
- * Options for pushing/emitting events.
31
- */
32
- interface PushEventOptions {
33
- /** Configuration for debouncing the event. */
34
- debounced?: {
35
- key: string;
36
- delay: number;
37
- };
38
- }
39
- /**
40
- * Extracts the full Event object type from the map for a given key.
41
- */
42
- type Event<E extends EventTypeMap, T extends EventType<E>> = E[T];
43
- /**
44
- * Extracts the payload type from the map for a given key.
45
- */
46
- type EventPayload<E extends EventTypeMap, T extends EventType<E>> = E[T]['payload'];
47
- /**
48
- * Array of available event type keys.
49
- */
50
- type EventTypes<E extends EventTypeMap> = (keyof E)[];
51
- /**
52
- * Represents a valid key (event name) from the EventTypeMap.
53
- */
54
- type EventType<E extends EventTypeMap> = keyof E;
55
- /**
56
- * Function signature for an event handler.
57
- */
58
- type EventHandler<E extends EventTypeMap, T extends EventType<E>> = (event: Event<E, T>) => void;
59
- /**
60
- * Options when subscribing to an event.
61
- */
62
- type EventSubscriptionOptions$1 = {
63
- /** If true, the handler will be called immediately with the last emitted event of this type (if any). */
64
- immediately?: boolean;
65
- /** If true, the subscription will be automatically removed after the first event is handled. */
66
- once?: boolean;
67
- };
68
- /**
69
- * A type-safe event system that handles subscription, emission (including debouncing), and buffering of events.
70
- * @template E The EventTypeMap defining all supported events.
71
- */
72
- declare class EventSystem<E extends EventTypeMap> {
73
- private _eventTypes;
74
- private subscriberId;
75
- private isProcessing;
76
- private buffer;
77
- private subscribers;
78
- private subscribersTypeMap;
79
- private lastEvents;
80
- private debouncedEvents;
81
- constructor(_eventTypes: EventTypes<E>);
82
- get eventTypes(): EventTypes<E>;
83
- /**
84
- * Subscribes a handler to a specific event type.
85
- * @param type The event type to subscribe to.
86
- * @param handler The function to call when the event occurs.
87
- * @param options Subscription options (once, immediately).
88
- * @returns A subscription ID that can be used to unsubscribe.
89
- */
90
- subscribe<T extends EventType<E>>(type: T, handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number;
91
- /**
92
- * Subscribes a handler to multiple event types.
93
- * @param types An array of event types to subscribe to.
94
- * @param handler The function to call when any of the events occur.
95
- * @param options Subscription options.
96
- * @returns An array of subscription IDs.
97
- */
98
- subscribeMany<T extends EventType<E>>(types: T[], handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number[];
99
- /**
100
- * Unsubscribes a specific subscription by ID.
101
- * @param id The subscription ID returned by subscribe().
102
- * @returns True if the subscription was found and removed, false otherwise.
103
- */
104
- unsubscribe(id: number): boolean;
105
- /**
106
- * Emits an event with the given type and payload.
107
- * @param type The type of event to emit.
108
- * @param payload The data associated with the event.
109
- */
110
- emit<T extends EventType<E>, P extends EventPayload<E, T>>(type: T, payload: P): void;
111
- /**
112
- * Adds a fully constructed event object to the system.
113
- * Similar to emit, but takes the full event object directly.
114
- * Supports debouncing if options are provided.
115
- * @param event The event object.
116
- * @param options Options for the event push (e.g., debouncing).
117
- */
118
- addEvent<T extends EventType<E>>(event: Event<E, T>, options?: PushEventOptions): void;
119
- private handleDebouncedEvent;
120
- private scheduleProcessing;
121
- private processEvents;
122
- private dequeue;
123
- private setLastEvent;
124
- private broadcastEvent;
125
- }
126
- //#endregion
127
- //#region src/services/logger/index.d.ts
128
- type Logger$1 = Logger;
129
- //#endregion
130
- //#region src/services/database/events/index.d.ts
131
- declare const DatabaseEventTypes: {
132
- readonly LocalQuery: "DATABASE_LOCAL_QUERY";
133
- readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
134
- };
135
- interface DatabaseQueryEventPayload {
136
- query: string;
137
- vars?: Record<string, unknown>;
138
- duration: number;
139
- success: boolean;
140
- error?: string;
141
- timestamp: number;
142
- }
143
- type DatabaseEventTypeMap = {
144
- [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
145
- [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
146
- };
147
- type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
148
- //#endregion
149
- //#region src/utils/surql.d.ts
150
- interface SealedQuery<T = void> {
151
- readonly sql: string;
152
- readonly extract: (results: unknown[]) => T;
153
- }
154
- //#endregion
155
8
  //#region src/services/database/database.d.ts
156
9
  declare abstract class AbstractDatabaseService {
157
- protected client: Surreal;
10
+ protected client: Surreal$1;
158
11
  protected logger: Logger$1;
159
12
  protected events: DatabaseEventSystem;
160
13
  protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
161
- constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
14
+ constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
162
15
  abstract connect(): Promise<void>;
163
- getClient(): Surreal;
16
+ getClient(): Surreal$1;
164
17
  getEvents(): DatabaseEventSystem;
165
18
  tx(): Promise<SurrealTransaction>;
166
19
  private queryQueue;
@@ -172,21 +25,12 @@ declare abstract class AbstractDatabaseService {
172
25
  close(): Promise<void>;
173
26
  }
174
27
  //#endregion
175
- //#region src/services/database/local.d.ts
176
- declare class LocalDatabaseService extends AbstractDatabaseService {
177
- private config;
178
- protected eventType: "DATABASE_LOCAL_QUERY";
179
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
180
- getConfig(): SpookyConfig<any>['database'];
181
- connect(): Promise<void>;
182
- }
183
- //#endregion
184
28
  //#region src/services/database/remote.d.ts
185
29
  declare class RemoteDatabaseService extends AbstractDatabaseService {
186
30
  private config;
187
31
  protected eventType: "DATABASE_REMOTE_QUERY";
188
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
189
- getConfig(): SpookyConfig<any>['database'];
32
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
33
+ getConfig(): Sp00kyConfig<any>['database'];
190
34
  connect(): Promise<void>;
191
35
  signin(params: any): Promise<any>;
192
36
  signup(params: any): Promise<any>;
@@ -194,38 +38,44 @@ declare class RemoteDatabaseService extends AbstractDatabaseService {
194
38
  invalidate(): Promise<void>;
195
39
  }
196
40
  //#endregion
197
- //#region src/modules/sync/queue/queue-up.d.ts
198
- type CreateEvent = {
199
- type: 'create';
200
- mutation_id: RecordId;
201
- record_id: RecordId;
202
- data: Record<string, unknown>;
203
- record?: Record<string, unknown>;
204
- tableName?: string;
205
- options?: PushEventOptions;
41
+ //#region src/modules/sync/queue/queue-down.d.ts
42
+ type RegisterEvent = {
43
+ type: 'register';
44
+ payload: {
45
+ hash: string;
46
+ };
206
47
  };
207
- type UpdateEvent = {
208
- type: 'update';
209
- mutation_id: RecordId;
210
- record_id: RecordId;
211
- data: Record<string, unknown>;
212
- record?: Record<string, unknown>;
213
- beforeRecord?: Record<string, unknown>;
214
- options?: PushEventOptions;
48
+ type SyncEvent = {
49
+ type: 'sync';
50
+ payload: {
51
+ hash: string;
52
+ };
215
53
  };
216
- type DeleteEvent = {
217
- type: 'delete';
218
- mutation_id: RecordId;
219
- record_id: RecordId;
220
- options?: PushEventOptions;
54
+ type HeartbeatEvent = {
55
+ type: 'heartbeat';
56
+ payload: {
57
+ hash: string;
58
+ };
221
59
  };
222
- type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
60
+ type CleanupEvent = {
61
+ type: 'cleanup';
62
+ payload: {
63
+ hash: string;
64
+ };
65
+ };
66
+ type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
223
67
  //#endregion
224
68
  //#region src/services/stream-processor/wasm-types.d.ts
225
69
  interface WasmStreamUpdate {
226
70
  query_id: string;
227
71
  result_hash: string;
228
72
  result_data: RecordVersionArray;
73
+ timing_store_apply_ms?: number;
74
+ timing_circuit_step_ms?: number;
75
+ timing_transform_ms?: number;
76
+ timing_parse_ms?: number;
77
+ timing_plan_ms?: number;
78
+ timing_snapshot_ms?: number;
229
79
  }
230
80
  //#endregion
231
81
  //#region src/services/stream-processor/index.d.ts
@@ -246,6 +96,25 @@ interface StreamUpdate {
246
96
  queryHash: string;
247
97
  localArray: RecordVersionArray;
248
98
  op?: 'CREATE' | 'UPDATE' | 'DELETE';
99
+ /**
100
+ * End-to-end ingest latency for the WASM call that produced this update,
101
+ * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
102
+ * for the initial register_view snapshot.
103
+ */
104
+ materializationTimeMs?: number;
105
+ /** SSP internal sub-phase timings (ms) for this ingest, from the WASM binding. */
106
+ storeApplyMs?: number;
107
+ circuitStepMs?: number;
108
+ transformMs?: number;
109
+ /**
110
+ * One-shot registration timings (ms). Only set on the StreamUpdate returned
111
+ * by `registerQueryPlan` (the register_view snapshot), not on ingest updates.
112
+ */
113
+ registration?: {
114
+ parseMs: number;
115
+ planMs: number;
116
+ snapshotMs: number;
117
+ };
249
118
  }
250
119
  type StreamProcessorEvents = {
251
120
  stream_update: EventDefinition<'stream_update', StreamUpdate[]>;
@@ -265,19 +134,89 @@ declare class StreamProcessorService {
265
134
  private processor;
266
135
  private isInitialized;
267
136
  private receivers;
268
- constructor(events: EventSystem<StreamProcessorEvents>, db: LocalDatabaseService, persistenceClient: PersistenceClient, logger: Logger);
137
+ private batching;
138
+ private batchBuffer;
139
+ private sessionAuth;
140
+ private stateKeySuffix;
141
+ private stateGeneration;
142
+ constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, persistenceClient: PersistenceClient, logger: Logger);
269
143
  /**
270
144
  * Add a receiver for stream updates.
271
145
  * Multiple receivers can be registered (DataManager, DevTools, etc.)
272
146
  */
273
147
  addReceiver(receiver: StreamUpdateReceiver): void;
274
148
  private notifyUpdates;
149
+ private dispatchUpdates;
150
+ /**
151
+ * Ingest a batch of record changes as a single bulk operation, firing only
152
+ * one coalesced `StreamUpdate` per affected query once every record has been
153
+ * ingested (instead of one update per record). Use this whenever multiple
154
+ * records land at once — e.g. sync fetching N missing rows — so a list query
155
+ * re-runs and the UI re-renders once for the whole batch rather than
156
+ * row-by-row.
157
+ *
158
+ * Internally opens a coalescing window, ingests each record, then flushes;
159
+ * processor state is persisted once for the whole batch. No-op for an empty
160
+ * batch.
161
+ */
162
+ ingestMany(records: Array<{
163
+ table: string;
164
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
165
+ id: string;
166
+ record: any;
167
+ }>): void;
168
+ /**
169
+ * Open a coalescing window. While open, the per-record stream updates
170
+ * emitted by `ingest` are buffered (one entry per queryHash) instead of
171
+ * dispatched. Always paired with `flushCoalescing()` in a try/finally by
172
+ * `ingestMany` so the window always closes — otherwise the processor stays
173
+ * stuck buffering forever.
174
+ *
175
+ * No-op if a window is already open (nested batches aren't expected here).
176
+ */
177
+ private beginCoalescing;
178
+ /**
179
+ * Close the coalescing window and flush: dispatch one coalesced
180
+ * `StreamUpdate` per buffered queryHash, then persist processor state once
181
+ * for the whole batch (instead of once per ingest).
182
+ */
183
+ private flushCoalescing;
275
184
  /**
276
185
  * Initialize the WASM module and processor.
277
186
  * This must be called before using other methods.
278
187
  */
279
188
  init(): Promise<void>;
189
+ /** Route the persisted circuit snapshot to a per-bucket key. */
190
+ setStateKeySuffix(bucketId: string): void;
191
+ private stateKey;
192
+ /**
193
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
194
+ * local-bucket switches: the old circuit holds the previous user's rows AND
195
+ * views registered with the previous `$auth` context, so neither may survive.
196
+ * Deliberately does NOT `loadState()` — a persisted snapshot references views
197
+ * under a dead sessionId salt; the DataModule rebind re-registers every live
198
+ * view against this fresh processor. Caller must re-seed `setPermissions`
199
+ * afterwards (a fresh circuit default-denies every table).
200
+ */
201
+ reset(): Promise<void>;
280
202
  loadState(): Promise<void>;
203
+ /**
204
+ * Seed per-table `select` permission predicates ({ [table]: whereText }).
205
+ * Must run after the processor exists and before any `register_view`, else
206
+ * non-`_00_` tables are default-denied and registration fails.
207
+ */
208
+ setPermissions(permissions: Record<string, string>): void;
209
+ /**
210
+ * Set the current session's auth identity for permission injection,
211
+ * mirroring the server's `fn::query::register`
212
+ * (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
213
+ * Stored as strings (empty when logged out) and applied to every
214
+ * `register_view` in {@link registerQueryPlan}. Must be set before a
215
+ * `$auth`-gated query registers (and re-set on auth state changes), or the
216
+ * in-browser SSP's `permission_inject` rejects it with
217
+ * "requires $auth but registration params lack it".
218
+ */
219
+ setSessionAuth(authId: string | null, access: string | null): void;
281
220
  saveState(): Promise<void>;
282
221
  /**
283
222
  * Ingest a record change into the processor.
@@ -297,203 +236,649 @@ declare class StreamProcessorService {
297
236
  private normalizeValue;
298
237
  }
299
238
  //#endregion
300
- //#region src/types.d.ts
301
- /**
302
- * The type of storage backend to use for the local database.
303
- * - 'memory': In-memory storage (transient).
304
- * - 'indexeddb': IndexedDB storage (persistent).
305
- */
306
- type StoreType = 'memory' | 'indexeddb';
239
+ //#region src/modules/cache/types.d.ts
240
+ type RecordWithId = Record<string, any> & {
241
+ id: RecordId<string>;
242
+ };
243
+ interface QueryConfig$1 {
244
+ queryHash: string;
245
+ surql: string;
246
+ params: Record<string, any>;
247
+ ttl: QueryTimeToLive | Duration;
248
+ lastActiveAt: Date;
249
+ }
250
+ interface CacheRecord {
251
+ table: string;
252
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
253
+ record: RecordWithId;
254
+ version: number;
255
+ }
256
+ //#endregion
257
+ //#region src/modules/cache/index.d.ts
307
258
  /**
308
- * Interface for a custom persistence client.
309
- * Allows providing a custom storage mechanism for the local database.
259
+ * CacheModule - Centralized storage and DBSP ingestion
260
+ *
261
+ * Single responsibility: Handle all local storage operations and DBSP ingestion.
262
+ * This module acts as the bridge between data operations and persistence.
310
263
  */
311
- interface PersistenceClient {
264
+ declare class CacheModule implements StreamUpdateReceiver {
265
+ private local;
266
+ private streamProcessor;
267
+ private logger;
268
+ private streamUpdateCallback;
269
+ private versionLookups;
270
+ constructor(local: LocalStore, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
312
271
  /**
313
- * Sets a value in the storage.
314
- * @param key The key to set.
315
- * @param value The value to store.
272
+ * Implements StreamUpdateReceiver interface
273
+ * Called directly by StreamProcessor when views change
316
274
  */
317
- set<T>(key: string, value: T): Promise<void>;
275
+ onStreamUpdate(update: StreamUpdate): void;
276
+ lookup(recordId: string): number;
277
+ /** Drop the version cache on a bucket switch — a stale version would make
278
+ * the sync diff skip fetching a body the new bucket legitimately needs. */
279
+ clearVersionLookups(): void;
318
280
  /**
319
- * Gets a value from the storage.
320
- * @param key The key to retrieve.
321
- * @returns The stored value or null if not found.
281
+ * Save a single record to local DB and ingest into DBSP
282
+ * Used by mutations (create/update)
322
283
  */
323
- get<T>(key: string): Promise<T | null>;
284
+ save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
324
285
  /**
325
- * Removes a value from the storage.
326
- * @param key The key to remove.
286
+ * Save multiple records in a batch
287
+ * More efficient than calling save() multiple times
288
+ * Used by sync operations
327
289
  */
328
- remove(key: string): Promise<void>;
329
- }
330
- /**
331
- * Supported Time-To-Live (TTL) values for cached queries.
332
- * Format: number + unit (m=minutes, h=hours, d=days).
333
- */
334
- type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
335
- /**
336
- * Result object returned when a query is registered or executed.
337
- */
338
- interface SpookyQueryResult {
339
- /** The unique hash identifier for the query. */
340
- hash: string;
341
- }
342
- type SpookyQueryResultPromise = Promise<SpookyQueryResult>;
343
- interface EventSubscriptionOptions {
344
- priority?: number;
345
- }
346
- /**
347
- * Configuration options for the Spooky client.
348
- * @template S The schema structure type.
349
- */
350
- interface SpookyConfig<S extends SchemaStructure> {
351
- /** Database connection configuration. */
352
- database: {
353
- /** The SurrealDB endpoint URL. */
354
- endpoint?: string;
355
- /** The namespace to use. */
356
- namespace: string;
357
- /** The database name. */
358
- database: string;
359
- /** The local store type implementation. */
360
- store?: StoreType;
361
- /** Authentication token. */
362
- token?: string;
290
+ saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
291
+ /**
292
+ * Delete a record from local DB and ingest deletion into DBSP
293
+ */
294
+ delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
295
+ /**
296
+ * Register a query with DBSP to create a materialized view
297
+ * Returns the initial result array
298
+ */
299
+ registerQuery(config: QueryConfig$1): {
300
+ localArray: RecordVersionArray;
301
+ registrationTimings?: {
302
+ parseMs: number;
303
+ planMs: number;
304
+ snapshotMs: number;
305
+ };
363
306
  };
364
- /** Unique client identifier. If not provided, one will be generated. */
365
- clientId?: string;
366
- /** The schema definition. */
367
- schema: S;
368
- /** The compiled SURQL schema string. */
369
- schemaSurql: string;
370
- /** Logging level. */
371
- logLevel: Level$1;
372
- /**
373
- * Persistence client to use.
374
- * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
375
- */
376
- persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
377
- /** OpenTelemetry collector endpoint for telemetry data. */
378
- otelEndpoint?: string;
379
- /**
380
- * Debounce time in milliseconds for stream updates.
381
- * Defaults to 100ms.
382
- */
383
- streamDebounceTime?: number;
384
- }
385
- type QueryHash = string;
386
- type RecordVersionArray = Array<[string, number]>;
387
- /**
388
- * Represents the difference between two record version sets.
389
- * Used for synchronizing local and remote states.
390
- */
391
- interface RecordVersionDiff {
392
- /** List of records added. */
393
- added: Array<{
394
- id: RecordId$1<string>;
395
- version: number;
396
- }>;
397
- /** List of records updated. */
398
- updated: Array<{
399
- id: RecordId$1<string>;
400
- version: number;
401
- }>;
402
- /** List of record IDs removed. */
403
- removed: RecordId$1<string>[];
404
- }
405
- /**
406
- * Configuration for a specific query instance.
407
- * Stores metadata about the query's state, parameters, and versioning.
408
- */
409
- interface QueryConfig {
410
- /** The unique ID of the query config record. */
411
- id: RecordId$1<string>;
412
- /** The SURQL query string. */
413
- surql: string;
414
- /** Parameters used in the query. */
415
- params: Record<string, any>;
416
- /** The version array representing the local state of results. */
417
- localArray: RecordVersionArray;
418
- /** The version array representing the remote (server) state of results. */
419
- remoteArray: RecordVersionArray;
420
- /** Time-To-Live for this query. */
421
- ttl: QueryTimeToLive;
422
- /** Timestamp when the query was last accessed/active. */
423
- lastActiveAt: Date;
424
- /** The name of the table this query targets (if applicable). */
425
- tableName: string;
426
- }
427
- type QueryConfigRecord = QueryConfig & {
428
- id: string;
429
- };
430
- /**
431
- * Internal state of a live query.
432
- */
433
- interface QueryState {
434
- /** The configuration for this query. */
435
- config: QueryConfig;
436
- /** The current cached records for this query. */
437
- records: Record<string, any>[];
438
- /** Timer for TTL expiration. */
439
- ttlTimer: NodeJS.Timeout | null;
440
- /** TTL duration in milliseconds. */
441
- ttlDurationMs: number;
442
- /** Number of times the query has been updated. */
443
- updateCount: number;
307
+ /**
308
+ * Unregister a query from DBSP
309
+ */
310
+ unregisterQuery(queryHash: string): void;
444
311
  }
445
- type QueryUpdateCallback = (records: Record<string, any>[]) => void;
446
- type MutationCallback = (mutations: UpEvent[]) => void;
447
- type MutationEventType = 'create' | 'update' | 'delete';
312
+ //#endregion
313
+ //#region src/modules/data/index.d.ts
448
314
  /**
449
- * Represents a mutation event (create, update, delete) to be synchronized.
315
+ * DataModule - Unified query and mutation management
316
+ *
317
+ * Merges the functionality of QueryManager and MutationManager.
318
+ * Uses CacheModule for all storage operations.
450
319
  */
451
- interface MutationEvent {
452
- /** Example: 'create', 'update', or 'delete'. */
453
- type: MutationEventType;
454
- /** unique id of the mutation */
455
- mutation_id: RecordId$1<string>;
456
- /** The ID of the record being mutated. */
457
- record_id: RecordId$1<string>;
458
- /** The data payload for create/update operations. */
459
- data?: any;
460
- /** The full record data (optional context). */
461
- record?: any;
462
- /** Options for the mutation event (e.g., debounce settings). */
463
- options?: PushEventOptions;
464
- /** Timestamp when the event was created. */
465
- createdAt: Date;
320
+ declare class DataModule<S extends SchemaStructure> {
321
+ private cache;
322
+ private local;
323
+ private schema;
324
+ private streamDebounceTime;
325
+ private activeQueries;
326
+ private pendingQueries;
327
+ private subscriptions;
328
+ private statusSubscriptions;
329
+ private mutationCallbacks;
330
+ private debounceTimers;
331
+ private pendingStreamUpdates;
332
+ private fetchDepth;
333
+ private logger;
334
+ /**
335
+ * Optional observer notified whenever a query's fetch status changes.
336
+ * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
337
+ * settable field (rather than a constructor arg) because DevTools is
338
+ * constructed after DataModule.
339
+ */
340
+ onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
341
+ /**
342
+ * Optional observer invoked when a still-subscribed query's TTL heartbeat
343
+ * fires (~90% of the TTL). Wired by Sp00kyClient to
344
+ * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
345
+ * row's `lastActiveAt` so an actively-watched query never expires. Settable
346
+ * field (not a constructor arg) because the sync engine is wired after
347
+ * DataModule is constructed — mirrors `onQueryStatusChange`.
348
+ */
349
+ onHeartbeat?: (hash: QueryHash) => void;
350
+ /**
351
+ * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
352
+ * viewport-windowed list cancelling an off-screen window) loses its last
353
+ * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
354
+ * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
355
+ * instead of leaving it for the TTL sweep. The local view + state are freed in
356
+ * {@link finalizeDeregister} only after that remote delete, so a fast
357
+ * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
358
+ */
359
+ onDeregister?: (hash: QueryHash) => void;
360
+ private sessionId;
361
+ private currentUserId;
362
+ constructor(cache: CacheModule, local: LocalStore, schema: S, logger: Logger$1, streamDebounceTime?: number);
363
+ init(sessionId: string): Promise<void>;
364
+ /**
365
+ * Update the session salt used in query-id hashing. Call this when the
366
+ * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
367
+ * registered queries will get fresh, session-scoped IDs.
368
+ */
369
+ setSessionId(sessionId: string): void;
370
+ /**
371
+ * Update the authenticated user record id. Pass `null` on sign-out.
372
+ * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
373
+ * the poll route to the same per-user `_00_list_ref_user_<id>` the
374
+ * SSP writes to.
375
+ */
376
+ setCurrentUserId(userId: string | null): void;
377
+ /** Read-only view of the authenticated user id used for per-user
378
+ * `_00_list_ref` routing. Other modules consult this so they pick the
379
+ * same table name DataModule does. */
380
+ getCurrentUserId(): string | null;
381
+ /**
382
+ * Register a query and return its hash for subscriptions
383
+ */
384
+ query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive, plan?: QueryPlan): Promise<QueryHash>;
385
+ /**
386
+ * Subscribe to query updates
387
+ */
388
+ subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
389
+ immediate?: boolean;
390
+ }): () => void;
391
+ /**
392
+ * Subscribe to a query's fetch-status changes (idle/fetching).
393
+ * With `{ immediate: true }` the callback fires synchronously with the
394
+ * current status (defaults to `idle` if the query isn't registered yet).
395
+ */
396
+ subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
397
+ immediate?: boolean;
398
+ }): () => void;
399
+ /**
400
+ * Set a query's fetch status and notify status observers (DevTools +
401
+ * `subscribeStatus` listeners). No-op when the status is unchanged or the
402
+ * query is unknown.
403
+ */
404
+ setQueryStatus(queryHash: string, status: QueryStatus): void;
405
+ /**
406
+ * Enter a fetch cycle for a query. Refcounted: registration and concurrent
407
+ * poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
408
+ * cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
409
+ * emits `idle`. Always pair with `endFetching` in a `finally`.
410
+ */
411
+ beginFetching(queryHash: string): void;
412
+ /** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
413
+ endFetching(queryHash: string): void;
414
+ /**
415
+ * Subscribe to mutations (for sync)
416
+ */
417
+ onMutation(callback: MutationCallback): () => void;
418
+ /**
419
+ * Handle stream updates from DBSP (via CacheModule)
420
+ */
421
+ onStreamUpdate(update: StreamUpdate): Promise<void>;
422
+ /**
423
+ * Process a query's pending (debounced) stream update NOW instead of on the
424
+ * trailing edge. Called by the sync engine before it flips a query back to
425
+ * `idle`, so the status change never races ahead of the rows it fetched.
426
+ * No-op when nothing is pending. The pending entry is removed before the
427
+ * await so a concurrently-firing timer can't process it twice.
428
+ */
429
+ flushPendingStreamUpdate(queryHash: string): Promise<void>;
430
+ private materializeRecords;
431
+ private processStreamUpdate;
432
+ /**
433
+ * Compute p55/p90/p99 from a rolling window of materialization samples.
434
+ * Returns nulls for any percentile that has no samples yet so SurrealDB
435
+ * `option<float>` columns stay NONE rather than 0 before the first ingest.
436
+ */
437
+ private computeMaterializationPercentiles;
438
+ /** Record a per-phase timing sample (ms) on a query's rolling window. */
439
+ private recordPhase;
440
+ /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
441
+ recordRemoteFetch(hash: string, ms: number): void;
442
+ /**
443
+ * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
444
+ * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
445
+ */
446
+ recordFrontendTiming(hash: string, ms: number): void;
447
+ /**
448
+ * Build the per-query processing-time breakdown surfaced to the DevTools panel
449
+ * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
450
+ * the rest come from the per-phase rolling windows + one-shot registration timings.
451
+ */
452
+ phaseTimings(q: QueryState): QueryTimings;
453
+ /**
454
+ * Get query state (for sync and devtools)
455
+ */
456
+ getQueryByHash(hash: string): QueryState | undefined;
457
+ /**
458
+ * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
459
+ * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
460
+ * We gate on `remoteArray`, not local `records`: a windowed query is often
461
+ * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
462
+ * but it still hasn't loaded its own full window from the server — so it should
463
+ * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
464
+ */
465
+ isCold(hash: string): boolean;
466
+ /**
467
+ * Walk a hydrated record's fields and append any EMBEDDED child records to
468
+ * `batch` (recursing for nested related fields). An embedded child is a
469
+ * value that is itself a record — a non-null object whose `id` is a
470
+ * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
471
+ * bare `RecordId` (a foreign-key reference) or any other value is skipped,
472
+ * so this never mistakes a FK column for an embedded body. Children are
473
+ * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
474
+ * to their table's real columns (which strips the alias/related fields).
475
+ * `seen` dedupes within the batch.
476
+ */
477
+ private collectEmbeddedChildren;
478
+ /**
479
+ * Prepare a subquery-bearing row (preload / hydration) for the schemafull
480
+ * local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
481
+ * with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
482
+ * ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
483
+ * own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
484
+ * with relations already RecordIds — passes through unchanged.
485
+ */
486
+ private flattenRelationsForStorage;
487
+ /**
488
+ * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
489
+ * surql run directly) so the query DISPLAYS immediately, while the full realtime
490
+ * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
491
+ * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
492
+ * `remoteArray` so windowed queries materialize the correct window (no sparse
493
+ * local-circuit issue). Runs at most once per query (the `hydrated` flag).
494
+ */
495
+ applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
496
+ /**
497
+ * Build the cache batch for a set of one-shot rows and persist it to the
498
+ * local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
499
+ * and extracts EMBEDDED related children (any nesting depth) as their own
500
+ * records — a `.related()` query returns its children embedded, and a later
501
+ * correlated re-materialization needs them present as standalone rows.
502
+ * Shared by `applyHydration` (live registration) and `persistSnapshot`
503
+ * (preload).
504
+ */
505
+ private buildAndSaveCacheBatch;
506
+ /**
507
+ * Preload/prewarm: persist one-shot rows (and their embedded related children)
508
+ * into the local cache WITHOUT registering a query — no `activeQueries` entry,
509
+ * no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
510
+ * ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
511
+ * first paint from them instantly, then registers a live view to freshen.
512
+ */
513
+ persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void>;
514
+ /**
515
+ * Read the durable preload freshness marker for a query hash, or null if this
516
+ * query was never preloaded in the current bucket. Co-located with the cached
517
+ * rows (per-bucket `_00_preload` table) so a bucket switch that clears the
518
+ * data also clears the marker — a stale marker can't claim "warm" when the
519
+ * rows are gone. Any read error is treated as cold.
520
+ */
521
+ getPreloadMarker(hash: string): Promise<{
522
+ fetchedAt: number;
523
+ rowCount: number;
524
+ } | null>;
525
+ /** Stamp the preload freshness marker after a successful snapshot fetch. */
526
+ writePreloadMarker(hash: string, rowCount: number): Promise<void>;
527
+ /** True while ≥1 live subscriber is watching this query (refcount guard). */
528
+ hasSubscribers(hash: string): boolean;
529
+ /**
530
+ * Opt-in eager teardown for a query whose LAST subscriber just left — used by
531
+ * viewport-windowed lists to cancel off-screen windows instead of leaving
532
+ * their remote views to expire on the TTL sweep. No-op while any subscriber
533
+ * remains (refcount). Only enqueues the remote cleanup here; the local WASM
534
+ * view + in-memory state are freed in {@link finalizeDeregister} after the
535
+ * remote delete completes, so a re-subscribe in between aborts/heals it.
536
+ *
537
+ * NOTE: most queries should NOT use this — the default keep-alive on
538
+ * unsubscribe avoids re-registration churn on navigation.
539
+ */
540
+ deregisterQuery(hash: string): void;
541
+ /**
542
+ * Final local teardown after the remote `_00_query` row was deleted: free the
543
+ * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
544
+ * (`cleanupQuery`) guarantees no subscriber remains.
545
+ */
546
+ finalizeDeregister(hash: string): void;
547
+ /**
548
+ * Get query state by id (for sync and devtools)
549
+ */
550
+ getQueryById(id: RecordId<string>): QueryState | undefined;
551
+ /**
552
+ * Get all active queries (for devtools)
553
+ */
554
+ getActiveQueries(): QueryState[];
555
+ getActiveQueryHashes(): QueryHash[];
556
+ updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
557
+ updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void>;
558
+ /**
559
+ * Cancel every armed timer ahead of a local-bucket switch: stream-update
560
+ * debounce timers (their pending updates carry the OLD bucket's id-sets) and
561
+ * per-query TTL heartbeats (they'd refresh the previous user's remote
562
+ * `_00_query` rows under the new session). The rebind re-arms heartbeats.
563
+ */
564
+ quiesce(): void;
565
+ /**
566
+ * Re-home every active query in a freshly-opened bucket, KEEPING its hash —
567
+ * `useQuery` subscriptions are keyed by hash and don't re-register on auth
568
+ * changes, so the hooks must stay attached. Per query:
569
+ * 1. reset the sync arrays + hydration flag and drop the previous user's
570
+ * records, notifying subscribers with the new-bucket materialization
571
+ * (usually empty) so their rows leave the UI immediately;
572
+ * 2. recreate the `_00_query` row in the new bucket;
573
+ * 3. re-register the SSP view on the (fresh, post-reset) processor — this
574
+ * also rebinds the view to the NEW `$auth` context;
575
+ * 4. restart the TTL heartbeat.
576
+ * Returns the hashes so the caller can enqueue remote re-registration, which
577
+ * refills records from the server via the normal register→sync→notify path.
578
+ */
579
+ rebindAfterBucketSwitch(): Promise<QueryHash[]>;
580
+ /**
581
+ * Called after a query's initial sync completes.
582
+ * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
583
+ */
584
+ notifyQuerySynced(queryHash: string): Promise<void>;
585
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
586
+ /**
587
+ * Build the outbox job record + resolve its table for a backend route.
588
+ *
589
+ * Every job is a single execution. Recurring work is declared server-side
590
+ * (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
591
+ * so nothing here needs to know about schedules.
592
+ */
593
+ private buildJobRecord;
594
+ /**
595
+ * Create a new record
596
+ */
597
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
598
+ /**
599
+ * Update an existing record
600
+ */
601
+ update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
602
+ /**
603
+ * Delete a record
604
+ */
605
+ delete(table: string, id: string): Promise<void>;
606
+ /**
607
+ * Rollback a failed optimistic create by deleting the record locally
608
+ */
609
+ rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
610
+ /**
611
+ * Rollback a failed optimistic update by restoring the previous record state
612
+ */
613
+ rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
614
+ /**
615
+ * Remove a record from all active query states and notify subscribers
616
+ */
617
+ private removeRecordFromQueries;
618
+ private createAndRegisterQuery;
619
+ private createNewQuery;
620
+ private calculateHash;
621
+ private startTTLHeartbeat;
622
+ private replaceRecordInQueries;
466
623
  }
467
624
  /**
468
- * Options for run operations.
625
+ * Parse update options to generate push event options
469
626
  */
470
- interface RunOptions {
471
- assignedTo?: string;
472
- max_retries?: number;
473
- retry_strategy?: 'linear' | 'exponential';
474
- }
627
+ //#endregion
628
+ //#region src/modules/sync/sync.d.ts
475
629
  /**
476
- * Options for update operations.
630
+ * Tunables for `Sp00kySync` construction.
477
631
  */
478
- interface UpdateOptions {
632
+ interface Sp00kySyncOptions {
633
+ /**
634
+ * Cadence (ms) for the `_00_list_ref` poll fallback that catches
635
+ * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
636
+ * values fall back to the default; see
637
+ * {@link resolveListRefPollInterval}.
638
+ */
639
+ refSyncIntervalMs?: number;
479
640
  /**
480
- * Debounce configuration for the update.
481
- * If boolean, enables default debounce behavior.
641
+ * Enable realtime sync for unauthenticated clients against the shared
642
+ * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
643
+ * Defaults to `false`.
482
644
  */
483
- debounced?: boolean | DebounceOptions;
645
+ anonymousLiveQueries?: boolean;
646
+ /**
647
+ * Consecutive failed sync rounds before sync health flips to `degraded`.
648
+ * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
649
+ * Defaults to `3`.
650
+ */
651
+ degradeAfterConsecutiveFailures?: number;
484
652
  }
485
653
  /**
486
- * Configuration options for debouncing updates.
654
+ * The main synchronization engine for Sp00ky.
655
+ * Handles the bidirectional synchronization between the local database and the remote backend.
656
+ * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
657
+ * @template S The schema structure type.
487
658
  */
488
- interface DebounceOptions {
659
+ declare class Sp00kySync<S extends SchemaStructure> {
660
+ private local;
661
+ private remote;
662
+ private cache;
663
+ private dataModule;
664
+ private schema;
665
+ private upQueue;
666
+ private downQueue;
667
+ private isInit;
668
+ private logger;
669
+ private syncEngine;
670
+ /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
671
+ * from `this.events`, which carries Sp00kySync-level events like
672
+ * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
673
+ get engineEvents(): SyncEventSystem;
674
+ private scheduler;
675
+ private wasDisconnected;
676
+ events: SyncEventSystem;
677
+ private currentUserId;
678
+ private refMode;
679
+ private readonly anonLiveEnabled;
680
+ private currentLiveQueryUuid;
681
+ private liveQueryUnsubscribe;
682
+ private listRefPollTimer;
683
+ private listRefPollRunning;
684
+ private listRefPollInFlight;
685
+ readonly refSyncIntervalMs: number;
686
+ private listRefIdleStreak;
687
+ private stillRemoteStreaks;
688
+ private lastLiveEventAt;
689
+ private _liveRetryCount;
690
+ get liveRetryCount(): number;
691
+ get isSyncing(): boolean;
692
+ get pendingMutationCount(): number;
693
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
694
+ private readonly degradeAfterFailures;
695
+ private consecutiveSyncFailures;
696
+ private syncHealthStatus;
697
+ private lastSyncErrorKind;
698
+ private lastSyncErrorMessage;
699
+ private hasSyncedOnce;
700
+ private selfHealTimer;
701
+ private selfHealAttempts;
702
+ private static readonly SELF_HEAL_BASE_MS;
703
+ private static readonly SELF_HEAL_MAX_MS;
704
+ /** Current sync-health snapshot. */
705
+ get syncHealth(): SyncHealth;
706
+ /**
707
+ * Observe sync health. The callback fires immediately with the current
708
+ * status and again on every healthy↔degraded transition. Returns an
709
+ * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
710
+ */
711
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
712
+ private emitSyncHealth;
713
+ /**
714
+ * Fed by the scheduler once per drained sync round. Individual failures are
715
+ * absorbed by the queue's retry; only a run of `degradeAfterFailures`
716
+ * consecutive failures flips the status to `degraded`, and the next clean
717
+ * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
718
+ * is 0).
719
+ */
720
+ private recordSyncOutcome;
721
+ /**
722
+ * Begin self-heal retries (no-op if already running). Started on the
723
+ * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
724
+ */
725
+ private startSelfHeal;
726
+ private scheduleSelfHeal;
727
+ private stopSelfHeal;
728
+ constructor(local: LocalStore, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
729
+ /**
730
+ * Initializes the synchronization system.
731
+ * Starts the scheduler and initiates the initial sync cycles.
732
+ * @throws Error if already initialized.
733
+ */
734
+ init(): Promise<void>;
735
+ /**
736
+ * Quiesce all sync activity ahead of a local-bucket switch. After this
737
+ * resolves, nothing in the sync module writes to the local store: the poll
738
+ * loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
739
+ * timers are cancelled (their outbox rows are already persisted), and the
740
+ * scheduler has drained its in-flight queue item — including that item's
741
+ * outbox-row delete, which must land in the OLD bucket. Queued down-events
742
+ * are dropped (they reference old-bucket query rows; the post-switch rebind
743
+ * re-enqueues registrations). The old user's un-pushed outbox is deliberately
744
+ * NOT drained: the remote session already belongs to the next user.
745
+ */
746
+ prepareBucketSwitch(): Promise<void>;
747
+ /**
748
+ * Resume syncing against the freshly-opened bucket: reload the mutation
749
+ * outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
750
+ * offline work) and restart the scheduler. LIVE + the list_ref poll restart
751
+ * via the `setCurrentUserId` call that follows in the auth listener.
752
+ */
753
+ completeBucketSwitch(): Promise<void>;
754
+ /**
755
+ * Push the authenticated user's record id from the parent client's
756
+ * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
757
+ * any) and re-registers it under the new user's dedicated table so
758
+ * SurrealDB binds the permission rule under the post-flip auth
759
+ * context. Pass `null` on sign-out.
760
+ *
761
+ * The dedicated `_00_list_ref_user_<id>` table is created lazily by
762
+ * the SSP when the first query registration arrives, which may be
763
+ * concurrent with this call. We retry the LIVE registration with a
764
+ * short backoff so a "table not found" race resolves without
765
+ * surfacing as a permanent auth-loading hang.
766
+ */
767
+ setCurrentUserId(userId: string | null): Promise<void>;
768
+ private startListRefPoll;
769
+ private stopListRefPoll;
770
+ /**
771
+ * One poll cycle: refetch `_00_list_ref` for every active query. Returns
772
+ * whether ANY query's remoteArray actually changed — the scheduler uses this
773
+ * to drive the adaptive idle backoff.
774
+ *
775
+ * Also the ONLY health signal that runs while the page is idle. Sync health is
776
+ * otherwise activity-driven (mutations/registrations via the scheduler,
777
+ * reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
778
+ * would linger until the next mutation and a genuine idle drop would be
779
+ * invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
780
+ * so idle health self-recovers (and self-degrades) with no user action. A clean
781
+ * cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
782
+ * `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
783
+ */
784
+ private pollListRefForActiveQueries;
785
+ /**
786
+ * Pull the upstream list_ref entries for `queryHash`, diff them
787
+ * against the local `remoteArray` cache, sync any added/updated rows
788
+ * through the SyncEngine, then persist the new remoteArray. This is
789
+ * the same shape `createRemoteQuery` does for its initial fetch and
790
+ * what `handleRemoteListRefChange` does per-LIVE-event — we reuse
791
+ * it on a timer as a fallback for missed LIVE notifications.
792
+ */
793
+ private refetchListRefForQuery;
794
+ /**
795
+ * Resolve the current `_00_list_ref` table name for the active auth
796
+ * context. Public so the `createRemoteQuery` initial-fetch path can
797
+ * read from the right per-user table.
798
+ *
799
+ * Reads the user id from `DataModule` rather than the local mirror,
800
+ * because `DataModule.setCurrentUserId` runs synchronously from the
801
+ * auth callback (before any `await`), whereas `sync.setCurrentUserId`
802
+ * is async — the userQuery's initial fetch can fire between those
803
+ * two points and we need the correct table name immediately.
804
+ */
805
+ listRefTable(): string;
806
+ private killRefLiveQuery;
807
+ private restartRefLiveQuery;
808
+ private subscribeToReconnect;
809
+ private startRefLiveQueries;
810
+ private handleRemoteListRefChange;
811
+ /**
812
+ * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
813
+ * `parent` set) for a `.related()` query. Unlike primary rows, child rows
814
+ * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
815
+ * keep the child BODY fresh in the local cache so the in-browser SSP's
816
+ * subquery-table dependency re-materializes the parent view.
817
+ *
818
+ * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
819
+ * no-op: a child leaving this query's set must not delete a body another
820
+ * query may still show (see `syncSubqueryChildren` deletion-safety note);
821
+ * a genuine record delete propagates via the normal delete path.
822
+ */
823
+ private handleRemoteSubqueryChange;
824
+ /**
825
+ * Enqueues a 'down' event (from remote to local) for processing.
826
+ * @param event The DownEvent to enqueue.
827
+ */
828
+ enqueueDownEvent(event: DownEvent): void;
829
+ private processUpEvent;
830
+ private handleRollback;
831
+ private processDownEvent;
832
+ /**
833
+ * Synchronizes a specific query by hash.
834
+ * Compares local and remote version arrays and fetches differences.
835
+ * @param hash The hash of the query to sync.
836
+ */
837
+ syncQuery(hash: string): Promise<void>;
838
+ /**
839
+ * Run a sync for a single query while reflecting its fetch status. Marks the
840
+ * query `fetching` for the duration when the diff actually pulls records
841
+ * (added/updated), then resets to `idle` in a `finally` so a failed sync
842
+ * never leaves a query stuck `fetching`. Part A's notification coalescing
843
+ * means the single resulting UI update lands after this completes.
844
+ */
845
+ private runSyncForQuery;
846
+ /**
847
+ * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
848
+ * Sync must not re-fetch/re-insert these — the remote delete is async, so the
849
+ * server's `_00_list_ref` still lists them until it's processed, and the diff
850
+ * would otherwise resurrect a just-deleted record.
851
+ */
852
+ private getPendingDeleteIds;
853
+ /**
854
+ * Enqueues a list of mutations (up events) to be sent to the remote.
855
+ * @param mutations Array of UpEvents (create/update/delete) to enqueue.
856
+ */
857
+ enqueueMutation(mutations: UpEvent[]): Promise<void>;
858
+ private registerQuery;
859
+ private createRemoteQuery;
489
860
  /**
490
- * The key to use for debouncing.
491
- * - 'recordId': Debounce based on the specific record ID. WARNING: IT WILL ONLY ACCEPT THE LATEST CHANGE AND DOES *NOT* MERGE THE PREVIOUS ONCES. IF YOU ARE UNSURE JUST USE 'recordId_x_fields'.
492
- * - 'recordId_x_fields': Debounce based on record ID and specific fields.
861
+ * Sync the BODIES of a `.related()` query's subquery child rows into the
862
+ * local cache, separately from the primary window array. The SSP writes
863
+ * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
864
+ * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
865
+ * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
866
+ * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
867
+ * them into the local DB AND the in-browser SSP, whose subquery-table
868
+ * dependency then re-materializes the parent view (no explicit notify).
869
+ *
870
+ * Deletion safety: we pass `removed: []` deliberately. A child body can be
871
+ * shared by other queries; letting `handleRemovedRecords` delete one that
872
+ * merely left THIS query's child set would clobber data another query still
873
+ * shows. Genuine record deletes flow through the normal delete path; a
874
+ * lingering orphan body is invisible (the correlated WHERE stops matching).
875
+ *
876
+ * Kept off `runSyncForQuery` on purpose so child fetches never flip the
877
+ * query to `fetching` or skew its DevTools timings.
493
878
  */
494
- key?: 'recordId' | 'recordId_x_fields';
495
- /** The debounce delay in milliseconds. */
496
- delay?: number;
879
+ private syncSubqueryChildren;
880
+ heartbeatQuery(queryHash: string): Promise<void>;
881
+ private cleanupQuery;
497
882
  }
498
883
  //#endregion
499
884
  //#region src/modules/auth/events/index.d.ts
@@ -518,6 +903,13 @@ declare class AuthService<S extends SchemaStructure> {
518
903
  token: string | null;
519
904
  currentUser: any | null;
520
905
  isAuthenticated: boolean;
906
+ /**
907
+ * The record-access method name for the current session (e.g. `"account"`),
908
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
909
+ * permission injection so `$access`-gated table predicates resolve locally,
910
+ * mirroring the server's `$access`. Null when logged out.
911
+ */
912
+ access: string | null;
521
913
  isLoading: boolean;
522
914
  private events;
523
915
  get eventSystem(): AuthEventSystem;
@@ -539,11 +931,292 @@ declare class AuthService<S extends SchemaStructure> {
539
931
  */
540
932
  signOut(): Promise<void>;
541
933
  private setSession;
934
+ /** Fallback when the token carries no `AC` claim: if the schema defines
935
+ * exactly one record-access method, assume the session used it. */
936
+ private defaultAccessName;
542
937
  signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
543
938
  signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
544
939
  }
545
940
  //#endregion
546
- //#region src/spooky.d.ts
941
+ //#region src/modules/crdt/crdt-field.d.ts
942
+ declare const CURSOR_COLORS: string[];
943
+ declare function cursorColorFromName(name: string): string;
944
+ declare class CrdtField {
945
+ private fieldName;
946
+ private doc;
947
+ private pushTimer;
948
+ private local;
949
+ private remote;
950
+ private recordId;
951
+ private sessionId;
952
+ private unsubscribe;
953
+ private lastPushTime;
954
+ private lastCursorPushTime;
955
+ private loadedFromCrdt;
956
+ private pushRetryCount;
957
+ private logger;
958
+ private cursorsEnabled;
959
+ /** Remote-push debounce. Local writes happen immediately on every Loro
960
+ * update; the remote UPSERT is coalesced over this window. Configured
961
+ * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
962
+ private remoteDebounceMs;
963
+ private _onCursorUpdate;
964
+ private pendingCursorUpdate;
965
+ /** Callback set by the editor to receive remote cursor updates.
966
+ * Any cursor data that arrived before this callback was set will be replayed. */
967
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
968
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
969
+ /**
970
+ * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
971
+ * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
972
+ * import graph so it only ships to apps that use CRDT fields.
973
+ */
974
+ constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
975
+ getDoc(): LoroDoc;
976
+ /** Whether the LoroDoc was loaded from saved CRDT state */
977
+ hasContent(): boolean;
978
+ startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
979
+ /**
980
+ * Stop syncing this field. Flushes one final remote push by default so the
981
+ * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
982
+ * the remote session already belongs to the NEXT user, and pushing this
983
+ * (previous user's) snapshot under it would clobber the record remotely.
984
+ */
985
+ stopSync(options?: {
986
+ flush?: boolean;
987
+ }): void;
988
+ importRemote(state: Uint8Array): void;
989
+ exportSnapshot(): Uint8Array;
990
+ /** Push this session's cursor blob into the parent row at
991
+ * `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
992
+ * field — the editor still calls this method optimistically, but
993
+ * without `@cursor` on the schema there's nowhere to store the blob.
994
+ * The UPDATE itself fires the parent table's LIVE feed, so other
995
+ * browsers receive the cursor change without a separate `_00_rv` bump. */
996
+ pushCursorState(encoded: Uint8Array): Promise<void>;
997
+ /** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
998
+ importRemoteCursor(base64State: string): void;
999
+ private scheduleRemotePush;
1000
+ /** SET path inside a parent row for the current snapshot. `@crdt`-only
1001
+ * fields hold the snapshot directly (`<field>`); `@crdt @cursor`
1002
+ * fields hold a `{ state, cursors }` object so the snapshot lives at
1003
+ * `<field>.state` next to per-session cursor blobs. */
1004
+ private statePath;
1005
+ /** Mirror the LoroDoc snapshot into the parent row locally. Runs on
1006
+ * every local update and every remote import so reloads (online or
1007
+ * offline) see the freshest content immediately. Failures are
1008
+ * swallowed — a stale local write must never block user input. */
1009
+ private persistLocal;
1010
+ private pushToRemote;
1011
+ }
1012
+ //#endregion
1013
+ //#region src/modules/crdt/index.d.ts
1014
+ /**
1015
+ * CrdtManager manages active CrdtField instances and their sync channels.
1016
+ *
1017
+ * Collaborative state lives in two dedicated tables (defined in
1018
+ * `apps/cli/src/meta_tables_remote.surql`):
1019
+ * - `_00_crdt` { record_id, field, state } — one row per (record, field)
1020
+ * - `_00_cursor` { record_id, session_id, field, state } — one row per
1021
+ * (record, session, field)
1022
+ *
1023
+ * Splitting them off the parent row is what makes offline edits mergeable:
1024
+ * each (record, field) gets its own row, so concurrent offline writes don't
1025
+ * collide on the parent's last-write-wins semantics.
1026
+ *
1027
+ * Cross-browser delivery still rides the parent table's existing LIVE feed
1028
+ * to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
1029
+ * (issues 3602, 4026). On every meta UPSERT the writer also bumps the
1030
+ * parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
1031
+ * feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
1032
+ * via subquery. Permission inheritance happens server-side via
1033
+ * `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
1034
+ */
1035
+ declare class CrdtManager {
1036
+ private schema;
1037
+ private local;
1038
+ private remote;
1039
+ private debounceMs;
1040
+ private fields;
1041
+ private liveByTable;
1042
+ private pendingLive;
1043
+ private logger;
1044
+ private sessionId;
1045
+ constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
1046
+ /** Set the session id that scopes this client's cursor entries. Must be
1047
+ * called before `open()` for cursors to be pushed under a stable key.
1048
+ * Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
1049
+ * for the data-module salt). */
1050
+ setSessionId(sessionId: string): void;
1051
+ /**
1052
+ * Open a CRDT field for collaborative editing.
1053
+ *
1054
+ * @param table - Table name
1055
+ * @param recordId - Full record ID (e.g., "thread:abc")
1056
+ * @param field - Field name (e.g., "title", "content")
1057
+ * @param fallbackText - Current plain text from the record, used to seed the
1058
+ * LoroDoc if no CRDT state exists yet (migration path)
1059
+ */
1060
+ open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
1061
+ close(table: string, recordId: string, field: string): void;
1062
+ /**
1063
+ * Close every open field + table LIVE. Fields flush a final remote push by
1064
+ * default; pass `{ flush: false }` on a bucket switch, where that flush
1065
+ * would push the previous user's snapshot under the next user's session.
1066
+ */
1067
+ closeAll(options?: {
1068
+ flush?: boolean;
1069
+ }): void;
1070
+ /** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
1071
+ * every open CrdtField on `table`. */
1072
+ private ensureTableSubscription;
1073
+ /** Apply a parent-row payload from a non-LIVE source (e.g. the
1074
+ * list_ref-driven sync engine, when the cross-user LIVE on the
1075
+ * parent table is filtered out by the SurrealDB cross-session
1076
+ * permission gap). Same semantics as the internal `dispatchRow`. */
1077
+ applyRow(table: string, row: Record<string, unknown>): void;
1078
+ /** Dispatch a parent-row LIVE event to every open CrdtField on that
1079
+ * record. Each open field reads its slice of the row directly — the
1080
+ * CRDT snapshot is a column on the parent now, so there is no
1081
+ * follow-up subquery. */
1082
+ private dispatchRow;
1083
+ /** One-shot remote fetch for a row whose CRDT field hasn't synced
1084
+ * locally yet (fresh device, memory-backed local DB after reload, …).
1085
+ * Used by `open()` when the local read came up empty. Subsequent
1086
+ * cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
1087
+ private fetchAndDispatchRow;
1088
+ /** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
1089
+ * Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
1090
+ private fieldHasCursor;
1091
+ /** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
1092
+ * the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
1093
+ * `{ state, cursors }` where `state` carries the snapshot bytes. */
1094
+ private extractSnapshot;
1095
+ private killTableSubscription;
1096
+ private makeKey;
1097
+ /**
1098
+ * Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
1099
+ * typos, removed annotations, and stale schema codegen at the call site instead
1100
+ * of silently producing a non-CRDT writer.
1101
+ */
1102
+ private assertCrdtField;
1103
+ }
1104
+ //#endregion
1105
+ //#region src/modules/feature-flag/index.d.ts
1106
+ interface FeatureFlagSnapshot {
1107
+ variant: string | undefined;
1108
+ payload: unknown | undefined;
1109
+ }
1110
+ interface FeatureFlagOptions {
1111
+ fallback?: string;
1112
+ ttl?: QueryTimeToLive;
1113
+ }
1114
+ declare class FeatureFlagHandle {
1115
+ readonly key: string;
1116
+ readonly fallback: string | undefined;
1117
+ private latest;
1118
+ private listeners;
1119
+ private unsubscribeFn;
1120
+ private onCloseFn;
1121
+ private closed;
1122
+ constructor(key: string, fallback: string | undefined);
1123
+ attach(unsubscribe: () => void): void;
1124
+ detach(): void;
1125
+ set(snapshot: FeatureFlagSnapshot): void;
1126
+ variant(): string | undefined;
1127
+ payload<T = unknown>(): T | undefined;
1128
+ enabled(): boolean;
1129
+ subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void;
1130
+ onClose(cb: () => void): void;
1131
+ close(): void;
1132
+ }
1133
+ interface FeatureFlagModuleDeps<S extends SchemaStructure> {
1134
+ dataModule: DataModule<S>;
1135
+ sync: Sp00kySync<S>;
1136
+ auth: AuthService<S>;
1137
+ logger: Logger$1;
1138
+ }
1139
+ declare class FeatureFlagModule<S extends SchemaStructure> {
1140
+ private deps;
1141
+ private logger;
1142
+ private handles;
1143
+ private authUnsubscribe;
1144
+ private lastUserId;
1145
+ private querySubscription;
1146
+ private starting;
1147
+ private ttl;
1148
+ private snapshots;
1149
+ private loaded;
1150
+ constructor(deps: FeatureFlagModuleDeps<S>);
1151
+ init(): void;
1152
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
1153
+ closeAll(): Promise<void>;
1154
+ /** Auth changed: drop the old user's query/snapshots and re-observe. */
1155
+ private refresh;
1156
+ private teardownQuery;
1157
+ /** Start the single shared live query (idempotent; no-op with no handles). */
1158
+ private ensureStarted;
1159
+ /** Live query result → per-key snapshots → push to every active handle. */
1160
+ private applyRecords;
1161
+ }
1162
+ //#endregion
1163
+ //#region src/modules/app-release/index.d.ts
1164
+ interface AppReleaseSnapshot {
1165
+ /** Latest announced version for the app, or undefined when no row exists. */
1166
+ version: string | undefined;
1167
+ /** Clients should clear SW/caches when reloading onto this version. */
1168
+ cacheBust: boolean;
1169
+ /** Clients should reload/update immediately instead of asking. */
1170
+ mandatory: boolean;
1171
+ releasedAt: string | undefined;
1172
+ }
1173
+ interface AppReleaseOptions {
1174
+ ttl?: QueryTimeToLive;
1175
+ }
1176
+ declare class AppReleaseHandle {
1177
+ readonly app: string;
1178
+ private latest;
1179
+ private listeners;
1180
+ private onCloseFn;
1181
+ private closed;
1182
+ constructor(app: string);
1183
+ set(snapshot: AppReleaseSnapshot): void;
1184
+ snapshot(): AppReleaseSnapshot;
1185
+ version(): string | undefined;
1186
+ /** True when the announced version is semver-newer than `currentVersion`. */
1187
+ updateAvailable(currentVersion: string): boolean;
1188
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
1189
+ onClose(cb: () => void): void;
1190
+ close(): void;
1191
+ }
1192
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
1193
+ dataModule: DataModule<S>;
1194
+ sync: Sp00kySync<S>;
1195
+ auth: AuthService<S>;
1196
+ logger: Logger$1;
1197
+ }
1198
+ declare class AppReleaseModule<S extends SchemaStructure> {
1199
+ private deps;
1200
+ private logger;
1201
+ private handles;
1202
+ private authUnsubscribe;
1203
+ private lastUserId;
1204
+ private querySubscription;
1205
+ private starting;
1206
+ private ttl;
1207
+ private snapshots;
1208
+ private loaded;
1209
+ constructor(deps: AppReleaseModuleDeps<S>);
1210
+ init(): void;
1211
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
1212
+ closeAll(): Promise<void>;
1213
+ private refresh;
1214
+ private teardownQuery;
1215
+ private ensureStarted;
1216
+ private applyRecords;
1217
+ }
1218
+ //#endregion
1219
+ //#region src/sp00ky.d.ts
547
1220
  declare class BucketHandle {
548
1221
  private bucketName;
549
1222
  private remote;
@@ -557,7 +1230,7 @@ declare class BucketHandle {
557
1230
  rename(sourcePath: string, targetPath: string): Promise<void>;
558
1231
  list(prefix?: string): Promise<string[]>;
559
1232
  }
560
- declare class SpookyClient<S extends SchemaStructure> {
1233
+ declare class Sp00kyClient<S extends SchemaStructure> {
561
1234
  private config;
562
1235
  private local;
563
1236
  private remote;
@@ -567,28 +1240,161 @@ declare class SpookyClient<S extends SchemaStructure> {
567
1240
  private dataModule;
568
1241
  private sync;
569
1242
  private devTools;
1243
+ private crdtManager;
1244
+ private featureFlags;
1245
+ private appReleases;
1246
+ private preloadedHashes;
1247
+ private pendingQueryInits;
570
1248
  private logger;
571
1249
  auth: AuthService<S>;
572
1250
  streamProcessor: StreamProcessorService;
573
- get remoteClient(): Surreal;
574
- get localClient(): Surreal;
1251
+ get remoteClient(): surrealdb0.Surreal;
1252
+ get localClient(): unknown;
575
1253
  get pendingMutationCount(): number;
1254
+ /** Number of times the initial list_ref LIVE subscription retried on
1255
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
1256
+ * pre-emptive user-table creation got there first; >0 when LIVE
1257
+ * registration hit a "table not found" race. Exposed so the e2e
1258
+ * suite can guard the pre-emptive path against regression. */
1259
+ get liveRetryCount(): number;
576
1260
  subscribeToPendingMutations(cb: (count: number) => void): () => void;
577
- constructor(config: SpookyConfig<S>);
1261
+ /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
1262
+ get syncHealth(): SyncHealth;
1263
+ /**
1264
+ * Observe sync health. Fires immediately with the current status and again
1265
+ * on every healthy↔degraded transition. Returns an unsubscribe.
1266
+ */
1267
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
1268
+ constructor(config: Sp00kyConfig<S>);
578
1269
  /**
579
1270
  * Setup direct callbacks instead of event subscriptions
580
1271
  */
581
1272
  private setupCallbacks;
582
1273
  init(): Promise<void>;
1274
+ private bucketSwitchChain;
1275
+ private pendingBucketTarget;
1276
+ /**
1277
+ * Ensure the local store is this user's bucket, switching if needed. Called
1278
+ * from the auth listener on every auth flip; concurrent calls are chained
1279
+ * and superseded intermediates are skipped (latest target wins).
1280
+ */
1281
+ private ensureLocalBucket;
1282
+ /**
1283
+ * The bucket-switch choreography: drain → swap → rebind.
1284
+ *
1285
+ * Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
1286
+ * outbox delete lands in the OLD bucket, debounce timers cancelled),
1287
+ * DataModule timers cleared, CRDT fields closed WITHOUT their final flush
1288
+ * (the remote session already belongs to the next user).
1289
+ *
1290
+ * Swap: gate closes so any local query issued mid-switch (sibling auth
1291
+ * subscribers, FeatureFlagModule) waits and then runs against the NEW
1292
+ * bucket; store swaps open-new-before-close-old; schema provisions
1293
+ * (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
1294
+ * sessionId-salted hashes with stale arrays — record bodies stay warm);
1295
+ * SSP resets to a fresh circuit with re-seeded permissions.
1296
+ *
1297
+ * Rebind: auth token re-persisted (the surrealdb persistence client wrote it
1298
+ * into the OLD bucket's `_00_kv` before this listener ran), active queries
1299
+ * re-homed keeping their hashes, sync resumed on the new bucket's own
1300
+ * outbox, and every query re-registered remotely to refill from the server.
1301
+ */
1302
+ private doSwitchBucket;
583
1303
  close(): Promise<void>;
1304
+ /**
1305
+ * Subscribe to a feature flag for the current user. Returns a
1306
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
1307
+ * accessors reflect the latest assignment from `_00_user_feature`,
1308
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
1309
+ *
1310
+ * Permissions are enforced by SurrealDB: a client can only ever see
1311
+ * its own row, and cannot create or modify assignments.
1312
+ */
1313
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
1314
+ /**
1315
+ * Observe the announced release of an app (`_00_app_release:<app>`, written
1316
+ * by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
1317
+ * announced version plus the cache-bust/mandatory flags, and
1318
+ * `updateAvailable(currentVersion)` compares it semver-wise against the
1319
+ * running build. World-readable; writes are root-only.
1320
+ */
1321
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
584
1322
  authenticate(token: string): Promise<surrealdb0.Tokens>;
1323
+ /**
1324
+ * Open a CRDT field for collaborative editing.
1325
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
1326
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
1327
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
1328
+ */
1329
+ openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
1330
+ /**
1331
+ * Close a CRDT field when editing is done.
1332
+ */
1333
+ closeCrdtField(table: string, recordId: string, field: string): void;
585
1334
  deauthenticate(): Promise<void>;
586
- query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, SpookyQueryResultPromise>;
1335
+ query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
587
1336
  private initQuery;
1337
+ /**
1338
+ * Background tail of {@link initQuery}: instant-hydrate (opt-in via
1339
+ * `config.instantHydrate`, and only when the query is cold) followed by
1340
+ * enqueuing the `register` down-event. Never rejects — both halves catch and
1341
+ * log, so `void`-ing the returned promise can't produce an unhandled
1342
+ * rejection. By default (hydrate off) the register lifecycle is the single
1343
+ * freshness path; the one-shot fetch is an optimization apps enable
1344
+ * explicitly, and it runs regardless of preload state — cache-first delivery
1345
+ * never depends on WHY rows are cached.
1346
+ */
1347
+ private finishQueryInit;
1348
+ /**
1349
+ * Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
1350
+ * live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
1351
+ *
1352
+ * Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
1353
+ * - COLD (never preloaded in this bucket): fetch the query one-shot from the
1354
+ * remote, persist the rows (+ embedded `.related()` children), stamp the
1355
+ * marker — and AWAIT it. This is the "smart waiting" first load: callers can
1356
+ * `await db.preload(...)` to hold the UI until the data is ready.
1357
+ * - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
1358
+ * whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
1359
+ * Default `onUse` does nothing; the data freshens when the real `useQuery`
1360
+ * mounts and registers its live view.
1361
+ *
1362
+ * Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
1363
+ * written, so it's retried next load). Deduped per session by query hash.
1364
+ */
1365
+ preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
1366
+ /**
1367
+ * One-shot remote fetch + local persist for a preload query. Returns the row
1368
+ * count on success, or -1 on failure (best-effort: logged, never thrown) so
1369
+ * the caller skips stamping the freshness marker and retries next load.
1370
+ */
1371
+ private fetchAndPersist;
588
1372
  queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
589
1373
  subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
590
1374
  immediate?: boolean;
591
1375
  }): Promise<() => void>;
1376
+ /**
1377
+ * Opt-in eager teardown for a query whose last subscriber has gone away
1378
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
1379
+ * while any subscriber remains. Tears down the remote `_00_query` view +
1380
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
1381
+ * (no call here) keeps the view resident for cheap re-subscription.
1382
+ */
1383
+ deregisterQuery(queryHash: string): void;
1384
+ /**
1385
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
1386
+ * `{ immediate: true }` the callback fires synchronously with the current
1387
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
1388
+ */
1389
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
1390
+ immediate?: boolean;
1391
+ }): () => void;
1392
+ /**
1393
+ * Report the frontend processing time (ms) a client framework spent applying
1394
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
1395
+ * surface the "frontend" phase of the per-query timing breakdown.
1396
+ */
1397
+ reportFrontendTiming(queryHash: string, ms: number): void;
592
1398
  run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
593
1399
  bucket<B extends BucketNames<S>>(name: B): BucketHandle;
594
1400
  create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
@@ -597,15 +1403,29 @@ declare class SpookyClient<S extends SchemaStructure> {
597
1403
  }>;
598
1404
  delete(table: string, id: string): Promise<void>;
599
1405
  useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
600
- private persistClientId;
601
- private loadOrGenerateClientId;
1406
+ /**
1407
+ * Fetch SurrealDB's `session::id()` as a string. Used as a salt for
1408
+ * query-id hashing so two sessions for the same user get distinct
1409
+ * `_00_query` rows. Returns empty string if the query fails (we still
1410
+ * boot, just without session scoping for IDs).
1411
+ */
1412
+ private fetchSessionId;
602
1413
  }
603
1414
  //#endregion
1415
+ //#region src/utils/semver.d.ts
1416
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
1417
+ declare function semverGt(a: unknown, b: unknown): boolean;
1418
+ //#endregion
604
1419
  //#region src/utils/index.d.ts
605
1420
  declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
1421
+ /**
1422
+ * Convert plain text to simple HTML paragraphs.
1423
+ * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
1424
+ */
1425
+ declare function textToHtml(text: string): string;
606
1426
  /**
607
1427
  * Helper for retrying DB operations with exponential backoff
608
1428
  */
609
1429
 
610
1430
  //#endregion
611
- export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, DebounceOptions, EventSubscriptionOptions, type Level, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryTimeToLive, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RunOptions, SpookyClient, SpookyConfig, SpookyQueryResult, SpookyQueryResultPromise, StoreType, UpdateOptions, createAuthEventSystem, fileToUint8Array };
1431
+ export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagSnapshot, Level, MATERIALIZATION_SAMPLE_WINDOW, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, createAuthEventSystem, cursorColorFromName, fileToUint8Array, semverGt, textToHtml };