@spooky-sync/client-react 0.0.0-stage → 0.0.1-canary.384

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 ADDED
@@ -0,0 +1,93 @@
1
+ # `@spooky-sync/client-react`: agent guide
2
+
3
+ ## What this package is
4
+
5
+ The **React** binding for sp00ky (React 18 and 19, peer `react`). Same `SyncedDb` and the same hook set as `@spooky-sync/client-solid` / `client-solid2`, written the React way: hooks return plain values, not accessors, and inputs are plain values (a query, an id, a path), not thunks.
6
+
7
+ Browser only (React DOM: Vite, Next.js client components, Remix). The core client runs SurrealDB / SQLite as WebAssembly with IndexedDB / OPFS and web workers, which React Native does not have. Do not suggest it for React Native; native mobile apps use the Flutter client.
8
+
9
+ Internals: every hook reads through `useSyncExternalStore` (tear-free, re-renders only when its value changed). `useQuery` feeds each live emission through a pure reducer (`reduceQuery` in `src/query.ts`) and structurally shares it with the previous result (`share`): rows matched by `id` keep their object identity, a deep-equal emission returns the same state and does not render. Client, registrations, CRDT fields, channels and file leases live in effects, so StrictMode's double mount ends with exactly one of each.
10
+
11
+ ## Setup pattern
12
+
13
+ ```ts
14
+ // db.ts
15
+ import type { SyncedDbConfig } from '@spooky-sync/client-react';
16
+ import { schema, SURQL_SCHEMA } from './schema.gen'; // generated by `spky generate`
17
+
18
+ export const dbConfig: SyncedDbConfig<typeof schema> = {
19
+ schema,
20
+ schemaSurql: SURQL_SCHEMA,
21
+ database: {
22
+ namespace: 'main',
23
+ database: 'app',
24
+ endpoint: 'ws://localhost:8666/rpc',
25
+ store: 'indexeddb',
26
+ },
27
+ };
28
+ ```
29
+
30
+ ```tsx
31
+ // App.tsx
32
+ <Sp00kyProvider config={dbConfig} fallback={<Splash />}>
33
+ {/* app */}
34
+ </Sp00kyProvider>
35
+ ```
36
+
37
+ Provider props: `config` (read once at mount; remount with a new `key` to switch databases), `fallback`, `preload` (awaited before children render, best-effort), `onReady`, `onError`. The client is created in an effect, so server renders show the fallback. A client that was handed to the tree is deliberately not closed on unmount; one whose init outlived the provider is.
38
+
39
+ Vite needs `vite-plugin-wasm`, `build.target: 'esnext'`, `optimizeDeps.exclude: ['@spooky-sync/client-react', '@spooky-sync/core', '@spooky-sync/ssp-wasm', '@surrealdb/wasm', '@surrealdb/wasm-native', '@sqlite.org/sqlite-wasm']` and `optimizeDeps.include: ['@spooky-sync/core > pino', '@spooky-sync/core > fast-json-patch']`. Pre-bundled, the client looks for its `.wasm` files and workers in the wrong folder (dev only: a 404 or `expected magic word`); `vite-plugin-top-level-await` is not needed and crashes with current `@swc/core`.
40
+
41
+ ## Key API
42
+
43
+ - **`useDb<typeof schema>()`**: the `SyncedDb<S>`. `create`, `update`, `delete`, `query`, `preload`, `run`, `channel`, `bucket`, `remoteQuery`, `useRemote`, `auth` / `signOut`, `pendingMutationCount`, `syncHealth` / `storageHealth` and their subscribe methods. Throws outside a provider.
44
+ - **`useQuery(query, options?)`** (or `useQuery(db, query, options?)`): live query. `query` is a BUILT query (`.build()`, `.one().build()`), or `null` / `undefined` to skip. Build it inline: re-registration keys on the query's identity hash (surql + vars), not the object. Returns:
45
+ - `data`: rows, or the row / `null` for `.one()`. `[]` / `null` before the first result. Structurally shared between emissions.
46
+ - `error`: registration / sync failure (e.g. SSP 503 NOT_READY). Never thrown; the scheduler retries.
47
+ - `isLoading`: cold first load only (nothing painted for this identity, server not heard, no error). A cached paint ends it; the server answering with zero rows ends it.
48
+ - `isFetching`: a fetch cycle is in flight.
49
+ - `isAuthoritative`: `data` holds the rendered rows of a known membership (server's, or a previous session's on this device). Latched until the identity changes.
50
+ - `hasData`: rows for a list, a row for `.one()`.
51
+ - `isEmpty`: authoritative AND no data. Empty states go on this, never on `!hasData`.
52
+ - `isSettled`: authoritative AND idle. Gate windowed-list end detection and create-if-missing on it. Not monotonic.
53
+ - Options: `enabled?: boolean`, `deregisterOnCleanup?: boolean`.
54
+ - On an identity change the previous `data` stays until the new identity emits (flags reset), so growing `.limit()` never flashes empty.
55
+ - **`usePreload(query, options?)`**: fire-and-forget prewarm of a likely-next query (`db.preload`), keyed on its identity. Options: `enabled?: boolean`, `signal?`.
56
+ - **`useSubmission(fn)`**: `{ submit, pending, error, result, clearError }`. `submit` is stable, calls the latest `fn`, never rejects. No optimistic layer: the engine already commits locally first.
57
+ - **`usePendingMutations()`**: number of unacknowledged local writes.
58
+ - **`useSyncStatus()`**: `{ health, status, isHealthy, isDegraded, everConnected, isOffline, connection, isReconnecting }`.
59
+ - **`useSyncActivity(options?)`** (or `(db, options?)`): `{ fetchingQueries, pendingMutations, isDownloading, isUploading }`, debounced on (`downloadDelayMs` 200, `uploadDelayMs` 150, `uploadThreshold` 0) and off at once.
60
+ - **`useStorageStatus()`**: `{ health, status, isPersistent, isMemoryFallback }`.
61
+ - **`useImpersonation({ rendersBanner? })`**: `{ impersonation, isImpersonating, stop }`.
62
+ - **`useFeatureFlag(key, { fallback?, ttl? })`**: `{ variant, payload, enabled }`.
63
+ - **`useAppRelease({ app, currentVersion, ttl? })`**: `{ latestVersion, updateAvailable, mandatory, cacheBust, reload }`.
64
+ - **`useCrdtField(table, recordId, field)`**: the `CrdtField` once loaded, else `null`. `recordId` is a value (`null` / `undefined` waits).
65
+ - **`useChannel(query, peers)`** (experimental): WebRTC channel while mounted for the rows `query` matches (a builder, built query, or list, on a `-- @channel` table; only its `where` counts; `null` closes it). Query and peers are compared by value. Returns `{ status, peers, update, create, delete }`. See `/docs/client/channels`.
66
+ - **Files**: `useFileUpload(bucket)` (`{ upload, download, remove, exists, isUploading, error, clearError }`, validates `maxSize` / `allowedExtensions`), `useDownloadFile(bucket, path, options?)` (`{ url, isLoading, error, refetch }`, refcounted shared object URL, OPFS-persisted by default), `useBlurhash(bucket, path)`, `useBucketImage(bucket, path, options?)` (adds `blurhash`, `ready`, and a `gate` ref callback for the `<img>`), components `<BucketImage bucket path className imgClassName fit fallback transition />` and `<Blurhash hash className style />`. Every file hook also takes `(db, bucket, ...)`.
67
+
68
+ ## Mutations
69
+
70
+ ```ts
71
+ await db.create('post:' + crypto.randomUUID(), { title: 'Hi' });
72
+ await db.update('post', 'post:xyz', { title: 'Edited' });
73
+ await db.delete('post', row.id); // a row's RecordId works directly
74
+ await db.run('backend', 'sendMail', { to });
75
+ ```
76
+
77
+ Track a backend job by querying its outbox row: `useQuery(db.query('job_outbox').where({ id: jobId }).one().build())`.
78
+
79
+ ## Common gotchas
80
+
81
+ - **Queries need `.build()`** (or `.one().build()`). A bare `db.query('post')` is a builder.
82
+ - **No Suspense mode.** There is no `ready()` like Solid 2; branch on `isLoading` / `isEmpty`.
83
+ - **`config` is read once.** Changing the provider's `config` prop does nothing; remount with a `key`.
84
+ - **React Native is unsupported** (no WebAssembly engines there).
85
+ - **Keys**: row ids are `RecordId` instances; use `key={String(row.id)}`.
86
+ - **Provider is mandatory** for every hook except the `(db, ...)` overloads.
87
+
88
+ ## Pointers
89
+
90
+ - Walkthrough: `QUICK_START.md` (same content as the docs' [React guide](https://mono424.github.io/sp00ky/docs/guide/react))
91
+ - Skill for coding agents: `skills/sp00ky-react/SKILL.md`
92
+ - Sync engine: `node_modules/@spooky-sync/core/AGENTS.md`
93
+ - Query builder DSL: `node_modules/@spooky-sync/query-builder/AGENTS.md`
package/QUICK_START.md ADDED
@@ -0,0 +1,173 @@
1
+ # Quick start: Sp00ky with React
2
+
3
+ The same content as the docs' [React guide](https://mono424.github.io/sp00ky/docs/guide/react).
4
+
5
+ ## 1. Install
6
+
7
+ ```bash
8
+ pnpm add @spooky-sync/core @spooky-sync/client-react
9
+ pnpm add -D vite-plugin-wasm
10
+ ```
11
+
12
+ ## 2. Configure Vite
13
+
14
+ The core client loads its engines as WebAssembly and starts web workers, both found next to its own files. Keep the client's packages out of dependency pre-bundling (pre-bundled, they look in the wrong folder), pre-bundle the core's CommonJS dependencies instead, and build for `esnext`:
15
+
16
+ ```ts
17
+ // vite.config.ts
18
+ import { defineConfig } from 'vite';
19
+ import react from '@vitejs/plugin-react';
20
+ import wasm from 'vite-plugin-wasm';
21
+
22
+ export default defineConfig({
23
+ plugins: [react(), wasm()],
24
+ optimizeDeps: {
25
+ // Served as is: pre-bundled, these look for their .wasm files and
26
+ // workers in the wrong folder.
27
+ exclude: [
28
+ '@spooky-sync/client-react',
29
+ '@spooky-sync/core',
30
+ '@spooky-sync/ssp-wasm',
31
+ '@surrealdb/wasm',
32
+ '@surrealdb/wasm-native',
33
+ '@sqlite.org/sqlite-wasm',
34
+ ],
35
+ // The excluded core's CommonJS dependencies, pre-bundled for it.
36
+ include: ['@spooky-sync/core > pino', '@spooky-sync/core > fast-json-patch'],
37
+ },
38
+ // The client uses top-level await.
39
+ build: { target: 'esnext' },
40
+ });
41
+ ```
42
+
43
+ ## 3. Generate types and configure the client
44
+
45
+ ```bash
46
+ spky generate
47
+ ```
48
+
49
+ ```ts
50
+ // src/db.ts
51
+ import type { SyncedDbConfig } from '@spooky-sync/client-react';
52
+ import { schema, SURQL_SCHEMA } from './schema.gen';
53
+
54
+ export const dbConfig: SyncedDbConfig<typeof schema> = {
55
+ schema,
56
+ schemaSurql: SURQL_SCHEMA,
57
+ database: {
58
+ namespace: 'main',
59
+ database: 'main',
60
+ endpoint: 'ws://localhost:8666/rpc',
61
+ store: 'indexeddb',
62
+ },
63
+ };
64
+ ```
65
+
66
+ ## 4. Mount the provider
67
+
68
+ ```tsx
69
+ import { Sp00kyProvider } from '@spooky-sync/client-react';
70
+ import { dbConfig } from './db';
71
+
72
+ export default function App() {
73
+ return (
74
+ <Sp00kyProvider
75
+ config={dbConfig}
76
+ fallback={<div>Initializing database…</div>}
77
+ preload={async (db) => {
78
+ // Optional: gate the first paint on essential data.
79
+ await db.preload(db.query('config').build());
80
+ }}
81
+ onError={(err) => console.error(err)}
82
+ >
83
+ <MainContent />
84
+ </Sp00kyProvider>
85
+ );
86
+ }
87
+ ```
88
+
89
+ `config` is read once, when the provider mounts. To switch databases, remount it with a new `key`.
90
+
91
+ ## 5. Query
92
+
93
+ ```tsx
94
+ import { useDb, useQuery } from '@spooky-sync/client-react';
95
+ import type { schema } from './schema.gen';
96
+
97
+ function PostList() {
98
+ const db = useDb<typeof schema>();
99
+ // Build inline: the hook re-registers only when the query's identity changes.
100
+ const posts = useQuery(
101
+ db.query('post').related('author').orderBy('created_at', 'desc').limit(20).build()
102
+ );
103
+
104
+ if (posts.isLoading) return <div>Loading…</div>;
105
+ if (posts.isEmpty) return <div>No posts yet.</div>;
106
+ return (
107
+ <ul>
108
+ {posts.data.map((post) => (
109
+ <li key={String(post.id)}>{post.title}</li>
110
+ ))}
111
+ </ul>
112
+ );
113
+ }
114
+ ```
115
+
116
+ Pass `null` (or `{ enabled: false }`) to skip a query:
117
+
118
+ ```tsx
119
+ const post = useQuery(postId ? db.query('post').where({ id: postId }).one().build() : null);
120
+ ```
121
+
122
+ | Field | Meaning |
123
+ | ----------------- | ------------------------------------------------------------------------------ |
124
+ | `data` | Rows, or the row / `null` for `.one()`. `[]` / `null` before the first result. |
125
+ | `error` | Registration or sync error. Never thrown; the scheduler retries. |
126
+ | `isLoading` | Cold first load only. A cached paint or an empty server answer ends it. |
127
+ | `isFetching` | A fetch cycle is in flight. |
128
+ | `isAuthoritative` | `data` is an answer (a known membership is painted), not a cache guess. |
129
+ | `hasData` | `data` holds rows / a row. |
130
+ | `isEmpty` | Authoritative and no data. Render empty states on this. |
131
+ | `isSettled` | Authoritative and idle. |
132
+
133
+ ## 6. Mutate
134
+
135
+ ```ts
136
+ await db.create('post:' + crypto.randomUUID(), { title: 'Hi' });
137
+ await db.update('post', 'post:xyz', { title: 'Edited' });
138
+ await db.delete('post', row.id);
139
+ await db.run('backend', 'sendMail', { to });
140
+ ```
141
+
142
+ For a button spinner:
143
+
144
+ ```tsx
145
+ const save = useSubmission((title: string) => db.create('post:' + crypto.randomUUID(), { title }));
146
+ <button disabled={save.pending} onClick={() => save.submit(title)}>
147
+ Save
148
+ </button>;
149
+ {
150
+ save.error && <p>{save.error.message}</p>;
151
+ }
152
+ ```
153
+
154
+ ## 7. Status
155
+
156
+ ```tsx
157
+ const sync = useSyncStatus();
158
+ const pending = usePendingMutations();
159
+ if (sync.isDegraded) return <Banner>Offline, {pending} change(s) queued.</Banner>;
160
+ ```
161
+
162
+ ## Coming from the Solid bindings
163
+
164
+ | client-solid / client-solid2 | client-react |
165
+ | --------------------------------------------- | ------------------------------------ |
166
+ | `useQuery(() => q)` / `createQuery(() => q)` | `useQuery(q)`, `null` to skip |
167
+ | `posts.data()` | `posts.data` |
168
+ | `{ enabled: () => boolean }` | `{ enabled: boolean }` |
169
+ | `ready()` + `<Loading>` | not available: branch on `isLoading` |
170
+ | `createSubmission` | `useSubmission` |
171
+ | `createPreload(() => q)` | `usePreload(q)` |
172
+ | accessor arguments (`() => id`, `() => path`) | plain values |
173
+ | `class` | `className` |
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # @spooky-sync/client-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React bindings for the Sp00ky reactive local-first SurrealDB framework. React 18 and 19, in the
4
+ browser (React DOM). The core client runs its engines as WebAssembly with IndexedDB / OPFS storage,
5
+ so React Native is not supported; use the Flutter client for native mobile apps.
6
+
7
+ ```bash
8
+ pnpm add @spooky-sync/core @spooky-sync/client-react
9
+ ```
10
+
11
+ ```tsx
12
+ import { Sp00kyProvider, useDb, useQuery } from '@spooky-sync/client-react';
13
+
14
+ function Posts() {
15
+ const db = useDb<typeof schema>();
16
+ const posts = useQuery(db.query('post').orderBy('created_at', 'desc').limit(20).build());
17
+ if (posts.isLoading) return <p>Loading…</p>;
18
+ if (posts.isEmpty) return <p>No posts yet.</p>;
19
+ return (
20
+ <ul>
21
+ {posts.data.map((p) => (
22
+ <li key={String(p.id)}>{p.title}</li>
23
+ ))}
24
+ </ul>
25
+ );
26
+ }
27
+
28
+ <Sp00kyProvider config={dbConfig} fallback={<Splash />}>
29
+ <Posts />
30
+ </Sp00kyProvider>;
31
+ ```
32
+
33
+ What "native" means here:
34
+
35
+ - Every hook reads through `useSyncExternalStore`: tear-free under concurrent rendering, and a hook
36
+ re-renders only when the value it returns changed.
37
+ - `useQuery` results are structurally shared between live emissions. Rows are matched by `id`,
38
+ unchanged rows keep their object identity, and a deep-equal emission does not re-render.
39
+ `React.memo` rows work as expected.
40
+ - The client, query registrations, CRDT fields, channels and file leases are opened in effects and
41
+ released in their cleanups, never during render. StrictMode's double mount ends with one of each.
42
+ - Mutations stay plain `await db.create(...)` calls: the engine is already optimistic local-first.
43
+ `useSubmission` only adds button pending and error state.
44
+ - The bundle starts with `'use client'`, so a Next.js App Router layout can render the provider.
45
+
46
+ The query flags (`isLoading`, `isFetching`, `isAuthoritative`, `hasData`, `isEmpty`, `isSettled`)
47
+ follow the same contract as `@spooky-sync/client-solid2`, as plain values.
48
+
49
+ See `QUICK_START.md` for a walkthrough, `AGENTS.md` for the full API, and the
50
+ [React guide](https://mono424.github.io/sp00ky/docs/guide/react).
51
+
52
+ ```bash
53
+ pnpm --filter @spooky-sync/client-react test
54
+ pnpm --filter @spooky-sync/client-react build
55
+ ```