@basictech/react 0.9.0-beta.0 → 0.11.0-beta.1

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/readme.md DELETED
@@ -1,413 +0,0 @@
1
- # @basictech/react
2
-
3
- React SDK for [Basic](https://basic.tech) — authentication and an offline-first, synced database for your React app.
4
-
5
- Basic gives every user their own personal datastore (a PDS). Your app authenticates with OAuth, gets its own sandboxed slice of the user's datastore, and this SDK keeps a local replica of that data in the browser — reads are instant and local, writes work offline, and everything syncs live across the user's devices over the Basic **Sync/2** protocol.
6
-
7
- > **Breaking change (0.9):** this version is a ground-up rewrite for the new Basic auth system and the Sync/2 sync engine. The 0.8.x sync client speaks a protocol the server no longer supports. See [Migrating from 0.8](#migrating-from-08).
8
-
9
- ---
10
-
11
- ## Contents
12
-
13
- - [Installation](#installation)
14
- - [Quick start](#quick-start)
15
- - [How it works](#how-it-works)
16
- - [Authentication](#authentication)
17
- - [Database](#database)
18
- - [Live queries](#live-queries)
19
- - [Sync status, offline behavior & errors](#sync-status-offline-behavior--errors)
20
- - [Shares (multiplayer)](#shares-multiplayer)
21
- - [Typed schemas](#typed-schemas)
22
- - [REST mode](#rest-mode)
23
- - [API reference](#api-reference)
24
- - [Advanced usage](#advanced-usage)
25
- - [Migrating from 0.8](#migrating-from-08)
26
-
27
- ---
28
-
29
- ## Installation
30
-
31
- ```bash
32
- npm install @basictech/react
33
- ```
34
-
35
- Requires React 16.8+ (hooks). React 17, 18, and 19 are supported.
36
-
37
- ## Quick start
38
-
39
- ### 1. Define your schema
40
-
41
- Create a `basic.config.ts` with your project id (from [app.basic.tech](https://app.basic.tech)) and your tables:
42
-
43
- ```typescript
44
- // basic.config.ts
45
- export const schema = {
46
- project_id: "YOUR_PROJECT_ID",
47
- version: 1,
48
- tables: {
49
- todos: {
50
- type: "collection",
51
- fields: {
52
- title: { type: "string", indexed: true, required: true },
53
- completed: { type: "boolean", indexed: true },
54
- },
55
- },
56
- },
57
- };
58
- ```
59
-
60
- Field types: `string`, `number`, `boolean`, `json`. Publish the schema from the Basic dashboard — sync is enabled once the published version matches your local one.
61
-
62
- ### 2. Wrap your app
63
-
64
- ```tsx
65
- // main.tsx
66
- import { BasicProvider } from "@basictech/react";
67
- import { schema } from "./basic.config";
68
-
69
- createRoot(document.getElementById("root")!).render(
70
- <BasicProvider schema={schema} devToolbar>
71
- <App />
72
- </BasicProvider>,
73
- );
74
- ```
75
-
76
- ### 3. Sign in and use the database
77
-
78
- ```tsx
79
- import { useBasic, useQuery } from "@basictech/react";
80
-
81
- function Todos() {
82
- const { isSignedIn, signIn, signOut, user, db } = useBasic();
83
- const todos = useQuery(() => db.table("todos").getAll());
84
-
85
- if (!isSignedIn) {
86
- return <button onClick={() => signIn()}>Sign in with Basic</button>;
87
- }
88
-
89
- return (
90
- <div>
91
- <p>hi {user?.email} <button onClick={() => signOut()}>sign out</button></p>
92
-
93
- <button onClick={() => db.table("todos").create({ title: "hello", completed: false })}>
94
- add todo
95
- </button>
96
-
97
- {todos?.map((todo) => (
98
- <label key={todo.id}>
99
- <input
100
- type="checkbox"
101
- checked={!!todo.completed}
102
- onChange={() => db.table("todos").patch(todo.id, { completed: !todo.completed })}
103
- />
104
- {String(todo.title)}
105
- <button onClick={() => db.table("todos").delete(todo.id)}>×</button>
106
- </label>
107
- ))}
108
- </div>
109
- );
110
- }
111
- ```
112
-
113
- That's the whole loop: `signIn()` runs the OAuth flow, `db.table(...)` writes apply instantly to the local replica (and queue offline), and `useQuery` re-renders whenever local data changes — whether the change came from this tab, another tab, another device, or another user via a share.
114
-
115
- ## How it works
116
-
117
- In the default `sync` mode, the SDK maintains a **local replica** of your app's slice of the user's datastore, in IndexedDB, and syncs it over one WebSocket:
118
-
119
- 1. **Bootstrap** — on first run the SDK fetches a snapshot of current state, then subscribes for live changes from that point.
120
- 2. **Writes are ops** — every write is a `put` (create/replace), `patch` (shallow field merge), or `delete` operation with a client-minted unique id. Ops apply to the local view immediately (optimistic), queue in IndexedDB, and push to the server when online. Retries are always safe: the server deduplicates by op id.
121
- 3. **Reads are local** — `get`/`getAll`/`find` read the local view: confirmed server state with your pending writes layered on top. No network round-trip.
122
- 4. **The server is the authority** — it orders all ops (last-writer-wins per record; `patch`es merge per field), validates them against your published schema, and echoes them to every connected device. If it rejects a write, the SDK rolls it back locally and surfaces it (see [rejected ops](#rejected-ops)).
123
- 5. **Sign-out is clean** — local data is deleted, the session is revoked server-side, and other tabs update in place. No page reloads.
124
-
125
- ## Authentication
126
-
127
- Basic is the OAuth provider. `signIn()` redirects to the user's Basic sign-in page; after consent the user lands back on your app with a code the SDK exchanges automatically (PKCE, rotating refresh tokens — all handled for you).
128
-
129
- ```tsx
130
- const auth = useAuth(); // or grab the same fields from useBasic()
131
-
132
- auth.status; // 'bootstrapping' | 'authenticated' | 'recovering' | 'reauth_required' | 'signed_out'
133
- auth.isSignedIn; // boolean (stays true during reauth_required so you can show user info)
134
- auth.user; // { sub, email, name, picture } | null
135
- auth.did; // the user's decentralized id
136
- auth.scope; // scopes granted to your app
137
-
138
- await auth.signIn(); // redirect flow (current URL is the redirect URI)
139
- await auth.signIn("https://app.com/done"); // custom redirect URI
140
- await auth.signInWithHandle("alice.basic.id"); // federated: resolve the user's own PDS first
141
- await auth.signOut(); // revokes server-side + clears local data
142
- ```
143
-
144
- ### Auth status lifecycle
145
-
146
- | Status | Meaning | What to render |
147
- | --- | --- | --- |
148
- | `bootstrapping` | SDK is initializing | splash / nothing (provider hides children by default) |
149
- | `authenticated` | Healthy session | your app |
150
- | `recovering` | Session likely exists but unconfirmed (offline, mid-refresh) | your app (data still works locally) |
151
- | `reauth_required` | Session definitively invalid — user must sign in again | user info + a sign-in prompt |
152
- | `signed_out` | No session | sign-in screen |
153
-
154
- ### Calling your own API
155
-
156
- `getToken()` returns a valid access token, refreshing it automatically (tokens are short-lived — never cache them yourself):
157
-
158
- ```typescript
159
- const token = await auth.getToken();
160
- await fetch("https://your-api.example/thing", {
161
- headers: { Authorization: `Bearer ${token}` },
162
- });
163
- // after a 401 from your API:
164
- await auth.getToken({ forceRefresh: true });
165
- ```
166
-
167
- ### Scopes
168
-
169
- Default requested scopes are `profile,email,app:admin`. Check what was actually granted:
170
-
171
- ```typescript
172
- auth.hasScope("app:db:read"); // note: app:admin implies all app:db:* scopes
173
- auth.missingScopes(); // requested but not granted
174
- ```
175
-
176
- ## Database
177
-
178
- `db.table(name)` returns the table API (name must exist in your schema):
179
-
180
- ```typescript
181
- const todos = db.table("todos");
182
-
183
- const created = await todos.create({ title: "buy milk" });
184
- // → { id: "0198…", title: "buy milk" } — id minted locally, works offline
185
-
186
- await todos.put(id, { title: "replace", completed: false });
187
- // create-or-replace the WHOLE record with these fields
188
-
189
- await todos.patch(id, { completed: true });
190
- // shallow-merge the given fields; returns null if the record doesn't exist
191
-
192
- await todos.delete(id); // idempotent — deleting a missing record is fine
193
-
194
- await todos.get(id); // record or null
195
- await todos.getAll(); // all records
196
- await todos.find((t) => !t.completed);
197
- ```
198
-
199
- Semantics worth knowing:
200
-
201
- - **`put` replaces, `patch` merges.** Two devices patching *different* fields of the same record both win; patching the *same* field, the last write wins.
202
- - **`json` fields are atomic** — patching a `json` field replaces its whole value (no deep merge).
203
- - Writes are **validated locally** against your schema before queueing (same rules the server enforces), so typos fail fast with a thrown error instead of a round-trip.
204
- - In sync mode, `create` mints the id client-side — you get the full record back synchronously-ish, even offline.
205
-
206
- ## Live queries
207
-
208
- `useQuery` re-runs your query and re-renders whenever the underlying data changes:
209
-
210
- ```tsx
211
- const todos = useQuery(() => db.table("todos").getAll()); // undefined while loading
212
- const open = useQuery(() => db.table("todos").find((t) => !t.completed));
213
- const one = useQuery(() => db.table("todos").get(selectedId), [selectedId]); // deps like useEffect
214
- ```
215
-
216
- For advanced queries, `table.ref` exposes the underlying [Dexie](https://dexie.org) table over the local view (sync mode only) — indexed fields from your schema are Dexie indexes:
217
-
218
- ```tsx
219
- const recent = useQuery(() =>
220
- db.table("todos").ref!.where("completed").equals(0).limit(10).toArray(),
221
- );
222
- ```
223
-
224
- ## Sync status, offline behavior & errors
225
-
226
- ```tsx
227
- const sync = useSyncStatus();
228
-
229
- sync.status; // 'idle' | 'connecting' | 'online' | 'offline' | 'auth_required' | 'revoked' | 'stopped'
230
- sync.enabled; // false when the schema is invalid/unpublished
231
- sync.pendingCount; // local writes not yet confirmed by the server
232
- ```
233
-
234
- **Offline is not an error.** Writes keep working and queue in IndexedDB; reads serve the local view; everything pushes on reconnect (safe to retry — ops are idempotent). The queue survives page reloads.
235
-
236
- `revoked` means the user disconnected your app from their account — data access is gone until they sign in and consent again.
237
-
238
- ### Rejected ops
239
-
240
- If the server terminally rejects a write (schema validation, permissions, payload too large), the SDK **rolls the record back**, parks the op in a rejected store, and will never retry it:
241
-
242
- ```tsx
243
- const sync = useSyncStatus();
244
- const rejected = await sync.listRejected();
245
- // [{ op_id, op: { type, table, record_id, data }, error: 'SCHEMA_VALIDATION_FAILED', message, rejected_at }]
246
- await sync.clearRejected();
247
- ```
248
-
249
- You can also listen live:
250
-
251
- ```typescript
252
- const { client } = useBasic();
253
- useEffect(() => client.engine?.on("rejected", ({ rejection }) => {
254
- toast.error(`write rejected: ${rejection.error}`);
255
- }), [client]);
256
- ```
257
-
258
- ## Shares (multiplayer)
259
-
260
- Users can grant other users access to a slice of their data — a whole table or specific records, read-only or read-write. Grants are created by the user on basic.id (apps can never share a user's data on their own); your app **lists** and **mounts** them:
261
-
262
- ```tsx
263
- function SharedTodos() {
264
- const { received } = useShares(); // shares other users granted to me
265
- const share = received[0];
266
- const { db: sharedDb, status } = useShare(share?.id); // 'mounting' | 'mounted' | 'error' | 'revoked'
267
- const todos = useQuery(() => sharedDb?.table("todos").getAll(), [sharedDb]);
268
-
269
- if (!share) return <p>nothing shared with you yet</p>;
270
- if (status !== "mounted") return <p>{status}…</p>;
271
-
272
- return (
273
- <ul>
274
- {todos?.map((t) => (
275
- <li key={t.id} onClick={() => sharedDb!.table("todos").patch(t.id, { completed: true })}>
276
- {String(t.title)}
277
- </li>
278
- ))}
279
- </ul>
280
- );
281
- }
282
- ```
283
-
284
- Mounted shares live in their **own local keyspace** — separate replica, separate offline queue — and are never merged with the user's own data. Writes work when the share permission is `write` (the owner sees your changes attributed to the guest). When the owner revokes the share, the mount status flips to `revoked` and the local copy is purged.
285
-
286
- ## Typed schemas
287
-
288
- `@basictech/schema` (a dependency of this package) can infer record types from your schema:
289
-
290
- ```typescript
291
- import { defineSchema, type InferRecord } from "@basictech/schema";
292
-
293
- export const schema = defineSchema({
294
- project_id: "…",
295
- version: 1,
296
- tables: {
297
- todos: {
298
- fields: {
299
- title: { type: "string", required: true },
300
- completed: { type: "boolean" },
301
- },
302
- },
303
- },
304
- });
305
-
306
- type Todo = InferRecord<typeof schema, "todos">;
307
- // { id: string; title: string; completed?: boolean }
308
-
309
- const todos = db.table<Todo>("todos"); // fully typed CRUD
310
- ```
311
-
312
- ## REST mode
313
-
314
- Don't want a local replica? `mode="rest"` makes every table call a direct API request — no IndexedDB, no WebSocket, no offline support:
315
-
316
- ```tsx
317
- <BasicProvider schema={schema} mode="rest">
318
- ```
319
-
320
- The table API is identical, with REST semantics: `create` gets its id from the server, `put`/`patch`/`delete` on missing records return null/no-op, reads hit the network. `useQuery` won't live-update in this mode (re-run queries with deps).
321
-
322
- ## API reference
323
-
324
- ### `<BasicProvider>` props
325
-
326
- | Prop | Default | Description |
327
- | --- | --- | --- |
328
- | `schema` | — | Your Basic schema document (`project_id` is read from it) |
329
- | `mode` | `"sync"` | `"sync"` (local replica) or `"rest"` (direct API) |
330
- | `auth.scopes` | `"profile,email,app:admin"` | OAuth scopes to request |
331
- | `auth.pds_url` | `https://pds.basic.id` | The Basic server (auth + data + sync) |
332
- | `auth.sync_url` | `wss://<pds>/sync/` | Sync WebSocket URL (rarely needed) |
333
- | `storage` | `localStorage` | Custom `BasicStorage` adapter for auth state |
334
- | `debug` | `false` | Verbose console logging |
335
- | `devToolbar` | `false` | Floating status toolbar (dev environments only) |
336
- | `renderWhileLoading` | `false` | Render children before auth bootstrap finishes |
337
-
338
- ### Hooks
339
-
340
- | Hook | Returns |
341
- | --- | --- |
342
- | `useBasic()` | Everything: auth fields + actions, `db`, `sync`, `devInfo`, `client` |
343
- | `useAuth()` | `{ isReady, isSignedIn, status, user, did, scope, hasScope, missingScopes, signIn, signInWithHandle, signInWithCode, signOut, getToken, getSignInUrl }` |
344
- | `useDb()` | The table API for the user's own data |
345
- | `useQuery(fn, deps?)` | Live query result (`undefined` while loading) |
346
- | `useSyncStatus()` | `{ status, enabled, pendingCount, listRejected, clearRejected }` |
347
- | `useShares()` | `{ granted, received, isLoading, error, refresh }` |
348
- | `useShare(shareId)` | `{ db, status, error }` — a mounted share |
349
-
350
- ### Table API
351
-
352
- | Method | Sync mode | REST mode |
353
- | --- | --- | --- |
354
- | `create(data)` | client-minted id, offline-capable | server-minted id |
355
- | `put(id, data)` | create **or replace** | replace; throws if missing |
356
- | `patch(id, partial)` | merge; `null` if missing locally | merge; `null` if missing |
357
- | `delete(id)` | idempotent | no-op if missing |
358
- | `get(id)` / `getAll()` / `find(fn)` | local view | network |
359
- | `ref` | Dexie table (live queries, indexes) | `undefined` |
360
-
361
- ## Advanced usage
362
-
363
- ### Outside React
364
-
365
- Everything is available without React — `BasicClient` is the framework-agnostic core (`AuthManager` + `SyncEngine` + `RestClient`):
366
-
367
- ```typescript
368
- import { createBasicClient } from "@basictech/react";
369
-
370
- const client = createBasicClient({ schema, debug: true });
371
- await client.start();
372
- client.subscribe(() => console.log(client.getSnapshot()));
373
- await client.db.table("todos").create({ title: "from anywhere" });
374
- ```
375
-
376
- The Sync/2 protocol layer (`SyncEngine`, `SyncConnection`, `SyncStore`, and all wire types) is exported too, for building custom clients or other runtimes — pass a `WebSocketImpl` (e.g. the `ws` package) to run in Node.
377
-
378
- ### Events
379
-
380
- ```typescript
381
- const { client } = useBasic();
382
- client.engine?.on("status", (s) => {}); // sync status changes
383
- client.engine?.on("change", ({ sub, tables }) => {}); // records changed
384
- client.engine?.on("rejected", ({ sub, rejection }) => {}); // terminal write rejection
385
- client.engine?.on("revoked", ({ code }) => {}); // app connection revoked
386
- ```
387
-
388
- ### Custom storage
389
-
390
- Auth state lives in `localStorage` by default. Provide any `{ get, set, remove }` async adapter via the `storage` prop (see `BasicStorage`). `STORAGE_KEYS` lists every key the SDK uses.
391
-
392
- ## Migrating from 0.8
393
-
394
- 0.9 is a breaking rewrite — the server's legacy sync endpoint was removed, so 0.8 sync no longer functions. Changes you'll make:
395
-
396
- | 0.8 | 0.9 |
397
- | --- | --- |
398
- | `db.collection("todos")` | `db.table("todos")` |
399
- | `.add(data)` | `.create(data)` |
400
- | `.update(id, partial)` | `.patch(id, partial)` |
401
- | `.put({ id, ...fields })` | `.put(id, fields)` |
402
- | `dbStatus` / `DBStatus` enum | `useSyncStatus().status` |
403
- | `dbMode="remote"` | `mode="rest"` |
404
- | `auth.ws_url` | `auth.sync_url` (you almost never need it) |
405
- | `signOut()` reloads the page | in-place teardown, no reload |
406
-
407
- Local data migrates by re-bootstrap: the old `basicdb` IndexedDB database is deleted automatically and 0.9 builds fresh replicas in `basic-sync:<project_id>` databases from the server (the server is the source of truth, so nothing is lost).
408
-
409
- ---
410
-
411
- ## License
412
-
413
- ISC