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