@spooky-sync/client-solid 0.0.0-canary.1 → 0.0.1-alpha.2

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.
@@ -1,4 +1,4 @@
1
- import {
1
+ import type {
2
2
  ColumnSchema,
3
3
  FinalQuery,
4
4
  SchemaStructure,
@@ -6,9 +6,10 @@ import {
6
6
  QueryResult,
7
7
  } from '@spooky-sync/query-builder';
8
8
  import { createEffect, createSignal, onCleanup, useContext } from 'solid-js';
9
+ import { createStore, reconcile } from 'solid-js/store';
9
10
  import { SyncedDb } from '..';
10
- import { SpookyQueryResultPromise } from '@spooky-sync/core';
11
- import { SpookyContext } from './context';
11
+ import type { Sp00kyQueryResultPromise } from '@spooky-sync/core';
12
+ import { Sp00kyContext } from './context';
12
13
 
13
14
  type QueryArg<
14
15
  S extends SchemaStructure,
@@ -17,13 +18,23 @@ type QueryArg<
17
18
  RelatedFields extends Record<string, any>,
18
19
  IsOne extends boolean,
19
20
  > =
20
- | FinalQuery<S, TableName, T, RelatedFields, IsOne, SpookyQueryResultPromise>
21
+ | FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>
21
22
  | (() =>
22
- | FinalQuery<S, TableName, T, RelatedFields, IsOne, SpookyQueryResultPromise>
23
+ | FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>
23
24
  | null
24
25
  | undefined);
25
26
 
26
- type QueryOptions = { enabled?: () => boolean };
27
+ type QueryOptions = {
28
+ enabled?: () => boolean;
29
+ /**
30
+ * Tear down the query (remote `_00_query` view + local WASM view) when this
31
+ * hook is disposed and no other subscriber remains, instead of keeping it
32
+ * resident for cheap re-subscription. Use for viewport-windowed lists that
33
+ * mount/unmount a query per scroll window and want off-screen windows
34
+ * cancelled. Trade-off: scrolling back to a torn-down window re-registers it.
35
+ */
36
+ deregisterOnCleanup?: boolean;
37
+ };
27
38
 
28
39
  // Overload: context-based (no explicit db)
29
40
  export function useQuery<
@@ -36,7 +47,13 @@ export function useQuery<
36
47
  >(
37
48
  finalQuery: QueryArg<S, TableName, T, RelatedFields, IsOne>,
38
49
  options?: QueryOptions,
39
- ): { data: () => TData | undefined; error: () => Error | undefined; isLoading: () => boolean };
50
+ ): {
51
+ data: () => TData | undefined;
52
+ error: () => Error | undefined;
53
+ isLoading: () => boolean;
54
+ isFetching: () => boolean;
55
+ isSettled: () => boolean;
56
+ };
40
57
 
41
58
  // Overload: explicit db (backward-compatible)
42
59
  export function useQuery<
@@ -50,7 +67,13 @@ export function useQuery<
50
67
  db: SyncedDb<S>,
51
68
  finalQuery: QueryArg<S, TableName, T, RelatedFields, IsOne>,
52
69
  options?: QueryOptions,
53
- ): { data: () => TData | undefined; error: () => Error | undefined; isLoading: () => boolean };
70
+ ): {
71
+ data: () => TData | undefined;
72
+ error: () => Error | undefined;
73
+ isLoading: () => boolean;
74
+ isFetching: () => boolean;
75
+ isSettled: () => boolean;
76
+ };
54
77
 
55
78
  // Implementation
56
79
  export function useQuery<
@@ -82,11 +105,11 @@ export function useQuery<
82
105
  options = maybeOptions;
83
106
  } else {
84
107
  // Context-based overload: useQuery(query, options?)
85
- const contextDb = useContext(SpookyContext);
108
+ const contextDb = useContext(Sp00kyContext);
86
109
  if (!contextDb) {
87
110
  throw new Error(
88
- 'useQuery: No db argument provided and no SpookyContext found. ' +
89
- 'Either pass a SyncedDb instance or wrap your app in <SpookyProvider>.'
111
+ 'useQuery: No db argument provided and no Sp00kyContext found. ' +
112
+ 'Either pass a SyncedDb instance or wrap your app in <Sp00kyProvider>.'
90
113
  );
91
114
  }
92
115
  db = contextDb as SyncedDb<S>;
@@ -94,31 +117,125 @@ export function useQuery<
94
117
  options = queryOrOptions as QueryOptions | undefined;
95
118
  }
96
119
 
97
- const [data, setData] = createSignal<TData | undefined>(undefined);
98
120
  const [error, setError] = createSignal<Error | undefined>(undefined);
99
121
  const [isFetched, setIsFetched] = createSignal(false);
100
- const [unsubscribe, setUnsubscribe] = createSignal<(() => void) | undefined>(undefined);
122
+ const [isFetching, setIsFetching] = createSignal(false);
123
+ // Results live in a store (not a signal) so consecutive live-query emissions
124
+ // are merged with `reconcile`: unchanged rows keep their object identity and
125
+ // changed rows are mutated in place. That keeps Solid's reference-keyed `<For>`
126
+ // rows — and any `useQuery` subscriptions mounted inside them — alive across
127
+ // updates, instead of tearing every row down and re-registering its queries.
128
+ const [state, setState] = createStore<{ value: TData | undefined }>({ value: undefined });
129
+ // `reconcile` (below) merges each emission into `state.value` IN PLACE, keeping
130
+ // the array reference stable. That's ideal for granular per-row reactivity, but
131
+ // it means a *coarse* reader of `data()` — `<For each={data()}>`, or an effect
132
+ // that copies the whole array elsewhere (e.g. GameList's windowed store) — is
133
+ // NOT re-run when rows are added/removed/reordered within a same-length result
134
+ // (the classic case: deleting a row in a windowed list shifts the next one in,
135
+ // so length stays 50 and the array ref never changes). Bump a version on every
136
+ // emission and read it in `data()` so every consumer re-runs on any change while
137
+ // reconcile still preserves row identity underneath.
138
+ const [version, setVersion] = createSignal(0);
139
+ const data = () => {
140
+ version();
141
+ return state.value;
142
+ };
143
+
101
144
  let prevQueryString: string | undefined;
145
+ // Monotonic token for each subscription generation. Bumped whenever the query
146
+ // identity changes or the hook is disposed, so a slow async `initQuery`
147
+ // continuation can detect it was superseded and avoid installing a stale (and
148
+ // leaked) subscription.
149
+ let runId = 0;
150
+ let activeUnsub: (() => void) | undefined;
151
+ // The hash of the currently-installed subscription, for opt-in deregister on
152
+ // dispose (see `deregisterOnCleanup`).
153
+ let activeHash: string | undefined;
102
154
 
103
- const spooky = db.getSpooky();
155
+ const teardownActive = () => {
156
+ activeUnsub?.();
157
+ activeUnsub = undefined;
158
+ };
104
159
 
160
+ const sp00ky = db.getSp00ky();
161
+
162
+ /**
163
+ * Registration can fail — the canonical case is the SSP answering 503
164
+ * NOT_READY while it bootstraps. Nothing here used to catch that: the
165
+ * rejection escaped as an unhandled promise, `isFetched` stayed false, and
166
+ * `isLoading()` therefore stayed true FOREVER, which is what a spinner that
167
+ * never resolves actually was. Surface it as `error()` instead; the sync
168
+ * scheduler retries the registration underneath, so a transient failure
169
+ * still recovers on its own.
170
+ */
105
171
  const initQuery = async (
106
- query: FinalQuery<S, TableName, T, RelatedFields, IsOne, SpookyQueryResultPromise>
172
+ query: FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>,
173
+ myRun: number
174
+ ) => {
175
+ try {
176
+ await subscribeQuery(query, myRun);
177
+ } catch (err) {
178
+ // A superseded run's failure is not this subscription's problem.
179
+ if (myRun !== runId) return;
180
+ setError(err instanceof Error ? err : new Error(String(err)));
181
+ }
182
+ };
183
+
184
+ const subscribeQuery = async (
185
+ query: FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>,
186
+ myRun: number
107
187
  ) => {
108
188
  const { hash } = await query.run();
189
+ // A newer query identity (or disposal) won the race while we awaited run().
190
+ if (myRun !== runId) return;
191
+ activeHash = hash;
109
192
  setError(undefined);
110
193
 
111
- const unsub = await spooky.subscribe(
194
+ let isFirstCall = true;
195
+ const unsub = await sp00ky.subscribe(
112
196
  hash,
113
197
  (e) => {
114
- const data = (query.isOne ? e[0] : e) as TData;
115
- setData(() => data);
116
- setIsFetched(true);
198
+ const queryData = (query.isOne ? e[0] : e) as TData;
199
+ // Merge into the store by record id: unchanged rows keep their identity,
200
+ // changed rows update in place. Replaces wholesale for `one()`/null.
201
+ // Time the reconcile → report as the "frontend" phase for DevTools/MCP.
202
+ const reconcileStart = performance.now();
203
+ setState('value', reconcile(queryData as any, { key: 'id' }));
204
+ // Notify coarse `data()` readers (see the `version` note above): reconcile
205
+ // keeps the array ref stable, so this is what re-runs `<For>`/copy-effects
206
+ // on add/remove/reorder.
207
+ setVersion((v) => v + 1);
208
+ sp00ky.reportFrontendTiming(hash, performance.now() - reconcileStart);
209
+ // The first (immediate) callback with no data likely means the local DB
210
+ // hasn't synced yet — don't mark as fetched so UI shows loading state
211
+ const hasData = query.isOne ? queryData !== null && queryData !== undefined : (e as any[]).length > 0;
212
+ if (!isFirstCall || hasData) {
213
+ setIsFetched(true);
214
+ }
215
+ isFirstCall = false;
117
216
  },
118
217
  { immediate: true }
119
218
  );
120
219
 
121
- setUnsubscribe(() => unsub);
220
+ // Mirror the query's fetch status so the UI can show a "loading more"
221
+ // state while the sync engine pulls missing records in the background.
222
+ const unsubStatus = sp00ky.subscribeQueryStatus(
223
+ hash,
224
+ (status) => setIsFetching(status === 'fetching'),
225
+ { immediate: true }
226
+ );
227
+
228
+ const teardown = () => {
229
+ unsub();
230
+ unsubStatus();
231
+ };
232
+
233
+ // Superseded while awaiting subscribe()? Don't leak — tear down immediately.
234
+ if (myRun !== runId) {
235
+ teardown();
236
+ return;
237
+ }
238
+ activeUnsub = teardown;
122
239
  };
123
240
 
124
241
  createEffect(() => {
@@ -136,30 +253,60 @@ export function useQuery<
136
253
  return;
137
254
  }
138
255
 
139
- // Prevent re-running if query hasn't changed
140
- const queryString = JSON.stringify(query);
256
+ // Dedup on the query's stable identity hash (cyrb53 of surql + vars), not a
257
+ // full `JSON.stringify` of the FinalQuery (which walks the whole schema +
258
+ // inner query on every reactive tick and isn't guaranteed stable). When the
259
+ // identity is unchanged we keep the existing subscription alive.
260
+ const queryString = String(query.hash);
141
261
  if (queryString === prevQueryString) {
142
262
  return;
143
263
  }
144
264
  prevQueryString = queryString;
145
265
 
146
- // Reset fetched state when query changes
266
+ // New query identity → supersede the previous subscription and start fresh.
267
+ const myRun = ++runId;
268
+ teardownActive();
147
269
  setIsFetched(false);
148
- initQuery(query);
270
+ // A new identity starts clean: a previous identity's failure must not keep
271
+ // this one out of its loading state.
272
+ setError(undefined);
273
+ void initQuery(query, myRun);
274
+ });
149
275
 
150
- // Cleanup
151
- onCleanup(() => {
152
- unsubscribe?.();
153
- });
276
+ // Tear down the live subscription when the hook's owner is disposed. Registered
277
+ // on the hook (component) scope rather than inside the effect, so an effect
278
+ // re-run that early-returns (unchanged query) doesn't clean up the still-valid
279
+ // subscription. Bumping runId also invalidates any in-flight initQuery.
280
+ onCleanup(() => {
281
+ runId++;
282
+ teardownActive();
283
+ // Opt-in: cancel the query once this hook (its last subscriber) is gone.
284
+ // teardownActive() above already removed this hook's callback, so
285
+ // deregisterQuery's refcount guard sees the true remaining-subscriber count.
286
+ if (options?.deregisterOnCleanup && activeHash) {
287
+ sp00ky.deregisterQuery(activeHash);
288
+ }
154
289
  });
155
290
 
156
291
  const isLoading = () => {
157
292
  return !isFetched() && error() === undefined;
158
293
  };
159
294
 
295
+ // True once the query has delivered a result AND no fetch cycle is in flight
296
+ // (registration + initial sync included — the core holds `fetching` across
297
+ // the whole registration and flushes debounced results before flipping back
298
+ // to idle). While settled, the results are authoritative: a windowed query
299
+ // returning fewer rows than its LIMIT really is the end of the list, so
300
+ // virtualized lists may size themselves to it without the scrollbar jumping
301
+ // when a still-syncing window transiently reports short. Resets to false
302
+ // whenever the query identity changes.
303
+ const isSettled = () => isFetched() && !isFetching();
304
+
160
305
  return {
161
306
  data,
162
307
  error,
163
308
  isLoading,
309
+ isFetching,
310
+ isSettled,
164
311
  };
165
312
  }
@@ -0,0 +1,44 @@
1
+ import { createSignal, onCleanup, type Accessor } from 'solid-js';
2
+ import { useDb } from './context';
3
+ import type { StorageHealth, StorageHealthStatus } from '@spooky-sync/core';
4
+
5
+ export interface UseStorageStatus {
6
+ /** Full durability snapshot; updates reactively. */
7
+ health: Accessor<StorageHealth>;
8
+ /** `'unknown'` | `'persistent'` | `'memory'`. */
9
+ status: Accessor<StorageHealthStatus>;
10
+ /** `true` when the local store survives a reload. */
11
+ isPersistent: Accessor<boolean>;
12
+ /**
13
+ * `true` only when durable storage was requested and could NOT be opened, so
14
+ * the dataset is sitting in RAM and local writes die on reload. Drive a
15
+ * warning off this, not off `status`: a store configured as in-memory reports
16
+ * `'memory'` too, and that is a choice rather than a problem.
17
+ */
18
+ isMemoryFallback: Accessor<boolean>;
19
+ }
20
+
21
+ /**
22
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
23
+ *
24
+ * Under `localEngine: 'sqlite'` with `store: 'indexeddb'` the durable store is
25
+ * the OPFS SAHPool VFS, and only ONE client per bucket can hold it open: a
26
+ * second tab of the same app cannot get it and runs in memory instead (the
27
+ * engine retries first, so a closing tab's lock is usually waited out). Must be
28
+ * used within a `<Sp00kyProvider>`.
29
+ */
30
+ export function useStorageStatus(): UseStorageStatus {
31
+ const db = useDb();
32
+ // subscribeToStorageHealth fires synchronously with the current snapshot, so
33
+ // the signal is correct from the first read; the initial value avoids a flash.
34
+ const [health, setHealth] = createSignal<StorageHealth>(db.storageHealth);
35
+ const unsub = db.subscribeToStorageHealth(setHealth);
36
+ onCleanup(unsub);
37
+
38
+ return {
39
+ health,
40
+ status: () => health().status,
41
+ isPersistent: () => health().status === 'persistent',
42
+ isMemoryFallback: () => health().fallback,
43
+ };
44
+ }
@@ -0,0 +1,64 @@
1
+ import { createSignal, onCleanup, type Accessor } from 'solid-js';
2
+ import { useDb } from './context';
3
+ import type { ConnectionState, SyncHealth, SyncHealthStatus } from '@spooky-sync/core';
4
+
5
+ export interface UseSyncStatus {
6
+ /** Full health snapshot; updates reactively on every transition. */
7
+ health: Accessor<SyncHealth>;
8
+ /** `'healthy'` | `'degraded'`. */
9
+ status: Accessor<SyncHealthStatus>;
10
+ isHealthy: Accessor<boolean>;
11
+ /** `true` once sync has failed for a sustained run — drive a banner off this. */
12
+ isDegraded: Accessor<boolean>;
13
+ /** `true` once at least one sync round has succeeded this session. */
14
+ everConnected: Accessor<boolean>;
15
+ /**
16
+ * `true` only for a real lost connection: degraded AFTER a first successful
17
+ * sync. Stays `false` during the initial "connecting" phase (degraded but
18
+ * never reached the server yet), so an indicator can show nothing until the
19
+ * app has actually connected once.
20
+ */
21
+ isOffline: Accessor<boolean>;
22
+ /**
23
+ * Transport state of the remote WebSocket. Flips the instant the socket
24
+ * drops, unlike `status`, which only degrades after a sustained run of failed
25
+ * sync rounds — so this is what to drive a "reconnecting…" affordance off.
26
+ */
27
+ connection: Accessor<ConnectionState>;
28
+ /**
29
+ * `true` while the connection is being re-established. Usually still
30
+ * `isHealthy()`: a short reconnect is invisible to sync, and writes made
31
+ * during it are queued locally and pushed once the socket is back.
32
+ */
33
+ isReconnecting: Accessor<boolean>;
34
+ }
35
+
36
+ /**
37
+ * Observe sync health for a "can't reach the server" banner / indicator.
38
+ *
39
+ * Backed by `db.subscribeToSyncHealth`. Individual sync failures (a transient
40
+ * remote 500 on query registration, a dropped socket) are absorbed by the
41
+ * retry and never flip this; `isDegraded()` only goes true once failures
42
+ * persist for the configured number of consecutive rounds (sp00ky core config
43
+ * `syncHealth.degradeAfterConsecutiveFailures`, default 3), and flips back on
44
+ * the next successful round. Must be used within a `<Sp00kyProvider>`.
45
+ */
46
+ export function useSyncStatus(): UseSyncStatus {
47
+ const db = useDb();
48
+ // subscribeToSyncHealth fires synchronously with the current status, so the
49
+ // signal is correct from first read; the initial value just avoids a flash.
50
+ const [health, setHealth] = createSignal<SyncHealth>(db.syncHealth);
51
+ const unsub = db.subscribeToSyncHealth(setHealth);
52
+ onCleanup(unsub);
53
+
54
+ return {
55
+ health,
56
+ status: () => health().status,
57
+ isHealthy: () => health().status === 'healthy',
58
+ isDegraded: () => health().status === 'degraded',
59
+ everConnected: () => health().everConnected,
60
+ isOffline: () => health().status === 'degraded' && health().everConnected,
61
+ connection: () => health().connection,
62
+ isReconnecting: () => health().connection === 'reconnecting',
63
+ };
64
+ }
@@ -1,7 +1,6 @@
1
- import type { Surreal } from 'surrealdb';
2
1
  import type { SyncedDb } from '../index';
3
- import { GenericSchema } from '../lib/models';
4
- import type { SpookyConfig } from '@spooky-sync/core';
2
+ import type { GenericSchema } from '../lib/models';
3
+ import type { Sp00kyConfig } from '@spooky-sync/core';
5
4
  import type { SchemaStructure, TableNames, GetTable, TableModel } from '@spooky-sync/query-builder';
6
5
 
7
6
  /**
@@ -44,7 +43,7 @@ export type InferRelationshipsFromConst<S extends SchemaStructure, Schema extend
44
43
  // Prettify helper expands types for better intellisense
45
44
  type Prettify<T> = { [K in keyof T]: T[K] } & {};
46
45
 
47
- export type SyncedDbConfig<S extends SchemaStructure> = Prettify<SpookyConfig<S>>;
46
+ export type SyncedDbConfig<S extends SchemaStructure> = Prettify<Sp00kyConfig<S>>;
48
47
 
49
48
  // export interface LocalDbConfig {
50
49
  // name: string;
@@ -1,55 +0,0 @@
1
- import { createSignal, onMount, createComponent, createMemo, JSX, mergeProps } from 'solid-js';
2
- import type { SchemaStructure } from '@spooky/query-builder';
3
- import type { SyncedDbConfig } from '../types';
4
- import { SyncedDb } from '../index';
5
- import { SpookyContext } from './context';
6
-
7
- export interface SpookyProviderProps<S extends SchemaStructure> {
8
- config: SyncedDbConfig<S>;
9
- fallback?: JSX.Element;
10
- onError?: (error: Error) => void;
11
- onReady?: (db: SyncedDb<S>) => void;
12
- children: JSX.Element;
13
- }
14
-
15
- export function SpookyProvider<S extends SchemaStructure>(
16
- props: SpookyProviderProps<S>
17
- ): JSX.Element {
18
- const merged = mergeProps(
19
- {
20
- fallback: undefined as JSX.Element | undefined,
21
- },
22
- props
23
- );
24
-
25
- const [db, setDb] = createSignal<SyncedDb<S> | undefined>(undefined);
26
-
27
- onMount(async () => {
28
- try {
29
- const instance = new SyncedDb<S>(merged.config);
30
- await instance.init();
31
- setDb(() => instance);
32
- merged.onReady?.(instance);
33
- } catch (e) {
34
- const error = e instanceof Error ? e : new Error(String(e));
35
- if (merged.onError) {
36
- merged.onError(error);
37
- } else {
38
- console.error('SpookyProvider: Failed to initialize database', error);
39
- }
40
- }
41
- });
42
-
43
- const content = createMemo(() => {
44
- const instance = db();
45
- if (!instance) return merged.fallback;
46
- return createComponent(SpookyContext.Provider, {
47
- value: instance,
48
- get children() {
49
- return merged.children;
50
- },
51
- });
52
- });
53
-
54
- return content as unknown as JSX.Element;
55
- }