@spooky-sync/client-react 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.
- package/AGENTS.md +93 -0
- package/QUICK_START.md +162 -0
- package/README.md +54 -2
- package/dist/index.cjs +1351 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +623 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.ts +623 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1312 -0
- package/dist/index.js.map +1 -0
- package/package.json +71 -4
- package/skills/sp00ky-react/SKILL.md +73 -0
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`, `vite-plugin-top-level-await`, `build.target: 'esnext'` and `optimizeDeps.exclude: ['@surrealdb/wasm', '@surrealdb/wasm-native', '@sqlite.org/sqlite-wasm']`.
|
|
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,162 @@
|
|
|
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 vite-plugin-top-level-await
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## 2. Configure Vite
|
|
13
|
+
|
|
14
|
+
The core client loads its engines as WebAssembly. Keep them out of dependency pre-bundling:
|
|
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
|
+
import topLevelAwait from 'vite-plugin-top-level-await';
|
|
22
|
+
|
|
23
|
+
export default defineConfig({
|
|
24
|
+
plugins: [react(), wasm(), topLevelAwait()],
|
|
25
|
+
optimizeDeps: {
|
|
26
|
+
exclude: ['@surrealdb/wasm', '@surrealdb/wasm-native', '@sqlite.org/sqlite-wasm'],
|
|
27
|
+
},
|
|
28
|
+
build: { target: 'esnext' },
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## 3. Generate types and configure the client
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
spky generate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// src/db.ts
|
|
40
|
+
import type { SyncedDbConfig } from '@spooky-sync/client-react';
|
|
41
|
+
import { schema, SURQL_SCHEMA } from './schema.gen';
|
|
42
|
+
|
|
43
|
+
export const dbConfig: SyncedDbConfig<typeof schema> = {
|
|
44
|
+
schema,
|
|
45
|
+
schemaSurql: SURQL_SCHEMA,
|
|
46
|
+
database: {
|
|
47
|
+
namespace: 'main',
|
|
48
|
+
database: 'main',
|
|
49
|
+
endpoint: 'ws://localhost:8666/rpc',
|
|
50
|
+
store: 'indexeddb',
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 4. Mount the provider
|
|
56
|
+
|
|
57
|
+
```tsx
|
|
58
|
+
import { Sp00kyProvider } from '@spooky-sync/client-react';
|
|
59
|
+
import { dbConfig } from './db';
|
|
60
|
+
|
|
61
|
+
export default function App() {
|
|
62
|
+
return (
|
|
63
|
+
<Sp00kyProvider
|
|
64
|
+
config={dbConfig}
|
|
65
|
+
fallback={<div>Initializing database…</div>}
|
|
66
|
+
preload={async (db) => {
|
|
67
|
+
// Optional: gate the first paint on essential data.
|
|
68
|
+
await db.preload(db.query('config').build());
|
|
69
|
+
}}
|
|
70
|
+
onError={(err) => console.error(err)}
|
|
71
|
+
>
|
|
72
|
+
<MainContent />
|
|
73
|
+
</Sp00kyProvider>
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`config` is read once, when the provider mounts. To switch databases, remount it with a new `key`.
|
|
79
|
+
|
|
80
|
+
## 5. Query
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
import { useDb, useQuery } from '@spooky-sync/client-react';
|
|
84
|
+
import type { schema } from './schema.gen';
|
|
85
|
+
|
|
86
|
+
function PostList() {
|
|
87
|
+
const db = useDb<typeof schema>();
|
|
88
|
+
// Build inline: the hook re-registers only when the query's identity changes.
|
|
89
|
+
const posts = useQuery(
|
|
90
|
+
db.query('post').related('author').orderBy('created_at', 'desc').limit(20).build()
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
if (posts.isLoading) return <div>Loading…</div>;
|
|
94
|
+
if (posts.isEmpty) return <div>No posts yet.</div>;
|
|
95
|
+
return (
|
|
96
|
+
<ul>
|
|
97
|
+
{posts.data.map((post) => (
|
|
98
|
+
<li key={String(post.id)}>{post.title}</li>
|
|
99
|
+
))}
|
|
100
|
+
</ul>
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Pass `null` (or `{ enabled: false }`) to skip a query:
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
const post = useQuery(postId ? db.query('post').where({ id: postId }).one().build() : null);
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
| Field | Meaning |
|
|
112
|
+
| ----------------- | ------------------------------------------------------------------------------ |
|
|
113
|
+
| `data` | Rows, or the row / `null` for `.one()`. `[]` / `null` before the first result. |
|
|
114
|
+
| `error` | Registration or sync error. Never thrown; the scheduler retries. |
|
|
115
|
+
| `isLoading` | Cold first load only. A cached paint or an empty server answer ends it. |
|
|
116
|
+
| `isFetching` | A fetch cycle is in flight. |
|
|
117
|
+
| `isAuthoritative` | `data` is an answer (a known membership is painted), not a cache guess. |
|
|
118
|
+
| `hasData` | `data` holds rows / a row. |
|
|
119
|
+
| `isEmpty` | Authoritative and no data. Render empty states on this. |
|
|
120
|
+
| `isSettled` | Authoritative and idle. |
|
|
121
|
+
|
|
122
|
+
## 6. Mutate
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
await db.create('post:' + crypto.randomUUID(), { title: 'Hi' });
|
|
126
|
+
await db.update('post', 'post:xyz', { title: 'Edited' });
|
|
127
|
+
await db.delete('post', row.id);
|
|
128
|
+
await db.run('backend', 'sendMail', { to });
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
For a button spinner:
|
|
132
|
+
|
|
133
|
+
```tsx
|
|
134
|
+
const save = useSubmission((title: string) => db.create('post:' + crypto.randomUUID(), { title }));
|
|
135
|
+
<button disabled={save.pending} onClick={() => save.submit(title)}>
|
|
136
|
+
Save
|
|
137
|
+
</button>;
|
|
138
|
+
{
|
|
139
|
+
save.error && <p>{save.error.message}</p>;
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## 7. Status
|
|
144
|
+
|
|
145
|
+
```tsx
|
|
146
|
+
const sync = useSyncStatus();
|
|
147
|
+
const pending = usePendingMutations();
|
|
148
|
+
if (sync.isDegraded) return <Banner>Offline, {pending} change(s) queued.</Banner>;
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Coming from the Solid bindings
|
|
152
|
+
|
|
153
|
+
| client-solid / client-solid2 | client-react |
|
|
154
|
+
| --------------------------------------------- | ------------------------------------ |
|
|
155
|
+
| `useQuery(() => q)` / `createQuery(() => q)` | `useQuery(q)`, `null` to skip |
|
|
156
|
+
| `posts.data()` | `posts.data` |
|
|
157
|
+
| `{ enabled: () => boolean }` | `{ enabled: boolean }` |
|
|
158
|
+
| `ready()` + `<Loading>` | not available: branch on `isLoading` |
|
|
159
|
+
| `createSubmission` | `useSubmission` |
|
|
160
|
+
| `createPreload(() => q)` | `usePreload(q)` |
|
|
161
|
+
| accessor arguments (`() => id`, `() => path`) | plain values |
|
|
162
|
+
| `class` | `className` |
|
package/README.md
CHANGED
|
@@ -1,3 +1,55 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spooky-sync/client-react
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
```
|