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