# Sorus Documentation > Sorus — reactive state that’s hard to get wrong. Synchronous state for domain models, built so the usual state bugs cannot happen and the rest fail where you, or your agent, can see them. This file is generated mechanically from the Markdown source for the Sorus documentation. --- # Start URL: https://sorus.frondruntime.dev/docs/start Description: Read when starting with Sorus. Install it, make a realm, boxes, and a computed value for a chat's composer, write in an update, and show the value in React. ## Install Each package has the same name under every package manager. ```bash bun add @frondruntime/sorus # or npm install, pnpm add, yarn add ``` `@frondruntime/sorus-react` adds React hooks, with React 19 or later as a peer dependency. `@frondruntime/sorus-effect` adds Effect Schema, with `effect` 4.1 or a later 4.x as a peer dependency; `sorus` and `sorus-react` never import it, so an application without Effect never installs it. ```bash bun add @frondruntime/sorus @frondruntime/sorus-react bun add @frondruntime/sorus @frondruntime/sorus-effect effect ``` The rules for an agent install as skills, one per task: [Agent skills](./skills.md). ## Example The samples on these pages build one chat: rooms, messages that stream in over a socket, a composer, and a message that shows as pending until the server takes it. Its boxes hold the open room, the composer's fields, and the socket's state. ```ts import { Box } from "@frondruntime/sorus"; import { app } from "./realm.ts"; interface Composer { readonly text: string; readonly replyTo: string | null; } const $roomId = Box.make(app, "general", { name: "roomId" }); const $composer = Box.make(app, { text: "", replyTo: null }, { name: "composer" }); const $connection = Box.make<"connecting" | "open" | "closed">(app, "connecting", { name: "connection", }); ``` An update writes the boxes; the throw undoes the first write. ```ts import { Realm } from "@frondruntime/sorus"; import { app } from "./realm.ts"; const typeText = (text: string) => { Realm.update(app, (read, write) => { write($composer, { ...read($composer), text }); }); }; const openRoom = (roomId: string) => { Realm.update(app, (_read, write) => { write($composer, { text: "", replyTo: null }); // Throwing undoes the write above: the composer keeps its text. if (roomId === "") throw new Error("a room id is not blank"); write($roomId, roomId); }); }; ``` ## Rules - Name an observable with a leading `$`. Everything else is plain data, so a read of an observable is visible in the code. - Read and write through the place that hands them out: `read` and `write` are not methods of an observable, so a misplaced one throws where it is made. - Pass the realm to a call that makes something or opens an update, and the observable to a call about one: there is no default realm to fall back on. - Import from `@frondruntime/sorus` and `@frondruntime/sorus-react` for Effect-free code, and from `@frondruntime/sorus-effect`, which re-exports every call of `sorus`, where a schema checks writes. ## Answers | Call | Answers | | --- | --- | | `Realm.make()` | The realm that holds every observable it makes: [Realms](../state/realms.md). | | `Box.make(realm, initial)` | One value, written only in an update: [Boxes and computed](../state/boxes.md). | | `Computed.make(realm, (read) => ...)` | A cached value derived from what the function reads: [Boxes and computed](../state/boxes.md). | | `Realm.update(realm, (read, write) => ...)` | Runs the recipe atomically: [Updates](../state/updates.md). | | `useValue($x)` | The value of `$x`, rerendering when it changes: [Hooks](../react/hooks.md). | ## See also - [Why Sorus](./why.md): the principles, their costs, and the packages. - [Coming from MobX](./mobx.md): the Sorus call for each MobX one. - [Realms](../state/realms.md): where state lives and when it ends. - [Boxes and computed](../state/boxes.md): boxes, computed values, atoms, models. - [Schema-checked boxes](../effect/boxes.md): the same calls on Effect Schema. --- # Why Sorus URL: https://sorus.frondruntime.dev/docs/start/why Description: Read when deciding whether Sorus fits, or when one of its rules looks arbitrary. The claims behind its design, what each costs, when to pick it, and which package holds what. Sorus is glitch-free reactive state for code an agent writes and a person reviews, not for the fewest keystrokes. A read or a write in the wrong place fails with a type error or a named error instead of half-working, so the agent sees the mistake and fixes it. That takes more code than implicit tracking, and it takes speed. Sorus pays both on purpose. ## Reads are explicit With implicit tracking, `composer.text` looks the same whether or not the read is tracked, and forgetting it produces no error, only a value that stops updating. In Sorus an observable is not its value: it is a box, a computed value, an atom, or a collection, named with a leading `$`, with no read or write methods. Every place that reads hands its function a `read`, and `read($x)` returns the value and, where reads are tracked, subscribes that place. Without `read`, arithmetic, property access, and typed arguments fail to compile. ```ts import { Computed } from "@frondruntime/sorus"; import { app } from "./realm.ts"; import { $composer } from "./state.ts"; // Each read(...) returns the value and subscribes $hasText to that box. const $hasText = Computed.make(app, (read) => read($composer).text.trim() !== ""); // The same value without read does not compile. A box is not its value: // error TS2339, property 'text' does not exist on type 'Box'. const $broken = Computed.make(app, () => $composer.text.trim() !== ""); ``` A component's render body has no `read`, so React hooks are the only way in and there is no `observer` wrapper. The cost is code: every read is a call, a derived value is a `$` field built with `Computed.make` instead of a getter, and `read` is passed down. ## A write has one place A box changes only inside `Realm.update`, through the `write` it hands out; a box field has no setter, and a `write` kept past its update throws. An update is atomic: an error thrown from the recipe undoes every write before it, and watchers run once, after the update ends. ```ts import { Realm } from "@frondruntime/sorus"; import { app } from "./realm.ts"; const typeText = (text: string) => { Realm.update(app, (read, write) => { write($composer, { ...read($composer), text }); }); }; const openRoom = (roomId: string) => { Realm.update(app, (_read, write) => { write($composer, { text: "", replyTo: null }); // Throwing undoes the write above: the composer keeps its text. if (roomId === "") throw new Error("a room id is not blank"); write($roomId, roomId); }); }; ``` The cost is that familiar patterns are errors. An update in a computed value throws, so a derived value never writes, and a write after an `await` needs a new `Realm.update`. The [reactive-framework-test-suite](https://github.com/johnsoncodehk/reactive-framework-test-suite) case that expects a throwing batch to keep its writes fails by design. [Updates](../state/updates.md) has the rest. ## Misuse is loud A write outside `Realm.update`, a `read` outside a place, and an update inside a computed value throw and name where to write instead. Every error carries a literal `_tag` ([Errors](../guides/errors.md)). Detection has limits. TypeScript accepts any object in a condition and in a string conversion, so a forgotten `read` in `if ($done)` or a template literal compiles: the condition is always truthy, and the string is `[object Object]`. The other limits are in [Errors and debugging](../guides/errors.md). ## Glitch-free by construction A watcher never sees a half-applied update, and a derived value never computes from a stale source. A write marks its dependents, a read validates, and watchers run after the write settles. The cost is speed: every read is tracked and every schema box write is checked. The budget for 1.0, measured on Hermes, is the public layer within 2× of alien-signals and the graph core within 1.6× ([performance.md](https://github.com/frondruntime/sorus/blob/main/docs/performance.md)). ## Observation is a lifecycle A value is live while something observes it. `Source.onObserved` is the one hook for starting and stopping work: a socket opens with the first reader and closes with the last. The cost is that `Source.peek` and `Realm.untracked` start no socket. See [Lifecycles](../state/lifecycles.md). ## Hermes first A React Native app runs on Hermes, so a change counts when Hermes confirms it, and a Bun-only win is a hint. Live bytes after a full collection stay flat in the latest run for rows added and removed and a realm made and dropped per screen. A workload outside the measured scenarios is not covered. ## The synchronous counterpart to Effect Effect runs the programs; Sorus holds the state they read and write. Schema models are Effect Schema classes in `sorus-effect`: one class decodes wire data, checks every write to its fields, and `Program.*` ties watches and streams to a scope. State stays synchronous: a read returns a value, and an update finishes before it returns. The cost sits in `sorus-effect`. `Model.decode` provides the realm as a service, about 1.2 µs more per instance, and `Model.Schema` reads two internals of Effect's `Schema.Class` (`effect` 4.1.0) and throws if either is gone. ## Why not Effect's Atom `Atom` in `effect/reactivity` was the first base tried, and was set aside for what it does on a write, as of `effect` 4.1.0. - **An unbatched write shows a mixed state.** With `b` and `c` derived from `a` and `d` reading both, one write to `a` computes `d` twice, once from the new `b` and the old `c`. Sorus computes it once ([bench/diamond.ts](https://github.com/frondruntime/sorus/blob/main/packages/sorus/bench/diamond.ts)). - **A failed batch keeps its writes.** A Sorus update is undone. - **A write is not checked.** `Atom` uses Schema to store a value, not to check a write. `Atom` is the better choice for values that come from an Effect or a `Stream`, and both can live in one application. The cost is a second reactive layer, owned by this project and not by Effect's maintainers. ## When to pick it Sorus fits state an application models and derives: forms, lists loaded from a server, messages streamed into rows, and sorted, totaled views over them. A write to one row reruns only that row's readers, and a view moves that row's key instead of sorting every row. Per-frame work (a chart, a simulation) reads through `Realm.untracked` from its own loop and keeps per-entity state in plain arrays. What it costs, measured: - **Adding or removing rows in a large collection.** Each key copies the key order: about 120 µs at 10,000 rows on Hermes. In `apps/rn-bench` at 10,000 rows, 100 inserts took 14 ms against MobX's 2.7 (2026-11-16, before the 0.2 core, not re-measured). Many new rows go in through one `write.replaceAll`. - **The schema path.** 3.3 to 7.5× the plain path's time to build 10,000 rows, over seven runs. Data that needs no check goes in a plain `Box.make`. ## Maturity Sorus is before 1.0, so a release may change the API; a migration ships as a codemod. ## Packages | Package | For | | --- | --- | | `@frondruntime/sorus` | Boxes, computed values, atoms, collections, models, updates, watchers. No Effect. | | `@frondruntime/sorus-effect` | Every name of `sorus`, plus schema-checked boxes and models, decoding, and Effect programs. `effect` is a peer dependency. | | `@frondruntime/sorus-react` | `useValue`, `useValues`, `useSelect`, `useRealm`, `RealmProvider`. | | `@frondruntime/sorus-core` | The graph, with no runtime dependencies. | Install commands are on [Start](./index.md#install). ## The decision Where a guarantee and speed conflict, the guarantee wins and the budget says by how much. The rules ship with the package, in [AGENTS.md](https://github.com/frondruntime/sorus/blob/main/packages/sorus/AGENTS.md), and the [agent skills](./skills.md) carry them one task at a time. ## See also - [Start](./index.md): a realm, boxes, a computed value, and an update. - [Coming from MobX](./mobx.md): the Sorus call for each MobX one. - [Errors and debugging](../guides/errors.md): what throws, and `Source.inspect`. --- # Coming from MobX URL: https://sorus.frondruntime.dev/docs/start/mobx Description: Read when moving an app from MobX. The chat's composer as a MobX store and as a Sorus model, the Sorus call for each MobX one, and the habits that do not carry over. ## Example The chat's composer in MobX: an observable class, a getter, two actions, a reaction, and an `observer` component. ```tsx import { makeAutoObservable, reaction } from "mobx"; import { observer } from "mobx-react-lite"; class ChatStore { roomId = "general"; composer = { text: "", replyTo: null as string | null }; constructor() { makeAutoObservable(this); } get hasText() { return this.composer.text.trim() !== ""; } type(text: string) { this.composer.text = text; } openRoom(roomId: string) { this.roomId = roomId; this.composer = { text: "", replyTo: null }; } } const store = new ChatStore(); reaction( () => store.roomId, (roomId) => console.log(`opened ${roomId}`), ); const StoreSendButton = observer(function StoreSendButton() { return ( ); }); ``` In Sorus the same composer is the `Chat` model: the fields that change are boxes named with `$`, the getter is a computed value, and each action calls `Realm.update`. ```ts import { Box, Computed, Model, Realm } from "@frondruntime/sorus"; import type { Composer } from "./state.ts"; class Chat extends Model.Class { readonly $roomId = Box.make(this.realm, "general", { name: "roomId" }); readonly $composer = Box.make( this.realm, { text: "", replyTo: null }, { name: "composer", }, ); readonly $hasText = Computed.make(this.realm, (read) => read(this.$composer).text.trim() !== ""); type(text: string): void { Realm.update(this.realm, (_read, write) => { write.modify(this.$composer, (draft) => { draft.text = text; }); }); } openRoom(roomId: string): void { Realm.update(this.realm, (_read, write) => { write(this.$roomId, roomId); write(this.$composer, { text: "", replyTo: null }); }); } } ``` ## Rules - Read through `read` and write through `write`, never by property access or assignment: `store.hasText` becomes `read(chat.$hasText)` or `useValue(chat.$hasText)`, an assignment `write.modify(chat.$composer, ...)` in a `Realm.update`. A read is tracked only through a `read` it is handed. - A box holds plain data and belongs to one realm: there are no deep proxies (a keyed list is a [collection](../state/collections.md)) and no global state, so two realms share no batch, tracking, or watcher. - `Realm.watch` runs for changes only. Where MobX passes `fireImmediately: true`, pass `{ immediate: true }`. - `flow` has no counterpart: `await` outside, then one `Realm.update` per step, checking an `AbortController` before each write ([Live data](../guides/live-data.md)). ## Answers | MobX | Sorus | | --- | --- | | `observable.box` | `Box.make(realm, initial)` | | `makeAutoObservable`, `makeObservable`, `@observable` | `class X extends Model.Class` with `$` fields; with Effect, `Model.boxField(schema)` in a `Model.Schema` | | `observable` arrays and objects | a `Box.make` of plain data, written whole or through `write.modify` | | `ObservableMap` | `Collection.make(realm, { keyOf })`, or a box of an array written through `Collection.reconcile`; with Effect, a `Model.collectionField` | | `computed`, a getter | `Computed.make(realm, (read) => ...)` | | `computedFn` (mobx-utils) | `Computed.fn` | | `action`, `runInAction` | `Realm.update(realm, (read, write) => ...)` | | `flow` | an `async` function that awaits outside and opens one `Realm.update` per step | | `reaction(select, effect)` | `Realm.watch(realm, (read) => ..., effect)` | | `autorun` | `Realm.autorun(realm, (read) => ...)` | | `when`, a `reaction` with `delay` | a `Realm.watch`; with Effect, `Program.changes($x)` | | `untracked` | `Realm.untracked(realm, (read) => ...)` | | `onBecomeObserved`, `onBecomeUnobserved` | `Source.onObserved($x, start)` ([Lifecycles](../state/lifecycles.md)) | | `computed({ keepAlive: true })` | `Source.observe($x)`, released when done | | `createAtom` | `Atom.make(realm)` | | `fromPromise` (mobx-utils) | `Computed.fromPromise(realm, (signal) => fetch(url, { signal }), initial)` ([Async state](../guides/async-state.md)) | | `fromStream`, `fromResource` (mobx-utils) | `Program.fromStream` from `sorus-effect` | | `trace`, `getDependencyTree` | `Source.inspect($x)` | | `onReactionError` | `Realm.make({ onError })` | | `observer(Component)` | nothing: `useValue($x)` for each value the component shows | | `useLocalObservable` | `useState(() => Box.make(realm, ...))`, with the realm from `useRealm()` | | `toJS` | nothing: a box holds plain data | ## With Effect An application on Effect Schema writes the store as a `Model.Schema` with `Model.boxField` fields, so every write is checked: see [Classes](../effect/classes.md). ## See also - [Start](./index.md): a realm, boxes, and a computed value. - [Boxes and computed](../state/boxes.md): the `Chat` model and its fields. - [Updates](../state/updates.md): atomic updates, where `action` maps. - [Classes](../effect/classes.md): `Model.Schema`, `Model.boxField`, and `Model.decode`. - [Live data](../guides/live-data.md): a WebSocket feed and a fetch that refetches, with and without Effect, where MobX would use `flow`. --- # Realms URL: https://sorus.frondruntime.dev/docs/state/realms Description: Read when deciding where state lives and when it ends. Make a realm, keep each observable to the realm that made it, see where errors with no caller go, and dispose a realm. ## Example A realm holds the observables it makes, with their updates and watchers. The chat makes one, `app`, in module code. ```ts import { Realm } from "@frondruntime/sorus"; // The chat's realm, made once in module code. const app = Realm.make({ name: "app", // An error with no caller, such as a throw in a watch's effect, lands here. onError: (error) => console.error("chat:", error), }); ``` A screen disposes its realm when it closes. ```ts import { Box, Realm, Source } from "@frondruntime/sorus"; // A screen's realm, disposed when the screen closes. const screen = Realm.make({ name: "screen" }); const $unread = Box.make(screen, 3, { name: "unread" }); const closeScreen = () => { Realm.status(screen); // "open" Realm.dispose(screen); Realm.status(screen); // "disposed" Source.peek($unread); // 3: reads return the last values // Realm.update(screen, ...) now throws sorus/realm-disposed. Realm.dispose(screen); // a second call does nothing }; ``` ## Rules - There is no default realm: every call that makes an observable or opens an update takes the realm first, so a request or a test with its own realm shares no update, watcher, or error. - A realm's `read` and `write` take only what that realm made: another realm's observable throws `sorus/foreign-realm`. - `onError` receives the errors no caller can catch, from a watch's effect, an autorun, or a hook, because the write that caused them has landed. It defaults to the host's `reportError`. - Dispose a realm when its screen, request, or program ends, from an event handler or a teardown: inside an update or a watcher, `Realm.dispose` throws `sorus/dispose-not-at-rest`. ## Answers | Call | Answers | | --- | --- | | `Realm.make({ onError?, name? })` | A realm. `name` labels it in `Source.inspect` and in errors, and is never compared. | | `Realm.status(realm)` | `"open"`, `"disposing"` while `Realm.dispose` runs, or `"disposed"`. | | `Realm.dispose(realm)` | `void`; also `realm[Symbol.dispose]()`, and a second call does nothing. Ends every autorun, row listener, open stage, and hook; after it, reads give the last values and an update or a new observer throws `sorus/realm-disposed`. | ## With Effect `Realm.scoped(options?)` makes a realm and disposes it when its scope closes: see [Programs](../effect/programs.md). ## See also - [Start](../start/index.md): the app's realm, boxes, and a computed value. - [Reacting](./reacting.md): where reads are tracked, and `Realm.untracked`. - [Lifecycles](./lifecycles.md): what disposal ends, and a realm in React. - [Testing](../guides/testing.md): `testRealm`, one realm per test. - [Error messages](../reference/errors.md): every error named here. --- # Boxes and computed URL: https://sorus.frondruntime.dev/docs/state/boxes Description: Read when declaring state. Make a box, derive a cached computed value, make one per argument, stand for outside state with an atom, and read a value outside an update. ## Example A box is observable state, named with a `$` prefix. A computed value is derived from what its function reads and cached until a source it read changes. `$canSend` reads two boxes declared in [Start](../start/index.md). ```ts import { Computed } from "@frondruntime/sorus"; import { app } from "./realm.ts"; const $canSend = Computed.make( app, (read) => read($composer).text.trim() !== "" && read($connection) === "open", { name: "canSend" }, ); ``` `$scrollTop` replaces the comparison. `lastMessageIn(roomId)` is a computed value per room, read from a [collection](./collections.md)'s `rows`. ```ts import { Box, Computed, Source } from "@frondruntime/sorus"; import { $messages } from "./messages.ts"; import { app } from "./realm.ts"; import { $canSend, $roomId } from "./state.ts"; // A scroll within a pixel of the current position notifies nobody. const $scrollTop = Box.make(app, 0, { name: "scrollTop", equals: (previous, next) => Math.abs(previous - next) < 1, }); // One computed value per room id, shared while something observes it. const lastMessageIn = Computed.fn( app, (read, roomId: string) => read($messages.rows) .filter((message) => message.roomId === roomId) .at(-1), { name: "lastMessageIn" }, ); const $lastInRoom = Computed.make(app, (read) => read(lastMessageIn(read($roomId)))); // An event handler reads one value once, with nothing tracked. const logRoom = () => console.info("room", Source.peek($roomId)); Source.inspect($canSend).name; // "canSend" ``` ## Rules - A box holds plain data and is written whole. A change in place reaches no watcher, so finer grain is more boxes or a [collection](./collections.md). - A computed value only reads. A write, watch, autorun, `Source.observe`, or release inside it throws, as does its `equals`, because it must stay a function of its sources. - A computed value that throws keeps the error and throws it to each read until a source it read changes. - Observed (by a watch, an autorun, a mounted `useValue`, `Source.observe`, or another observed computed value), a computed value stays linked and a write marks it stale. Unobserved, it holds no links and a read checks its sources. - `Computed.fn` compares arguments by identity, one per position, and drops an entry nothing observes, so the next call makes a new one. ## Answers | Call | Answers | | --- | --- | | `Box.make(realm, initial, { name?, equals? })` | A box. A write equal to the current value notifies nobody. `equals` defaults to `Object.is`, so a new array counts as a change. | | `Computed.make(realm, (read) => ..., { name?, equals? })` | A computed value. | | `Computed.fn(realm, (read, ...args) => ..., options?)` | A function from arguments to a computed value, shared while observed. | | `Atom.make(realm)` | An atom, state kept outside Sorus. `read($atom)` returns `undefined` and subscribes. | | `write.changed($atom)` | Reruns what observed the atom, inside an update. An atom nothing observes counts as changed on every check. | | `class X extends Model.Class` | A model without a schema: `new X(realm)`, field initializers read `this.realm`, writes go through methods that call `Realm.update`. With Effect: [Classes](../effect/classes.md). | | `read($x)` | The value, and a subscription where reads are tracked ([Reacting](./reacting.md)). | | `Read` | The type of `read`: `(read: Read) => ...`. | | `Source.peek($x)` | The value, once, outside every place that reads, with nothing tracked. | | `{ name }` | Labels a value for tools: `Source.inspect` reports it, and a computed value's errors name it. | ## See also - [Updates](./updates.md): writing boxes. - [Collections](./collections.md): rows by key, tracked per row. - [Lifecycles](./lifecycles.md): what observing a value starts. - [Schema-checked boxes](../effect/boxes.md): a box that checks every write. --- # Updates URL: https://sorus.frondruntime.dev/docs/state/updates Description: Read when writing state. Write boxes and rows in one update, draft arrays and objects, await before an update, rely on an update being undone when it throws, and run effects after it ends. ## Example A box has one way in, `Realm.update`, which hands out `read` and `write`. Sending a message writes the message and clears the composer in one update, so no watcher sees one without the other. ```ts import { Realm } from "@frondruntime/sorus"; import { $messages } from "./messages.ts"; import { app } from "./realm.ts"; import { $composer, $roomId } from "./state.ts"; // One update writes the sent message and clears the composer: no watcher sees // one without the other. The id and the time are made by the caller. const send = (id: string, sentAt: number) => { Realm.update(app, (read, write) => { const { text } = read($composer); write.upsert( $messages, { id, roomId: read($roomId), author: "me", text, sentAt }, { at: "end" }, ); write($composer, { text: "", replyTo: null }); }); }; ``` An array or a plain object is changed through a draft from `write.modify`. ```ts import { Box, Realm } from "@frondruntime/sorus"; import { app } from "./realm.ts"; import { $composer } from "./state.ts"; const $typing = Box.make>(app, [], { name: "typing" }); const replyTo = (messageId: string) => { Realm.update(app, (_read, write) => { write.modify($composer, (draft) => { draft.replyTo = messageId; }); }); }; const startTyping = (author: string) => { Realm.update(app, (_read, write) => { write.modify($typing, (authors) => { authors.push(author); }); }); }; ``` ## Rules - Pass `read` and `write` down as arguments, never keep them: outside an update a kept `write` throws; a kept `read` acts as another place's own. - Change a value with `write` or `write.modify`, never in place: a value is not a proxy, so no watcher sees an in-place change. - A box's value is a tree: an assigned object is copied on its first write through a draft. Refer to one object by a key, row, or box: a write through one key is not seen at the other. - An update is synchronous: a recipe returning a promise throws. Await first, then update, from an event, a watch's effect, or an autorun. - Run an effect that cannot be taken back, such as a request, after the update: a throw undoes the writes, not what the recipe sent. ## Answers | Call | Answers | | --- | --- | | `Realm.update(realm, (read, write) => ..., { name? })` | Runs the recipe atomically: a throw restores every box it wrote, but not a `write.changed`. A nested call joins the outermost update, whose end runs watchers once; `name` names its record ([Changes](./changes.md)). | | `write($box, value)` | Replaces the value: a number, a string, a boolean, or a whole new array or object. | | `write.modify($box, (draft) => ...)` | Writes the drafted array or plain object back once. Any other value throws `sorus/modify-not-draftable`. | | `Write` | The type of `write`, for a function an update hands it to. | | `UpdateRecipe` | `(read, write) => undefined`: what `Realm.update` and `Stage.update` run. | ## See also - [Collections](./collections.md): `write.upsert`, `write.remove`, and `write.replaceAll`. - [Stages](./stages.md): writes held until asynchronous work succeeds. - [Reacting](./reacting.md): watchers that run after an update. - [Boxes and computed](./boxes.md): the boxes an update writes. - [Error messages](../reference/errors.md): draft errors and `sorus/update-in-derivation`. --- # Collections URL: https://sorus.frondruntime.dev/docs/state/collections Description: Read when state holds rows by key. Make a keyed collection, write and read rows, render one row per key, keep a value a row at a time, and choose between a collection and a box of an array. ## Example A collection holds rows by key, a box for each key a reader reads, and one box for the order of the keys, so a write to one row reruns the readers of that row, not the readers of the list. The chat's messages are a collection keyed by id. ```ts import { Collection } from "@frondruntime/sorus"; import { app } from "./realm.ts"; interface Message { readonly id: string; readonly roomId: string; readonly author: string; readonly text: string; readonly sentAt: number; } const $messages = Collection.make(app, { keyOf: (message: Message) => message.id, // A refetch builds new objects; a message with the same text is kept. equals: (previous, next) => previous.text === next.text, name: "messages", }); ``` A list component reads `keys` and hands each row its key, so a change to one message rerenders that row alone. `onRowChange` keeps a count a row at a time. ```tsx import { Box, Collection, Realm } from "@frondruntime/sorus"; import { useValue } from "@frondruntime/sorus-react"; import { memo } from "react"; import { $messages, type Message } from "./messages.ts"; import { app } from "./realm.ts"; // A message from the socket replaces the one under its id, or comes last. const receiveMessage = (message: Message) => { Realm.update(app, (_read, write) => { write.upsert($messages, message, { at: "end" }); }); }; // A refetch makes these the rows. A message that `equals` finds unchanged is // kept: what read its row does not rerun. const receiveHistory = (messages: ReadonlyArray) => { Realm.update(app, (_read, write) => { write.replaceAll($messages, messages); }); }; // Rerenders when a message is added, removed, or moved; never for a message's // own change. function MessageList() { const ids = useValue($messages.keys); return (
    {ids.map((id) => ( ))}
); } // Rerenders when the message under its id changes. const MessageRow = memo(function MessageRow({ id }: { readonly id: string }) { const message = useValue($messages.row(id)); return message === undefined ? null : (
  • {message.author}: {message.text}
  • ); }); // How many messages the user sent, kept a row at a time. It rolls back with // the write that changed the row, and first hears each row held, as added. const $sentByMe = Box.make(app, 0, { name: "sentByMe" }); const stopSentByMe = Collection.onRowChange($messages, (change, read, write) => { const mine = (message: Message | undefined) => (message?.author === "me" ? 1 : 0); const added = mine(change.after) - mine(change.before); if (added !== 0) write($sentByMe, read($sentByMe) + added); }); ``` ## Rules - Write a collection with `write.upsert`, `write.remove`, and `write.replaceAll`, inside an update. A failed update puts back the keys and every row. - A row is never `undefined`: `row(key)` and `read.row` return `undefined` for a missing key, so `write.upsert` and `write.replaceAll` reject it, schema collections included. - A held key's row is compared with `equals`, `Object.is` without one. A refetch builds new objects, so without `equals` it reruns the readers of every row. - A list reads `keys` and gives each row component `row(key)`; `rows` reruns its reader on any row or order change. - Where nothing tracks, read through `read.row($messages, key)`: `read($messages.row(key))` there makes a computed value and a box the collection keeps until the key is removed. - Adding or removing a key copies the key order, about 15 µs at 1,000 rows, so many new rows go in through one `write.replaceAll`, not an `upsert` each. - A list written or read a row at a time is a collection. A box of an array is written whole and every write reruns every reader; one written whole on each refetch goes through `Collection.reconcile` ([Collection fields](../effect/collections.md)). ## Answers | Call | Answers | | --- | --- | | `Collection.make(realm, { keyOf, equals?, name? })` | An empty collection. `name` labels `.keys` and `.rows` in `Source.inspect` and errors. | | `$messages.row(key)` | A computed value of that row, or `undefined`. | | `$messages.keys`, `$messages.rows` | Computed values of the keys, and of every row, in order. | | `read.row($messages, key)` | That row, or `undefined`; tracked in a tracked place, no box made elsewhere. | | `write.upsert($messages, row, { at? })` | Replaces the row under its key in place, or adds it first, or last with `{ at: "end" }`. | | `write.remove($messages, key)` | Removes the row under `key`; a missing key changes nothing. | | `write.replaceAll($messages, rows)` | Makes `rows` the rows, in order, keeping each unchanged one. A repeated key throws. | | `Collection.onRowChange($messages, (change, read, write) => ...)` | Calls the listener inside the update of each write that adds, replaces, or removes a row; `change` holds `key`, `before`, `after`. First reports every held row as added. Returns the function that removes it. | ## Indexes and sets A sorted order, the keys of each group, and a total per group are [views](./views.md). A set of keys is a collection keyed by the key itself, so `read.row` tracks one key and a change to another reruns nothing. A value per key that no view keeps is a collection a listener writes a row at a time; a plain `Map` it fills is not undone with a failed write, a `Map` of boxes is. ## With Effect A collection whose rows a schema checks is a `Model.collectionField`: see [Collection fields](../effect/collections.md). ## See also - [Updates](./updates.md): the update every write runs in. - [Views](./views.md): sorted orders, groups, and totals kept a row at a time. - [Hooks](../react/hooks.md): every way a component reads. - [Equality and hashing](../effect/equality.md): what `equals` counts as unchanged. --- # Views URL: https://sorus.frondruntime.dev/docs/state/views Description: Read when a list sorts or filters a collection, or a value follows a collection by group. Make a sorted, filtered order, the keys of each group, or a count and total per group, kept a row at a time. ## Example A view is kept up to date a row at a time: a write to one of 10,000 rows moves that row's key, and nothing sorts or sums the other 9,999. `View.ordered` keeps keys sorted and filtered, `View.grouped` the keys of each group, and `View.totals` a count and total per group. ```ts import { Box, Computed, View } from "@frondruntime/sorus"; import { $messages } from "./messages.ts"; import { app } from "./realm.ts"; import { $roomId } from "./state.ts"; const $newestFirst = Box.make(app, false, { name: "newestFirst" }); // The open room's messages, oldest first. A message written to the room moves // one key; nothing sorts the room again. const $timeline = View.ordered($messages, { // Reads $newestFirst: writing it sorts every message again. compare: (read) => { const sign = read($newestFirst) ? -1 : 1; return (left, right) => sign * (left.sentAt - right.sentAt); }, // Reads $roomId: opening another room filters the sorted messages again. filter: (read) => { const roomId = read($roomId); return (message) => message.roomId === roomId; }, name: "timeline", }); // The keys the scrolled list shows: ranks 40 to 60 of the open room. A write // that leaves those keys in place reruns nothing that reads them. const $visible = $timeline.range(40, 60); // "100 of 1,000 messages": the open room's messages of all the chat's const $shown = Computed.make( app, (read) => `${read($timeline.size)} of ${read($timeline.totalSize)} messages`, ); ``` `compare` and `filter` are factories whose reads are tracked, and `range` gives the keys at ranks for a list that scrolls. `View.totals` keeps the unread messages, with arithmetic the caller gives. ```ts import { Collection, View } from "@frondruntime/sorus"; import { app } from "./realm.ts"; // The messages not yet read: a message from someone else joins on arrival, and // leaves when its room is read. interface Unread { readonly id: string; readonly roomId: string; readonly mentionsMe: boolean; } const $unreadMessages = Collection.make(app, { keyOf: (unread: Unread) => unread.id, name: "unreadMessages", }); // Per room, the count of unread messages and, as the total, how many mention // the user. Whole numbers add and subtract exactly, so the total never drifts. const $unread = View.totals($unreadMessages, { project: (unread) => ({ group: unread.roomId, value: unread.mentionsMe ? 1 : 0 }), arithmetic: { zero: 0, add: (total, mentions) => total + mentions, subtract: (total, mentions) => total - mentions, }, name: "unread", }); // { count: 3, total: 1 }: three unread, one of them mentions the user const $unreadInSupport = $unread.group("support"); ``` ## Rules - Keep what `compare` and `filter` read to boxes that rarely change: a write to one `compare` reads sorts every row again, `O(n log n)`; one only `filter` reads filters again, `O(n)`; a row write is `O(log n)`. - The comparator and predicate `compare` and `filter` return, `groupOf`, and `project` read no observable, answer the same for a row every time, and see rows replaced, never mutated: a changed answer throws `sorus/view-out-of-step` or drifts a total silently. - `View.totals` needs exact arithmetic, because `add` and `subtract` must undo each other: floating-point amounts drift, so keep cents as integers or use bigints. - `View.grouped` copies a group's keys when one joins or leaves: a group of 10,000 keys copies 50 million keys while it fills. It fits many small groups, such as orders per customer. - Sort, group, and total by plain fields: a view sees rows replaced, never a write to a `Model.boxField` inside a row, so a sum over a box field is a `Computed.make`. ## Answers | Call | Answers | | --- | --- | | `View.ordered($items, { compare, filter?, name? })` | A view of `$items`'s keys sorted by `compare(read)`'s comparator, kept by `filter(read)`'s predicate, or every key when it returns `undefined`. | | `view.size`, `view.totalSize` | Computed values of the count of keys that pass the filter, and of every key. | | `view.keys` | A computed value of every key that passes the filter, in order; it reruns on any change to that order. | | `view.range(start, end)` | A computed value of the keys at ranks `start` up to, not including, `end`, clamped to `size`. | | `View.grouped($items, { groupOf, name? })` | A view of `$items`'s keys by `groupOf(row, key)`, or out of every group for `undefined`. | | `view.group(group)` | A computed value of the group's keys, in the order they joined; empty for a group with none. | | `view.groups` | A computed value of the groups that hold a key. | | `View.totals($items, { project, arithmetic, name? })` | A view of a count and total per group: `project(row, key)` gives `{ group, value }`, or `undefined` to leave the row out. `arithmetic` is `{ zero, add, subtract, equals? }`. | | `view.group(group)` | A computed value of `{ count, total }` for the group. | | `View.dispose(view)` | Stops the view where its owner ends; a second call does nothing, and a read through it throws `sorus/view-disposed`. | | `View.status(view)` | `"open"`, or `"disposed"` after `View.dispose` or `Realm.dispose`. | `name` names the view in errors and in `testRealm`, and its computed values for `Source.inspect`, such as `.size`. ## With Effect `View.orderedScoped`, `View.groupedScoped`, and `View.totalsScoped` from `sorus-effect` take the arguments of the plain calls and dispose the view when the scope closes. ## See also - [Collections](./collections.md): `Collection.onRowChange`, which every view listens with. - [Stages](./stages.md): reading a view over staged rows. - [Realms](./realms.md): `Realm.dispose`. - [Error messages](../reference/errors.md): the view errors. --- # Stages URL: https://sorus.frondruntime.dev/docs/state/stages Description: Read when asynchronous work writes only if it succeeds, or shows its writes before the server answers. Hold the writes in a stage, land them in one update or discard them, refuse a landing when what it read changed, and show an optimistic write that a failure takes off. ## Example A stage holds the writes of asynchronous work until it succeeds: `Stage.apply` lands them in one update, `Stage.drop` discards them. Until then no box changes, so nothing renders a half-done result and a failure leaves nothing to undo. ```ts import { Stage } from "@frondruntime/sorus"; import { $messages, type Message } from "./messages.ts"; import { app } from "./realm.ts"; import { $composer } from "./state.ts"; // The message lands once the server takes it; until then no box changes and // nothing reruns, so the composer still shows the text. A post that fails // leaves the composer and the messages as they were. const sendStaged = async (message: Message, post: Post) => { const stage = Stage.make(app, { name: "send" }); try { Stage.update(stage, (read, write) => { write.upsert($messages, message, { at: "end" }); // The recipe runs again at apply: text typed while the server took the // message is kept, and only the text that was sent is cleared. if (read($composer).text === message.text) write($composer, { text: "", replyTo: null }); }); await post(message); Stage.apply(stage); } finally { // Does nothing once applied: a throw anywhere above leaves nothing behind. Stage.drop(stage); } }; ``` A stage made with `{ visible: true }` shows its writes over the realm's confirmed values at once, until it applies or drops. An optimistic write is a visible stage, and a failure takes it off. ```ts import { Collection, Stage } from "@frondruntime/sorus"; import { $messages, type Message } from "./messages.ts"; import { app } from "./realm.ts"; // The ids of the messages the server has not taken yet. const $sending = Collection.make(app, { keyOf: (id: string) => id, name: "sending" }); // The message shows at once, marked as sending, over the realm's confirmed // values; the guess is the answer, so the stage applies on success. const sendShown = async (message: Message, post: Post) => { const guess = Stage.make(app, { name: "send (guess)", visible: true }); try { Stage.update(guess, (_read, write) => { write.upsert($messages, message, { at: "end" }); // Marks the message as sending for exactly as long as the guess shows. write.upsert($sending, message.id); }); await post(message); Stage.update(guess, (_read, write) => { write.remove($sending, message.id); }); Stage.apply(guess); } finally { // A failed post takes the message off the screen. Stage.drop(guess); } }; ``` ## Rules - Make an id, a time, or a model outside a recipe and close over it. A recipe runs at `Stage.update` and again at each `Stage.apply`, so a value made inside it lands differently than the one staged. - A recipe creates no observable and calls no stage call, `Realm.watch`, or `Realm.autorun`; each throws in every build. `Realm.update(otherRealm, ...)` is not guarded, runs on every replay, and its writes survive `Stage.drop`. - `{ conflicts: "fail" }` makes `Stage.apply` throw `StageConflictError` and drop the stage when a box or collection it read or wrote changed. By default it lands: adding 2 at 1 gives 7 after another update set 5. - A stage closes once, `"applied"` or `"dropped"`; `Stage.drop` after that does nothing, so a `finally` drops whether or not the work applied. Any other call on a closed stage throws `StageClosedError`. - A stage left open holds its overlay until applied, dropped, or its realm is disposed. A test realm's dispose reports it ([Testing](../guides/testing.md)). - A `Realm.update` recipe reads and writes confirmed values, not a guess: adding 1 to a shown 11 leaves 12 after the guess drops. Change a guessed value in a stage above it; Sorus does not check this. - When the server's answer wins over the guess, hold the answer in a hidden stage and apply it and drop the guess in one `Realm.update`, so a watcher runs once with the settled value. ## Answers | Call | Answers | | --- | --- | | `Stage.make(realm, { name?, conflicts?, visible? })` | A `Stage` over the realm, holding nothing. `conflicts: "fail"` makes `Stage.apply` refuse on a change. `visible: true` shows its writes until it applies or drops. | | `Stage.make(stage, { name? })` | A child stage: a savepoint that applies into its parent. A parent with an open child does not apply; dropping the parent drops the child. | | `Stage.update(stage, (read, write) => ...)` | Runs the recipe at once and keeps it. No box changes; over a visible stage, readers rerun on what is shown. A recipe that throws is not kept. | | `Stage.read(stage, (read) => ...)` | The function's result, reading the stage's writes, then the realm's current values. | | `Stage.realmRead(stage, (read) => ...)` | The function's result, reading the realm's confirmed values, ignoring every stage. | | `Stage.apply(stage)` | Replays the recipes, then lands the final state in one update, nested in an open one. A conflict or a replay throw drops the stage and reaches the caller. | | `Stage.drop(stage)` | Closes the stage and its open children, discarding their writes. | | `Stage.status(stage)` | `"open"`, `"applied"`, or `"dropped"`. | | `Stage.inspect(stage)` | Name, parent, status, conflict mode, what the stage wrote and read, `showing`, and `failure`. A visible stage that `Stage.apply` would refuse stops showing and keeps its error in `failure`. | | `StageClosedError` | Thrown by a call on a closed stage; carries `stage` and `status`. | | `StageConflictError` | Thrown by `Stage.apply` on a conflict; carries `stage` and `changed`, the names of what changed. | ## With Effect `Stage.scoped` applies a stage when an Effect section succeeds and drops it when the section fails, dies, or is interrupted; a conflict fails with `StageConflictError`. See [Programs](../effect/programs.md). ## See also - [Updates](./updates.md): `Realm.update`, which a stage lands in. - [Programs](../effect/programs.md): `Stage.scoped`. - [Testing](../guides/testing.md): a stage left open in a test realm. --- # Live data URL: https://sorus.frondruntime.dev/docs/guides/live-data Description: Read when state comes from a socket or a server. Open a socket while a value is observed and reconnect after a drop, write each event in one update, refetch without losing row identity, and keep an aborted request from writing. ## Example The chat's messages arrive over a WebSocket: a history when it opens, then one event per message sent or deleted. The socket is open while something observes the feed, and reconnects after a drop. ```ts import { Atom, Computed, Realm } from "@frondruntime/sorus"; import { $messages } from "./messages.ts"; import { app } from "./realm.ts"; import { $connection } from "./state.ts"; const chatUrl = "wss://example.com/chat"; // Stands for the socket: observing a value below that reads it opens it. const $socket = Atom.make(app); // The socket's state, read through the atom. const $status = Computed.make( app, (read) => { read($socket); return read($connection); }, { name: "status" }, ); // One room's messages, read through the atom. const messagesIn = Computed.fn( app, (read, roomId: string) => { read($socket); return read($messages.rows).filter((message) => message.roomId === roomId); }, { name: "messagesIn" }, ); const setConnection = (state: "connecting" | "open" | "closed") => { Realm.update(app, (_read, write) => write($connection, state)); }; const receive = (data: unknown) => { const event = parseEvent(data); if (event === undefined) { // The host's error sink, which a realm made without onError uses too. reportError(new TypeError("chat: dropped an event that is not one")); return; } // One update per event: a reader sees all of it or none of it. Realm.update(app, (_read, write) => { switch (event.type) { case "history": // A message equal to the one held keeps its row and notifies nobody. return write.replaceAll($messages, event.messages); case "message": return write.upsert($messages, event.message, { at: "end" }); case "deleted": return write.remove($messages, event.id); } }); }; ``` ```ts import { Source } from "@frondruntime/sorus"; // Opens the socket, and reopens it after each drop: 0.5 s after the first, // doubling up to 30 s, back to 0.5 s once an event arrives. Returns what // closes it. The state lives in this call, so a socket from an earlier // observation never schedules a reconnect. const connect = () => { let socket: WebSocket | undefined; let timer: ReturnType | undefined; let attempt = 0; const open = () => { setConnection("connecting"); const next = new WebSocket(chatUrl); next.onopen = () => { setConnection("open"); }; next.onmessage = (event: MessageEvent) => { attempt = 0; receive(event.data); }; next.onclose = () => { setConnection("closed"); timer = setTimeout(open, Math.min(30_000, 500 * 2 ** attempt)); attempt++; }; socket = next; }; open(); return () => { clearTimeout(timer); if (socket !== undefined) { socket.onclose = null; socket.close(); } // $canSend reads $connection without observing the feed: it must not // stay "open" once the socket is closed. setConnection("closed"); }; }; Source.onObserved($socket, connect); ``` A request without a socket takes the same shape: a newer request aborts the older one, and `Collection.reconcile` keeps unchanged members' objects. ```ts import { Box, Collection, Realm } from "@frondruntime/sorus"; import { app } from "./realm.ts"; type Load = | { readonly state: "loading" } | { readonly state: "loaded" } | { readonly state: "failed"; readonly error: unknown }; const membersUrl = "https://example.com/members"; interface Member { readonly id: string; readonly name: string; } const $members = Box.make>(app, [], { name: "members" }); const $membersLoad = Box.make(app, { state: "loading" }, { name: "membersLoad" }); const toMember = (value: unknown): Member => { if (isRecord(value)) { const { id, name } = value; if (typeof id === "string" && typeof name === "string") { return { id, name }; } } throw new TypeError("members: a row is not a member"); }; let controller: AbortController | undefined; // Loads a room's members. A newer call aborts this one, and an aborted call // writes nothing, so the last call wins. The members stay on screen while // the next ones load. const refreshMembers = async (roomId: string): Promise => { controller?.abort(); const current = new AbortController(); controller = current; Realm.update(app, (_read, write) => write($membersLoad, { state: "loading" })); try { const response = await fetch(`${membersUrl}/${encodeURIComponent(roomId)}`, { signal: current.signal, }); if (!response.ok) { throw new Error(`members: the server answered ${response.status}`); } const body: unknown = await response.json(); if (!Array.isArray(body)) { throw new TypeError("members: the body is not a list"); } const next = body.map(toMember); if (current.signal.aborted) { return; } Realm.update(app, (read, write) => { // Unchanged members keep their object; nothing changed keeps the array. write( $members, Collection.reconcile(read($members), next, { keyOf: (member) => member.id, equals: (previous, latest) => previous.name === latest.name, }), ); write($membersLoad, { state: "loaded" }); }); } catch (error) { // An aborted fetch rejects too; the newer call owns the status. if (current.signal.aborted) { return; } Realm.update(app, (_read, write) => write($membersLoad, { state: "failed", error })); } }; ``` ## Rules - Hang `Source.onObserved` on an atom that `$status` and `messagesIn` read, not on `$messages.keys`: `row(key)` never reads `keys`, so a hook there misses a reader of one row. - Write each event in one update, and a history through `write.replaceAll` on a collection with `equals`: a reader sees a history whole, and an unchanged row keeps its object, so a reconnect reruns no reader. - Write `"connecting"` in the hook and `"closed"` in the cleanup: `$canSend` reads the state without observing the feed, and would offer Send on a closed socket if `"open"` stayed. - Keep a connection's state inside the call that opens it, and detach `onclose` before closing, so a socket from an earlier observation schedules no reconnect. - Check `signal.aborted` before writing a result or a failure: an aborted `fetch` rejects, and its failure would overwrite the newer request's `"loading"`. ## With Effect `Program.fromStream` ([Programs](../effect/programs.md)) feeds a value from an Effect stream that owns the socket. ## See also - [Lifecycles](../state/lifecycles.md): `Source.onObserved`, atoms, `Source.observe`. - [Collections](../state/collections.md): `write.replaceAll`, `equals`, `Collection.reconcile`. - [Updates](../state/updates.md): an update is synchronous. - [Hooks](../react/hooks.md): `useValue` and a list that rerenders one row. --- # Async state URL: https://sorus.frondruntime.dev/docs/guides/async-state Description: Read when a value comes from a request. Load a promise into a value while it is observed, map its failure into the value, and keep the status and retry policy in the request library. ## Example Sorus ships no loading flag, refetch, cache, or Suspense hook; a request library, such as TanStack Query, owns those, and Sorus holds the answer. The chat's profile request is loaded into `$profile`, with a status union the application writes once. ```ts import { Computed } from "@frondruntime/sorus"; import { app } from "./realm.ts"; // The application's own status type: Sorus ships none. interface Profile { readonly id: string; readonly name: string; } type ProfileLoad = | { readonly state: "loading" } | { readonly state: "loaded"; readonly profile: Profile } | { readonly state: "failed"; readonly error: unknown }; // The request runs while something observes $profile, and its signal aborts // when the last observer leaves. The failure is mapped into the value, so // the screen shows it; a rejection left unmapped goes to the realm's onError. const $profile = Computed.fromPromise( app, (signal) => fetch(profileUrl, { signal }) .then((response) => { if (!response.ok) throw new Error(`profile: the server answered ${response.status}`); return response.json(); }) .then((body): ProfileLoad => ({ state: "loaded", profile: toProfile(body) })) // After the parse, so a body that is not a profile fails too. .catch((error: unknown): ProfileLoad => ({ state: "failed", error })), { state: "loading" }, { name: "profile" }, ); // The composer's placeholder, empty until the profile arrives. const $placeholder = Computed.make( app, (read) => { const load = read($profile); return load.state === "loaded" ? `Message as ${load.profile.name}` : ""; }, { name: "placeholder" }, ); ``` ## Rules - `load` starts the request and passes it `signal`, never returns a started promise: the last observer leaving aborts it, and each new observation requests again. - Map a failure the screen shows into the value, inside `load`. A rejection left unmapped goes to the realm's `onError`, and the value keeps what it held. - Hold a value that must keep its answer across screens with `Source.observe` ([Lifecycles](../state/lifecycles.md)). Unobserved, it resets to `initial`, and the next observer requests again. - Keep the status, retry, and refetch policy in the request library or in plain code. Sorus holds the answer; the library decides when to ask. ## Answers | Call | Answers | | --- | --- | | `Computed.fromPromise(realm, load, initial, { equals?, name? })` | A read-only computed value. `load(signal)` runs from the first observer and is aborted by the last; the value is `initial` until it resolves and again once unobserved. | ## With Effect `Program.fromEffect` answers the same kind of value over an Effect, interrupted when the last observer leaves: see [Programs](../effect/programs.md). ## See also - [Lifecycles](../state/lifecycles.md): `Source.observe` and `Source.onObserved`. - [Live data](./live-data.md): a request whose answer replaces rows. - [Saving state](./saving.md): a result that must be saved or restored. - [Programs](../effect/programs.md): `Program.fromEffect`. --- # Lifecycles URL: https://sorus.frondruntime.dev/docs/state/lifecycles Description: Read when state comes from outside Sorus. Start a listener when a value gains its first observer and stop it after the last, stand for outside state with an atom, hold a value observed, and dispose a realm to end everything it runs. ## Example `Source.onObserved` runs a hook on an observable's first observer and its cleanup after the last. The chat's socket opens on the first observer of `$socket` and closes after the last ([Live data](../guides/live-data.md)). ```ts import { Source } from "@frondruntime/sorus"; // Opens the socket, and reopens it after each drop: 0.5 s after the first, // doubling up to 30 s, back to 0.5 s once an event arrives. Returns what // closes it. The state lives in this call, so a socket from an earlier // observation never schedules a reconnect. const connect = () => { let socket: WebSocket | undefined; let timer: ReturnType | undefined; let attempt = 0; const open = () => { setConnection("connecting"); const next = new WebSocket(chatUrl); next.onopen = () => { setConnection("open"); }; next.onmessage = (event: MessageEvent) => { attempt = 0; receive(event.data); }; next.onclose = () => { setConnection("closed"); timer = setTimeout(open, Math.min(30_000, 500 * 2 ** attempt)); attempt++; }; socket = next; }; open(); return () => { clearTimeout(timer); if (socket !== undefined) { socket.onclose = null; socket.close(); } // $canSend reads $connection without observing the feed: it must not // stay "open" once the socket is closed. setConnection("closed"); }; }; Source.onObserved($socket, connect); ``` `Source.observe` holds a value observed with nothing rendered. ```ts import { Source } from "@frondruntime/sorus"; // Keeps the profile across rooms, as a store that loads once in its // constructor does: until the release runs, $profile stays observed and // keeps its answer. const holdProfile = () => Source.observe($profile); ``` ## Rules - An observer holds what it read until its stop function, release, unmount, or scope ends. `Realm.untracked` and an update read without observing, so they start no hook. - A hook starts once the call that observed has linked, and syncs outside state there: nothing reports changes made while unobserved. - `Realm.dispose` runs each begun hook's cleanup once, even while the value is observed, and no later observer starts a hook. - Make a realm a component owns in the effect that disposes it: React may discard a render without cleanup. Under StrictMode the first realm is disposed and the second kept. ## Answers | Call | Answers | | --- | --- | | `Source.onObserved($x, () => cleanup)` | The function that removes the hook. The hook returns the cleanup. | | `Source.observe($x)` | A release. Until it runs, `$x`'s hooks stay started and a computed value stays cached. | ## With Effect `Source.observeScoped` releases when its scope closes: see [Programs](../effect/programs.md). ## See also - [Realms](./realms.md): `Realm.dispose` and what a disposed realm answers. - [Reacting](./reacting.md): watches and autoruns. - [Boxes and computed](./boxes.md): atoms and `write.changed`. - [Async state](../guides/async-state.md): `Computed.fromPromise`. --- # Reacting URL: https://sorus.frondruntime.dev/docs/state/reacting Description: Read when code outside React runs because a value changed. Watch a selection, run an autorun with a cleanup, and write from an autorun without a loop. ## Example `Realm.watch` runs its effect when the select's result changes, not on the first run. The chat scrolls to the room's last message when another one becomes last. ```ts import { Realm } from "@frondruntime/sorus"; import { $lastInRoom } from "./boxes.ts"; import { app } from "./realm.ts"; // Scrolls to the room's last message when another one becomes last, not on // the first run. const stopScroll = Realm.watch( app, (read) => read($lastInRoom)?.id, (id, previous) => { if (id !== undefined && previous !== undefined) { document.getElementById(id)?.scrollIntoView(); } }, ); ``` `Realm.autorun` runs at once, and again when what its last run read changes. The function it returns is its cleanup, run before the next run and at the stop: the Escape listener exists only while the composer holds a reply. ```ts import { Computed, Realm } from "@frondruntime/sorus"; import { app } from "./realm.ts"; import { $composer } from "./state.ts"; // Escape cancels a reply while the composer holds one. The autorun reads // whether there is a reply, not the composer: typing does not rerun it. const $replying = Computed.make(app, (read) => read($composer).replyTo !== null, { name: "replying", }); const stopEscape = Realm.autorun(app, (read) => { if (!read($replying)) return undefined; const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") { Realm.update(app, (read, write) => write($composer, { ...read($composer), replyTo: null })); } }; window.addEventListener("keydown", onKey); // Runs before the next run, and when the autorun stops. return () => window.removeEventListener("keydown", onKey); }); ``` ## Rules - Reads are tracked in a computed value, a computed function, a watch's select, an autorun, and `useSelect`. An update, `Realm.untracked`, a watch's effect, and a hook read without tracking and subscribe nothing. - Derive with a computed value, not an autorun that writes a box: the box is a second copy, and the autorun runs on every change whether or not anything reads it. - Write from an autorun or an effect through `Realm.update`, which runs untracked. An autorun that writes what it read reruns until it settles; after 100 rounds `sorus/watchers-unsettled` goes to `onError`. - An error from the first run is thrown to the caller and nothing is watched; a later one goes to `onError`. An async effect is a type error, because its rejection would reach no one. - A `scheduler` defers every run after the first until it calls the `run` it is handed, so writes between calls join one run. Sorus ships none; the host's frame or a timer serves. ## Answers | Call | Answers | | --- | --- | | `Realm.watch(realm, (read) => ..., (value, previous) => ..., { name?, equals?, scheduler?, immediate? })` | The stop function; a second stop does nothing. `equals` decides what counts as a change; `Object.is` by default. `immediate: true` also runs the effect at the call with `previous` `undefined`, ignoring `equals`, and throws `sorus/watch-immediate-in-update` inside an update. | | `Realm.autorun(realm, (read) => ..., { scheduler? })` | The stop function; a second stop does nothing. | | `Scheduler` | The type `(run: () => void) => void`. | | `Realm.isTracking(realm)` | `true` where reads are tracked, `false` elsewhere. | | `Realm.untracked(realm, (read) => ...)` | What the function returns. Its reads subscribe nothing. | ## With Effect `Program.watchScoped` is a watch whose effect is an Effect program: the watch stops when the caller's scope closes, and a change interrupts the effect still running for the one before it. `Program.changes` is a stream of the current value, then each change. Both are on [Programs](../effect/programs.md). ## See also - [Updates](./updates.md): writing from an effect. - [Lifecycles](./lifecycles.md): what a watch or an autorun holds observed. - [Programs](../effect/programs.md): `Program.watchScoped` and `Program.changes` as Effect programs. - [Hooks](../react/hooks.md): reading in React. - [Live data](../guides/live-data.md): a watch that refetches when its input changes. --- # Change stream URL: https://sorus.frondruntime.dev/docs/state/changes Description: Read when tools need every write as data. Listen to each landed update's record with Realm.onUpdate, and build undo and replay with write.revert and write.replay. ## Example `Realm.onUpdate` hands a listener one record per landed update: each box, collection, and atom the update changed, with values before and after. The chat's activity log reads the rows of `$messages` each record holds. ```ts import { Realm } from "@frondruntime/sorus"; import { $messages, type Message } from "./messages.ts"; import { app } from "./realm.ts"; // One record per landed update, after its watchers ran: each row of // $messages it changed, with the row before and after. const activity: Array = []; const stopActivity = Realm.onUpdate(app, (record) => { for (const change of record.collections) { if (change.collection !== $messages) continue; for (const row of change.rows) { const what = row.before === undefined ? "added" : row.after === undefined ? "removed" : "edited"; activity.push(`${record.name ?? "update"}: ${what} ${String(row.key)}`); } } }); // A record is net: the row is added and edited in one update, so the record // holds one entry, from absent to the edited row. const receiveCorrected = (message: Message, text: string) => { Realm.update( app, (_read, write) => { write.upsert($messages, message, { at: "end" }); write.upsert($messages, { ...message, text }); }, { name: "receive" }, ); }; ``` The composer's undo reverts the last named edit with `write.revert`, and its redo replays it. ```ts import { isSorusError, Realm, type UpdateRecord } from "@frondruntime/sorus"; import { app } from "./realm.ts"; import { $composer } from "./state.ts"; // Typing is named, so the undo stack takes only typing. The records of an // undo and a redo are named "undo" and "redo", and never join it. const typed: Array = []; const undone: Array = []; const stopTyping = Realm.onUpdate(app, (record) => { if (record.name === "type") { typed.push(record); // A new edit ends what could be redone. undone.length = 0; } }); const type = (text: string) => { Realm.update(app, (read, write) => write($composer, { ...read($composer), text }), { name: "type", }); }; // A record applies only to the state it left: once a send has cleared the // composer, the last edit no longer holds, and the revert throws before it // writes anything. const restore = (record: UpdateRecord, direction: "revert" | "replay") => { try { Realm.update(app, (_read, write) => write[direction](record), { name: direction === "revert" ? "undo" : "redo", }); return true; } catch (error) { if (isSorusError(error, "SorusUsageError") && error.code === "sorus/record-not-applicable") { typed.length = 0; undone.length = 0; return false; } throw error; } }; const undoTyping = () => { const record = typed.pop(); if (record === undefined || !restore(record, "revert")) return false; undone.push(record); return true; }; // Replays the edit undone last: the composer holds its `before` again. const redoTyping = () => { const record = undone.pop(); if (record === undefined || !restore(record, "replay")) return false; typed.push(record); return true; }; ``` ## Rules - A record is net, one per outermost update: a box written three times is one entry, a nested update joins its outer record, and an update that throws or changes nothing makes none. Undo and persistence need the net change. - A record holds confirmed values only. A visible stage makes none until `Stage.apply` lands it, and the record's `stages` names the stage. - A listener runs after the update's watchers, outside any update. A listener that updates on every record loops; a listener's error goes to `onError`. - `write.revert` and `write.replay` take only a record `Realm.onUpdate` handed out, and only while the state is as the record left it; anything else throws `sorus/record-not-applicable` before a write. Revert newest first, replay oldest first. - A record names boxes and collections by identity, so it lives for one session; a consumer that persists maps them to paths itself. A view and a collection's own boxes are in no record. ## Answers | Call | Answers | | --- | --- | | `Realm.onUpdate(realm, (record) => ...)` | Adds a listener and returns its stop, which does nothing the second time. Throws in a computed value, a watch's select, a stage recipe, and once the realm is disposing. | | `UpdateRecord` | `{ name, stages, boxes, collections, atoms }`. `collections` holds each collection's `rows` (`key`, `before`, `after`) and, when it moved, `keys`. | | `write.revert(record)` | Writes each `before` back, as a write inside `Realm.update` or a stage recipe. A throw puts back every write it made. | | `write.replay(record)` | The same, writing each `after`. | ## See also - [Updates](./updates.md): `Realm.update`, its `name`, and nested updates. - [Stages](./stages.md): what a visible stage shows before it lands. - [Collections](./collections.md): `Collection.onRowChange`, the row change. - [Programs](../effect/programs.md): `Program.updates`, the stream of records. - [Error messages](../reference/errors.md#change-stream): what a restore throws. --- # Snapshots URL: https://sorus.frondruntime.dev/docs/state/snapshots Description: Read when state goes out as plain data and comes back. Declare a shape of boxes and collections, read it with read.snapshot, and write it back with write.restore. ## Example A snapshot is the state of a declared shape as plain data. The chat saves its settings, its rooms, and its `Chat` model's open room and composer, and restores them. The shape's keys are the snapshot's keys; the hovered room is not in the shape, so it stays out. No call snapshots a whole realm, which lists no boxes. ```ts import { Box, Collection, Realm, type Snapshot } from "@frondruntime/sorus"; import { Chat } from "./model.ts"; import { app } from "./realm.ts"; interface Settings { readonly notifications: boolean; readonly theme: "light" | "dark"; } interface Room { readonly id: string; readonly name: string; } const $settings = Box.make( app, { notifications: true, theme: "light" }, { name: "settings" }, ); const $rooms = Collection.make(app, { keyOf: (room: Room) => room.id, equals: (previous, next) => previous.name === next.name, name: "rooms", }); // Shown on screen, never saved: it is not in the shape. const $hoveredRoom = Box.make(app, undefined, { name: "hoveredRoom" }); const chat = new Chat(app); // The keys are the snapshot's keys: renaming a box leaves saved data as it was. // A Model.Class instance declares no fields, so its boxes go in by name. const shape = { settings: $settings, rooms: $rooms, chat: { roomId: chat.$roomId, composer: chat.$composer }, }; const saved: Snapshot = Realm.untracked(app, (read) => read.snapshot(shape)); // { // settings: { notifications: true, theme: "light" }, // rooms: [], // chat: { roomId: "general", composer: { text: "", replyTo: null } }, // } const restore = (data: Snapshot): void => { Realm.update(app, (_read, write) => { // Every box and row lands, or none: a throw puts the restore back. write.restore(shape, data); }); }; ``` ## Rules - A shape holds boxes, collections, `Model.Schema` instances, and plain objects and arrays of them. A computed value, atom, `Model.Class` instance, or plain value throws `sorus/snapshot-not-state`; a restore writes the boxes a computed value reads, so the shape holds those. - A snapshot reads as `read` does where it runs. In a computed value it tracks every box and collection in the shape, so the value recomputes on a write under the shape and on no other. - The data matches the shape exactly: a missing or added key, or an array of another length, throws `sorus/restore-shape`. A partial restore is a restore of a smaller shape. - A collection takes the data's rows by key: a key the data lacks is removed, and `equals` decides whether a held row is kept. Plain data for a model row the collection lacks throws `sorus/restore-cannot-make-row`. - A restore writes boxes and rows, and runs no model method. What must happen on a change, such as closing a room's socket, belongs in a `Realm.watch`. ## Answers | Call | Answers | | --- | --- | | `read.snapshot(shape)` | The shape as plain data: each box's value, each collection's rows in key order, each `Model.Schema` instance's data under its wire keys. | | `write.restore(shape, data)` | Writes `data` across `shape` inside the update; returns `undefined`. | | `Snapshot` | The type `read.snapshot(shape)` returns. | | `RestoreData` | The type `write.restore` takes: a snapshot, where a `Model.Schema` instance may stand in for its data. | ## With Effect `Model.restore` decodes an input and restores it into a held `Model.Schema` instance in place: see [Classes](../effect/classes.md). ## See also - [Updates](./updates.md): the update a restore lands with. - [Stages](./stages.md): `Stage.read` snapshots a stage's state. - [Classes](../effect/classes.md): `Model.Schema`, `Model.restore`, and the wire form. - [Saving state](../guides/saving.md): saving a computed projection of what to keep. - [Error messages](../reference/errors.md#snapshots): every message a snapshot and a restore throw. --- # Saving state URL: https://sorus.frondruntime.dev/docs/guides/saving Description: Read when state outlives a reload. Save a computed projection of what to keep, restore before the watch starts, write one save per burst, and save state a visible stage shows from the records of Realm.onUpdate. ## Example The chat keeps `$settings` ([Snapshots](../state/snapshots.md)) in `localStorage` across reloads. The storage is passed in, so a test hands the saver one that keeps saves in memory or refuses them. Disposing the saver stops its watch and writes a save still queued. ```ts import { Box, Computed, Model, Realm } from "@frondruntime/sorus"; import type { Settings } from "./snapshots.ts"; interface TextStorage { readonly load: () => string | undefined; // Throws when the storage refuses the write, as a full localStorage does. readonly save: (text: string) => void; } const browserStorage: TextStorage = { load: () => localStorage.getItem("chat-settings") ?? undefined, save: (text) => localStorage.setItem("chat-settings", text), }; class SettingsSaver extends Model.Class implements Disposable { readonly $storageError = Box.make(this.realm, undefined, { name: "storageError", }); // The text to save, and nothing else: it reads $settings alone, so a write // to the open room or the hovered room leaves it, and the watch below, // untouched. private readonly $saved: Computed; private readonly $settings: Box; private readonly storage: TextStorage; private readonly stopSaving: () => void; private queued = false; private lastSaved: string; constructor(realm: Realm, $settings: Box, storage: TextStorage) { super(realm); this.$settings = $settings; this.storage = storage; this.$saved = Computed.make(realm, (read) => JSON.stringify(read($settings))); // Restored before the watch starts, so restoring saves nothing back. this.restore(); this.lastSaved = Realm.untracked(realm, (read) => read(this.$saved)); this.stopSaving = Realm.watch( realm, (read) => read(this.$saved), () => { this.queue(); }, ); } private restore() { const text = this.storage.load(); if (text === undefined) return; let saved: { readonly notifications?: unknown; readonly theme?: unknown } | null; try { saved = JSON.parse(text); } catch { return; // a damaged save starts from the defaults } // Each field is taken only when it is valid, so one bad field keeps the rest. Realm.update(this.realm, (read, write) => { const settings = read(this.$settings); write(this.$settings, { notifications: typeof saved?.notifications === "boolean" ? saved.notifications : settings.notifications, theme: saved?.theme === "light" || saved?.theme === "dark" ? saved.theme : settings.theme, }); }); } // A burst of updates in one task queues one save, which reads the end state. private queue() { if (this.queued) return; this.queued = true; queueMicrotask(() => this.flush()); } flush() { if (!this.queued) return; this.queued = false; const text = Realm.untracked(this.realm, (read) => read(this.$saved)); if (text === this.lastSaved) { // The burst ended where it began: the storage already holds this text. Realm.update(this.realm, (_read, write) => write(this.$storageError, undefined)); return; } try { this.storage.save(text); this.lastSaved = text; Realm.update(this.realm, (_read, write) => write(this.$storageError, undefined)); } catch (error) { // Kept as state for the screen to show; the next change tries again. const message = error instanceof Error ? error.message : String(error); Realm.update(this.realm, (_read, write) => write(this.$storageError, message)); } } [Symbol.dispose]() { this.stopSaving(); this.flush(); // a save still queued is written now, not lost } } ``` `$saved` reads `$settings` alone, so a write to the hovered room neither recomputes it nor runs the watch. ## Rules - Save a `Computed.make` that builds the stored text, not the boxes one by one: the watch runs only when it changes. - Restore before starting the watch, taking each field only when valid and keeping the default for the rest; otherwise the restore queues a save of what it loaded. Set the last saved text from it. - Queue the save with `queueMicrotask`, read the text when it runs, and skip it when it equals the last text written. A watch runs once per outermost update, so a burst saves once; one ending where it began saves nothing. - Catch a storage error in `flush` and write it to a box: a microtask has no caller to receive a throw. The last saved text stays, so the next change saves again. - Save state a visible stage writes from the records of `Realm.onUpdate`, never from a watch: a tracked read returns the shown guess, a record the confirmed value. Run the storage write after the update, not in its recipe ([Updates](../state/updates.md)). ## With Effect `readSaved` decodes stored text through a schema, and each field recovers from a refusal with `Schema.catchDecoding`, so one bad field keeps its default and the others restore. `$settings` stays a plain box: only the restore needs the check. ```ts import { Realm } from "@frondruntime/sorus-effect"; import { Effect, Option, Schema } from "effect"; import { app } from "./realm.ts"; import { $settings } from "./snapshots.ts"; // A field the schema refuses decodes to no field at all, so it keeps its // default and the other fields still restore. const SavedSettings = Schema.fromJsonString( Schema.Struct({ theme: Schema.optionalKey( Schema.Literals(["light", "dark"]).pipe(Schema.catchDecoding(() => Effect.succeedNone)), ), notifications: Schema.optionalKey( Schema.Boolean.pipe(Schema.catchDecoding(() => Effect.succeedNone)), ), }), ); // Text that does not parse decodes to no fields, so the settings keep their defaults. const readSaved = (text: string): typeof SavedSettings.Type => Schema.decodeUnknownOption(SavedSettings)(text).pipe(Option.getOrElse(() => ({}))); // Each field the save holds, over the current settings, in one update. const restoreSaved = (text: string): void => { Realm.update(app, (read, write) => { write($settings, { ...read($settings), ...readSaved(text) }); }); }; ``` ## See also - [Snapshots](../state/snapshots.md): `$settings`, and a shape read as plain data. - [Stages](../state/stages.md): a visible stage, shown and confirmed values. - [Change stream](../state/changes.md): `Realm.onUpdate` and its records. - [Reacting](../state/reacting.md): `Realm.watch` and `Realm.untracked`. - [Testing](./testing.md): `testRealm`, and the dispose that checks for a running watch. --- # Hooks URL: https://sorus.frondruntime.dev/docs/react/hooks Description: Read when showing the chat in React. Pick a hook, rerender less under memo, read in an event handler, keep a component's own state in a box, and defer a slow render after a write. ## Example The send button reads `$canSend` with `useValue`. Under `memo`, it rerenders only when that value changes. `ChatRoot` gives the components under it the chat's realm. ```tsx import { RealmProvider, useValue } from "@frondruntime/sorus-react"; import { memo, type ReactNode } from "react"; import { app } from "./realm.ts"; import { $canSend } from "./state.ts"; // Under memo, it rerenders when $canSend changes, not with the form around it. const SendButton = memo(function SendButton() { const canSend = useValue($canSend); return ( ); }); function ChatRoot({ children }: { readonly children: ReactNode }) { // useValue needs no provider; useRealm and useSelect below it do. return {children}; } ``` `useSelect` runs view logic over observables: the mark beside a message rerenders when that message becomes, or stops being, the one replied to, and not on a keystroke. ```tsx import { useSelect } from "@frondruntime/sorus-react"; import { $composer } from "./state.ts"; // Rerenders when this message becomes, or stops being, the one replied to. function ReplyMark({ id }: { readonly id: string }) { const replying = useSelect((read) => read($composer).replyTo === id); return replying ? ↩ : null; } ``` ## Rules - There is no `observer` wrapper: the hooks read through React's `useSyncExternalStore`, so they work with the React Compiler as they are. - To rerender less, read in a small component under `memo`, and pass it values that are the same on every render: an observable, a key, or data made once. An array, object, or function built in the render defeats `memo`. - In an event handler, read inside `Realm.untracked` and write through a function that calls `Realm.update`, such as `send`. - A component's own state is a box made once in the provider's realm: `const realm = useRealm()`, then `useState(() => Box.make(realm, ...))`. - A slow render after a write reads `useDeferredValue(useValue($x))`. A `startTransition` around the write changes nothing: React renders a change of an outside store as a blocking update. ## Answers | Call | Answers | | --- | --- | | `useValue($x)` | The value of `$x`. Needs no provider. | | `useValues([$a, $b])` | The values as a typed array, which keeps its identity until one changes. Needs no provider; observables of two realms throw. | | `useSelect((read) => ...)` | The function's result, rerendering when it changes under `Object.is`. Throws without a provider. An inline arrow runs it and a layout effect on every render; `useValue` of a computed value does neither. | | `` | Gives the components under it a realm. | | `useRealm()` | The nearest provider's realm. Throws without a provider. | ## With Effect A model from `sorus-effect` is read with the same hooks ([Classes](../effect/classes.md)). ## See also - [Start](../start/index.md): the chat's composer from box to button. - [Collections](../state/collections.md): a list that rerenders one row. - [Lifecycles](../state/lifecycles.md): what an observer holds, and a realm in a React effect. - [Classes](../effect/classes.md): the models a component reads on Effect. - [Testing](../guides/testing.md): a realm per test. --- # Schema-checked boxes URL: https://sorus.frondruntime.dev/docs/effect/boxes Description: Read when an app already uses Effect and needs a box or collection that checks an Effect Schema on every write. ## Example `Box.schema`, from `@frondruntime/sorus-effect`, makes a box that checks an Effect Schema on every write. The composer's text holds at most 2,000 characters. ```ts import { Box } from "@frondruntime/sorus-effect"; import { Schema } from "effect"; import { app } from "./realm.ts"; const Composer = Schema.Struct({ text: Schema.String.check(Schema.isMaxLength(2000)), replyTo: Schema.NullOr(Schema.String), }); const $composer = Box.schema(app, Composer, { text: "", replyTo: null }, { name: "composer" }); const $mentions = Box.schema(app, Schema.Array(Schema.String), [], { name: "mentions" }); ``` `Collection.schema` checks each row as it lands, after `Model.decode` has checked the wire data. ```ts import { Collection, Model, Realm } from "@frondruntime/sorus-effect"; import { Schema } from "effect"; import { app } from "./realm.ts"; const MessageData = Schema.Struct({ id: Schema.String, roomId: Schema.String, author: Schema.String, text: Schema.String.check(Schema.isMaxLength(2000)), sentAt: Schema.Number, }); // Each row is checked as it lands: an upsert of a message over 2,000 // characters throws and undoes its update. const $messages = Collection.schema(app, MessageData, { keyOf: (message) => message.id, name: "messages", }); const receive = (json: unknown) => { // decode checks the wire data; upsert checks the row again as it lands. const message = Model.decode(app, MessageData)(json); Realm.update(app, (_read, write) => { write.upsert($messages, message, { at: "end" }); }); }; ``` ## Rules - A write or an `initial` the schema rejects throws `ValueRejectedError` and undoes the update, so no box holds a rejected value. No option turns the check off; a plain `Box.make` checks nothing. - A schema box compares as [Equality and hashing](./equality.md) lists, so an equal array or object notifies nobody. - A box of a plain `Schema.Array(element)` checks only the elements a write put there; any other box checks its whole value on every write. A list written one row at a time is a [collection field](./collections.md). - A check runs when a value is written, never on a read or a recompute, so it holds only what the value decides: terms that must agree are one schema value with one check. ## Answers | Call | Answers | | --- | --- | | `Box.schema(realm, schema, initial, { name?, equals? })` | A box of the values `schema` accepts. Throws `ValueRejectedError` when `initial` does not fit. | | `Collection.schema(realm, schema, { keyOf, name?, equals? })` | A collection whose rows `schema` accepts, each checked as it lands. | ## See also - [Boxes and computed](../state/boxes.md): the box with no schema. - [Updates](../state/updates.md): what an update undoes. - [Equality and hashing](./equality.md): what each schema counts as equal. - [Classes](./classes.md): boxes as fields of a model. - [Errors and debugging](../guides/errors.md#with-effect): errors a schema adds. --- # Classes URL: https://sorus.frondruntime.dev/docs/effect/classes Description: Read when modeling domain data. Declare a Model.Schema with box fields, derive values on it, write from its methods, decode it from the wire, and hand it the caller's own values, in a decode or an Effect program. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). ## Example A model is a `Model.Schema`: a `Schema.Class` whose instances hold a realm that its wire form never carries. A `$` field is a `Model.boxField` or a [`Model.collectionField`](./collections.md), and its wire key drops the `$`; any other field is plain, `readonly` data. A message's text is a box field because an edit writes it. The sample decodes, makes, encodes, and restores a `Message`. ```ts import { Computed, Model, Realm } from "@frondruntime/sorus-effect"; import { Schema } from "effect"; import { app } from "./realm.ts"; class Message extends Model.Schema("Message")({ id: Schema.String, roomId: Schema.String, author: Schema.String, // A box field: an edit writes it, and the wire key is "text". $text: Model.boxField(Schema.String.check(Schema.isMaxLength(2000))), sentAt: Schema.Number, }) { readonly $preview = Computed.make(this.realm, (read) => `${this.author}: ${read(this.$text)}`); edit(text: string): void { Realm.update(this.realm, (_read, write) => { write(this.$text, text); }); } } // Throws a DecodeError, holding the SchemaError, when the input does not fit. const hello = Model.decode( app, Message, )({ id: "m1", roomId: "general", author: "ada", text: "hi", sentAt: 1 }); hello.edit("hello"); const preview = Realm.untracked(app, (read) => read(hello.$preview)); // "ada: hello" // From values in hand: $text's starting value under "text", checked. const draft = Message.make({ id: "m2", roomId: "general", author: "me", text: "on my way", sentAt: 2, realm: app, }); // The wire fields alone, $text's current value under "text": // { id: "m1", roomId: "general", author: "ada", text: "hello", sentAt: 1 }. const wire = Realm.untracked(app, () => Schema.encodeSync(Message)(hello)); // The server's copy of an edit, restored into the held message: $text takes // the new text, and a plain field that differs throws. const applyEdit = (json: unknown): void => { Model.restore(app, Message)(hello, json); }; ``` A `Model.context` field holds the service of an Effect tag, such as a formatter, and is never on the wire. ```ts import { Computed, Model } from "@frondruntime/sorus-effect"; import { Context, Schema } from "effect"; import { app } from "./realm.ts"; interface TimeFormat { readonly format: (at: number) => string; } // An Effect service: the field requires it, and the caller provides it. class Times extends Context.Service()("chat/Times") {} // A notice from the server, shown with its time. class Notice extends Model.Schema("Notice")({ $text: Model.boxField(Schema.String), sentAt: Schema.Number, times: Model.context(Times), // the caller's own value, never on the wire }) { readonly $line = Computed.make( this.realm, (read) => `${this.times.format(this.sentAt)} ${read(this.$text)}`, ); } const clock: TimeFormat = { format: (at) => new Date(at).toISOString().slice(11, 16) }; const notice = Model.decode( app, Notice, Context.make(Times, clock), )({ text: "Maintenance at noon", sentAt: 0 }); ``` ## Rules - Build an instance with `Model.decode` from wire data or `Message.make` from values in hand: both put its boxes in the given realm, which field initializers read as `this.realm`. - A plain field is never written after decode: it is no box, so no `read` tracks it and a write reruns no reader. A value that changes is a `$` field. - Derive a value with `Computed.make(this.realm, ...)` in a `$` property of the class body; a getter, or a method that takes `read`, is not cached. - A context field's tag is a requirement of the decode: pass a `Context` holding it to `Model.decode`, or provide it in the Effect program. - Encoding gives the wire fields alone and reads each `$` field as `read` does, so in a computed value it tracks and the value recomputes on a field write. ## Answers | Call | Answers | | --- | --- | | `Model.Schema(identifier)(fields)` | A class whose `$` fields are boxes or collections, checked by its schema. It seals `extend`, `mapFields`, `makeOption`, and `makeEffect`. | | `Model.boxField(schema)` | A box field of `schema`. | | `Model.decode(realm, schema, context?)(input)` | The decoded value, or throws `DecodeError` whose `cause` is the `Schema.SchemaError`. | | `Model.context(tag)` | A field holding the service of `tag`, never on the wire. | | `Message.make({ ...values, realm })` | An instance from values in hand, each `$` field's value under its wire key, checked even under `{ disableChecks: true }`. | | `Model.restore(realm, schema, context?)(held, input)` | Decodes `input` and restores it into `held` in place. Throws `DecodeError` as `Model.decode` does, and `sorus/restore-plain-field` when a plain field differs. | ## With Effect `Schema.decodeUnknownEffect(Message)` decodes in a program, with `RealmService` and each context tag as requirements: see [Programs](./programs.md). ## See also - [Schema-checked boxes](./boxes.md): what a `$` field checks on a write. - [Collection fields](./collections.md): rows by key, as a `$` field. - [Snapshots](../state/snapshots.md): `read.snapshot` of a model, unencoded. - [Error messages](../reference/errors.md): every message a model throws. - [Hooks](../react/hooks.md): reading a model in a component. --- # Collection fields URL: https://sorus.frondruntime.dev/docs/effect/collections Description: Read when a model holds rows by key, or when a schema-checked box of an array is refetched whole. Declare a Model.collectionField, decode it from a plain array, and reconcile a refetch. ## Example A `Model.collectionField` is the core's [collection](../state/collections.md) as a field of a `Model.Schema`, each row checked against the row schema and a plain array on the wire. A room's thread holds the `Message` of [Classes](./classes.md). ```ts import { Computed, Model, Realm } from "@frondruntime/sorus-effect"; import { Schema } from "effect"; import { Message } from "./classes.ts"; import { app } from "./realm.ts"; class Thread extends Model.Schema("Thread")({ roomId: Schema.String, $messages: Model.collectionField(Message, { keyOf: (message) => message.id }), }) { // Reads each message's $text: an edit to one reruns this. readonly $mentionsMe = Computed.make( this.realm, (read) => read(this.$messages.rows).filter((message) => read(message.$text).includes("@me")).length, { name: "Thread.mentionsMe" }, ); add(message: Message): void { Realm.update(this.realm, (_read, write) => { write.upsert(this.$messages, message, { at: "end" }); }); } remove(id: string): void { Realm.update(this.realm, (_read, write) => { write.remove(this.$messages, id); }); } } // On the wire, a collection is a plain array. const thread = Model.decode( app, Thread, )({ roomId: "general", messages: [ { id: "t1", roomId: "general", author: "ada", text: "hi @me", sentAt: 1 }, { id: "t2", roomId: "general", author: "grace", text: "hello", sentAt: 2 }, ], }); const mentions = Realm.untracked(app, (read) => read(thread.$mentionsMe)); // 1 ``` A `Box.schema` of an array refetched whole goes through `Collection.reconcile`, so an unchanged item keeps its object. ```ts import { Box, Collection, Computed, Model, Realm } from "@frondruntime/sorus-effect"; import { Schema } from "effect"; import { app } from "./realm.ts"; const Typist = Schema.Struct({ userId: Schema.String, since: Schema.Number }); const sameTypist = Schema.toEquivalence(Typist); const $typing = Box.schema(app, Schema.Array(Typist), [], { name: "typing" }); const typistOf = Computed.fn(app, (read, userId: string) => read($typing).find((typist) => typist.userId === userId), ); const receiveTyping = (json: unknown) => { const next = Model.decode(app, Schema.Array(Typist))(json); Realm.update(app, (read, write) => { // An unchanged typist keeps its previous object, so typistOf for it // returns the same value and its readers do not rerun. write( $typing, Collection.reconcile(read($typing), next, { keyOf: (typist) => typist.userId, equals: sameTypist, }), ); }); }; ``` ## Rules - A `Model.collectionField` checks each row on `Model.decode`, `write.upsert`, and `write.replaceAll`; a rejected row throws and the update is undone. - A repeated key fails `Model.decode` and `Collection.reconcile`, so no row is changed. - A model row with a `$` field is a new instance after every `Model.decode`; `write.replaceAll`, `write.upsert`, and `Collection.reconcile` merge it into the held row, so only the readers of a changed box rerun ([Equality and hashing](./equality.md)). - `Collection.reconcile` takes arrays: one refetched model is a list of one on each side, under any key. ## Answers | Call | Answers | | --- | --- | | `Model.collectionField(schema, { keyOf, name? })` | A field of rows by key, each checked against `schema`. `name` names every instance's collection, as `Collection.make`'s does. | | `Collection.reconcile(previous, next, { keyOf, equals? })` | `next` in its own order, with the previous object for each item whose key is held and which is equal; `previous` itself when nothing changed. `equals` defaults as [Equality and hashing](./equality.md) lists. | ## See also - [Collections](../state/collections.md): reading and writing a collection, and a box of an array. - [Classes](./classes.md): the model a collection field lives on. - [Equality and hashing](./equality.md): what a row or item compares with, and when a merge runs. - [Schema-checked boxes](./boxes.md): `Collection.schema` and `Box.schema`. - [Live data](../guides/live-data.md): a refetch and a feed written into a collection field. --- # Equality and hashing URL: https://sorus.frondruntime.dev/docs/effect/equality Description: Read when a write, a refetch, or a reconcile keeps or replaces a value. Shows what each box, collection, and reconcile compares with, when a refetched model is merged, and how a class defines its own Equal and Hash. ## Example A refetched `Model.Schema` row under a held key is merged into the held one: a component that reads the room list reruns when a plain field such as `name` changes, and one that reads `$topic` reruns when the topic does. ```ts import { Box, Collection, Model, Realm } from "@frondruntime/sorus-effect"; import { Schema } from "effect"; import { app } from "./realm.ts"; import { Room } from "./snapshotsEffect.ts"; const $rooms = Box.schema(app, Schema.Array(Room), [], { name: "rooms" }); const receiveRooms = (json: unknown) => { const fresh = Model.decode(app, Schema.Array(Room))(json); Realm.update(app, (read, write) => { // A held id keeps its Room, and the new topic goes into its $topic box. write($rooms, Collection.reconcile(read($rooms), fresh, { keyOf: (room) => room.id })); }); }; ``` `Unread` defines its own `[Equal.symbol]` and `[Hash.symbol]`: equal by room, whatever its `countedAt`, so a refetched count lands in the held `$count`. ```ts import { Box, Collection, Model, Realm } from "@frondruntime/sorus-effect"; import { Equal, Hash, Schema } from "effect"; import { app } from "./realm.ts"; class Unread extends Model.Schema("Unread")({ roomId: Schema.String, // When the server counted; Equal ignores it. countedAt: Schema.Number, $count: Model.boxField(Schema.Number), }) { // One count per room, whatever countedAt says. The key alone: Effect caches the hash. [Equal.symbol](that: unknown): boolean { return that instanceof Unread && that.realm === this.realm && this.roomId === that.roomId; } [Hash.symbol](): number { return Hash.string(this.roomId); } } const $unread = Box.schema(app, Schema.Array(Unread), [], { name: "unread" }); const receiveUnread = (json: unknown) => { const fresh = Model.decode(app, Schema.Array(Unread))(json); Realm.update(app, (read, write) => { // A room already held keeps its Unread instance; the new count is written into its box. write( $unread, Collection.reconcile(read($unread), fresh, { keyOf: (unread) => unread.roomId }), ); }); }; ``` ## Rules - A schema box with `Schema.Unknown`, `Schema.Any`, or `Schema.ObjectKeyword` compares with `Object.is`, because a structural compare would hash the whole value. - A `Model.Schema` instance compares its plain fields by value and its boxes and realm by identity, so two decodes of a model with a `$` field are not equal. - A refetched instance under a held key is merged when both are of one class and realm and their plain fields are equal, or, when the class defines `[Equal.symbol]`, that method finds them equal. Any other difference replaces the instance. - Define `[Hash.symbol]` beside `[Equal.symbol]`, on plain fields such as the key: Effect's `Equal.equals` compares hashes first and caches them. ## Answers | Constructor | Compares with, by default | | --- | --- | | `Box.make`, `Collection.make`, `Computed.make` | `Object.is`, row by row for a collection. A computed value keeps it over a `Box.schema`. | | `Box.schema`, `Model.boxField` | The schema's equivalence (`Schema.toEquivalence`). | | `Model.collectionField` | A merge for a `Model.Schema` row, the row schema's equivalence otherwise. | | `Collection.reconcile` | A merge for a `Model.Schema` row, a schema class's equivalence, else `Equal.equals`. Given `equals`, only `equals`, with no merge. | ## See also - [Schema-checked boxes](./boxes.md): the box that checks a schema on every write. - [Classes](./classes.md): the model whose fields these rules compare. - [Collection fields](./collections.md): `replaceAll` and `reconcile` on a refetch. --- # Programs URL: https://sorus.frondruntime.dev/docs/effect/programs Description: Read when an app is written as Effect programs. Run an effect per change, stream changes, hold a value observed for a scope, feed a value from a stream, run a feed while its data is read, and hold a section's writes in a stage until it succeeds. ## Example Programs are the Effect forms of `Realm.watch`, `Source.observe`, and `Stage.apply`, for applications already written in Effect. `@frondruntime/sorus-effect` exports them next to the rest; `Scoped` marks a call that lives for the caller's scope. ```ts import { Box, Program, Realm } from "@frondruntime/sorus-effect"; import { Effect, Schema } from "effect"; import { app } from "./realm.ts"; const $query = Box.schema(app, Schema.String, "", { name: "query" }); const $results = Box.schema(app, Schema.Array(Schema.String), [], { name: "results" }); const searchAsTyped = Program.watchScoped( app, (read) => read($query), (query) => Effect.gen(function* () { // A newer query interrupts this effect, here or in the search. yield* Effect.sleep("200 millis"); const results = yield* searchMessages(query); Realm.update(app, (_read, write) => write($results, results)); }), ); ``` A stream feeds a value the same way. ```ts import { Computed, Program } from "@frondruntime/sorus-effect"; import { Effect, Schedule, Stream } from "effect"; import { app } from "./realm.ts"; const onlineLabel = Effect.gen(function* () { // No count until the stream emits, then its latest count. The poll runs // only while $onlineCount is observed. Losing the last observer resets it // to undefined, so a stale count never shows as current. const $onlineCount = yield* Program.fromStream( app, Stream.fromEffectSchedule(fetchOnlineCount, Schedule.spaced("30 seconds")), undefined, { name: "onlineCount" }, ); return Computed.make(app, (read) => { const count = read($onlineCount); return count === undefined ? "" : `${count} online`; }); }); ``` ## Rules - No program requires a service for the realm: `Program.watchScoped` and `Program.fromStream` take it first, and `Program.changes`, `Source.observeScoped`, and `Program.whileObserved` take it from the observable. Only a decoded `Model.Schema` requires `RealmService` ([Classes](./classes.md)). - A `Program.fromStream` value is the stream's latest element while observed and `initial` otherwise. The stream's error type is `never`: a failure a screen shows is an element, made with `Stream.catch`, and the value keeps it until the last observer leaves. - A `Program.whileObserved` run ends when its program returns, though the value is still observed; the next run starts after the last observer leaves and another arrives. A feed ends on the stream it runs. - `Program.whileObserved` and `Program.fromStream` keep the services of the program that called them, not of the code that observes later. Provide a service before the call. - Write several values per element from `Program.whileObserved`, in one update: `Program.fromStream` publishes each element in an update of its own, so a reader of two such values sees them disagree. - Choose the owner of the lifetime: observation (`Program.fromStream`, `Program.whileObserved`) for data shown only while read, a fiber for a feed kept whether shown or not, a scope for a command that runs to its end. - Stop a program by closing its scope, not by keeping stop functions: the scope runs every release in reverse order, also when the program fails or is interrupted. ## Answers | Call | Answers | | --- | --- | | `Program.watchScoped(realm, (read) => ..., (value, previous) => effect, { equals?, name?, scheduler?, immediate? })` | Starts `Realm.watch` in the caller's scope. A new value interrupts the running effect; a defect is logged at the error level and the watch keeps running. | | `Program.changes($x)` | A stream of the current value of a box or computed value, then each change; a slow consumer skips to the newest. Ends when the realm is disposed. | | `Program.updates(realm)` | A stream of each `Realm.onUpdate` record from the next update on, none skipped. Ends when the realm is disposed ([Changes](../state/changes.md)). | | `Source.observeScoped($x)` | Holds a box, computed value, or atom observed until the scope closes, so its hooks keep running with nothing rendered ([Lifecycles](../state/lifecycles.md)). | | `Program.whileObserved($x, program)` | Runs `program` while `$x` is observed, each run in a scope of its own, interrupted when the last observer leaves. A defect is logged and the next observation runs it again. | | `Program.fromStream(realm, stream, initial, { equals?, name? })` | A read-only value, released with the scope. The stream runs only while the value is observed, restarts on the next observation, and resets the value to `initial` when the last observer leaves. `equals` defaults to `Object.is`. | | `Program.fromEffect(realm, effect, initial, { equals?, name? })` | `Program.fromStream` over one effect, run again on each first observer. Its error type is `never`; a defect is logged. | | `Realm.scoped(options?)` | A realm disposed with `Realm.dispose` when the scope closes, after the programs started in that scope. `Layer.effect(RealmService, Realm.scoped())` makes a layer ([Realms](../state/realms.md)). | | `Stage.scoped(realm, (stage) => section, { name?, conflicts?, visible?, guess? })` | The section's value, with its stage applied on success; a failure, defect, or interruption drops it. With `conflicts: "fail"`, a changed read fails with `StageConflictError`. `visible` and `guess` show the writes meanwhile ([Stages](../state/stages.md)). | | `Stage.scoped(stage, (child) => section, { name? })` | A savepoint over `stage`: a failure drops only the child, and each `Effect.retry` attempt opens a fresh one. | ## See also - [Reacting](../state/reacting.md): `Realm.watch` and `Realm.autorun` without Effect. - [Stages](../state/stages.md): conflicts, replay, and visible stages. - [Live data](../guides/live-data.md): a socket feed into a collection. - [Testing](../guides/testing.md): a test realm and `TestClock`. --- # Errors and debugging URL: https://sorus.frondruntime.dev/docs/guides/errors Description: Read when something throws or reruns unexpectedly. Know which errors reach the caller and which go to onError, find why a value recomputed with inspect, and tell errors apart. ## Example `Source.inspect` reports what a value read and why it last recomputed. ```ts import { Realm, Source } from "@frondruntime/sorus"; import { app } from "./realm.ts"; import { $canSend, typeText } from "./state.ts"; const inspectCanSend = () => { const stop = Realm.watch( app, (read) => read($canSend), () => undefined, ); typeText("hi"); const inspected = Source.inspect($canSend); // { name: "canSend", realm: "app", dependencies: ["composer", "connection"], // observers: 1, lastReason: "composer changed", stages: [] } stop(); return inspected; }; ``` Every error Sorus throws is a `SorusError`, told apart by its `_tag`. ```ts import { isSorusError } from "@frondruntime/sorus"; // What the chat's error reporter files an error under. const kindOf = (error: unknown): string => { // A misuse, a bug in the caller: its code names which. if (isSorusError(error, "SorusUsageError")) return error.code; // A condition code handles, such as "StageConflictError". if (isSorusError(error)) return error._tag; return "other"; }; ``` ## Rules - An error with a caller throws to it, and an update that throws is undone: every check runs in every build, since Sorus has no development mode. - An error with no caller goes to `onError` ([Realms](../state/realms.md)): a watch effect's, an autorun's after its first run, a hook's, a `Realm.onUpdate` listener's. The write has landed; the first run of a watch or autorun throws to the caller. - Name what gets debugged with `{ name }` on a box or a computed value: a named computed value keeps why it last recomputed, and its errors name it. - Match an error by `isSorusError`, never by `instanceof`, which fails across two copies of Sorus, or by message text, which changes with the API. ## Answers | Call | Answers | | --- | --- | | `Source.inspect($x)` | `{ name, realm, dependencies, observers, lastReason, stages }`, one level deep. `lastReason` is `undefined` unless the value is a named computed value that has run. | | `isSorusError(error, tag?)` | Whether `error` is a `SorusError`; with `tag`, whether it is that error, narrowed to its class. | ## With Effect A schema adds `ValueRejectedError` and `DecodeError`, each with the `Schema.SchemaError` as `cause`: see [Schema-checked boxes](../effect/boxes.md). A program's defect is logged, not thrown: see [Programs](../effect/programs.md). ## See also - [Error messages](../reference/errors.md): every message, its cause, and the fix. - [Updates](../state/updates.md): what an update undoes when it throws. - [Reacting](../state/reacting.md): watch and autorun, and their first run. - [Testing](./testing.md): asserting on a rejected write. --- # Testing URL: https://sorus.frondruntime.dev/docs/guides/testing Description: Read when writing tests. Make a test realm per test, record what a select changes to, check what a collection still holds, hold every stop in using, and test programs on TestClock. ## Example A test makes its own realm with `testRealm` from `@frondruntime/sorus/testing`. `ChatUnderTest` is the chat's model with a connection, `$canSend`, and the messages; the first test records `$canSend` across updates. ```ts import { expect, test } from "bun:test"; import { Realm } from "@frondruntime/sorus"; import { record, testRealm } from "@frondruntime/sorus/testing"; test("typing text lets a message be sent", () => { // A realm per test: nothing one test made is seen by the next. Its dispose, // when the test ends, throws if anything the test started is still running. using realm = testRealm(); const chat = new ChatUnderTest(realm); chat.type("hi"); expect(Realm.untracked(realm, (read) => read(chat.$canSend))).toBe(true); }); test("typing twice in one update records one change", () => { using realm = testRealm(); const chat = new ChatUnderTest(realm); // Declared after the realm, so it stops before the realm checks. using canSend = record(realm, (read) => read(chat.$canSend)); Realm.update(realm, () => { chat.type("h"); chat.type("hi"); }); chat.type("hi again"); // "hi again" leaves $canSend true: no change, nothing recorded. expect(canSend.values).toEqual([true]); }); ``` A collection that dropped a row keeps nothing for its key, and `retainedKeys` checks it where a count of rows cannot. ```ts import { expect, test } from "bun:test"; import { Realm, Source } from "@frondruntime/sorus"; import { held, retainedKeys, testRealm } from "@frondruntime/sorus/testing"; test("a refetch lets go of the messages it drops", () => { using realm = testRealm(); const chat = new ChatUnderTest(realm); Realm.update(realm, (_read, write) => { write.replaceAll(chat.$messages, [hello, { ...hello, id: "m2" }, { ...hello, id: "m3" }]); }); // A reader of a row makes a box and a computed value for its key. using _ = held(Source.observe(chat.$messages.row("m3"))); Realm.update(realm, (_read, write) => { write.replaceAll(chat.$messages, [hello]); }); // "m3" is gone with its box and computed value, though still observed. expect(retainedKeys(chat.$messages)).toEqual(new Set(["m1"])); }); ``` ## Rules - One realm per test, made with `using realm = testRealm()`. A realm made at module level carries state from one test into the next. - Read with `Realm.untracked`, write with `Realm.update` or a model method that calls it. The testing entry adds no reader or writer, so a test runs the same calls as application code. - Hold every stop in `using`, the realm first: `record` for a watch, `held` for the rest. `using` disposes in reverse order, and a stop function called at the end is skipped when an assertion fails. - Stop every watch, autorun, `Source.observe`, `Collection.onRowChange` listener, view, and `Realm.onUpdate` listener, and apply or drop every stage. The realm's dispose throws one `sorus/test-realm-not-at-rest` naming each one left. - Check a collection with `retainedKeys`, never its private fields: they change without notice. ## Answers | Call | Answers | | --- | --- | | `testRealm(options?)` | A realm that is disposed with its `using` scope. Used after its dispose, it throws `sorus/realm-disposed`. | | `record(realm, select, options?)` | `values`, each value `select` changed to, oldest first, rerun once per update; and `stop`, which `using` also runs. | | `held(stop)` | A `Disposable` that runs `stop` when its `using` scope ends. | | `retainedKeys($items)` | A copy of the set of keys `$items` keeps a row, a box, or a computed value for. Throws for a value Sorus did not make. | ## With Effect `Model.decode(realm, Model)(json)` decodes into the test's realm, and a program takes it as `Program.watchScoped(realm, ...)` does; close every program's scope before the dispose. A program that sleeps runs on `TestClock` from `effect/testing`, and the test waits on a `Deferred` or on `Program.changes`, never on `TestClock.adjust`. ## See also - [Stages](../state/stages.md): a stage left open in a test realm. - [Reacting](../state/reacting.md): when a watch reruns. - [Programs](../effect/programs.md): `Program.*` and `Source.observeScoped`. - [Error messages](../reference/errors.md): `sorus/test-realm-not-at-rest`. --- # Error messages URL: https://sorus.frondruntime.dev/docs/reference/errors Description: Read when Sorus throws or logs a message. Every message Sorus and sorus-effect throw or log, its _tag or code, what caused it, and the fix. This page lists every message Sorus and `@frondruntime/sorus-effect` throw or log, grouped by the call that causes it, with its `_tag` or `code`, the cause, and the fix. It holds no samples: each group names the page whose samples make the calls, so a case is shown once. [Errors and debugging](../guides/errors.md) covers where an error goes and how to find why a value recomputed. ## Rules - Every error Sorus throws is a `SorusError`, branded with the key `"~sorus/Error"`, and carries a literal `_tag` equal to its class name. Match it with `isSorusError(error)` or `isSorusError(error, tag)`, which narrows to the class, never with `instanceof`: two copies of Sorus in one application each have their own classes, and `instanceof` fails across them. - A condition code handles has its own class: `StageConflictError`, `StageClosedError`, `ValueRejectedError`, and sorus-effect's `DecodeError`. Misuse, a bug in the caller, is one `SorusUsageError` whose `code` names it, in the Code column below. A minor version may add a code, so `code` is typed open: a `switch` over it keeps a `default`. - Match on `_tag` and `code`, never on the message: messages name the calls of the current API and change with it. - `toJSON` gives `_tag`, `name`, `message`, and the class's own fields, so a structured logger records them. `StageConflictError` leaves out `observables`, which hold realms. - Every message starts with `sorus: `, except the test realm's ([Testing](../guides/testing.md)). - A part in angle brackets is filled in. `` is the value's `{ name }`. Without one, a `read`, a `write`, or a stage message prints `$observable`; a cycle or a write while computing prints `a derived value`, and `sorus/depth-rebuilt` prints `a computed value`. - A `read` or a `write` message puts the name in quotes, such as `read("count")`. ## Answers ### Reading and writing The calls are on [Updates](../state/updates.md) and [Boxes and computed](../state/boxes.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: read() runs outside a place. ...` | `sorus/read-outside-place` | A `read` used outside every place of its realm, such as one kept in a closure. Pass `read` down instead. | | `sorus: read.row($collection, key) runs outside a place. ...` | `sorus/read-outside-place` | The same, for `read.row`. | | `sorus: write inside Realm.update` | `sorus/write-outside-update` | A `write` kept past its update. | | `sorus: Source.peek runs where reads are tracked, ...` | `sorus/peek-while-tracking` | `Source.peek` inside a computed value, a watch's select, or an autorun, where the result would go stale. Read with that place's `read`. | | `sorus: Source.peek runs inside a stage recipe, ...` | `sorus/peek-in-recipe` | `Source.peek` inside a stage recipe, where it would read the value from before the stage. Read through the recipe's own `read`. | | `sorus: () is handed an observable of another realm. ...` | `sorus/foreign-realm` | A `read` or a `write` of one realm given what another realm made. `` is `read`, `read.row`, `write`, `write.modify`, `write.upsert`, `write.remove`, `write.replaceAll`, or `write.changed`. A realm made with `Realm.make({ name })` is named in the message, such as `(realm "inbox", not "app")`. Build each observable from the realm that reads it. | | `sorus: needs a box, a computed value, or an atom` | `sorus/not-made-by-sorus` | `Source.onObserved`, `Source.observe`, or `Source.inspect` given a value Sorus did not make. | | `sorus: expected a box, a computed value, or an atom` | `sorus/not-made-by-sorus` | `useValues`, `Source.peek`, or `Program.changes` given a value Sorus did not make. | ### Updates The calls are on [Updates](../state/updates.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: Realm.update cannot run in a computed value; ...` | `sorus/update-in-derivation` | An update inside a computed value or a computed function's value. Write from an event, a watch's effect, or an autorun. `Collection.onRowChange` or `Realm.onUpdate` called there says its own name in place of `Realm.update`. | | `sorus: Realm.update cannot run in a watch's select or a selector; ...` | `sorus/update-in-derivation` | An update inside a watch's select or a `useSelect` function. Write from an event, a watch's effect, or an autorun. `Collection.onRowChange` or `Realm.onUpdate` called there says its own name in place of `Realm.update`. | | `sorus: Realm.update recipes are synchronous; await outside, then Realm.update` | `sorus/async-recipe` | A recipe that returned a promise. The update is undone. Await outside, then update. | | `sorus: a Realm.update recipe returns nothing` | `sorus/recipe-returns-value` | A recipe that returned a value other than `undefined` or a promise. The update is undone. | | `sorus: cannot write while it computes` | `sorus/write-while-computing` | A computed value that wrote, through a `write` kept from an update. | ### Stages The calls are on [Stages](../state/stages.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: runs on a stage after it was ; ...` | `_tag` `StageClosedError` | A `StageClosedError`: a stage call after `Stage.apply` or `Stage.drop` closed it. `` is `Stage.update`, `Stage.read`, `Stage.realmRead`, `Stage.apply`, or `Stage.make` of a child; a named stage reads `the stage ""`. `Stage.status` and `Stage.inspect` remain callable outside a recipe after closing. `Stage.drop` on a closed stage does nothing. | | `sorus: changed since read ; nothing lands` | `_tag` `StageConflictError` | A `StageConflictError`: a stage opened with `{ conflicts: "fail" }` read or wrote a box or a collection that changed in the realm before it landed. `` is `the stage` or `the stage ""`. `Stage.apply` throws it; on a visible stage it stops the stage at the update that moved the value, and `Stage.update` and `Stage.read` throw it too. `` names each by its `{ name }`: an unnamed box is ``, an unnamed collection `a Collection.make`. The stage is dropped. Retry the work over the new values, or open the stage without the option to replay over them. | | `sorus: of a stage runs after its recipe returned; ...` | `sorus/stage-handle-kept` | A `read` or a `write` a stage handed out, kept past its recipe. `` is `read`, `read.row`, `write`, `write.modify`, `write.upsert`, `write.remove`, `write.replaceAll`, or `write.changed`. | | `sorus: runs inside a stage recipe, ...` | `sorus/call-in-recipe` | A stage call, `Source.onObserved`, `Collection.onRowChange`, or `Realm.onUpdate` on the stage's realm inside a recipe, a `Stage.read` function, or a computed value the stage evaluates. Call it outside the recipe or evaluation. | | `sorus: a stage recipe writes the realm, through Realm.update or a write kept from one; ...` | `sorus/realm-write-in-recipe` | A realm write inside a stage recipe, which would show at once and survive a drop. Write through the recipe's own `write`. Also a box's `equals` that updates while visible stages settle what they show; the stack reports it to `onError` and counts the values unequal. | | `sorus: read() of the realm runs inside a stage recipe, ...` | `sorus/realm-read-in-recipe` | A `read` of the stage's realm, kept from another place, inside a recipe, a `Stage.read` function, or a computed value the stage evaluates, where it would skip the stage's values. `read.row` and `Realm.untracked` say so in its place. Read through the stage's `read`. | | `sorus: is made inside a stage recipe, ...` | `sorus/made-in-recipe` | A box, a computed value, a computed function, an atom, a collection, or a model made on the stage's realm inside a recipe, a `Stage.read` function, or a computed value the stage evaluates; replay would make it again. Make it outside and close over it. | | `sorus: a stage recipe cannot observe or release while it computes` | `sorus/observe-while-computing` | A `Realm.watch`, a `Realm.autorun`, or a `Source.observe` started inside a stage recipe. | | `sorus: runs in Stage.read, which writes nothing; write in Stage.update` | `sorus/stage-read-writes` | A write inside a `Stage.read` function, such as a `Collection.reconcile` merge. | | `sorus: Stage.apply runs on a stage while a child stage of it is open; ...` | `sorus/stage-child-open` | A precondition failure: the stage stays open. Apply or drop the child first. | | `sorus: conflicts is "replay" or "fail", not ` | `sorus/stage-conflicts-option` | `Stage.make` given another `conflicts` value, from code the types did not check. | | `sorus: a child stage takes no conflicts option; ...` | `sorus/stage-conflicts-option` | `Stage.make(stage, { conflicts })`. The root stage's option covers what its children read. | | `sorus: visible is true or false, not ` | `sorus/stage-visible-option` | `Stage.make` given another `visible` value, from code the types did not check. | | `sorus: a child stage takes no visible option; ...` | `sorus/stage-visible-option` | `Stage.make(stage, { visible })`. A child is a savepoint that shows through its parent once applied; a second guess that must show at once is a second stage over the realm. | | `sorus: Stage.scoped takes a guess or visible, not both: a stage is the guess or the answer` | `sorus/stage-visible-option` | `Stage.scoped` given both `guess` and `visible`, from code the types did not check: a stage is the guess or the answer. | | `sorus: Stage.scoped takes a guess over a realm alone: a child stage is a savepoint and shows nothing` | `sorus/stage-visible-option` | `Stage.scoped(stage, section, { guess })`, from code the types did not check: a child stage is a savepoint and shows nothing. | | A visible stage's kept error | as thrown | `Stage.update`, `Stage.read`, or `Stage.apply` on a visible stage that stopped: the error that stopped it, a `StageConflictError` or its recipe's own throw. `Stage.apply` also drops it. `Stage.inspect(stage).failure` holds it. | | `sorus: is read while a stage evaluates it (cycle)` | `sorus/cycle` | A computed value that reads itself, read through a stage. | | `sorus: Stage.update cannot run in a computed value; ...` | `sorus/update-in-derivation` | As for `Realm.update`, with `Stage.update` or `Stage.apply` in its place, and the same for a watch's select or a selector. This precondition failure leaves the stage open. | | `sorus: Stage.read cannot run in a computed value; ...` | `sorus/update-in-derivation` | `Stage.read` or `Stage.realmRead` in a computed value, a watch's select, or a selector: a stage's reads are not tracked, so the derivation would go stale. | | `sorus: Stage.update recipes are synchronous; await outside, then Stage.update` | `sorus/async-recipe` | A `Stage.update` recipe that returned a promise. Its writes to the stage are undone. | | `sorus: a Stage.update recipe returns nothing` | `sorus/recipe-returns-value` | A `Stage.update` recipe that returned a value other than `undefined` or a promise. | ### Drafts `write.modify` is on [Updates](../state/updates.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: write.modify drafts arrays and plain objects; ...` | `sorus/modify-not-draftable` | `write.modify` on a box holding another kind of value. Write it whole with `write($box, value)`. | | `sorus: a modify recipe returns nothing; write through the draft` | `sorus/recipe-returns-value` | A `write.modify` recipe that returned a value. | | `sorus: a draft is used after its recipe returned` | `sorus/draft-kept` | A draft kept past its recipe. | | `sorus: write.modify left an object it wrote under two keys; ...` | `sorus/draft-at-two-keys` | A recipe wrote a draft and left it at a second key, inside itself, or inside an object the recipe placed at two keys, such as `draft.history.push(draft.present)` followed by a write to `draft.present`. The update is undone. Refer to the object by a key, or read a snapshot with `read($box)` before the write. | | `sorus: write.modify was given a draft another recipe wrote; ...` | `sorus/draft-of-another-recipe` | An outer `write.modify`'s draft, written, assigned inside an inner `write.modify`. The outer recipe can still change it after the inner box's check, so a copy would hide that write. The update is undone. Read the value with `read($box)`, or write the inner box from the outer recipe. | | `sorus: a checked box was given a draft of an open write.modify; ...` | `sorus/draft-in-write` | A `Box.schema` or `Model.boxField` written with a draft of a `write.modify` still running, or a value holding one, such as `write($checked, draft.child)` inside another box's recipe. The recipe can change the draft after the check accepts it. The update is undone. Write the box inside the recipe with `write.modify`, or pass a value read with `read($box)`. | | `sorus: a draft does not take defineProperty; assign instead` | `sorus/draft-unsupported` | `Object.defineProperty` on a draft. | | `sorus: a draft cannot change its prototype` | `sorus/draft-unsupported` | `Object.setPrototypeOf` on a draft. | ### Declaring The calls are on [Boxes and computed](../state/boxes.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: a name is a non-empty string` | `sorus/empty-name` | `{ name: "" }`, `Realm.update`'s included. | | `sorus: Box.make takes a value, not a schema; ...` | `sorus/box-takes-schema` | `Box.make` given an Effect schema. A box that checks a schema is `Box.schema` from `@frondruntime/sorus-effect`. | ### Computed values and watchers The calls are on [Boxes and computed](../state/boxes.md) and [Reacting](../state/reacting.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: is read while it computes (cycle)` | `sorus/cycle` | A computed value that reads itself, directly or through others. | | `sorus: stopped past depth 256 and ran again more than 64 times in one read, as one that makes a new chain of computed values each time it computes does; ...` | `sorus/depth-rebuilt` | A computed value whose read stopped past depth 256 and ran again more than 64 times in one read. A read past depth 256 waits while the value it stopped at computes, then the outer compute runs again; one that makes a new chain on every run never reaches the value computed for it. A compute that makes and keeps one deep chain per run finishes in chains + 1 runs, so up to 63 kept chains read. Make the chain outside the computed value, or keep it between runs. | | `sorus: cannot observe or release while it computes` | `sorus/observe-while-computing` | A `Realm.watch`, a `Realm.autorun`, a `Source.observe`, or a release inside a computed value. | | `sorus: watchers did not settle after 100 rounds` | `sorus/watchers-unsettled` | Sent to `onError`: watchers kept changing what they read, such as an autorun that writes what it reads on every run. Make the write settle. | | `sorus: ran 100 times in a row for its own writes; ...` | `sorus/watchers-unsettled` | Sent to `onError`: a scheduled watch or autorun whose every run writes what it read. It runs again at the next change from outside its own runs. Make the write settle. | | `sorus: 's scheduler called run inside an update, ...` | `sorus/scheduled-run-not-at-rest` | A scheduler's `run` called inside an update, a computed value, a watch's select, an autorun, or a stage recipe, where values are not settled. Call it from a frame, a timer, an event handler, or a watch's effect. | | `sorus: with { immediate: true } is made inside Realm.update, ...` | `sorus/watch-immediate-in-update` | A `Realm.watch` or `Program.watchScoped` with `{ immediate: true }` made inside an update, where its first effect would run before the update lands. Nothing is watched. Make the watch outside the update. | | `sorus: Source.onObserved hooks did not settle after 100 passes` | `sorus/hooks-unsettled` | Sent to `onError`: hooks kept starting other hooks. The hooks still due wait for the next settle. | ### Collections The calls are on [Collections](../state/collections.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: the collection key appears twice` | `sorus/repeated-key` | A [collection](../state/collections.md)'s `write.replaceAll` given two rows of one key. Nothing is written. | | `sorus: a collection row cannot be undefined` | `sorus/undefined-row` | A collection made, or a `write.upsert` or `write.replaceAll`, given an `undefined` row, even where the row schema accepts `undefined`: `row(key)` and `read.row` return `undefined` for a missing key, so an `undefined` row would read as no row. Nothing is written. | | `sorus: reconcile: the key appears twice` | `sorus/repeated-key` | `Collection.reconcile` given two items of one key in `next`. | | `sorus: on the collection a Collection.onRowChange listener is reporting; ...` | `sorus/row-listener-reentrant` | A listener that wrote the collection it listens to. `` is `write.upsert`, `write.remove`, or `write.replaceAll`. The write fails and is undone. | | `sorus: Collection.onRowChange on the collection a Collection.onRowChange listener is reporting` | `sorus/row-listener-reentrant` | A listener that added another listener to the collection it listens to. | | `sorus: a Collection.onRowChange listener is synchronous and returns nothing` | `sorus/row-listener-returns-value` | A listener that returned a value, such as a promise. The write fails and is undone. | | `sorus: Collection.onRowChange needs a collection made by Sorus` | `sorus/not-made-by-sorus` | `Collection.onRowChange` given a value Sorus did not make. | | `sorus: retainedKeys takes a collection Sorus made` | `sorus/not-made-by-sorus` | `retainedKeys` from the testing entry given a value Sorus did not make. | ### Views `` is the call that made the [view](../state/views.md), with its name when it has one: `View.ordered "timeline"`, or `View.ordered`. | Error | Code | Answers | | --- | --- | --- | | `sorus: is disposed, so its is no longer kept up to date` | `sorus/view-disposed` | A read through a view after `View.dispose` or `Realm.dispose`: `size`, `totalSize`, `keys`, `range`, `group`, or `groups`. Make a new view, or read the collection. | | `sorus: 's compare finds the rows of keys and equal, and keys that are not both strings, numbers, or bigints cannot break the tie; break it in compare` | `sorus/view-tie` | `View.ordered`'s comparator returned 0 for two rows whose keys have no order. The write fails and is undone. | | `sorus: 's compare returned ; it returns a negative number, zero, or a positive number` | `sorus/view-compare-result` | `View.ordered`'s comparator returned `NaN` or a non-number. The write fails and is undone. | | `sorus: did not find the row of key where placed it; ...` | `sorus/view-out-of-step` | A view's callbacks answered differently for a row than when it was placed, or the row was changed after it was written. `` names `compare`, `filter`, `compare and filter`, `groupOf`, or `project`. The write fails and is undone. Make the callbacks a function of the row alone, and write a new row instead of changing one. | | `sorus: cannot start while holds writes to its collection; ...` | `sorus/view-staged-rows` | `View.ordered`, `View.grouped`, or `View.totals` made while an open hidden stage has written the collection; a visible stage does not count. `` is `a stage` or `the stage ""`. Make the view before the stage writes the collection, or after it is applied or dropped. | | `sorus: .range takes whole numbers from 0, not and ` | `sorus/view-range` | `range` given a negative, fractional, or non-finite rank. | | `sorus: View.ordered needs a collection made by Sorus` | `sorus/not-made-by-sorus` | `View.ordered`, `View.grouped`, or `View.totals` given a value Sorus did not make; the message names the call. | | `sorus: View.dispose needs a view made by Sorus` | `sorus/not-made-by-sorus` | `View.dispose` or `View.status` given a value Sorus did not make. | A view is made where `Collection.onRowChange` can be called, and its creation throws what `Collection.onRowChange` throws there, naming the view's call: `sorus/update-in-derivation`, `sorus/call-in-recipe`, `sorus/row-listener-reentrant`, and `sorus/realm-disposed`. ### Snapshots The calls are on [Snapshots](../state/snapshots.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: read.snapshot at finds ; a shape holds boxes, collections, Model.Schema instances, ...` | `sorus/snapshot-not-state` | A [snapshot](../state/snapshots.md)'s shape holds a computed value, an atom, a `Model.Class` instance, or a plain value at ``, or a collection holds a `Model.Class` row. Put the boxes a computed value reads in the shape, and a `Model.Class` instance's boxes by name. `write.restore` throws the same for its shape. | | `sorus: read.snapshot at reaches an object that holds it; a shape is a tree` | `sorus/snapshot-cycle` | A shape that holds itself. `write.restore` throws the same. | | `sorus: write.restore at takes , and the data holds ` | `sorus/restore-shape` | The data at `` is not the shape's form: an object for an object, an array of the same length for an array, an array of rows for a collection, a model's data or an instance of its class for a `Model.Schema`. The restore's writes are undone. | | `sorus: write.restore at takes the shape's keys exactly; the data lacks "", and the data adds ""` | `sorus/restore-shape` | The data at `` misses a key of the shape or adds one. Restore a smaller shape for a partial restore. | | `sorus: write.restore at cannot key a data row: the collection's keyOf throws on it; ...` | `sorus/restore-shape` | A collection whose `keyOf` calls a method of a `Model.Schema` row, which the row's data lacks. Key rows by a plain field, which the data holds under the same name. | | `sorus: write.restore at finds "" of the held there different in the data; ...` | `sorus/restore-plain-field` | A plain field of a `Model.Schema` that the data, or an instance standing in for it, holds differently, or holds where the other leaves an optional field out. A plain field is never written after the model is made: restore into a model whose plain fields match, or make a new one with `Model.decode`. Also `Model.restore` for a decoded input whose plain field differs from the held instance's. | | `sorus: write.restore at [key ] adds a model row from plain data; a restore never makes a model. ...` | `sorus/restore-cannot-make-row` | A collection of `Model.Schema` rows that lacks ``, given plain data for it. Pass the instance in the data, made with `Model.decode` or `make`, or decode the whole input with `Model.restore`. | ### Change stream The calls are on [Change stream](../state/changes.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: write.revert takes a record Realm.onUpdate handed out, and this is not one: ...` | `sorus/record-not-applicable` | `write.revert` or `write.replay` of an object `Realm.onUpdate` did not hand out: a copy such as `{ ...record, name: "undo" }`, or a record made by hand. The realm keeps beside each record which listeners its update had, and a copy loses it. Pass the record itself. Nothing is written. | | `sorus: write.revert needs to hold the record's after, and it changed since; ...` | `sorus/record-not-applicable` | `write.revert` of a record a box no longer holds the `after` of, by `Object.is`; `write.replay` reads `before`. The state moved since the record landed: a later update applied, or records reverted or replayed out of order. The check runs before the first write, so nothing is written. Apply records in the order they landed, and revert them newest first. `` reads `the box ""` for a named box, else `a box`. | | `sorus: write.revert needs the row under of to be the record's after, and it changed since; ...` | `sorus/record-not-applicable` | The same for a row the record changed: the row held under `` is not the record's `after` (`before` for `write.replay`), by `Object.is`, absent counted as `undefined`. Nothing is written. | | `sorus: write.revert needs the key order of to be the record's after, and it changed since; ...` | `sorus/record-not-applicable` | The same for a key order the record moved, compared key by key. Nothing is written. | | `sorus: write.revert cannot apply a record whose update added a Collection.onRowChange listener to : ...` | `sorus/record-not-applicable` | A record of a `Realm.update` inside which `Collection.onRowChange` added a listener, whether or not the update changed rows. The record holds what the new listener wrote as it heard the rows held, and its `before` holds that state from before the listener existed, so restoring it leaves a running listener with state that does not match the rows. Add listeners at rest, outside an update: the record of that registration restores. A view is in no record and is never refused. `write.replay` throws the same. | | `sorus: write.revert wrote the row under of , and a Collection.onRowChange listener added after the record changed it as it heard the restore of another collection; ...` | `sorus/record-not-applicable` | `write.revert` or `write.replay` of a record that lists two or more collections, where a `Collection.onRowChange` listener added after the record, hearing a later collection's restore, wrote a row the record lists, or a key order it moved, in a collection restored before. Each collection is compared, by `Object.is`, with what its own restore left once all are written; writing it again would run its later listeners again, so the restore throws rather than land a value the record does not hold. Reads `the key order` for a moved order. Every write the call made is undone. Stop that listener before the restore, or apply the change with `Realm.update`. | | `sorus: write.replay needs to hold the rows its Collection.onRowChange listener heard when it was added, and they changed since; ...` | `sorus/record-not-applicable` | `write.replay` or `write.revert` of the record a listener added at rest made, while the collection holds other rows or another key order than the ones that listener first heard. Apply records in the order they landed. Nothing is written. | | `sorus: write.replay needs the row under of , which neither the record nor the collection holds; ...` | `sorus/record-not-applicable` | A key the record's order needs that neither its rows nor the collection hold. The check above runs first, so a record applied in order never meets it. Every write the call made is undone. | ### Disposal The calls are on [Realms](../state/realms.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: cannot start in the disposed realm; make a new realm` | `sorus/realm-disposed` | `Realm.update`, `Realm.watch`, `Realm.autorun`, `Source.observe`, `Source.onObserved`, `Computed.fromPromise`, `Collection.onRowChange`, `Realm.onUpdate`, `View.ordered`, `View.grouped`, `View.totals`, `Stage.make`, or a hook mounting, in a realm `Realm.dispose` disposed. `` names the call, such as `Realm.update`, `a Realm.watch`, or `useValue`; a named realm reads `the disposed realm ""`. Every call but `Realm.update` throws from the moment disposal begins, so a cleanup cannot start what would outlive it. Make a new realm; reads of the disposed one still return its last values. | | `sorus: Realm.dispose runs while the realm is running ...` | `sorus/dispose-not-at-rest` | `Realm.dispose` inside an update, a computed value, a watch's select or effect, an autorun, `Realm.untracked`, a hook, a stage recipe, a row listener, or a `Realm.onUpdate` listener (the error goes to `onError`, as every listener error does). Nothing is stopped. Dispose from an event handler or a teardown, once the realm is at rest. | | `sorus: needs a realm made by Realm.make()` | `sorus/not-made-by-sorus` | `Realm.dispose`, `Realm.status`, or `Realm.onUpdate` given a value `Realm.make` did not make. | ### Testing The calls are on [Testing](../guides/testing.md). | Error | Code | Answers | | --- | --- | --- | | `The test realm is not at rest: .` | `sorus/test-realm-not-at-rest` | A `testRealm` disposed with a watch, an autorun, a `Source.observe`, a `Collection.onRowChange` listener, a view, a `Realm.onUpdate` listener, or a stage still running. The realm is disposed anyway, so the next use of it throws `sorus/realm-disposed`. Stop each in the test. | ### Internal These guard Sorus's own packages; application code reaches them only through a bug in Sorus. Report one with its stack. | Error | Code | Answers | | --- | --- | --- | | `sorus: cannot track inside its own run`, `... cannot adopt inside its own run` | `sorus/reentrant-run` | A reaction that tracks inside its own run. | | `sorus: endBatch needs a beginBatch before it` | `sorus/unbalanced-batch` | A batch ended twice. | | `sorus: Source.onObserved needs a source from this graph`, `sorus: onObservedNow needs a source from this graph, inside a batch` | `sorus/foreign-source` | A hook on another graph's source. | | `sorus: Schema.Class no longer exposes its ast as a getter`, `sorus: Schema.Class no longer builds its instance in one transformation` | `sorus-effect/schema-class-changed` | An Effect version whose `Schema.Class` sorus-effect does not support. Effect is pinned at 4.1.0. | ### React The hooks are on [Hooks](../react/hooks.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: useRealm and useSelect need a RealmProvider above the component` | `sorus-react/no-provider` | `useRealm` or `useSelect` with no `RealmProvider` above. `useValue` and `useValues` need none. | | `sorus: expected a realm made by Realm.make()` | `sorus-react/not-a-realm` | `useSelect` under a `RealmProvider` given something other than a realm. | | `sorus: useValues takes observables of one realm` | `sorus-react/mixed-realms` | `useValues` given observables of two realms; named realms are named in the message. | ## With Effect The calls are on [Schema-checked boxes](../effect/boxes.md), [Classes](../effect/classes.md), and [Programs](../effect/programs.md). | Error | Code | Answers | | --- | --- | --- | | `sorus: the box rejects this value: ...` | `_tag` `ValueRejectedError` | A write the schema refused: `reason` says why, and `cause` is the `Schema.SchemaError`. The update is undone. | | `sorus: Todo.a and Todo.b both read "key"; rename one` | `sorus-effect/wire-key-twice` | Two fields under one wire key, thrown when the class is defined. | | `sorus: Todo.realm reads "realm", ...` | `sorus-effect/field-named-realm` | A field whose wire key is `realm`, which the instance holds. Rename the field. | | `sorus: Todo.__proto__ cannot hold a plain field, ...` | `sorus-effect/reserved-field-name` | A plain field named `__proto__`, whose value would be lost on decode because assignment sets the prototype. Rename the field, or declare it `$__proto__` as a box field. | | `sorus: Todo.$done is named as a box; ...` | `sorus-effect/box-field-undeclared` | A `$` field that is not a `Model.boxField` or a `Model.collectionField`. | | `sorus: Todo.done holds a box; name it $done` | `sorus-effect/box-field-unprefixed` | A `Model.boxField` or `Model.collectionField` without the `$`. | | `sorus: Todo. is not supported; ...` | `sorus-effect/unsupported-static` | A `Schema.Class` static a `Model.Schema` refuses, `extend`, `mapFields`, `makeOption`, or `makeEffect`. | | `sorus: Todo.make takes the value of $done under "done", never a box under "$done"` | `sorus-effect/make-takes-wire-key` | `make` given a box. Pass the value under its wire key. | | `sorus: a Todo field of another schema takes an instance; ...` | `sorus-effect/make-takes-instance` | Another schema's `make` given a plain object where a `Model.Schema` instance belongs. Build it with `Todo.make` or `Model.decode`. | | `sorus: expected a realm made by Realm.make()` | `sorus-effect/not-a-realm` | `RealmService` provided with something other than a realm. | | `sorus: the collection key appears twice` | none: inside the `DecodeError` | Also a `Model.decode` of a [collection field](../effect/collections.md) given two rows of one key, inside the `Schema.SchemaError`. | | `sorus: a watch effect died`, `sorus: a stream into a value died`, `sorus: a program run while observed died` | none: logged | Logged at the error level, with the defect as its cause: a `Program.watchScoped` effect, a `Program.fromStream` stream, or a `Program.whileObserved` program died. The watch keeps running. A stream's value keeps its last element while observed and resets to `initial` when the last observer leaves. The next observation starts a stream or a program again. | | `sorus: decode rejects the input: ...` | `_tag` `DecodeError` | `Model.decode` or `Model.restore` input that does not fit the schema; `Model.restore` writes nothing. `cause` is the `Schema.SchemaError`, and `issue` its issue. An Effect program that decodes with `Schema.decodeUnknownEffect` gets the `SchemaError` in its error channel instead. | ## See also - [Errors and debugging](../guides/errors.md): which errors reach the caller, which go to `onError`, and `Source.inspect`. - [Updates](../state/updates.md): what an update undoes when it throws. - [Collections](../state/collections.md): the writes that report a repeated key. - [Classes](../effect/classes.md): the naming errors a `Model.Schema` throws when it is defined. - [Testing](../guides/testing.md): what the test realm's dispose reports. --- # Agent skills URL: https://sorus.frondruntime.dev/docs/start/skills Description: Read when an agent writes code on Sorus. Install the agent skills, see which skill covers each task, and point an agent without skills at llms.txt. ## Example The agent skills are Sorus's rules for an agent, split by task. The `skills` command line () installs them into a project. ```bash npx skills add frondruntime/sorus ``` ## Rules - `sorus-overview` loads first: it maps every module and names the skill for each task, so an agent loads one task's rules, not all of them. - `node_modules/@frondruntime/sorus/AGENTS.md` wins where it and a skill differ: it ships with the installed version, and the skills install from the repository. - An agent without skills reads `/llms.txt`, which links each page's Markdown with its description, or `/llms-full.txt`, every page in one file. ## Skills Each skill is built from `AGENTS.md` and these pages, and a test fails when a skill differs from them. | Skill | Loads for | | --- | --- | | `sorus-overview` | any work with Sorus, first: every module, its calls, and the skill for each task | | `sorus-state` | boxes, computed values, models, updates, collections, views, watches, and autoruns | | `sorus-react-components` | a React component that shows or changes state | | `sorus-with-effect` | Effect Schema boxes and models, decoding from the wire, and Effect programs | | `sorus-stages-and-live-data` | writes held until asynchronous work ends, optimistic writes, and state from a request or a socket | | `sorus-saving-and-history` | snapshots, restore, undo, redo, and a log of every write | | `sorus-testing-and-errors` | a test of code on Sorus, and an error to trace | | `sorus-from-mobx` | code moving from MobX | ## See also - [Start](./index.md): install the packages, and the first realm. - [Why Sorus](./why.md): why the rules are what they are. - [Errors and debugging](../guides/errors.md): what an agent sees when it breaks one.