duratom 0.0.0-stage → 0.1.0

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/llms-full.txt ADDED
@@ -0,0 +1,1361 @@
1
+ # duratom: full documentation
2
+
3
+ Every duratom doc in one file: the README, the recipes and the API reference.
4
+
5
+ <!-- README.md -->
6
+
7
+ ## duratom
8
+
9
+ Durable, live Jotai atoms over a Y.Doc: read typed values, write validated patches, and re-render only when what an atom shows changes.
10
+
11
+ A [Y.Doc](https://docs.yjs.dev) is the shared, conflict-free state that sync providers keep the same on every device. duratom turns a node of it into a Jotai atom: you read a value your schema has checked, you write a patch that is merged into the doc and validated first, and a component re-renders only when the value it shows changes, whoever changed the doc. Persistence and network sync come from existing Yjs providers; duratom has no provider code of its own.
12
+
13
+ ### Install
14
+
15
+ ```bash
16
+ npm install duratom jotai jotai-family yjs
17
+ ```
18
+
19
+ Add a [Standard Schema](https://standardschema.dev) validator for typed atoms, such as zod, valibot or arktype, and React for `duratom/react`. duratom needs `yjs` 13.6.33 or later, `jotai` 2.9 or later and `jotai-family`.
20
+
21
+ ### Quick start
22
+
23
+ Paste this into `src/main.tsx` of a new Vite React app (`npm create vite@latest my-app -- --template react-ts`), then `npm install duratom jotai jotai-family yjs zod` and `npm run dev`.
24
+
25
+ ```tsx
26
+ // src/main.tsx of a new Vite React app: npm create vite@latest my-app -- --template react-ts
27
+ import { docAtom, select, typedAtom } from 'duratom'
28
+ import { createStore, Provider, useAtom } from 'jotai'
29
+ import { StrictMode } from 'react'
30
+ import { createRoot } from 'react-dom/client'
31
+ import * as Y from 'yjs'
32
+ import { z } from 'zod'
33
+
34
+ // What a todo is, and where it lives in the doc: the map `first` in the root map `todos`.
35
+ // `title` is collaborative text, so two people typing in it both keep their edits.
36
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
37
+ const todoAtom = typedAtom(select.map('todos').child('first'), Todo, { title: 'text' })
38
+
39
+ // One Y.Doc per Jotai store. A sync provider would connect this doc to other devices.
40
+ const store = createStore()
41
+ store.set(docAtom, new Y.Doc())
42
+
43
+ function TodoRow() {
44
+ // undefined while the todo is missing, { issues } while it's invalid, { value } otherwise.
45
+ const [todo, setTodo] = useAtom(todoAtom)
46
+ if (!todo) {
47
+ // Setting a missing node with a whole valid value creates it.
48
+ return <button onClick={() => setTodo({ title: 'Learn duratom', done: false })}>Add</button>
49
+ }
50
+ if (todo.issues) return <p>Can't read this todo: {todo.issues[0]?.message}</p>
51
+ return (
52
+ <label>
53
+ {/* A patch changes only the fields it names. */}
54
+ <input
55
+ type="checkbox"
56
+ checked={todo.value.done}
57
+ onChange={(e) => setTodo({ done: e.target.checked })}
58
+ />
59
+ <input value={todo.value.title} onChange={(e) => setTodo({ title: e.target.value })} />
60
+ </label>
61
+ )
62
+ }
63
+
64
+ createRoot(document.getElementById('root')!).render(
65
+ <StrictMode>
66
+ <Provider store={store}>
67
+ <TodoRow />
68
+ </Provider>
69
+ </StrictMode>,
70
+ )
71
+ ```
72
+
73
+ Add a sync provider to the doc ([sync recipe](docs/recipes/sync.md)) and the same atom shows and edits the todo on every device, with no change to the atom or the component.
74
+
75
+ ### Rules
76
+
77
+ Four rules cover how duratom behaves; the [API reference](https://duratom.karolnov.dev/api) has the details.
78
+
79
+ - **One doc per store.** Atoms read the Y.Doc in `docAtom`, so set it once on each Jotai store before reading an atom. An app with several docs gives an atom its own doc atom: `typedAtom(locator, Schema, shape, { docAtom: otherDocAtom })`.
80
+ - **Patches merge.** Setting a typed atom with `{ priority: 'high' }` reads the node as it is in the doc at that moment, merges the patch into it and writes only what changed, so a peer's concurrent edit to another field survives. `set(prev => patch)` gets that fresh value as `prev`. On a node with no valid value, the patch is the whole value: that creates a missing node, or repairs an invalid one.
81
+ - **Results, not exceptions.** A typed atom reads as `undefined` while its node is missing, `{ issues }` while the node doesn't satisfy the schema, and `{ value }` otherwise. Setting it returns the schema's result; an invalid patch changes nothing and returns `{ issues }`. Only misconfiguration throws: an async schema (`AsyncValidationUnsupportedError`), a value a `Y.Map` can't store (`UnsupportedValueError`), or no doc in `docAtom`.
82
+ - **Subscribed atoms follow the doc.** An atom observes its node while something is subscribed to it (a component, or `store.sub`), and then only that node. Read with `store.get` while nothing is subscribed, it can show a value from before a peer's edit; it does see its own writes. Use `live` from `duratom/core` to read the doc as it is now outside Jotai.
83
+
84
+ ### Shapes
85
+
86
+ A schema says what a value is; a shape says which of its fields are Yjs shared types, so that peers editing them at once merge their edits. Every field the shape doesn't name is a plain value, where the last writer wins.
87
+
88
+ - `'text'`: a `Y.Text`, read as a string. Two people typing in it both keep their edits.
89
+ - `'xml'`: a `Y.XmlFragment`, read as the fragment itself, for rich-text editors.
90
+ - `map(shape)`: a nested `Y.Map` with fixed keys, read as an object.
91
+ - `record(itemShape)`: a `Y.Map` of item maps with any keys, read as an object of objects.
92
+ - `array()`: a `Y.Array` of plain values, read as an array.
93
+
94
+ A shape's keys are checked against the schema's type, so a key the schema doesn't have, or a kind its field can't hold, is a type error. An empty shape, `{}`, makes every field plain.
95
+
96
+ ### Collections
97
+
98
+ `collection` covers a map of items: an `ids` atom that changes only when an item is added or removed, a typed atom per item, and `create` and `remove`.
99
+
100
+ ```tsx
101
+ import { collection, select } from 'duratom'
102
+ import { useAtom, useAtomValue, useSetAtom } from 'jotai'
103
+ import { z } from 'zod'
104
+
105
+ const Todo = z.object({ title: z.string().min(1), done: z.boolean() })
106
+
107
+ // Every todo in the root map `todos`, each one a Y.Map read through `Todo`.
108
+ const todos = collection(select.map('todos'), Todo, { title: 'text' })
109
+
110
+ export function TodoList() {
111
+ // Changes only when a todo is added or removed, not when one is edited.
112
+ const ids = useAtomValue(todos.ids)
113
+ const create = useSetAtom(todos.create)
114
+ const add = () => {
115
+ const result = create({ title: 'New todo', done: false })
116
+ if (result.issues) console.warn(result.issues)
117
+ }
118
+ return (
119
+ <>
120
+ <ul>
121
+ {ids.map((id) => (
122
+ <TodoItem key={id} id={id} />
123
+ ))}
124
+ </ul>
125
+ <button onClick={add}>Add</button>
126
+ </>
127
+ )
128
+ }
129
+
130
+ function TodoItem({ id }: { id: string }) {
131
+ // The same typed atom for the same id; it re-renders this row only.
132
+ const [todo, setTodo] = useAtom(todos.item(id))
133
+ const remove = useSetAtom(todos.remove)
134
+ if (!todo || todo.issues) return <li>Unreadable todo</li>
135
+ return (
136
+ <li>
137
+ <input
138
+ type="checkbox"
139
+ checked={todo.value.done}
140
+ onChange={(e) => setTodo({ done: e.target.checked })}
141
+ />
142
+ {todo.value.title}
143
+ <button onClick={() => remove(id)}>Remove</button>
144
+ </li>
145
+ )
146
+ }
147
+ ```
148
+
149
+ ### Typed atoms in a hook
150
+
151
+ `useTypedAtom` from `duratom/react` is `typedAtom` for a path that depends on props. It returns `[result, set]`, as `useAtom` does, and rebuilds the atom only when `deps` change.
152
+
153
+ ```tsx
154
+ import { select } from 'duratom'
155
+ import { useTypedAtom } from 'duratom/react'
156
+ import { z } from 'zod'
157
+
158
+ const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
159
+
160
+ // The card's path depends on a prop: the hook rebuilds the atom only when `id` changes.
161
+ export function CardRow({ id }: { id: string }) {
162
+ const [card, setCard] = useTypedAtom(
163
+ () => select.map('cards').child(id),
164
+ Card,
165
+ { title: 'text' },
166
+ [id],
167
+ )
168
+ if (!card) return <button onClick={() => setCard({ title: 'New', priority: 'low' })}>Add</button>
169
+ if (card.issues) return <span>Unreadable card</span>
170
+ return (
171
+ <label>
172
+ {card.value.title}
173
+ <input
174
+ type="checkbox"
175
+ checked={card.value.priority === 'high'}
176
+ onChange={(e) => setCard({ priority: e.target.checked ? 'high' : 'low' })}
177
+ />
178
+ </label>
179
+ )
180
+ }
181
+ ```
182
+
183
+ ### Custom projections
184
+
185
+ `liveAtom` is the read-only atom under `typedAtom`, for values a schema doesn't describe: one field, a count, anything computed from a node. `select` builds what it reads, and the atom re-renders only when the result changes.
186
+
187
+ ```tsx
188
+ import { liveAtom, select } from 'duratom'
189
+ import { useLiveAtom } from 'duratom/react'
190
+ import { useAtomValue } from 'jotai'
191
+ import * as Y from 'yjs'
192
+
193
+ // One field, with a fallback for a missing map, a missing key or a value of another type.
194
+ const boardName = liveAtom(select.map('board').get('name', 'Untitled'))
195
+
196
+ // Your own projection: re-renders only when the counts change, not on every edit to a todo.
197
+ const progress = liveAtom(
198
+ select.map('todos').project((todos) => {
199
+ let done = 0
200
+ todos?.forEach((todo) => {
201
+ if (todo instanceof Y.Map && todo.get('done') === true) done++
202
+ })
203
+ return { done, total: todos?.size ?? 0 }
204
+ }),
205
+ )
206
+
207
+ export function Header() {
208
+ const name = useAtomValue(boardName)
209
+ const { done, total } = useAtomValue(progress)
210
+ return (
211
+ <h1>
212
+ {name}: {done} of {total} done
213
+ </h1>
214
+ )
215
+ }
216
+
217
+ // A selector that depends on props: the hook rebuilds the atom only when `id` changes.
218
+ export function Title({ id }: { id: string }) {
219
+ const title = useLiveAtom(() => select.map('todos').child(id).text('title'), [id])
220
+ return <span>{title}</span>
221
+ }
222
+ ```
223
+
224
+ ### Several docs
225
+
226
+ Every atom takes a last argument, `{ docAtom }`, naming the atom that holds its doc. Atoms without it read `docAtom`.
227
+
228
+ ```ts
229
+ import { select, typedAtom } from 'duratom'
230
+ import { atom, createStore } from 'jotai'
231
+ import * as Y from 'yjs'
232
+ import { z } from 'zod'
233
+
234
+ // A second doc, beside the one in `docAtom`: settings kept apart from the shared board, say.
235
+ const settingsDocAtom = atom<Y.Doc | null>(null)
236
+
237
+ const Settings = z.object({ theme: z.enum(['light', 'dark']) })
238
+ const settingsAtom = typedAtom(
239
+ select.map('settings').child('user'),
240
+ Settings,
241
+ {},
242
+ {
243
+ docAtom: settingsDocAtom,
244
+ },
245
+ )
246
+
247
+ const store = createStore()
248
+ store.set(settingsDocAtom, new Y.Doc())
249
+ store.set(settingsAtom, { theme: 'dark' })
250
+ ```
251
+
252
+ ### Without Jotai
253
+
254
+ `duratom/core` has the pieces under the atoms, for other state libraries or none: `live` follows one node of a doc, and `read` and `write` read and write a `Y.Map` through a schema.
255
+
256
+ ```ts
257
+ import { live, read, select, write } from 'duratom/core'
258
+ import * as Y from 'yjs'
259
+ import { z } from 'zod'
260
+
261
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
262
+ const doc = new Y.Doc()
263
+ const todo = doc.getMap('todos').set('first', new Y.Map())
264
+
265
+ // Validated writes and typed reads, on any Y.Map.
266
+ write(Todo, { title: 'text' }, todo, { title: 'Learn duratom', done: false })
267
+ const result = read(Todo, { title: 'text' }, todo) // { value: { title: 'Learn duratom', done: false } }
268
+
269
+ // A live value in the shape useSyncExternalStore takes, for any state library or none.
270
+ const done = live(doc, select.map('todos').child('first').get('done', false))
271
+ const stop = done.subscribe((value) => console.log('done is now', value))
272
+ write(Todo, { title: 'text' }, todo, { title: 'Learn duratom', done: true }) // logs: done is now true
273
+ stop()
274
+
275
+ export { result }
276
+ ```
277
+
278
+ ### Docs
279
+
280
+ - [API reference](https://duratom.karolnov.dev/api): every export, generated from the TSDoc.
281
+ - Recipes: [sync between devices](docs/recipes/sync.md), [offline storage](docs/recipes/offline.md), [repair a broken node](docs/recipes/repair.md).
282
+ - Example apps: [a two-pane shared todo list](examples/todo), and [an offline-first todo list synced through a Durable Object](examples/sync), with end-to-end tests.
283
+ - For AI agents: [`llms.txt`](llms.txt), [`llms-full.txt`](llms-full.txt) (every doc in one file) and an agent skill, [`skills/duratom/SKILL.md`](skills/duratom/SKILL.md). The npm package ships `llms-full.txt` and the skill, so an agent finds them in `node_modules/duratom`.
284
+
285
+ Every code snippet in these docs is compiled against the source in CI, and so is every `@example` in the TSDoc.
286
+
287
+ ### License
288
+
289
+ MIT
290
+
291
+ <!-- docs/recipes/sync.md -->
292
+
293
+ ## Sync between devices
294
+
295
+ Connect the doc in `docAtom` to a sync server with y-partyserver on Cloudflare; every atom then shows and edits the shared state, with no change to the atoms.
296
+
297
+ duratom atoms read whatever is in their doc, and a Yjs provider keeps a doc the same on every device. So sync is a provider attached to the doc you put in `docAtom`: atoms, components and schemas stay as they are. This recipe uses [y-partyserver](https://github.com/cloudflare/partykit/tree/main/packages/y-partyserver), which runs one Durable Object per room on Cloudflare Workers; any Yjs provider, such as y-websocket, plugs in the same way.
298
+
299
+ ### Client
300
+
301
+ ```bash
302
+ npm install y-partyserver
303
+ ```
304
+
305
+ ```ts
306
+ import { docAtom } from 'duratom'
307
+ import { createStore } from 'jotai'
308
+ import YProvider from 'y-partyserver/provider'
309
+ import * as Y from 'yjs'
310
+
311
+ const doc = new Y.Doc()
312
+ // Connects the doc to the room `my-board` of the `Docs` server, and keeps it in sync both ways.
313
+ // The host is the Worker's: localhost:8787 under `wrangler dev`.
314
+ const provider = new YProvider('localhost:8787', 'my-board', doc, { party: 'docs' })
315
+
316
+ export const store = createStore()
317
+ store.set(docAtom, doc)
318
+
319
+ // Before closing the app, or when the doc is no longer needed:
320
+ export const disconnect = () => provider.destroy()
321
+ ```
322
+
323
+ Pass `store` to Jotai's `<Provider store={store}>`. Edits made before the provider connects, or while it's offline, are sent when it connects.
324
+
325
+ ### Server
326
+
327
+ ```bash
328
+ npm install partyserver y-partyserver yjs
329
+ ```
330
+
331
+ ```ts
332
+ // src/index.ts of a Cloudflare Worker.
333
+ import { routePartykitRequest } from 'partyserver'
334
+ import { YServer } from 'y-partyserver'
335
+ import * as Y from 'yjs'
336
+
337
+ interface Env {
338
+ // The binding's name, in kebab case, is the `party` the client connects to: `docs`.
339
+ Docs: DurableObjectNamespace<Docs>
340
+ }
341
+
342
+ /** One Durable Object per room, holding that room's doc and saving it to its own storage. */
343
+ export class Docs extends YServer<Env> {
344
+ override async onLoad() {
345
+ const saved = await this.ctx.storage.get<Uint8Array>('doc')
346
+ if (saved) Y.applyUpdate(this.document, saved)
347
+ }
348
+
349
+ // Called a few seconds after edits, and when the last client leaves.
350
+ override async onSave() {
351
+ await this.ctx.storage.put('doc', Y.encodeStateAsUpdate(this.document))
352
+ }
353
+ }
354
+
355
+ export default {
356
+ async fetch(request, env) {
357
+ return (await routePartykitRequest(request, env)) ?? new Response('Not found', { status: 404 })
358
+ },
359
+ } satisfies ExportedHandler<Env>
360
+ ```
361
+
362
+ Bind the class as a Durable Object in `wrangler.jsonc`, then run `npx wrangler dev`, or `npx wrangler deploy` and point the client at the Worker's host:
363
+
364
+ ```jsonc
365
+ {
366
+ "name": "my-app-sync",
367
+ "main": "src/index.ts",
368
+ "compatibility_date": "2026-11-01",
369
+ "durable_objects": { "bindings": [{ "name": "Docs", "class_name": "Docs" }] },
370
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Docs"] }],
371
+ }
372
+ ```
373
+
374
+ Without `onLoad` and `onSave`, a room keeps its doc only while someone is connected. Durable Object storage limits the size of one value, so store a doc that grows past it in R2, or as several updates.
375
+
376
+ ### Offline as well
377
+
378
+ Sync and [offline storage](offline.md) work together: attach both providers to the same doc. Edits made offline are saved locally and sent when the connection comes back.
379
+
380
+ <!-- docs/recipes/offline.md -->
381
+
382
+ ## Offline storage
383
+
384
+ Save the doc in the browser with y-indexeddb, so the app opens with the last state and works offline; atoms don't change.
385
+
386
+ A Yjs provider that stores the doc locally is all it takes: [y-indexeddb](https://github.com/yjs/y-indexeddb) writes every change to IndexedDB and loads it back when the app starts.
387
+
388
+ ```bash
389
+ npm install y-indexeddb
390
+ ```
391
+
392
+ ```ts
393
+ import { docAtom } from 'duratom'
394
+ import { createStore } from 'jotai'
395
+ import { IndexeddbPersistence } from 'y-indexeddb'
396
+ import * as Y from 'yjs'
397
+
398
+ const doc = new Y.Doc()
399
+ // Saves every change to IndexedDB under this name, and loads what was saved last time.
400
+ const persistence = new IndexeddbPersistence('my-app', doc)
401
+
402
+ export const store = createStore()
403
+ store.set(docAtom, doc)
404
+
405
+ // Atoms read the doc as soon as it's set; this resolves once the saved state is loaded into it.
406
+ export const loaded = persistence.whenSynced
407
+ ```
408
+
409
+ Atoms can be read before `loaded` resolves: a typed atom reads `undefined` for a node that isn't loaded yet, then its value once it is, like a node a peer creates. To avoid showing an empty app for a moment, wait for `loaded` before rendering.
410
+
411
+ Use a name per doc: two docs saved under one name are merged into one. To share the doc between devices as well, add a [sync provider](sync.md) to the same doc.
412
+
413
+ <!-- docs/recipes/repair.md -->
414
+
415
+ ## Repair a broken node
416
+
417
+ Fix a node a peer stored with data your schema rejects, by setting its typed atom with a whole valid value.
418
+
419
+ A peer running an older or buggy version of an app can store a value your schema rejects: a string where a boolean belongs, a missing field. duratom never throws for it. The node's typed atom reads `{ issues }`, and a collection still lists its id, so the app can show it as broken and offer to fix it.
420
+
421
+ Repairing is app code, because only the app knows what a sensible value is. While a node has no valid value, setting its typed atom takes a whole value and replaces what the schema rejected, keeping keys neither the shape nor the value names, such as fields a newer peer added.
422
+
423
+ ```ts
424
+ import { collection, docAtom, select } from 'duratom'
425
+ import { atom } from 'jotai'
426
+ import * as Y from 'yjs'
427
+ import { z } from 'zod'
428
+
429
+ const Todo = z.object({ title: z.string().min(1), done: z.boolean() })
430
+ const todos = collection(select.map('todos'), Todo, { title: 'text' })
431
+
432
+ /**
433
+ * Repairs a todo a peer stored with a value the schema rejects. While an item has no valid value,
434
+ * setting its atom takes a whole value and replaces what the schema rejected. Only the app knows
435
+ * what a sensible value is: here, the stored title when there is one, and not done.
436
+ */
437
+ export const repairTodo = atom(null, (get, set, id: string) => {
438
+ const stored = get(docAtom)?.getMap<unknown>('todos').get(id)
439
+ const title = stored instanceof Y.Map ? String(stored.get('title') ?? '').trim() : ''
440
+ return set(todos.item(id), { title: title || 'Repaired todo', done: false })
441
+ })
442
+
443
+ /** Whether a todo needs repair: listed, but read as `{ issues }` or not a map at all. */
444
+ export const needsRepair = (id: string) =>
445
+ atom((get) => {
446
+ const result = get(todos.item(id))
447
+ return !result || result.issues !== undefined
448
+ })
449
+ ```
450
+
451
+ A row can read `needsRepair(id)` to show a repair button, and call `useSetAtom(repairTodo)(id)` when it's pressed. `repairTodo` returns the schema's result: `{ issues }` if the value it built is still invalid, in which case nothing changed.
452
+
453
+ An entry a peer stored as a plain value is replaced the same way: the item's typed atom reads `undefined`, and setting it with a whole value stores a new map in its place. An entry stored as another shared type, such as a `Y.Text`, reads as `{ issues }` and can't be replaced through the item's atom; delete it with the collection's `remove` and create the item again.
454
+
455
+ <!-- docs/api.md -->
456
+
457
+ ## API reference
458
+
459
+ duratom has three entry points. `duratom` is the one most apps need; `duratom/react` adds hooks, and `duratom/core` has the pieces that work without Jotai.
460
+
461
+ ### `duratom`
462
+
463
+ #### Functions and values
464
+
465
+ ##### `array`
466
+
467
+ ```ts
468
+ const array: () => ArrayKind
469
+ ```
470
+
471
+ A `Y.Array` of plain values, read as a plain array. Writing it changes only the items that
472
+ differ, so items peers add at once are all kept.
473
+
474
+ ```ts
475
+ const Card = z.object({ tags: z.array(z.string()) })
476
+ const card = typedAtom(select.map('cards').child('card-1'), Card, { tags: array() })
477
+ ```
478
+
479
+ ##### `isMap`
480
+
481
+ ```ts
482
+ const isMap: (value: unknown) => value is Y.Map<unknown>
483
+ ```
484
+
485
+ Whether `value` is a `Y.Map` that duratom reads as one: a `Y.XmlHook` extends `Y.Map`, but peers
486
+ decode it as its own type, so it isn't.
487
+
488
+ ```ts
489
+ const stored = doc.getMap('todos').get(id)
490
+ if (isMap(stored)) console.log(stored.get('title'))
491
+ ```
492
+
493
+ ##### `map`
494
+
495
+ ```ts
496
+ const map: <const S extends AnyShape>(shape: S) => MapKind<S>
497
+ ```
498
+
499
+ A nested `Y.Map` with the fixed keys `shape` describes, read as a plain object.
500
+
501
+ ```ts
502
+ const Card = z.object({ title: z.string(), meta: z.object({ note: z.string() }) })
503
+ const card = typedAtom(select.map('cards').child('card-1'), Card, { meta: map({ note: 'text' }) })
504
+ ```
505
+
506
+ ##### `record`
507
+
508
+ ```ts
509
+ const record: <const S extends AnyShape>(itemShape: S) => RecordKind<S>
510
+ ```
511
+
512
+ A `Y.Map` with dynamic keys whose every value is a `Y.Map` following `itemShape`.
513
+
514
+ ```ts
515
+ const Board = z.object({ cards: z.record(z.string(), z.object({ title: z.string() })) })
516
+ const board = typedAtom(select.map('boards').child('b1'), Board, { cards: record({ title: 'text' }) })
517
+ ```
518
+
519
+ ##### `ArrayPath`
520
+
521
+ ```ts
522
+ class ArrayPath<V = unknown>
523
+ ```
524
+
525
+ A path to a `Y.Array`. End it with a projection to get a `Selector`.
526
+
527
+ ```ts
528
+ const log = select.map('board').child('log', 'array')
529
+ const entries = liveAtom(log.length())
530
+ ```
531
+
532
+ - `toArray(): Selector<V[]>`
533
+
534
+ The items as stored, `[]` when the array is missing. Compared shallowly.
535
+
536
+ - `length(): Selector<number>`
537
+
538
+ The number of items, 0 when the array is missing.
539
+
540
+ - `toJSON(): Selector<unknown[]>`
541
+
542
+ `toJSON()` of the array and everything under it, `[]` when missing. Observes deeply; compared deeply.
543
+
544
+ - `readonly locator: Locator<Y.Array<V>>`
545
+ - `project<T>(project: (node: Y.Array<V> | undefined) => T, options?: ProjectOptions<T>): Selector<T>`
546
+
547
+ Your own projection of the node, `undefined` when it is missing or of
548
+ another kind. Observes deeply and compares with `deepEqual` unless
549
+ `options` say otherwise; `keys` alone observes only those keys.
550
+
551
+ - `project<T>(projection: Projection<T>): Selector<T>`
552
+
553
+ A packaged projection, such as `reader(schema, shape)`, with its own
554
+ observe options and `equals`. It gets the node as stored, whatever its kind.
555
+
556
+
557
+ ##### `at`
558
+
559
+ ```ts
560
+ const at: {
561
+ map: <V = unknown>(name: string) => Locator<Y.Map<V>>;
562
+ array: <V = unknown>(name: string) => Locator<Y.Array<V>>;
563
+ }
564
+ ```
565
+
566
+ Starts a `Locator` at a root type of the doc. `select` builds on it, and is what most code
567
+ uses; `at` is for a `LiveSpec` written by hand.
568
+
569
+ ```ts
570
+ const spec = {
571
+ locate: () => at.map('cards').child<Y.Map<unknown>>('card-1'),
572
+ project: (card: Y.Map<unknown> | undefined) => card?.size ?? 0,
573
+ }
574
+ ```
575
+
576
+ ##### `deepEqual`
577
+
578
+ ```ts
579
+ const deepEqual: (a: unknown, b: unknown) => boolean
580
+ ```
581
+
582
+ Compares arrays and plain objects all the way down, and bytes byte by byte.
583
+ Any other object (a `Map`, a `Set`, a `Date`, a shared type) equals only itself.
584
+
585
+ ```ts
586
+ deepEqual({ tags: ['a'] }, { tags: ['a'] }) // true
587
+ const tags = liveAtom({ ...select.map('card').get('tags', []), equals: deepEqual })
588
+ ```
589
+
590
+ ##### `Locator`
591
+
592
+ ```ts
593
+ class Locator<N extends Y.AbstractType<any> = Y.AbstractType<any>>
594
+ ```
595
+
596
+ A path from a root type to the node a component cares about. It is a path
597
+ rather than a bare function of the doc so the subscription can watch the key
598
+ in each parent map: that is how a node that does not exist yet (a card that
599
+ another tab has not created) or that gets deleted is noticed without
600
+ observing the whole doc.
601
+
602
+ ```ts
603
+ const card = at.map('cards').child<Y.Map<unknown>>('card-1')
604
+ card.resolve(doc) // the Y.Map, or undefined while it's missing
605
+ ```
606
+
607
+ - `constructor(readonly steps: readonly Step[])`
608
+ - `readonly steps: readonly Step[]`
609
+ - `child<C extends Y.AbstractType<any> = Y.AbstractType<any>>(key: string): Locator<C>`
610
+
611
+ Descend into the Y type stored under `key` of a map.
612
+
613
+ - `resolve(doc: Y.Doc): N | undefined`
614
+
615
+ ##### `MapPath`
616
+
617
+ ```ts
618
+ class MapPath<V = unknown>
619
+ ```
620
+
621
+ A path to a `Y.Map`. Descend with `child`, or end with a projection to get a `Selector`.
622
+ `select.map(name)` starts one; `typedAtom` and `collection` take one as their locator.
623
+
624
+ ```ts
625
+ const card = select.map('cards').child('card-1')
626
+ const title = liveAtom(card.text('title'))
627
+ const flags = liveAtom(card.pick({ done: false, starred: false }))
628
+ ```
629
+
630
+ - `child<W = V extends Y.Map<infer X> ? X : unknown>(key: string): MapPath<W>`
631
+
632
+ Descend into the `Y.Map` stored under `key`.
633
+
634
+ - `child<W = V extends Y.Array<infer X> ? X : unknown>(key: string, kind: 'array'): ArrayPath<W>`
635
+
636
+ Descend into the `Y.Array` stored under `key`.
637
+
638
+ - `get(key: string): Selector<V | undefined>`
639
+
640
+ The value under `key`, or `undefined` when it or the map is missing. Observes only `key`.
641
+
642
+ - `get<D>(key: string, fallback: D): Selector<undefined extends D ? V | Checked<D> : Checked<D>>`
643
+
644
+ The value under `key` when it has the same type as `fallback` (`typeof`,
645
+ with null, arrays, bytes and plain objects told apart), else `fallback`. So
646
+ a missing map, a missing key and a value of the wrong type all read as
647
+ `fallback`. An `undefined` fallback reads the value as `get(key)` does.
648
+ A literal type widens to its primitive, since only the kind is checked; the
649
+ items of an array and the fields of an object aren't checked. An array or
650
+ object fallback is read frozen, a bytes fallback as a copy. Observes only `key`.
651
+
652
+ - `pick<D extends Record<string, unknown>>(defaults: D): Selector<{ [K in keyof D]: Checked<D[K]> }>`
653
+
654
+ An object with each key of `defaults`, read as `get(key, defaults[key])`
655
+ reads it. Observes only those keys; compared shallowly.
656
+
657
+ - `text(key: string): Selector<string>`
658
+
659
+ The string of the `Y.Text` under `key`, `''` when it is missing or not a
660
+ `Y.Text` (a `Y.XmlText` included). Follows edits to the text.
661
+
662
+ - `keys(): Selector<string[]>`
663
+
664
+ The map's keys, sorted so every peer sees the same order. `[]` when the
665
+ map is missing. Only a key added or deleted counts, not a value replaced.
666
+ Its own `event` filter does that, so a spec that adds an `event` filter
667
+ calls it from its own: `{ ...ids, event: (e) => ids.event!(e) && mine(e) }`.
668
+
669
+ - `toJSON(): Selector<Record<string, unknown>>`
670
+
671
+ `toJSON()` of the map and everything under it, `{}` when missing. Observes deeply; compared deeply.
672
+
673
+ - `readonly locator: Locator<Y.Map<V>>`
674
+ - `project<T>(project: (node: Y.Map<V> | undefined) => T, options?: ProjectOptions<T>): Selector<T>`
675
+
676
+ Your own projection of the node, `undefined` when it is missing or of
677
+ another kind. Observes deeply and compares with `deepEqual` unless
678
+ `options` say otherwise; `keys` alone observes only those keys.
679
+
680
+ - `project<T>(projection: Projection<T>): Selector<T>`
681
+
682
+ A packaged projection, such as `reader(schema, shape)`, with its own
683
+ observe options and `equals`. It gets the node as stored, whatever its kind.
684
+
685
+
686
+ ##### `select`
687
+
688
+ ```ts
689
+ const select: {
690
+ map: <V = unknown>(name: string) => MapPath<V>;
691
+ array: <V = unknown>(name: string) => ArrayPath<V>;
692
+ }
693
+ ```
694
+
695
+ Builds selectors: `select.map('cards').child(id).get('title', '')`. Starts
696
+ at a root type of the doc, like `at`.
697
+
698
+ ```ts
699
+ const title = liveAtom(select.map('cards').child('card-1').get('title', ''))
700
+ const ids = liveAtom(select.map('cards').keys())
701
+ const order = liveAtom(select.array<string>('order').toArray())
702
+ ```
703
+
704
+ ##### `shallowEqual`
705
+
706
+ ```ts
707
+ const shallowEqual: (a: unknown, b: unknown) => boolean
708
+ ```
709
+
710
+ Whether two values are the same, or objects or arrays whose own keys hold the same values
711
+ (`Object.is`). The default `equals` of a `LiveSpec`.
712
+
713
+ ```ts
714
+ shallowEqual({ done: 1, total: 2 }, { done: 1, total: 2 }) // true
715
+ shallowEqual({ tags: ['a'] }, { tags: ['a'] }) // false: two different arrays
716
+ ```
717
+
718
+ ##### `docAtom`
719
+
720
+ ```ts
721
+ const docAtom: PrimitiveAtom<Y.Doc | null> & { init: Y.Doc | null;}
722
+ ```
723
+
724
+ Holds the live Y.Doc handle that atoms read by default. Set once per store; the doc never
725
+ changes, so this atom never notifies.
726
+
727
+ ```ts
728
+ const store = createStore()
729
+ store.set(docAtom, new Y.Doc())
730
+ ```
731
+
732
+ ##### `liveAtom`
733
+
734
+ ```ts
735
+ function liveAtom<N extends Y.AbstractType<any>, T>(
736
+ spec: LiveSpec<N, T>,
737
+ options: AtomOptions = {},
738
+ ): Atom<T>
739
+ ```
740
+
741
+ A read-only atom over one node of the doc in `docAtom` (or the doc atom given in `options`),
742
+ built on `live` from `duratom/core`. While something is subscribed it observes only the
743
+ located node, re-runs `project` on matching transactions and updates only when `equals` says
744
+ the result changed. Unsubscribes when the last subscriber goes away.
745
+
746
+ Read while nothing is subscribed (`store.get` outside a component), it can be stale: Jotai
747
+ keeps an unmounted atom's value until one of its atom dependencies changes, and a doc edit
748
+ isn't one. It projects the doc on its first read and again whenever it is mounted, but not
749
+ after later doc edits made while unmounted. Subscribe (`useAtomValue`, `store.sub`) to follow
750
+ the doc; outside Jotai, `live` from `duratom/core` reads the doc as it is now.
751
+
752
+ A change skipped by the `origin` filter is not remembered: the value catches up at the next
753
+ accepted change.
754
+
755
+ ```ts
756
+ const titleAtom = liveAtom(select.map('cards').child('card-1').get('title', ''))
757
+ ```
758
+
759
+ ##### `collection`
760
+
761
+ ```ts
762
+ function collection<Schema extends StandardSchemaV1, const S extends object>(
763
+ locator: Locator<any> | MapPath<any>,
764
+ schema: Schema,
765
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
766
+ options: AtomOptions = {},
767
+ ): Collection<StandardSchemaV1.InferOutput<Schema>>
768
+ ```
769
+
770
+ A collection over the `Y.Map` at `locator`, whose every entry is an item `Y.Map` read through
771
+ `schema` and `shape`. `ids` lists the items and stays quiet while their fields change, `item(id)`
772
+ is a `typedAtom` per item, and `create` and `remove` add and delete items.
773
+
774
+ Like any duratom atom, `ids` and `item(id)` can read stale while nothing is subscribed, except
775
+ right after the collection's own `create` or `remove`, or a write through `item(id)` that
776
+ created the item. An entry a peer stored as something other than a `Y.Map` is still listed in
777
+ `ids`, so it can be found and repaired; its `item` atom reads it as `{ issues }`, or as
778
+ `undefined` for a plain value.
779
+
780
+ ```ts
781
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
782
+ const todos = collection(select.map('todos'), Todo, { title: 'text' })
783
+
784
+ const { id } = store.set(todos.create, { title: 'Buy milk', done: false }) as { id: string }
785
+ store.get(todos.ids) // [id]
786
+ store.set(todos.item(id), { done: true }) // changes only done
787
+ store.set(todos.remove, id)
788
+ ```
789
+
790
+ ##### `typedAtom`
791
+
792
+ ```ts
793
+ function typedAtom<Schema extends StandardSchemaV1, const S extends object>(
794
+ locator: Locator<any> | MapPath<any>,
795
+ schema: Schema,
796
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
797
+ options: AtomOptions = {},
798
+ ): TypedAtom<StandardSchemaV1.InferOutput<Schema>>
799
+ ```
800
+
801
+ A typed, writable atom over the `Y.Map` at `locator`, read through `schema` and `shape`: a
802
+ `liveAtom` over `reader(schema, shape)` with a setter. It observes only that node, skips edits
803
+ inside its `'xml'` fields, and re-renders only when the result changes. Like a `liveAtom`, it
804
+ can read stale while nothing is subscribed, except right after its own setter wrote.
805
+
806
+ Setting it reads the node as it is in the doc at write time, not the atom's last value, and
807
+ merges the patch into it: fields the patch leaves out, and keys the schema doesn't know, are
808
+ written back unchanged, so `write` changes only the patched fields and a peer's concurrent
809
+ edit to another field survives. A function patch gets that fresh value as `prev`.
810
+
811
+ Invalid data never throws: the setter returns the schema's result, and `{ issues }` changes
812
+ nothing.
813
+
814
+ While the node has no valid value, the patch is the whole value and a function patch gets
815
+ `undefined` as `prev`. On a missing node a valid value creates the `Y.Map` in its parent; when
816
+ the parent map is missing too, nothing is created and the result holds one issue saying so. On
817
+ an invalid node a valid value replaces what the schema rejected, keeping keys neither the shape
818
+ nor the value names: that is how a node a peer broke is repaired. A shared type of another kind
819
+ where the map belongs reads as issues, and only writing its parent can replace it.
820
+
821
+ ```ts
822
+ const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
823
+ const cardAtom = typedAtom(select.map('cards').child('card-1'), Card, { title: 'text' })
824
+
825
+ store.get(cardAtom) // undefined, { issues } or { value }
826
+ store.set(cardAtom, { title: 'Ship it', priority: 'low' }) // creates the card
827
+ store.set(cardAtom, { priority: 'high' }) // changes only priority
828
+ ```
829
+
830
+ #### Types
831
+
832
+ ##### `ArrayKind`
833
+
834
+ ```ts
835
+ interface ArrayKind {
836
+ readonly kind: 'array'
837
+ }
838
+ ```
839
+
840
+ An `array()` field: a Shared array of plain values.
841
+
842
+ ##### `MapKind`
843
+
844
+ ```ts
845
+ interface MapKind<S> {
846
+ readonly kind: 'map'
847
+ readonly shape: S
848
+ }
849
+ ```
850
+
851
+ A `map(shape)` field: a `Y.Map` with the fixed keys `shape` describes.
852
+
853
+ ##### `RecordKind`
854
+
855
+ ```ts
856
+ interface RecordKind<S> {
857
+ readonly kind: 'record'
858
+ readonly shape: S
859
+ }
860
+ ```
861
+
862
+ A `record(itemShape)` field: a `Y.Map` of item `Y.Map`s, each following `itemShape`.
863
+
864
+ ##### `Shape`
865
+
866
+ ```ts
867
+ type Shape<T> = {
868
+ readonly [K in KeyOf<T>]?: KindOf<FieldOf<T, K>>
869
+ }
870
+ ```
871
+
872
+ Which fields of a node are Shared fields, and of what kind. Every key it doesn't mention is a
873
+ Plain field. Keys are constrained to the fields of `T`, the schema's output, in any member of a
874
+ union, and each kind to fields its read value can fill.
875
+
876
+ ##### `At`
877
+
878
+ ```ts
879
+ type At = typeof at
880
+ ```
881
+
882
+ The type of `at`, which a `LiveSpec`'s `locate` gets.
883
+
884
+ ##### `ObserveOptions`
885
+
886
+ ```ts
887
+ interface ObserveOptions {
888
+ /** Use `observeDeep` on the located node, so changes in nested types count. */
889
+ deep?: boolean
890
+ /**
891
+ * Only count Y.Map changes to these keys. In deep mode, changes to the located
892
+ * node itself (children added or removed) always count.
893
+ */
894
+ keys?: readonly string[]
895
+ /** Return false to ignore a transaction by its origin. */
896
+ origin?: (origin: unknown) => boolean
897
+ /**
898
+ * Return false to ignore a change by its event. It decides whether a
899
+ * transaction counts, not what is seen: in deep mode it is called with the
900
+ * transaction's events under the node until one is accepted, so it may not
901
+ * see them all. It runs while the observer runs, so `event.changes` and
902
+ * `event.path` (relative to the located node) can be read.
903
+ */
904
+ event?: (event: Y.YEvent<any>) => boolean
905
+ }
906
+ ```
907
+
908
+ Which changes to the located node count, for `observeLocated`, `live` and every atom.
909
+
910
+ ##### `Projection`
911
+
912
+ ```ts
913
+ interface Projection<T> extends ProjectOptions<T> {
914
+ project: (node: Y.AbstractType<any> | undefined) => T
915
+ }
916
+ ```
917
+
918
+ A projection packaged with how to observe and compare it, such as
919
+ `reader(schema, shape)` from `@y-modern/schema`. Hand it to `project`, or
920
+ spread it into a spec beside `locate`. It takes the node as stored, of any
921
+ shared type, so it can report one of another kind than its path says, as
922
+ `reader` does, rather than see it as missing.
923
+
924
+ ##### `ProjectOptions`
925
+
926
+ ```ts
927
+ interface ProjectOptions<T> {
928
+ /** Default: `deepEqual`, since a custom projection usually builds a fresh value. */
929
+ equals?: (a: T, b: T) => boolean
930
+ /** Default: true without `keys`, so a change anywhere under the node counts; false with `keys`. */
931
+ deep?: boolean
932
+ keys?: readonly string[]
933
+ /** Return false to ignore a change by its event, as `ObserveOptions#event` says. */
934
+ event?: (event: Y.YEvent<any>) => boolean
935
+ }
936
+ ```
937
+
938
+ Options of `project`: how to observe the node and compare projections.
939
+
940
+ ##### `Selector`
941
+
942
+ ```ts
943
+ type Selector<T> = LiveSpec<any, T>
944
+ ```
945
+
946
+ A ready `LiveSpec`: path, observed keys, projection and equality in one
947
+ plain object. Pass it to `live` or a binding's `liveAtom` as it is, or
948
+ spread it to add an option (`{ ...selector, origin }`).
949
+
950
+ ##### `AtomOptions`
951
+
952
+ ```ts
953
+ interface AtomOptions {
954
+ /**
955
+ * The atom holding the doc this atom reads, for apps with several docs. Defaults to
956
+ * `docAtom`.
957
+ *
958
+ * @example
959
+ * const boardDocAtom = atom<Y.Doc | null>(null)
960
+ * const title = liveAtom(select.map('meta').get('title', ''), { docAtom: boardDocAtom })
961
+ */
962
+ docAtom?: Atom<Y.Doc | null | undefined>
963
+ }
964
+ ```
965
+
966
+ Options every duratom atom takes.
967
+
968
+ ##### `LiveSpec`
969
+
970
+ ```ts
971
+ interface LiveSpec<N extends Y.AbstractType<any>, T> extends ObserveOptions {
972
+ locate: (at: At) => Locator<N>
973
+ /** Plain snapshot. `undefined` when the located node does not exist. */
974
+ project: (node: N | undefined) => T
975
+ /** Whether two projections are the same; an equal result keeps the old reference and does not notify. Default: shallow. */
976
+ equals?: (a: T, b: T) => boolean
977
+ }
978
+ ```
979
+
980
+ What `live` and `liveAtom` read: where the node is, how to turn it into a value, and when the
981
+ value counts as changed. `select` builds one; write your own for anything it can't express.
982
+
983
+ ##### `Collection`
984
+
985
+ ```ts
986
+ interface Collection<T> {
987
+ /**
988
+ * The ids of every entry of the map, sorted so every peer sees the same order; `[]` while the
989
+ * map is missing. Notifies only when an id is added or removed, never when an item's fields
990
+ * change.
991
+ */
992
+ readonly ids: Atom<string[]>
993
+ /**
994
+ * The typed atom of the item under `id`, the same atom for the same id: it reads `undefined`,
995
+ * `{ issues }` or `{ value }` and merges a patch when set, as `typedAtom` does; setting a
996
+ * missing item creates it. The collection's `remove` drops the item's atom from the family, and
997
+ * `item.remove(id)` or `item.setShouldRemove` can drop others; an atom a caller still holds keeps
998
+ * working after it's dropped.
999
+ */
1000
+ readonly item: AtomFamily<string, TypedAtom<T>>
1001
+ /**
1002
+ * Validates a whole value and adds it as a new item under `id`, or under a random UUID when no
1003
+ * id is given. Returns the schema's result with the id. An invalid value, an id already in use,
1004
+ * or a missing map adds nothing and returns `{ issues }`: the value's own issues when it has
1005
+ * any, else one saying why it couldn't be added.
1006
+ */
1007
+ readonly create: WritableAtom<null, [value: T, id?: string], CreateResult<T>>
1008
+ /** Removes the item under `id`. Returns whether there was one. */
1009
+ readonly remove: WritableAtom<null, [id: string], boolean>
1010
+ }
1011
+ ```
1012
+
1013
+ Atoms over a `Y.Map` of items, each item a `Y.Map` read through one schema. Write with
1014
+ `store.set` or `useSetAtom`, like any Jotai atom.
1015
+
1016
+ ##### `CreateResult`
1017
+
1018
+ ```ts
1019
+ type CreateResult<T> =
1020
+ | (StandardSchemaV1.SuccessResult<T> & { readonly id: string })
1021
+ | StandardSchemaV1.FailureResult
1022
+ ```
1023
+
1024
+ What a collection's `create` returns: the schema's result, with the new item's id when valid.
1025
+
1026
+ ##### `Patch`
1027
+
1028
+ ```ts
1029
+ type Patch<T> = Partial<T> | ((prev: T | undefined) => Partial<T>)
1030
+ ```
1031
+
1032
+ What a typed atom's setter takes: a patch of the fields to change, or a function of the node's
1033
+ value as it is in the doc at write time (`undefined` while it has no valid value) returning one.
1034
+
1035
+ ##### `TypedAtom`
1036
+
1037
+ ```ts
1038
+ type TypedAtom<T> = WritableAtom<
1039
+ StandardSchemaV1.Result<T> | undefined,
1040
+ [patch: Patch<T>],
1041
+ StandardSchemaV1.Result<T>
1042
+ >
1043
+ ```
1044
+
1045
+ A Jotai atom over one `Y.Map` of the doc, read through a schema. It reads as `undefined` while
1046
+ the node is missing, `{ issues }` while it doesn't satisfy the schema, and `{ value }`
1047
+ otherwise. Setting it merges a patch and returns the schema's result.
1048
+
1049
+ ### `duratom/react`
1050
+
1051
+ #### Functions and values
1052
+
1053
+ ##### `useLiveAtom`
1054
+
1055
+ ```ts
1056
+ function useLiveAtom<N extends Y.AbstractType<any>, T>(
1057
+ spec: LiveSpec<N, T> | (() => LiveSpec<N, T>),
1058
+ deps: DependencyList,
1059
+ options?: AtomOptions,
1060
+ ): T
1061
+ function useLiveAtom<N extends Y.AbstractType<any>, T>(
1062
+ locate: LiveSpec<N, T>['locate'],
1063
+ project: LiveSpec<N, T>['project'],
1064
+ options?: SpecOptions<N, T>,
1065
+ deps?: DependencyList,
1066
+ ): T
1067
+ ```
1068
+
1069
+ Hook form of `liveAtom`, taking a whole spec, such as a selector from `select`, or a function
1070
+ that builds it: `useLiveAtom(() => select..., [id])` builds it only when `deps` change, rather
1071
+ than on every render. The atom is rebuilt only when `deps` change, so list whatever the spec
1072
+ closes over (an id, say), as with useMemo. `deps` is required: a spec built inline from props
1073
+ would otherwise keep its first value. `options.docAtom` reads another doc than `docAtom`.
1074
+
1075
+ Hook form of `liveAtom`. The atom is rebuilt only when `deps` change, so list whatever
1076
+ `locate` and `project` close over (an id, say), as with useMemo. `options.docAtom` reads
1077
+ another doc than `docAtom`.
1078
+
1079
+ ```ts
1080
+ const title = useLiveAtom(() => select.map('cards').child(id).get('title', ''), [id])
1081
+ ```
1082
+
1083
+ ```ts
1084
+ const title = useLiveAtom(
1085
+ (at) => at.map('cards').child(id),
1086
+ (card: Y.Map<unknown> | undefined) => String(card?.get('title') ?? ''),
1087
+ { keys: ['title'] },
1088
+ [id],
1089
+ )
1090
+ ```
1091
+
1092
+ ##### `useTypedAtom`
1093
+
1094
+ ```ts
1095
+ function useTypedAtom<Schema extends StandardSchemaV1, const S extends object>(
1096
+ locator: Locator<any> | MapPath<any> | (() => Locator<any> | MapPath<any>),
1097
+ schema: Schema,
1098
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
1099
+ deps: DependencyList,
1100
+ options?: AtomOptions,
1101
+ ): [
1102
+ result: StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>> | undefined,
1103
+ set: (
1104
+ patch: Patch<StandardSchemaV1.InferOutput<Schema>>,
1105
+ ) => StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>,
1106
+ ]
1107
+ ```
1108
+
1109
+ Hook form of `typedAtom`, returning `[result, set]` as `useAtom` does: `result` is `undefined`
1110
+ while the node is missing, `{ issues }` while it's invalid and `{ value }` otherwise, and
1111
+ `set(patch)` merges a patch and returns the schema's result. `locator` can be a function that
1112
+ builds it, so it's built only when `deps` change. The atom is rebuilt only when `deps` change,
1113
+ so list whatever the locator closes over (an id, say), as with useMemo; `schema` and `shape`
1114
+ are taken from the render that built it. `options.docAtom` reads another doc than `docAtom`.
1115
+
1116
+ ```ts
1117
+ const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
1118
+ const [card, setCard] = useTypedAtom(() => select.map('cards').child(id), Card, { title: 'text' }, [id])
1119
+ if (card && !card.issues) setCard({ priority: 'high' })
1120
+ ```
1121
+
1122
+ ### `duratom/core`
1123
+
1124
+ Also exports `deepEqual`, `shallowEqual`, `LiveSpec`, `at`, `Locator`, `At`, `ObserveOptions`, `ArrayPath`, `MapPath`, `select`, `Projection`, `ProjectOptions`, `Selector`, documented under `duratom`.
1125
+
1126
+ #### Functions and values
1127
+
1128
+ ##### `live`
1129
+
1130
+ ```ts
1131
+ function live<N extends Y.AbstractType<any>, T>(
1132
+ doc: Y.Doc,
1133
+ spec: LiveSpec<N, T>,
1134
+ ): Live<T, N>
1135
+ ```
1136
+
1137
+ A live projection of one node of `doc`. While anything is subscribed it
1138
+ observes only the located node (see `observeLocated`), re-runs `project` on
1139
+ matching transactions and notifies only when `equals` says the result
1140
+ changed. With no subscribers nothing is observed and `get` projects the
1141
+ current doc on each call.
1142
+
1143
+ A change skipped by the `origin` filter is not remembered while subscribed:
1144
+ the value catches up at the next accepted change. With no subscribers there
1145
+ is nothing to filter, so `get` shows every change made so far.
1146
+
1147
+ ```ts
1148
+ const title = live(doc, select.map('cards').child('card-1').get('title', ''))
1149
+ const stop = title.subscribe((value, prev) => console.log(prev, '->', value))
1150
+ title.get() // the title now
1151
+ stop()
1152
+ ```
1153
+
1154
+ ##### `observeLocated`
1155
+
1156
+ ```ts
1157
+ function observeLocated(
1158
+ doc: Y.Doc,
1159
+ locator: Locator,
1160
+ options: ObserveOptions,
1161
+ onChange: () => void,
1162
+ ): () => void
1163
+ ```
1164
+
1165
+ Calls `onChange` after a transaction that may have changed what the locator
1166
+ points at. Watches the located node (and nothing else in the doc) plus, for
1167
+ each step of the path, that one key of the parent map. Returns an unsubscribe.
1168
+
1169
+ ```ts
1170
+ const stop = observeLocated(doc, at.map('cards').child('card-1'), { deep: true }, () =>
1171
+ console.log('card-1 changed, or was created or deleted'),
1172
+ )
1173
+ stop()
1174
+ ```
1175
+
1176
+ ##### `AsyncValidationUnsupportedError`
1177
+
1178
+ ```ts
1179
+ class AsyncValidationUnsupportedError
1180
+ ```
1181
+
1182
+ Thrown by `read` and `write` when the schema's `~standard.validate` returns a Promise. The layer
1183
+ validates synchronously only, so an async schema is a configuration error, not bad data.
1184
+
1185
+ ```ts
1186
+ const Slow = z.object({ title: z.string() }).refine(async () => true)
1187
+ try {
1188
+ store.set(typedAtom(select.map('cards').child('c1'), Slow, {}), { title: 'Hi' })
1189
+ } catch (error) {
1190
+ if (error instanceof AsyncValidationUnsupportedError) console.error(error.vendor) // 'zod'
1191
+ }
1192
+ ```
1193
+
1194
+ - `constructor(vendor: string)`
1195
+ - `readonly vendor: string`
1196
+ - `name: string`
1197
+ - `message: string`
1198
+ - `stack?: string`
1199
+ - `cause?: unknown`
1200
+
1201
+ ##### `create`
1202
+
1203
+ ```ts
1204
+ function create<Schema extends StandardSchemaV1, const S extends object>(
1205
+ schema: Schema,
1206
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
1207
+ parent: Y.Map<unknown>,
1208
+ key: string,
1209
+ value: StandardSchemaV1.InferOutput<Schema>,
1210
+ ): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>
1211
+ ```
1212
+
1213
+ Validates `value` with `schema` and, if it's valid, stores it as a new `Y.Map` under `key` of
1214
+ `parent`, replacing whatever was stored there. Returns the schema's own result; an invalid
1215
+ value creates nothing, and a value the shape can't store throws before anything is created.
1216
+
1217
+ ```ts
1218
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
1219
+ create(Todo, { title: 'text' }, doc.getMap('todos'), 'todo-1', { title: 'Buy milk', done: false })
1220
+ ```
1221
+
1222
+ ##### `read`
1223
+
1224
+ ```ts
1225
+ function read<Schema extends StandardSchemaV1, const S extends object>(
1226
+ schema: Schema,
1227
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
1228
+ node: Y.AbstractType<any> | undefined,
1229
+ ): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>> | undefined
1230
+ ```
1231
+
1232
+ Projects a located `Y.Map` following `shape` and validates it with `schema`, returning the
1233
+ schema's own result. An absent node returns `undefined` without validating, and a node with a
1234
+ shape mismatch, or a shared type that isn't a `Y.Map`, returns the layer's own issues without
1235
+ validating.
1236
+
1237
+ ```ts
1238
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
1239
+ const result = read(Todo, { title: 'text' }, doc.getMap('todos').get(id) as Y.Map<unknown>)
1240
+ if (result?.issues) console.warn(result.issues)
1241
+ else if (result) console.log(result.value.title)
1242
+ ```
1243
+
1244
+ ##### `reader`
1245
+
1246
+ ```ts
1247
+ function reader<Schema extends StandardSchemaV1, const S extends object>(
1248
+ schema: Schema,
1249
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
1250
+ ): Reader<StandardSchemaV1.InferOutput<Schema>>
1251
+ ```
1252
+
1253
+ `read(schema, shape, node)` as a `Reader`, for `select...project(reader(schema, shape))`.
1254
+ `typedAtom` reads through it; use it for a read-only typed value outside Jotai.
1255
+
1256
+ ```ts
1257
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
1258
+ const todo = live(doc, select.map('todos').child(id).project(reader(Todo, { title: 'text' })))
1259
+ todo.subscribe((result) => console.log(result?.issues ?? result?.value))
1260
+ ```
1261
+
1262
+ ##### `UnsupportedValueError`
1263
+
1264
+ ```ts
1265
+ class UnsupportedValueError
1266
+ ```
1267
+
1268
+ Thrown by `write` when a plain field or `array()` item holds a value Yjs can't store faithfully: anything but
1269
+ JSON values, `undefined` and `Uint8Array` bytes, a cycle, a `__proto__` key, or a `constructor`
1270
+ key on the field's own object. The schema accepted it, so it's a schema that's too loose, not bad
1271
+ data. Nothing is written.
1272
+
1273
+ ```ts
1274
+ const Event = z.object({ at: z.date() }) // a Date syncs as {}, so it can't be stored
1275
+ try {
1276
+ store.set(typedAtom(select.map('events').child('e1'), Event, {}), { at: new Date() })
1277
+ } catch (error) {
1278
+ if (error instanceof UnsupportedValueError) console.error(error.path) // ['at']
1279
+ }
1280
+ ```
1281
+
1282
+ - `constructor(path: readonly PropertyKey[])`
1283
+ - `readonly path: readonly PropertyKey[]`
1284
+
1285
+ Where the value sits in the written value, starting at the field's key.
1286
+
1287
+ - `name: string`
1288
+ - `message: string`
1289
+ - `stack?: string`
1290
+ - `cause?: unknown`
1291
+
1292
+ ##### `write`
1293
+
1294
+ ```ts
1295
+ function write<Schema extends StandardSchemaV1, const S extends object>(
1296
+ schema: Schema,
1297
+ shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>,
1298
+ node: Y.Map<unknown>,
1299
+ value: StandardSchemaV1.InferOutput<Schema>,
1300
+ ): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>
1301
+ ```
1302
+
1303
+ Validates `value` with `schema` and, if it's valid, merges it into the located `Y.Map` so only
1304
+ the differences change. Returns the schema's own result; an invalid value changes nothing.
1305
+ Fields the value lacks are deleted, so pass the whole value; a typed atom merges a patch first.
1306
+
1307
+ ```ts
1308
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
1309
+ const node = doc.getMap('todos').get(id) as Y.Map<unknown>
1310
+ const result = write(Todo, { title: 'text' }, node, { title: 'Ship it', done: true })
1311
+ if (result.issues) console.warn(result.issues) // the doc is unchanged
1312
+ ```
1313
+
1314
+ #### Types
1315
+
1316
+ ##### `Live`
1317
+
1318
+ ```ts
1319
+ interface Live<T, N extends Y.AbstractType<any> = Y.AbstractType<any>> {
1320
+ /** The current projection. Keeps the same reference until `equals` says it changed. */
1321
+ get(): T
1322
+ /**
1323
+ * Calls `listener(value, prev)` after a change, with the new and the previous
1324
+ * projection. The first subscriber starts observing, the last one to leave stops.
1325
+ */
1326
+ subscribe(listener: (value: T, prev: T) => void): () => void
1327
+ /** The located node as it is now, `undefined` when it does not exist. */
1328
+ resolve(): N | undefined
1329
+ /**
1330
+ * Runs `fn` in one transaction of the doc with the located node as it is
1331
+ * now, `undefined` when it does not exist, and returns what `fn` returns.
1332
+ * The change comes back through `subscribe` like any other, so a write whose
1333
+ * origin the `origin` filter rejects leaves `get()` behind the doc until the
1334
+ * next accepted change.
1335
+ */
1336
+ write<R>(fn: (node: N | undefined, doc: Y.Doc) => R, origin?: unknown): R
1337
+ }
1338
+ ```
1339
+
1340
+ A read-only value over one node of a doc, in the shape `useSyncExternalStore` takes.
1341
+
1342
+ ##### `Reader`
1343
+
1344
+ ```ts
1345
+ interface Reader<T> {
1346
+ project: (node: Y.AbstractType<any> | undefined) => StandardSchemaV1.Result<T> | undefined
1347
+ deep: true
1348
+ event: (event: Y.YEvent<any>) => boolean
1349
+ equals: (
1350
+ a: StandardSchemaV1.Result<T> | undefined,
1351
+ b: StandardSchemaV1.Result<T> | undefined,
1352
+ ) => boolean
1353
+ }
1354
+ ```
1355
+
1356
+ `read` packaged as a store binding's projection: `project` reads a located node through
1357
+ `schema` and `shape`, `deep` observes every change under it, `event` skips edits inside an
1358
+ `'xml'` field, which a read returns as the fragment itself, and `equals` compares two results
1359
+ deeply, since each read returns a fresh tree. It has the shape `project` of a
1360
+ `select` selector and a `liveAtom` spec take, so the schema layer and the observation core
1361
+ stay independent of each other.