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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Karol Novljaković
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,307 @@
1
- # Temporary Holding Version
1
+ # duratom
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Durable, live Jotai atoms over a Y.Doc: read typed values, write validated patches, and re-render only when what an atom shows changes.
4
+
5
+ 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.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install duratom jotai jotai-family yjs
11
+ ```
12
+
13
+ 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`.
14
+
15
+ ## Quick start
16
+
17
+ 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`.
18
+
19
+ <!-- snippet: docs/snippets/quick-start.tsx -->
20
+
21
+ ```tsx
22
+ // src/main.tsx of a new Vite React app: npm create vite@latest my-app -- --template react-ts
23
+ import { docAtom, select, typedAtom } from 'duratom'
24
+ import { createStore, Provider, useAtom } from 'jotai'
25
+ import { StrictMode } from 'react'
26
+ import { createRoot } from 'react-dom/client'
27
+ import * as Y from 'yjs'
28
+ import { z } from 'zod'
29
+
30
+ // What a todo is, and where it lives in the doc: the map `first` in the root map `todos`.
31
+ // `title` is collaborative text, so two people typing in it both keep their edits.
32
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
33
+ const todoAtom = typedAtom(select.map('todos').child('first'), Todo, { title: 'text' })
34
+
35
+ // One Y.Doc per Jotai store. A sync provider would connect this doc to other devices.
36
+ const store = createStore()
37
+ store.set(docAtom, new Y.Doc())
38
+
39
+ function TodoRow() {
40
+ // undefined while the todo is missing, { issues } while it's invalid, { value } otherwise.
41
+ const [todo, setTodo] = useAtom(todoAtom)
42
+ if (!todo) {
43
+ // Setting a missing node with a whole valid value creates it.
44
+ return <button onClick={() => setTodo({ title: 'Learn duratom', done: false })}>Add</button>
45
+ }
46
+ if (todo.issues) return <p>Can't read this todo: {todo.issues[0]?.message}</p>
47
+ return (
48
+ <label>
49
+ {/* A patch changes only the fields it names. */}
50
+ <input
51
+ type="checkbox"
52
+ checked={todo.value.done}
53
+ onChange={(e) => setTodo({ done: e.target.checked })}
54
+ />
55
+ <input value={todo.value.title} onChange={(e) => setTodo({ title: e.target.value })} />
56
+ </label>
57
+ )
58
+ }
59
+
60
+ createRoot(document.getElementById('root')!).render(
61
+ <StrictMode>
62
+ <Provider store={store}>
63
+ <TodoRow />
64
+ </Provider>
65
+ </StrictMode>,
66
+ )
67
+ ```
68
+
69
+ <!-- /snippet -->
70
+
71
+ 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.
72
+
73
+ ## Rules
74
+
75
+ Four rules cover how duratom behaves; the [API reference](https://duratom.karolnov.dev/api) has the details.
76
+
77
+ - **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 })`.
78
+ - **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.
79
+ - **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`.
80
+ - **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.
81
+
82
+ ## Shapes
83
+
84
+ 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.
85
+
86
+ - `'text'`: a `Y.Text`, read as a string. Two people typing in it both keep their edits.
87
+ - `'xml'`: a `Y.XmlFragment`, read as the fragment itself, for rich-text editors.
88
+ - `map(shape)`: a nested `Y.Map` with fixed keys, read as an object.
89
+ - `record(itemShape)`: a `Y.Map` of item maps with any keys, read as an object of objects.
90
+ - `array()`: a `Y.Array` of plain values, read as an array.
91
+
92
+ 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.
93
+
94
+ ## Collections
95
+
96
+ `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`.
97
+
98
+ <!-- snippet: docs/snippets/collection.tsx -->
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
+ <!-- /snippet -->
150
+
151
+ ## Typed atoms in a hook
152
+
153
+ `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.
154
+
155
+ <!-- snippet: docs/snippets/typed-hook.tsx -->
156
+
157
+ ```tsx
158
+ import { select } from 'duratom'
159
+ import { useTypedAtom } from 'duratom/react'
160
+ import { z } from 'zod'
161
+
162
+ const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
163
+
164
+ // The card's path depends on a prop: the hook rebuilds the atom only when `id` changes.
165
+ export function CardRow({ id }: { id: string }) {
166
+ const [card, setCard] = useTypedAtom(
167
+ () => select.map('cards').child(id),
168
+ Card,
169
+ { title: 'text' },
170
+ [id],
171
+ )
172
+ if (!card) return <button onClick={() => setCard({ title: 'New', priority: 'low' })}>Add</button>
173
+ if (card.issues) return <span>Unreadable card</span>
174
+ return (
175
+ <label>
176
+ {card.value.title}
177
+ <input
178
+ type="checkbox"
179
+ checked={card.value.priority === 'high'}
180
+ onChange={(e) => setCard({ priority: e.target.checked ? 'high' : 'low' })}
181
+ />
182
+ </label>
183
+ )
184
+ }
185
+ ```
186
+
187
+ <!-- /snippet -->
188
+
189
+ ## Custom projections
190
+
191
+ `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.
192
+
193
+ <!-- snippet: docs/snippets/live-atom.tsx -->
194
+
195
+ ```tsx
196
+ import { liveAtom, select } from 'duratom'
197
+ import { useLiveAtom } from 'duratom/react'
198
+ import { useAtomValue } from 'jotai'
199
+ import * as Y from 'yjs'
200
+
201
+ // One field, with a fallback for a missing map, a missing key or a value of another type.
202
+ const boardName = liveAtom(select.map('board').get('name', 'Untitled'))
203
+
204
+ // Your own projection: re-renders only when the counts change, not on every edit to a todo.
205
+ const progress = liveAtom(
206
+ select.map('todos').project((todos) => {
207
+ let done = 0
208
+ todos?.forEach((todo) => {
209
+ if (todo instanceof Y.Map && todo.get('done') === true) done++
210
+ })
211
+ return { done, total: todos?.size ?? 0 }
212
+ }),
213
+ )
214
+
215
+ export function Header() {
216
+ const name = useAtomValue(boardName)
217
+ const { done, total } = useAtomValue(progress)
218
+ return (
219
+ <h1>
220
+ {name}: {done} of {total} done
221
+ </h1>
222
+ )
223
+ }
224
+
225
+ // A selector that depends on props: the hook rebuilds the atom only when `id` changes.
226
+ export function Title({ id }: { id: string }) {
227
+ const title = useLiveAtom(() => select.map('todos').child(id).text('title'), [id])
228
+ return <span>{title}</span>
229
+ }
230
+ ```
231
+
232
+ <!-- /snippet -->
233
+
234
+ ## Several docs
235
+
236
+ Every atom takes a last argument, `{ docAtom }`, naming the atom that holds its doc. Atoms without it read `docAtom`.
237
+
238
+ <!-- snippet: docs/snippets/several-docs.ts -->
239
+
240
+ ```ts
241
+ import { select, typedAtom } from 'duratom'
242
+ import { atom, createStore } from 'jotai'
243
+ import * as Y from 'yjs'
244
+ import { z } from 'zod'
245
+
246
+ // A second doc, beside the one in `docAtom`: settings kept apart from the shared board, say.
247
+ const settingsDocAtom = atom<Y.Doc | null>(null)
248
+
249
+ const Settings = z.object({ theme: z.enum(['light', 'dark']) })
250
+ const settingsAtom = typedAtom(
251
+ select.map('settings').child('user'),
252
+ Settings,
253
+ {},
254
+ {
255
+ docAtom: settingsDocAtom,
256
+ },
257
+ )
258
+
259
+ const store = createStore()
260
+ store.set(settingsDocAtom, new Y.Doc())
261
+ store.set(settingsAtom, { theme: 'dark' })
262
+ ```
263
+
264
+ <!-- /snippet -->
265
+
266
+ ## Without Jotai
267
+
268
+ `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.
269
+
270
+ <!-- snippet: docs/snippets/core.ts -->
271
+
272
+ ```ts
273
+ import { live, read, select, write } from 'duratom/core'
274
+ import * as Y from 'yjs'
275
+ import { z } from 'zod'
276
+
277
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
278
+ const doc = new Y.Doc()
279
+ const todo = doc.getMap('todos').set('first', new Y.Map())
280
+
281
+ // Validated writes and typed reads, on any Y.Map.
282
+ write(Todo, { title: 'text' }, todo, { title: 'Learn duratom', done: false })
283
+ const result = read(Todo, { title: 'text' }, todo) // { value: { title: 'Learn duratom', done: false } }
284
+
285
+ // A live value in the shape useSyncExternalStore takes, for any state library or none.
286
+ const done = live(doc, select.map('todos').child('first').get('done', false))
287
+ const stop = done.subscribe((value) => console.log('done is now', value))
288
+ write(Todo, { title: 'text' }, todo, { title: 'Learn duratom', done: true }) // logs: done is now true
289
+ stop()
290
+
291
+ export { result }
292
+ ```
293
+
294
+ <!-- /snippet -->
295
+
296
+ ## Docs
297
+
298
+ - [API reference](https://duratom.karolnov.dev/api): every export, generated from the TSDoc.
299
+ - Recipes: [sync between devices](docs/recipes/sync.md), [offline storage](docs/recipes/offline.md), [repair a broken node](docs/recipes/repair.md).
300
+ - 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.
301
+ - 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`.
302
+
303
+ Every code snippet in these docs is compiled against the source in CI, and so is every `@example` in the TSDoc.
304
+
305
+ ## License
306
+
307
+ MIT