@spooky-sync/client-svelte 0.0.0-stage → 0.0.1-canary.383

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.
@@ -0,0 +1,266 @@
1
+ import { untrack } from 'svelte';
2
+ import { SyncedDb } from './db.js';
3
+ import { read, toError, useDb } from './context.js';
4
+ // ---------------------------------------------------------------------------
5
+ // Pure part: structural sharing between emissions.
6
+ // NOTE: keep in sync with packages/client-react/src/query.ts (`share`).
7
+ // ---------------------------------------------------------------------------
8
+ const isPlainObject = (v) => {
9
+ if (v === null || typeof v !== 'object')
10
+ return false;
11
+ const proto = Object.getPrototypeOf(v);
12
+ return proto === Object.prototype || proto === null;
13
+ };
14
+ /**
15
+ * Value equality for the leaves `share` does not descend into. The decoder
16
+ * hands out a fresh RecordId / Date / Uuid / Duration for every record-link
17
+ * and datetime column on every emission, so by identity every such field
18
+ * "changed" every time. Two instances of the same class that print alike are
19
+ * the same value. A class whose `toString` is the default `[object X]`
20
+ * (ArrayBuffer, Map, ...) cannot be compared that way and counts as changed.
21
+ */
22
+ export function sameValue(a, b) {
23
+ if (a === b)
24
+ return true;
25
+ if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object')
26
+ return false;
27
+ if (a instanceof Date && b instanceof Date)
28
+ return a.getTime() === b.getTime();
29
+ const ctor = a.constructor;
30
+ if (!ctor || ctor !== b.constructor || ctor === Object || ctor === Array)
31
+ return false;
32
+ const text = String(a);
33
+ return !text.startsWith('[object ') && text === String(b);
34
+ }
35
+ const keyOf = (v) => {
36
+ if (!isPlainObject(v))
37
+ return undefined;
38
+ const id = v.id;
39
+ return id === undefined || id === null ? undefined : String(id);
40
+ };
41
+ /**
42
+ * Structural sharing between two emissions: returns `prev` itself where
43
+ * `next` is deep-equal to it, and a new value that reuses every unchanged
44
+ * subtree otherwise. Array items with an `id` are matched by id, so a row keeps
45
+ * its object identity across reorders, inserts and deletes.
46
+ *
47
+ * That is what makes `$state.raw` fine-grained enough here: a keyed `{#each}`
48
+ * hands an unchanged row the same object, so its block does not update, and a
49
+ * deep-equal emission is the same value, so nothing reading `data` re-runs.
50
+ *
51
+ * Never mutates either argument: the engine may hand the same row objects to
52
+ * several subscribers.
53
+ */
54
+ export function share(prev, next) {
55
+ if (prev === next)
56
+ return next;
57
+ if (Array.isArray(prev) && Array.isArray(next)) {
58
+ const byKey = new Map();
59
+ for (const item of prev) {
60
+ const k = keyOf(item);
61
+ if (k !== undefined)
62
+ byKey.set(k, item);
63
+ }
64
+ let same = prev.length === next.length;
65
+ const out = next.map((item, i) => {
66
+ const k = keyOf(item);
67
+ const base = k !== undefined ? byKey.get(k) : prev[i];
68
+ const v = base === undefined ? item : share(base, item);
69
+ if (v !== prev[i])
70
+ same = false;
71
+ return v;
72
+ });
73
+ return (same ? prev : out);
74
+ }
75
+ if (isPlainObject(prev) && isPlainObject(next)) {
76
+ const keys = Object.keys(next);
77
+ let same = keys.length === Object.keys(prev).length;
78
+ const out = {};
79
+ for (const k of keys) {
80
+ const v = k in prev ? share(prev[k], next[k]) : next[k];
81
+ if (v !== prev[k] || !(k in prev))
82
+ same = false;
83
+ out[k] = v;
84
+ }
85
+ return (same ? prev : out);
86
+ }
87
+ return (sameValue(prev, next) ? prev : next);
88
+ }
89
+ const EMPTY_LIST = Object.freeze([]);
90
+ export function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
91
+ const explicit = dbOrQuery instanceof SyncedDb ? dbOrQuery : null;
92
+ const db = explicit ?? useDb();
93
+ const queryArg = (explicit ? queryOrOptions : dbOrQuery);
94
+ const options = (explicit ? maybeOptions : queryOrOptions);
95
+ const sp00ky = db.getSp00ky();
96
+ // Rows are plain objects (`$state.raw`, never deep proxies): they reach
97
+ // `db.update(...)`, workers and third-party code as the engine produced them.
98
+ let data = $state.raw(null);
99
+ let error = $state.raw(undefined);
100
+ // Server membership known and painted for the current identity (core authority).
101
+ let isAuthoritative = $state(false);
102
+ // An emission WITH data was applied for the current identity. With
103
+ // `isAuthoritative` this ends the cold load: a cached paint ends it without
104
+ // the server, a server answer ends it without rows.
105
+ let hasPainted = $state(false);
106
+ let isFetching = $state(false);
107
+ // Registered hash of the attached query, for opt-in deregistration.
108
+ let activeHash;
109
+ // The built query (a new object whenever what the getter reads changes)…
110
+ const resolved = $derived.by(() => {
111
+ const enabled = read(options?.enabled ?? true);
112
+ return enabled ? (read(queryArg) ?? null) : null;
113
+ });
114
+ // …and its identity. Primitives, so the attach effect below only re-runs
115
+ // when the query really changed, not on every rebuild of the same one.
116
+ const identity = $derived(resolved ? String(resolved.hash) : null);
117
+ const isOne = $derived(resolved?.isOne);
118
+ $effect(() => {
119
+ const id = identity;
120
+ // A new identity starts clean: authority, the paint latch and a previous
121
+ // identity's error reset. `data` stays until the new identity emits, so
122
+ // growing a `.limit()` does not flash an empty list.
123
+ untrack(() => {
124
+ isAuthoritative = false;
125
+ hasPainted = false;
126
+ isFetching = false;
127
+ error = undefined;
128
+ });
129
+ if (id === null)
130
+ return;
131
+ const query = untrack(() => resolved);
132
+ if (!query)
133
+ return;
134
+ let disposed = false;
135
+ const cleanups = [];
136
+ // `sp00ky.subscribe` resolves its unsubscribe asynchronously; the status
137
+ // and authority subscriptions return one directly. If teardown already
138
+ // happened while the promise was in flight, unsubscribe at once.
139
+ const addCleanup = (c) => {
140
+ if (typeof c === 'function') {
141
+ if (disposed)
142
+ c();
143
+ else
144
+ cleanups.push(c);
145
+ return;
146
+ }
147
+ void c.then((fn) => {
148
+ if (disposed)
149
+ fn();
150
+ else
151
+ cleanups.push(fn);
152
+ }, () => { });
153
+ };
154
+ // Registration can fail, canonically the SSP answering 503 NOT_READY
155
+ // while it bootstraps. That surfaces as `error`; the sync scheduler retries
156
+ // the registration underneath, so a transient failure still recovers.
157
+ query.run().then(({ hash }) => {
158
+ if (disposed)
159
+ return;
160
+ activeHash = hash;
161
+ addCleanup(sp00ky.subscribeQueryStatus(hash, (status) => {
162
+ if (!disposed)
163
+ isFetching = status === 'fetching';
164
+ }, { immediate: true }));
165
+ addCleanup(sp00ky.subscribe(hash, (rows) => {
166
+ if (disposed)
167
+ return;
168
+ const t0 = performance.now();
169
+ // Every emission is applied as-is: the core only emits what it
170
+ // decided the query holds. One WITH data ends the cold load.
171
+ const next = query.isOne ? (rows[0] ?? null) : rows;
172
+ data = share(untrack(() => data), next);
173
+ if (query.isOne ? next !== null && next !== undefined : rows.length > 0) {
174
+ hasPainted = true;
175
+ }
176
+ sp00ky.reportFrontendTiming(hash, performance.now() - t0);
177
+ }, { immediate: true }));
178
+ // Subscribed after the rows, so the immediate deliveries keep the
179
+ // core's order: authority flips only after the rows it covers. This is
180
+ // the channel that ends a cold load whose honest answer is zero rows.
181
+ // A flip back to false is a bucket switch (another principal): what is
182
+ // painted is the previous one's, so the paint latch goes with it.
183
+ addCleanup(sp00ky.subscribeQueryAuthority(hash, (known) => {
184
+ if (disposed)
185
+ return;
186
+ isAuthoritative = known;
187
+ if (!known)
188
+ hasPainted = false;
189
+ }, { immediate: true }));
190
+ }, (err) => {
191
+ if (!disposed)
192
+ error = toError(err);
193
+ });
194
+ return () => {
195
+ disposed = true;
196
+ for (const c of cleanups)
197
+ c();
198
+ };
199
+ });
200
+ if (options?.deregisterOnCleanup) {
201
+ // Declared after the attach effect, so on destroy its teardown runs second:
202
+ // this hook's callback is already gone and deregisterQuery's refcount
203
+ // guard sees the true remaining-subscriber count.
204
+ $effect(() => () => {
205
+ if (activeHash)
206
+ sp00ky.deregisterQuery(activeHash);
207
+ });
208
+ }
209
+ const current = () => {
210
+ const v = data;
211
+ if (isOne === false && !Array.isArray(v))
212
+ return EMPTY_LIST;
213
+ if (isOne === true && Array.isArray(v))
214
+ return null;
215
+ return v;
216
+ };
217
+ const hasData = () => {
218
+ const v = current();
219
+ return Array.isArray(v) ? v.length > 0 : v !== null && v !== undefined;
220
+ };
221
+ return {
222
+ get data() {
223
+ return current();
224
+ },
225
+ get error() {
226
+ return error;
227
+ },
228
+ get isLoading() {
229
+ return !isAuthoritative && !hasPainted && error === undefined;
230
+ },
231
+ get isFetching() {
232
+ return isFetching;
233
+ },
234
+ get isAuthoritative() {
235
+ return isAuthoritative;
236
+ },
237
+ get hasData() {
238
+ return hasData();
239
+ },
240
+ get isEmpty() {
241
+ return isAuthoritative && !hasData();
242
+ },
243
+ get isSettled() {
244
+ return isAuthoritative && !isFetching;
245
+ },
246
+ };
247
+ }
248
+ export function usePreload(dbOrQuery, queryOrOptions, maybeOptions) {
249
+ const explicit = dbOrQuery instanceof SyncedDb ? dbOrQuery : null;
250
+ const db = explicit ?? useDb();
251
+ const queryArg = (explicit ? queryOrOptions : dbOrQuery);
252
+ const options = (explicit ? maybeOptions : queryOrOptions);
253
+ const resolved = $derived.by(() => read(options?.enabled ?? true) ? (read(queryArg) ?? null) : null);
254
+ const identity = $derived(resolved ? String(resolved.hash) : null);
255
+ $effect(() => {
256
+ if (identity === null)
257
+ return;
258
+ const query = untrack(() => resolved);
259
+ if (!query)
260
+ return;
261
+ void db
262
+ .getSp00ky()
263
+ .preload(query, { signal: options?.signal })
264
+ .catch(() => { });
265
+ });
266
+ }
@@ -0,0 +1,51 @@
1
+ import type { ChannelPeer, ChannelTableNames, SchemaStructure } from '@spooky-sync/query-builder';
2
+ import type { ChannelQuery, ChannelStatus, CrdtField, Sp00kyChannel } from '@spooky-sync/core';
3
+ import type { SyncedDb } from './db.js';
4
+ import type { ReactiveValue } from './status.svelte.js';
5
+ import type { MaybeGetter } from './types.js';
6
+ /**
7
+ * Open a `@crdt` field of the record `recordId` names, for an editor to bind
8
+ * to (`field.current?.getDoc()`). Re-opens when the id changes, closes with the
9
+ * component. Pass the id as a getter (`() => postId`) to follow state.
10
+ *
11
+ * `.current` stays `null` until the field is loaded (`CrdtField.isLoaded`):
12
+ * this device had the document, or the server answered. Until then show the
13
+ * column's text instead of binding an editor to a document still arriving.
14
+ */
15
+ export declare function useCrdtField(table: string, recordId: MaybeGetter<string | null | undefined>, field: string, db?: SyncedDb<any>): ReactiveValue<CrdtField | null>;
16
+ /** Who a channel connects to. */
17
+ export type ChannelPeers = Iterable<ChannelPeer>;
18
+ /** What a channel carries: the rows a query (or several) matches. */
19
+ export type ChannelQueries<S extends SchemaStructure, T extends ChannelTableNames<S>> = ChannelQuery<S, T> | ReadonlyArray<ChannelQuery<S, T>>;
20
+ /** An open channel, for as long as the component lives. Fields are reactive getters. */
21
+ export interface UseChannel<S extends SchemaStructure, T extends string> {
22
+ /** `idle` | `connecting` | `connected` | `failed` | `unsupported`. */
23
+ readonly status: ChannelStatus;
24
+ /** Users with a tab connected. */
25
+ readonly peers: ReadonlyArray<string>;
26
+ /** Writes that go to THIS channel's peers only (when the row matches its query), plus the database as always. */
27
+ update: Sp00kyChannel<S, T>['update'];
28
+ create: Sp00kyChannel<S, T>['create'];
29
+ delete: Sp00kyChannel<S, T>['delete'];
30
+ }
31
+ /**
32
+ * Open a peer to peer channel to `peers` for the rows `query` matches, for the
33
+ * lifetime of the component. The query must be on a `-- @channel` table and
34
+ * only its `where` counts; it is checked against each row, never registered.
35
+ * Writes to matching rows (`db.update` / `db.create` / `db.delete`, or the
36
+ * channel's own) reach the peers over WebRTC in tens of ms; `-- @ephemeral`
37
+ * fields travel only this way. A connection forms when both sides list each
38
+ * other; your own id is skipped.
39
+ *
40
+ * ```ts
41
+ * const ch = useChannel(
42
+ * () => db.query('message').where({ conversation: convoId }),
43
+ * () => [me, other]
44
+ * );
45
+ * ```
46
+ *
47
+ * Both arguments may be getters (re-read when what they read changes) and are
48
+ * compared by value, so rebuilding them is free. A `null` query closes the
49
+ * channel until a query comes back.
50
+ */
51
+ export declare function useChannel<S extends SchemaStructure, T extends ChannelTableNames<S>>(query: MaybeGetter<ChannelQueries<S, T> | null | undefined>, peers: MaybeGetter<ChannelPeers | null | undefined>, db?: SyncedDb<any>): UseChannel<S, T>;
@@ -0,0 +1,141 @@
1
+ import { untrack } from 'svelte';
2
+ import { read, useDb } from './context.js';
3
+ /**
4
+ * Open a `@crdt` field of the record `recordId` names, for an editor to bind
5
+ * to (`field.current?.getDoc()`). Re-opens when the id changes, closes with the
6
+ * component. Pass the id as a getter (`() => postId`) to follow state.
7
+ *
8
+ * `.current` stays `null` until the field is loaded (`CrdtField.isLoaded`):
9
+ * this device had the document, or the server answered. Until then show the
10
+ * column's text instead of binding an editor to a document still arriving.
11
+ */
12
+ export function useCrdtField(table, recordId, field, db = useDb()) {
13
+ let current = $state.raw(null);
14
+ $effect(() => {
15
+ const id = read(recordId);
16
+ if (!id)
17
+ return;
18
+ const sp00ky = db.getSp00ky();
19
+ let superseded = false;
20
+ let isOpen = false;
21
+ let offLoaded = () => { };
22
+ sp00ky
23
+ .openCrdtField(table, id, field)
24
+ .then((cf) => {
25
+ isOpen = true;
26
+ if (superseded) {
27
+ void sp00ky.closeCrdtField(table, id, field);
28
+ return;
29
+ }
30
+ // Handed out once loaded: an empty document before the server answered
31
+ // is "not arrived yet", not "empty".
32
+ offLoaded = cf.onLoaded(() => {
33
+ if (!superseded)
34
+ current = cf;
35
+ });
36
+ })
37
+ .catch((err) => {
38
+ // A silent rejection leaves the editor stuck on its fallback with no
39
+ // trail; surface the root cause (missing `@crdt` annotation, codegen
40
+ // drift, a local query failure).
41
+ // oxlint-disable-next-line no-console
42
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${id}:`, err);
43
+ });
44
+ return () => {
45
+ superseded = true;
46
+ offLoaded();
47
+ if (isOpen)
48
+ void sp00ky.closeCrdtField(table, id, field);
49
+ current = null;
50
+ };
51
+ });
52
+ return {
53
+ get current() {
54
+ return current;
55
+ },
56
+ };
57
+ }
58
+ const IDLE = { status: 'idle', peers: [] };
59
+ /** Identity of a channel's queries: their hashes (a builder is built first). */
60
+ function queriesKey(q) {
61
+ if (!q)
62
+ return null;
63
+ const list = (Array.isArray(q) ? q : [q]);
64
+ return list
65
+ .map((item) => String('build' in item && typeof item.build === 'function' ? item.build().hash : item.hash))
66
+ .join(',');
67
+ }
68
+ const peersKey = (peers) => [...peers].map((p) => String(p)).join('\u0000');
69
+ /**
70
+ * Open a peer to peer channel to `peers` for the rows `query` matches, for the
71
+ * lifetime of the component. The query must be on a `-- @channel` table and
72
+ * only its `where` counts; it is checked against each row, never registered.
73
+ * Writes to matching rows (`db.update` / `db.create` / `db.delete`, or the
74
+ * channel's own) reach the peers over WebRTC in tens of ms; `-- @ephemeral`
75
+ * fields travel only this way. A connection forms when both sides list each
76
+ * other; your own id is skipped.
77
+ *
78
+ * ```ts
79
+ * const ch = useChannel(
80
+ * () => db.query('message').where({ conversation: convoId }),
81
+ * () => [me, other]
82
+ * );
83
+ * ```
84
+ *
85
+ * Both arguments may be getters (re-read when what they read changes) and are
86
+ * compared by value, so rebuilding them is free. A `null` query closes the
87
+ * channel until a query comes back.
88
+ */
89
+ export function useChannel(query, peers, db = useDb()) {
90
+ let state = $state.raw(IDLE);
91
+ let channel = null;
92
+ const readQuery = () => read(query);
93
+ const readPeers = () => read(peers) ?? [];
94
+ const qKey = $derived(queriesKey(readQuery()));
95
+ const pKey = $derived(peersKey(readPeers()));
96
+ const isOpen = $derived(qKey !== null);
97
+ $effect(() => {
98
+ if (!isOpen)
99
+ return;
100
+ const ch = db.channel(untrack(readQuery), untrack(readPeers));
101
+ channel = ch;
102
+ const stop = ch.subscribe((s) => {
103
+ state = s;
104
+ });
105
+ return () => {
106
+ stop();
107
+ ch.close();
108
+ if (channel === ch)
109
+ channel = null;
110
+ state = IDLE;
111
+ };
112
+ });
113
+ // Re-scope and re-peer an open channel in place. Their first run repeats
114
+ // what the channel was just opened with, which is harmless.
115
+ $effect(() => {
116
+ void qKey;
117
+ const q = untrack(readQuery);
118
+ if (q)
119
+ channel?.setQueries(q);
120
+ });
121
+ $effect(() => {
122
+ void pKey;
123
+ channel?.setPeers(untrack(readPeers));
124
+ });
125
+ const open = () => {
126
+ if (!channel)
127
+ throw new Error('This channel is closed (its query is null, or the component is gone).');
128
+ return channel;
129
+ };
130
+ return {
131
+ get status() {
132
+ return state.status;
133
+ },
134
+ get peers() {
135
+ return state.peers;
136
+ },
137
+ update: ((...args) => open().update(...args)),
138
+ create: ((...args) => open().create(...args)),
139
+ delete: ((...args) => open().delete(...args)),
140
+ };
141
+ }
@@ -0,0 +1,185 @@
1
+ import { type AppReleaseOptions, type ConnectionState, type FeatureFlagOptions, type ImpersonationInfo, type StorageHealth, type StorageHealthStatus, type SyncHealth, type SyncHealthStatus } from '@spooky-sync/core';
2
+ import type { SyncedDb } from './db.js';
3
+ /** A single reactive value, read as `.current` (the `svelte/reactivity` convention). */
4
+ export interface ReactiveValue<T> {
5
+ readonly current: T;
6
+ }
7
+ /**
8
+ * Count of locally committed mutations not acknowledged by the server yet.
9
+ * Drive an "unsaved changes" indicator off `.current`.
10
+ */
11
+ export declare function usePendingMutations(db?: SyncedDb<any>): ReactiveValue<number>;
12
+ export interface UseSyncStatus {
13
+ /** Full health snapshot. */
14
+ readonly health: SyncHealth;
15
+ /** `'healthy'` | `'degraded'`. */
16
+ readonly status: SyncHealthStatus;
17
+ readonly isHealthy: boolean;
18
+ /** `true` once sync has failed for a sustained run. Drive a banner off this. */
19
+ readonly isDegraded: boolean;
20
+ /** `true` once at least one sync round has succeeded this session. */
21
+ readonly everConnected: boolean;
22
+ /**
23
+ * `true` only for a real lost connection: degraded AFTER a first successful
24
+ * sync. Stays `false` during the initial "connecting" phase.
25
+ */
26
+ readonly isOffline: boolean;
27
+ /**
28
+ * Transport state of the remote WebSocket. Flips the instant the socket
29
+ * drops, unlike `status`, which only degrades after a sustained run of failed
30
+ * sync rounds.
31
+ */
32
+ readonly connection: ConnectionState;
33
+ /** `true` while the connection is being re-established. Usually still healthy. */
34
+ readonly isReconnecting: boolean;
35
+ }
36
+ /**
37
+ * Observe sync health for a "can't reach the server" banner / indicator.
38
+ * Individual sync failures are absorbed by the retry; `isDegraded` only turns
39
+ * on once failures persist (core `syncHealth.degradeAfterConsecutiveFailures`,
40
+ * default 3) and turns off on the next successful round.
41
+ *
42
+ * Needs no component: with the client passed explicitly it also works in a
43
+ * shared `.svelte.ts` module.
44
+ */
45
+ export declare function useSyncStatus(db?: SyncedDb<any>): UseSyncStatus;
46
+ export interface UseStorageStatus {
47
+ /** Full durability snapshot. */
48
+ readonly health: StorageHealth;
49
+ /** `'unknown'` | `'persistent'` | `'memory'`. */
50
+ readonly status: StorageHealthStatus;
51
+ /** `true` when the local store survives a reload. */
52
+ readonly isPersistent: boolean;
53
+ /**
54
+ * `true` only when durable storage was requested and could NOT be opened, so
55
+ * local writes die on reload. Drive a warning off this, not off `status`: a
56
+ * store configured as in-memory reports `'memory'` too, by choice.
57
+ */
58
+ readonly isMemoryFallback: boolean;
59
+ }
60
+ /**
61
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
62
+ * Under `localEngine: 'sqlite'` + `store: 'indexeddb'` only one client per
63
+ * bucket can hold the OPFS store open; a second tab runs in memory.
64
+ */
65
+ export declare function useStorageStatus(db?: SyncedDb<any>): UseStorageStatus;
66
+ export interface UseSyncActivityOptions {
67
+ /**
68
+ * How long queries must be fetching before `isDownloading` turns on. Filters
69
+ * the sub-frame fetches a warm cache produces. Default 200 ms.
70
+ */
71
+ downloadDelayMs?: number;
72
+ /** `isUploading` turns on once MORE than this many writes are queued. Default 0. */
73
+ uploadThreshold?: number;
74
+ /**
75
+ * How long the outbox must stay above `uploadThreshold` before `isUploading`
76
+ * turns on: a write acknowledged within a round trip never lights it.
77
+ * Default 150 ms.
78
+ */
79
+ uploadDelayMs?: number;
80
+ }
81
+ export interface UseSyncActivity {
82
+ /** Queries with traffic the user waits on (core `fetchingQueryCount`). */
83
+ readonly fetchingQueries: number;
84
+ /** Locally committed writes the server has not acknowledged yet. */
85
+ readonly pendingMutations: number;
86
+ /** Fetching for longer than `downloadDelayMs`. Drives a "downloading" mark. */
87
+ readonly isDownloading: boolean;
88
+ /** More than `uploadThreshold` writes queued for longer than `uploadDelayMs`. */
89
+ readonly isUploading: boolean;
90
+ }
91
+ /**
92
+ * The two directions of sync traffic, for an indicator in the app chrome.
93
+ * `isDownloading` and `isUploading` are debounced ON by their delay and off at
94
+ * once, so a page that answers from cache and confirms with the server in a few
95
+ * milliseconds never flickers. Owns timers, so call it while a component
96
+ * initialises (or inside `$effect.root`).
97
+ */
98
+ export declare function useSyncActivity(options?: UseSyncActivityOptions): UseSyncActivity;
99
+ export declare function useSyncActivity(db: SyncedDb<any>, options?: UseSyncActivityOptions): UseSyncActivity;
100
+ export interface UseImpersonationOptions {
101
+ /**
102
+ * This component renders the app's own impersonation banner. Required with
103
+ * `impersonationBanner: { mode: 'custom' }`: it acknowledges the banner, so
104
+ * the client does not fall back to its built-in one.
105
+ */
106
+ rendersBanner?: boolean;
107
+ }
108
+ export interface UseImpersonation {
109
+ /** The active impersonation, or `null`. */
110
+ readonly impersonation: ImpersonationInfo | null;
111
+ readonly isImpersonating: boolean;
112
+ /** Return to the admin session. */
113
+ stop: () => Promise<void>;
114
+ }
115
+ /**
116
+ * Observe admin impersonation (started from the DevTools). The client already
117
+ * shows its own warning bar with a Stop button; use this for anything extra,
118
+ * such as hiding actions an admin should not take on someone's behalf.
119
+ */
120
+ export declare function useImpersonation(options?: UseImpersonationOptions, db?: SyncedDb<any>): UseImpersonation;
121
+ export interface UseFeatureFlag {
122
+ /** Resolved variant (`options.fallback` when unassigned). */
123
+ readonly variant: string | undefined;
124
+ readonly payload: unknown;
125
+ /** The variant is set and not `'off'`. */
126
+ readonly enabled: boolean;
127
+ }
128
+ /**
129
+ * A feature flag for the signed-in user. Updates whenever the
130
+ * server-materialized assignment in `_00_user_feature` changes, so
131
+ * `spky flag enable <key>` reaches the UI without a refresh. The handle closes
132
+ * with the component.
133
+ */
134
+ export declare function useFeatureFlag(key: string, options?: FeatureFlagOptions, db?: SyncedDb<any>): UseFeatureFlag;
135
+ export interface UseAppReleaseOptions extends AppReleaseOptions {
136
+ /** App name from sp00ky.yml, e.g. `web`. */
137
+ app: string;
138
+ /**
139
+ * The running build's version (X.Y.Z), typically baked in at build time
140
+ * (e.g. a vite `define` from package.json).
141
+ */
142
+ currentVersion: string;
143
+ }
144
+ export interface UseAppRelease {
145
+ /** Latest announced version for the app, or undefined when no row exists. */
146
+ readonly latestVersion: string | undefined;
147
+ /** Announced version is semver-newer than the running build. */
148
+ readonly updateAvailable: boolean;
149
+ /** The newer release asks clients to update/reload without prompting. */
150
+ readonly mandatory: boolean;
151
+ /** The newer release asks reloads to clear service-worker caches first. */
152
+ readonly cacheBust: boolean;
153
+ /**
154
+ * Reload onto the announced release. Plain `location.reload()` normally;
155
+ * with cache-bust, CacheStorage is cleared, the service worker is nudged to
156
+ * update (never unregistered) and navigation carries a `?cb=` token.
157
+ */
158
+ reload: () => Promise<void>;
159
+ }
160
+ /**
161
+ * Observe the app's announced release (`_00_app_release:<app>`, written by
162
+ * `spky deploy` / `spky release`) and compare it with the running build, for a
163
+ * "new version available, Reload" notice. Guard an automatic `reload()` on
164
+ * `mandatory` against loops with a per-version marker.
165
+ */
166
+ export declare function useAppRelease(options: UseAppReleaseOptions, db?: SyncedDb<any>): UseAppRelease;
167
+ export interface Submission<Args extends unknown[], R> {
168
+ /** Run the wrapped async fn. Never rejects; a failure lands in `error`. */
169
+ submit: (...args: Args) => Promise<R | undefined>;
170
+ /** True while at least one submit is in flight. */
171
+ readonly pending: boolean;
172
+ /** Error from the most recent settled submit, cleared on the next submit. */
173
+ readonly error: Error | undefined;
174
+ /** Result of the most recent successful submit. */
175
+ readonly result: R | undefined;
176
+ clearError: () => void;
177
+ }
178
+ /**
179
+ * Button pending / error state around a mutation. Deliberately no optimistic
180
+ * layer: the engine already commits writes locally and re-renders through live
181
+ * queries before it syncs. An `error` here means the LOCAL commit failed; sync
182
+ * failures surface through `useSyncStatus` and `usePendingMutations`. Needs no
183
+ * component and no provider.
184
+ */
185
+ export declare function useSubmission<Args extends unknown[], R>(fn: (...args: Args) => Promise<R>): Submission<Args, R>;