# Pinna Documentation > Pinna — 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 Pinna documentation. --- # Start URL: https://pinna.frondruntime.dev/docs/start Description: Read when starting with Pinna. Make a realm, a box, and a computed value, write in an update, show the value in React, and choose between a plain box and a schema box. ## Example A realm holds every observable it makes. Make one for the app, in module code. ```tsx import { createRealm } from "@frondruntime/pinna"; const realm = createRealm(); ``` A box is observable state. A computed value is derived from what its function reads, and cached. ```tsx import { box, computed } from "@frondruntime/pinna"; const $count = box(realm, 0, { name: "count" }); const $double = computed(realm, (read) => read($count) * 2, { name: "double" }); ``` - A name that starts with `$` is observable. Everything else is plain data. - `{ name }` names the value in `inspect` and in its errors. A box is written only inside `update`, which hands out `read` and `write`. ```tsx import { update } from "@frondruntime/pinna"; const increment = () => { update(realm, (read, write) => { write($count, read($count) + 1); }); }; ``` A component reads with `useValue` and rerenders when the value changes. It needs no provider: the value carries its realm. ```tsx import { useValue } from "@frondruntime/pinna-react"; function CounterButton() { const double = useValue($double); return ( ); } ``` State made more than once, such as once per test, is a model: a class that extends `Model`, whose fields are made against `this.realm` and whose methods write through `update`. ```tsx import { box, computed, Model, update } from "@frondruntime/pinna"; class Counter extends Model { readonly $count = box(this.realm, 0, { name: "count" }); readonly $double = computed(this.realm, (read) => read(this.$count) * 2, { name: "double" }); increment(): void { update(this.realm, (read, write) => { write(this.$count, read(this.$count) + 1); }); } } ``` A test makes the model in a realm of its own and reads as application code does, inside `untracked`. ```tsx import { createRealm, untracked } from "@frondruntime/pinna"; const counter = new Counter(createRealm()); counter.increment(); const double = untracked(counter.realm, (read) => read(counter.$double)); // 2 ``` ## Rules - An observable has no read or write methods. Every place that reads hands out `read`; `update` alone also hands out `write`. - An update that throws is undone: every write before the throw is taken back, except a `write.changed` on an atom, whose watchers still run. - There is no default realm. Batches, tracking, watchers, and errors stay inside the realm that made them, so a test with a realm of its own shares nothing with the next. - The samples on these pages use one realm made in module code, for brevity. - The pages under Core and React import from `@frondruntime/pinna`, which needs no Effect, and `@frondruntime/pinna-react`. The pages under Effect import from `@frondruntime/pinna-effect`, which re-exports every call of `@frondruntime/pinna` and adds boxes and models that check an Effect Schema on every write: see [Schema-checked boxes](../effect/boxes.md). ## Answers | Call | Answers | | --- | --- | | `createRealm({ onError?, name? })` | A realm. `onError` gets the errors with no caller, and defaults to the host's `reportError`. `name` labels the realm in `inspect` and in an error about another realm; it is never compared. | | `box(realm, initial, options?)` | A box. A write equal to the current value under `Object.is` notifies nobody. | | `computed(realm, (read) => ..., options?)` | A cached value derived from what the function reads. | | `update(realm, (read, write) => ...)` | Runs the recipe atomically. Watchers see its end state once. | | `useValue($x)` | The value of `$x`; the component rerenders when it changes. | | `class X extends Model` | A model that checks nothing. Field initializers read `this.realm`; `new X(realm)` makes one. | ## Plain or schema boxes The choice is per box, not per application. A plain `box` and a `collection` check nothing, and neither does `Model`, the base class of a model with no schema. A schema box, a `schemaBox` or a `SchemaModel`'s `BoxField`, checks every write against its schema, and a `CollectionField` checks each row against its row schema when the row lands. A value the schema rejects throws and undoes the update. - Data from outside the program, such as a response from the wire or user input, goes through a schema. `decode(realm, schema)(input)` checks it once at the boundary, whatever boxes then hold it. - A value whose writes need a runtime check takes a schema box: the check runs on every write. - Trusted data that is written often takes a plain box, which runs no check. - A schema box's check is never weakened for speed. The plain box is the way to check nothing; there is no option that turns a schema box's check off. A `SchemaModel`, from `@frondruntime/pinna-effect`, can hold a plain box in its class body beside its `BoxField`s. The plain box checks nothing, and the `BoxField` keeps checking. ```ts import { BoxField, box, decode, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; class Ticker extends SchemaModel("Ticker")({ symbol: Schema.String, $volume: BoxField(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0))), // checked on every write price: Schema.Number.check(Schema.isGreaterThan(0)), // checked once, by decode }) { // Starts at the decoded price; checks nothing, and is not on the wire. readonly $lastPrice = box(this.realm, this.price); tick(price: number): void { update(this.realm, (_read, write) => { write(this.$lastPrice, price); }); } } const ticker = decode(realm, Ticker)({ symbol: "ACME", volume: 0, price: 12 }); ticker.tick(12.5); ``` - A box in the class body is not a schema field, so it is not on the wire: `decode` does not fill it, and encoding does not write it. - A body box seeded from a decoded field, as `readonly $lastPrice = box(this.realm, this.price)`, starts from a value that `decode` checked once. Later writes to the box check nothing, and the field `price` and the encoded output stay at the decoded value. - No `$` field is both on the wire and unchecked. A `$` field on the wire is a `BoxField`, which checks every write, or a `CollectionField`, which checks every row written to it. ## See also - [Coming from MobX](./mobx.md): the Pinna call for each MobX one. - [Updates](../state/updates.md): drafts, atomic updates, and `reconcile`. - [Reacting](../state/reacting.md): watchers and autoruns. - [Schema-checked boxes](../effect/boxes.md): the same calls on Effect Schema, with models decoded from the wire. - [Hooks](../react/hooks.md): every way a component reads. --- # Design principles URL: https://pinna.frondruntime.dev/docs/start/principles Description: Read when deciding whether Pinna fits, or when one of its rules looks arbitrary. What Pinna is designed for, the mechanism behind each principle, and what each one costs. Pinna is written to be used by agents as much as by people. A read or a write in the wrong place fails with a type error or a named error instead of half-working; the mistakes that still pass silently are listed under [Misuse is loud](#misuse-is-loud). That takes more code than a library that tracks reads implicitly, and it takes speed. Pinna pays both on purpose. ## Reads are explicit With implicit tracking, a person or an agent reading `position.value` cannot tell whether it is a plain value or a tracked read, so cannot tell where tracking is needed. Forgetting it produces no error — only a value that stops updating. In Pinna an observable is not its value. It is a box, a computed value, an atom, or a collection, named with a leading `$`, and it has no read or write methods. Every place that reads hands its function a `read`, and `read($x)` both returns the value and subscribes that place. An observable used as its value without `read` does not type-check wherever the value's type matters: arithmetic, a comparison, a property or a method of the value, a variable or an argument typed as the value. A truthiness check and a string conversion accept any object, so they still compile; see [Misuse is loud](#misuse-is-loud). ```ts import { box, computed, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const $price = box(realm, 12); const $quantity = box(realm, 3); // Each read(...) returns the value and subscribes $total to that box. const $total = computed(realm, (read) => read($price) * read($quantity)); // The same value without read does not compile. A box is not a number: // error TS2362, the left-hand side of an arithmetic operation must be a number. const $broken = computed(realm, () => $price * $quantity); ``` A component's render body has no `read` at all, so a call to `read` there does not compile, and an observable used there as its value meets the same type errors. `useValue`, `useValues`, and `useSelect` are the only ways in, which is why there is no `observer` wrapper and no lint rule for reads in render. The cost is code. Every read is a call, a derived value is a `$` field built with `computed` instead of a getter, and `read` is passed down as an argument to whatever needs it. ## A write has one place A box changes only inside `update`, through the `write` it hands out. A box field has no setter, and a `write` kept past its update throws. So every write in an application sits inside an `update`. An update is atomic. An error thrown from the recipe, such as the `not enough in stock` below, undoes every write before it in the same update, and watchers run once, after the update ends. A write the schema of a `schemaBox` rejects throws in the recipe the same way, and is undone the same way: see [Schema-checked boxes](../effect/boxes.md). ```ts import { box, update } from "@frondruntime/pinna"; const $quantity = box(realm, 1); const $note = box(realm, ""); const take = (amount: number) => { update(realm, (read, write) => { write($note, `took ${amount}`); const left = read($quantity) - amount; if (left < 0) throw new Error("not enough in stock"); // $note is undone too write($quantity, left); }); }; ``` The cost is that some familiar patterns are errors. An update in a computed value or a watch's select throws, so a derived value never writes. An update is synchronous, so a write after an `await` opens a new update. One case of [reactive-framework-test-suite](https://github.com/johnsoncodehk/reactive-framework-test-suite) expects a batch that throws to keep its writes, and Pinna fails it by design. ## Misuse is loud A mistake that can be detected throws, and the error says where the call belongs: `read(...) runs outside a place`, `write inside update`, `the box rejects this value`. An observable made with `{ name }` is named in its errors, and `inspect($x)` reports what a value read and why it last recomputed. Some mistakes are not caught: - **An observable used where any value passes.** TypeScript accepts any object in a condition and in a string conversion, so a forgotten `read` there compiles and runs. `if ($done)`, `$done && ...`, `!$done`, and `$name ?? ""` test the observable, which is always truthy. A template literal, `String($x)`, and `"total: " + $x` give `[object Object]`, and `JSON.stringify($x)` writes the observable's internals, its realm included. - **A kept `read` called inside another place.** It acts as that place's own `read` and tracks there. Binding each `read` to its place would cost a closure per run. - **A kept `write` called inside another realm.** Each realm's `read` and `write` throw for an observable of another realm, but a `write` kept from one realm's `update` still writes that realm while the update is open, even from a computed value of another realm. - **A value of another realm, stored.** A box, a collection, or a nested `make` keeps a model instance of another realm, because a stored value is data and storing it compares no realm. Reading its boxes in the holder's realm throws, at the read, not where the value was stored. - **An update of one realm inside another's.** A rollback of the outer update leaves the writes the inner one made to its own realm. - **A value changed in place through a cast.** A value is plain data, not a proxy, so the change is checked by no schema and seen by no watcher. - **A write that breaks a check on the class as a whole.** A write checks the box's own schema. A check on a `SchemaModel` as a whole runs when an instance is made, decoded, or written to a schema box, never on a write to one of its boxes. ## 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 what depends on it; a derived value checks its sources' versions, in read order, before it recomputes; watchers run after the write settles. An update that writes a value and then its old value back recomputes nothing. The cost of these guarantees together is speed. Every read is tracked, every write to a `schemaBox` or a `BoxField` is checked against its schema, and Pinna does not trade either away. Its budget for 1.0, measured on Hermes, is the public layer within 2× of alien-signals and the graph core within 1.6×. The measurements are in [performance.md](https://github.com/frondruntime/pinna/blob/main/docs/performance.md). That makes Pinna a library for domain state: models, forms, lists loaded from a server, totals derived from them, and the charts and canvases that draw them once a frame. Per-entity simulation state, such as particles or physics, stays in plain arrays and objects, and writes what the UI shows once a frame. ## Hermes first Pinna is measured where applications ship. A React Native app runs on Hermes, where memory is at a premium, so a change counts when Hermes confirms it, and a win measured only in Bun counts as a hint. Memory is measured as live bytes after a full collection. They stay flat after warm-up in every measured scenario — rows added and removed, a realm made and dropped per screen, rejected writes, undone updates — and nothing outlives dispose beyond the measuring harness's own 15 to 30 KB. The limit is the list of scenarios. A number holds for what was measured, on Hermes, and a workload outside that list is not covered by it. ## The synchronous counterpart to Effect Effect runs the programs; Pinna holds the state they read and write. Pinna started on Effect, and its models are still Effect Schema classes: one class decodes server data, checks every write to its fields, and encodes back. The realm is an Effect service, and `watchScoped`, `changes`, and `fromStream` turn watches, streams, and changes into programs that stop with their scope. State itself stays synchronous. A read returns a value, not a program, and an update finishes before it returns. The hooks read through `useSyncExternalStore`, which takes a synchronous value. The graph was later extracted from the Effect layer. `pinna-core` imports nothing at runtime, and `@frondruntime/pinna` has the same calls on boxes that take no schema, with no Effect. The cost sits in `pinna-effect`. A `SchemaModel` decodes only through `decode`, which provides the realm as a service: about 1.2 µs more per instance than a decode without one. And `SchemaModel` reads two internals of Effect's `Schema.Class`, as of `effect` 4.1.0, and throws if either is gone. ## Why not Effect's Atom Effect ships a reactive layer of its own, `Atom` in `effect/reactivity`, and it was the first base tried for Pinna. It was set aside for what it does on a write. This holds as of `effect` 4.1.0. - **An unbatched write shows a mixed state.** `Atom` recomputes dependents eagerly, one after another. With `b` and `c` derived from `a`, and `d` reading both, one write to `a` computes `d` twice: first from the new `b` and the old `c`, then from both new. `Atom.batch` rebuilds dependents once, after its callback, which avoids this when every write is wrapped in one. Pinna computes `d` once. The case is [bench/diamond.ts](https://github.com/frondruntime/pinna/blob/main/packages/pinna/bench/diamond.ts), and `bun run --cwd packages/pinna bench` prints both. - **A failed batch keeps its writes.** What a batch wrote before it threw stays written. A Pinna update is undone. - **A write is not checked.** `Atom` uses Schema to store and to serialize a value, not to check one on a write. `AtomRef` makes a ref for each property of a plain value, and a collection of refs, and neither takes a schema. There is no class decoded from server data whose fields are checked boxes. `Atom` is built for a different job: values that come from an Effect or a Stream, with their loading and failure states. For that it is the better choice, and it is first-party. Pinna holds synchronous domain state — models, their fields, the values derived from them — and both can live in one application. The cost is a second reactive layer beside the one Effect ships, owned by this project and not by Effect's maintainers. ## The decision Where a guarantee and speed conflict, the guarantee wins and the budget says by how much. No API is speculative: nothing is added that nobody asked for, so the surface an agent has to learn stays small, and what is added is complete. The rules an agent follows while writing code ship with the package, in [AGENTS.md](https://github.com/frondruntime/pinna/blob/main/packages/pinna/AGENTS.md). ## See also - [Start](./index.md): a realm, a box, a computed value, and an update. - [Coming from MobX](./mobx.md): the Pinna call for each MobX one. - [Errors and debugging](../guides/errors.md): what throws, and `inspect`. --- # Coming from MobX URL: https://pinna.frondruntime.dev/docs/start/mobx Description: Read when moving an app from MobX. Find the Pinna call for each MobX one, and the habits that do not carry over. ## Example A cart in MobX: an observable class, a getter, an action, a reaction, and an `observer` component. ```tsx import { makeAutoObservable, reaction } from "mobx"; import { observer } from "mobx-react-lite"; class CartStore { quantity = 1; price = 10; constructor() { makeAutoObservable(this); } get total() { return this.quantity * this.price; } add() { this.quantity += 1; } } const store = new CartStore(); reaction( () => store.total, (total) => console.log(`total: ${total}`), ); const StoreTotal = observer(function StoreTotal() { return ( ); }); ``` The same cart in Pinna. The fields that change are boxes, named with `$`. The getter is a computed value, the action a method that calls `update`, the reaction a `watch`. The component reads with `useValue` and needs no wrapper. The cart is a `Model` made from a realm, so a test or a screen can make one of its own. ```tsx import { box, computed, createRealm, Model, update, watch } from "@frondruntime/pinna"; import { useValue } from "@frondruntime/pinna-react"; class Cart extends Model { readonly $quantity = box(this.realm, 1); readonly $price = box(this.realm, 10); readonly $total = computed(this.realm, (read) => read(this.$quantity) * read(this.$price)); add(): void { update(this.realm, (read, write) => { write(this.$quantity, read(this.$quantity) + 1); }); } } const realm = createRealm(); const cart = new Cart(realm); watch( realm, (read) => read(cart.$total), (total) => { console.log(`total: ${total}`); }, ); function CartTotal() { const total = useValue(cart.$total); return ( ); } ``` ## Rules - Nothing is read by property access. `store.total` becomes `read(cart.$total)` in a place, or `useValue(cart.$total)` in a component. - Nothing is written by assignment. `store.quantity += 1` becomes `write(cart.$quantity, ...)` in an `update`. - There are no deep proxies. A box holds plain data, replaced whole or through `write.modify`. A keyed list is a collection, tracked row by row: see [Collections](../state/collections.md). - An update is synchronous and atomic. An update that throws is undone: every write before the throw in the same update is taken back. - There is no global state. Every observable belongs to the realm that made it, as with `configure({ isolateGlobalState: true })` for every store. - `watch` runs for changes, not for the current value. Where MobX would pass `fireImmediately`, call the effect once by hand. - `flow` has no counterpart: `await` outside, then one `update` per step. For cancellation, write the work as an Effect program. - An `autorun` writes through `update`, whose reads do not subscribe it. - `toJS` is not needed: values are plain data already. ## Answers | MobX | Pinna | | --- | --- | | `observable.box` | `box(realm, initial)` | | `makeAutoObservable`, `makeObservable`, `@observable` | `class X extends Model` with `$` fields made by `box(this.realm, ...)` and `computed(this.realm, ...)`; with Effect, `BoxField(schema)` in a `SchemaModel` | | `observable` arrays and objects | a `box` of plain data, written whole or through `write.modify` | | `ObservableMap` | `collection(realm, { keyOf })`, or a box of an array written through `reconcile`; with Effect, a `CollectionField` | | `computed`, a getter | `computed(realm, (read) => ...)` | | `computedFn` (mobx-utils) | `computedFunction` | | `action`, `runInAction` | `update(realm, (read, write) => ...)` | | `reaction(select, effect)` | `watch(realm, (read) => ..., effect)` | | `autorun` | `autorun(realm, (read) => ...)` | | `when`, a `reaction` with `delay` | a `watch`; with Effect, `changes($x)` and an Effect `Stream` | | `untracked` | `untracked(realm, (read) => ...)` | | `onBecomeObserved`, `onBecomeUnobserved` | `onObserved($x, start)`: `start` runs when `$x` gains its first observer and returns the cleanup, which runs when the last leaves; `onObserved` returns the function that removes the hook | | `computed({ keepAlive: true })` | `observe($x)`, released when done | | `createAtom` | `atom(realm)` | | `fromStream`, `fromResource` (mobx-utils) | `fromStream` from `pinna-effect` | | `trace`, `getDependencyTree` | `inspect($x)` | | `onReactionError` | `createRealm({ onError })` | | `observer(Component)` | `useValue($x)` for each value the component shows | | `useLocalObservable` | `useState(() => box(realm, ...))`, with the realm from `useRealm()` | ## With Effect An application on Effect Schema writes the store as a `SchemaModel`: its `$` fields are `BoxField(schema)`, every write is checked, and `decode` makes it from server data. This is the same cart, with the `watch` and the component as above. ```ts import { BoxField, computed, decode, SchemaModel, update, watch } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; class Cart extends SchemaModel("Cart")({ $quantity: BoxField(Schema.Int), $price: BoxField(Schema.Number), }) { readonly $total = computed(this.realm, (read) => read(this.$quantity) * read(this.$price)); add(): void { update(this.realm, (read, write) => { write(this.$quantity, read(this.$quantity) + 1); }); } } const cart = decode(realm, Cart)({ quantity: 1, price: 10 }); watch( realm, (read) => read(cart.$total), (total) => { console.log(`total: ${total}`); }, ); ``` ## See also - [Start](./index.md): a realm, a box, and a computed value. - [Updates](../state/updates.md): drafts and atomic updates. - [Classes](../effect/classes.md): `SchemaModel`, `BoxField`, and `decode`. - [Live data](../guides/live-data.md): a WebSocket feed and a fetch that refetches, with and without Effect, where MobX would use `flow`. --- # Boxes and computed URL: https://pinna.frondruntime.dev/docs/state/boxes Description: Read when declaring state. Make a box, derive a cached value from it, make a computed value per argument, and name or compare them. ## Example A box is observable state. Its name starts with `$`. ```ts import { box, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const $price = box(realm, 10, { name: "price" }); const $tags = box(realm, ["sale"], { name: "tags" }); ``` A write equal to the current value notifies nobody. A box compares with `Object.is`, so a new array or object counts as a change. `{ equals }` replaces the comparison. To check every write against a schema, use [Schema-checked boxes](../effect/boxes.md). ```ts import { box } from "@frondruntime/pinna"; // A write within a cent of the current value notifies nobody. const $total = box(realm, 0, { equals: (previous, next) => Math.abs(previous - next) < 0.01, }); ``` A computed value is derived from what its function reads. It recomputes only when one of those changes. ```ts import { computed } from "@frondruntime/pinna"; const $count = computed(realm, (read) => read($tags).length, { name: "count" }); // A computed value reads other computed values the same way. const $label = computed(realm, (read) => `${read($count)} tags at ${read($price)}`); ``` `computedFunction` makes a computed value per argument, for a value that depends on an argument. ```ts import { computedFunction } from "@frondruntime/pinna"; const hasTag = computedFunction(realm, (read, tag: string) => read($tags).includes(tag)); // While something observes hasTag("sale"), a call with "sale" returns that same // computed value; nothing observes this one, so a later call makes a new one. const $onSale = hasTag("sale"); ``` A model groups boxes, computed values, and the methods that write them. A class that extends `Model` checks nothing, takes its realm in the constructor, and gives field initializers `this.realm`. A write goes through a method that calls `update`. ```ts import { box, computed, Model, update } from "@frondruntime/pinna"; // A model groups boxes and the methods that write them. `Model` checks // nothing and gives field initializers `this.realm`. class Basket extends Model { readonly $quantity = box(this.realm, 1, { name: "quantity" }); readonly $unitPrice = box(this.realm, 10, { name: "unitPrice" }); readonly $total = computed(this.realm, (read) => read(this.$quantity) * read(this.$unitPrice)); add(count: number): void { update(this.realm, (read, write) => write(this.$quantity, read(this.$quantity) + count)); } } const basket = new Basket(realm); basket.add(2); ``` ## Rules - A box holds plain data: numbers, strings, arrays, and plain objects. Its type is the value's own, not made `readonly`, so a change in place type-checks and reaches no watcher. A box is written whole, so a finer-grained update is more boxes, or a [collection](./collections.md) of rows by key. - A computed value only reads. A write, a `watch`, an `autorun`, an `observe`, or a release throws while it computes. Its `equals` is part of the compute and never does any of them either. - A computed value that throws keeps the error and throws it to each read, until a source it read changes. - While observed, a computed value stays linked to what it read. Unobserved, it holds no links, and a read checks its sources first. - A `computedFunction` compares arguments by identity, one per position. While nothing observes an entry, it is dropped, and the next call makes a new one. - A model with no schema extends `Model`, from `@frondruntime/pinna`. With Effect, a model is a `SchemaModel`: see [Classes](../effect/classes.md). There is no third form, such as a function that returns boxes: a draft leaves an instance of either class read-only, and a plain object of boxes it would draft. - `{ name }` is for tools: `inspect` reports it, and a named computed value's errors name it. An empty name throws. ## Answers | Call | Answers | | --- | --- | | `box(realm, initial, { name?, equals? })` | A box. `equals` defaults to `Object.is`. | | `computed(realm, (read) => ..., { name?, equals? })` | A computed value. `equals` defaults to `Object.is`. | | `computedFunction(realm, (read, ...args) => ..., options?)` | A function from arguments to a computed value, shared while observed. | | `class X extends Model` | A model that checks nothing. `new X(realm)` makes one; field initializers read `this.realm`. | | `read($x)` | The value, inside a computed value, a computed function, a watch's select, an autorun, `useSelect`, an update, or `untracked`. An atom reads as `undefined`. | | `read.row($collection, key)` | The row under `key`, or `undefined`: see [Collections](./collections.md). | | `Read` | The type of `read`, for a function that takes it: `(read: Read) => ...`. | | `isTracking(realm)` | `true` while reads are tracked: in a computed value, a watch's select, or an autorun. `false` in an update, `untracked`, a watch's effect, and a hook. | ## Constructor inputs A model's field initializers run when `Model`'s constructor returns, before the subclass's own constructor sets its parameter properties. An initializer reads `this.realm`, which `Model` has set. A computed value's function runs on its first read, which comes after the constructor unless the constructor itself reads the value, so it reads a parameter property such as `this.title` too. What matters is where `this.title` is read. Inside a function, such as the computed value's own or an `equals` written in place, it is read when the function runs, after the constructor. As a value passed when the field is made, such as a computed value's `name`, a box's initial value, or an `equals` that is itself a parameter property, it is read at once. A field initializer that reads it there does not compile, with `TS2729: Property 'title' is used before its initialization`, and at run time it reads `undefined`. That field is declared with its type and made in the constructor body, after `super`, where the parameter is set. ```ts import { box, type Computed, computed, Model, type Realm } from "@frondruntime/pinna"; class Shelf extends Model { readonly $count = box(this.realm, 0); // An option is read as the computed value is made. A field initializer runs // before `title` is set, so this field is made in the constructor body. readonly $label: Computed; constructor( realm: Realm, readonly title: string, ) { super(realm); // The function runs on the first read, after the constructor, so a field // initializer's function may read `this.title` too. this.$label = computed(realm, (read) => `${this.title}: ${read(this.$count)}`, { name: `${title}.label`, }); } } const shelf = new Shelf(realm, "Books"); ``` ## See also - [Updates](./updates.md): writing boxes. - [Collections](./collections.md): rows by key, tracked row by row. - [Lifecycles](./lifecycles.md): what observing a value starts and keeps. - [Schema-checked boxes](../effect/boxes.md): a box that checks every write against a schema. - [Equality and hashing](../effect/equality.md): what a box of each kind counts as the same value. - [Classes](../effect/classes.md): boxes and computed values as fields of a model. --- # Updates URL: https://pinna.frondruntime.dev/docs/state/updates Description: Read when writing state. Write a box in an update, draft arrays and objects, keep unchanged items across a refetch, rely on an update being undone when it throws, read without subscribing, and hold back the writes of asynchronous work in a stage until it succeeds. ## Example A box has one way in: `update`, which hands out `read` and `write`. An array or a plain object is changed through a draft from `write.modify` — mutated inside the recipe, then written back once. The samples on this page and on [Reacting](./reacting.md) share this realm and box. ```ts import { box, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const $tags = box>(realm, []); ``` ```ts import { update } from "@frondruntime/pinna"; const addTag = (tag: string) => { update(realm, (_read, write) => { write.modify($tags, (tags) => { tags.push(tag); }); }); }; ``` An update is atomic. An update that throws is undone: every write before the throw in the same update is taken back. Watchers run once the update ends, so after a rollback they see the old state. ```ts import { box, update } from "@frondruntime/pinna"; const $quantity = box(realm, 1); const $note = box(realm, ""); const take = (amount: number) => { update(realm, (read, write) => { write($note, `took ${amount}`); const left = read($quantity) - amount; if (left < 0) throw new Error("not enough in stock"); // $note is undone too write($quantity, left); }); }; ``` A refetch hands back new objects for items that did not change. `reconcile` keeps the previous object of every item that did not change, so what derives one item from the list returns the same value and its readers do not rerun. ```ts import { box, reconcile, update } from "@frondruntime/pinna"; interface Rate { readonly currency: string; readonly rate: number; } const $rates = box>(realm, []); const receiveRates = (next: ReadonlyArray) => { update(realm, (read, write) => { // An unchanged rate keeps its previous object, so what derives one rate // from $rates returns the same value and its readers do not rerun. write( $rates, reconcile(read($rates), next, { keyOf: (rate) => rate.currency, equals: (previous, latest) => previous.rate === latest.rate, }), ); }); }; ``` An event handler wants the value as it is now, not a subscription. It reads through `untracked`. ```ts import { untracked } from "@frondruntime/pinna"; const onSave = () => { const tags = untracked(realm, (read) => read($tags)); console.log("saving", tags); }; ``` ## Rules - Never keep a `read` or a `write` past its place. Neither is bound to the place that handed it out: outside every place of its realm a `read` throws, outside every update a `write` throws, and inside some other place a kept `read` acts as that place's own. Pass `read` down as an argument instead. - Values are plain data. Change them with `write` or `write.modify`, never in place: a value is not a proxy, so a change made in place is seen by no watcher. - A box's value is a tree: every key holds its own value. An array or object a recipe assigns is copied on the first write through the draft, so the caller's object keeps its value, and an object assigned at two keys is two values once one of them is written. Refer to one object from two places by a key (`selectedId`), a collection row, or a box, never by holding it twice: the next `write.modify` drafts each key apart, so a write through one key does not show at the other. - A draft the recipe wrote and left at a second key, inside itself, or inside an object the recipe placed at two keys, throws `pinna: write.modify left an object it wrote under two keys`, and the update is undone. `draft.history.push(draft.present)` followed by `draft.present.count++` throws; a snapshot is read before the write, with `read($box).present`, which is the plain value. A draft at two keys that the recipe never wrote finalizes to the one object the box held. - An update is synchronous. A recipe that returns a promise throws at once and is undone, because a write after an `await` would land outside the update. Await first, then open a new update. - Nested updates join the outermost one. Watchers run once, when it ends, and see only its end state. - An update runs from an event, a watch's effect, or an autorun's body. It throws in a computed value, a watch's select, or a selector, which only read. - An effect that cannot be taken back, such as a request, a message, or a file write, runs after the update, never inside its recipe. An update that throws undoes its writes, not what the recipe did outside the realm: a request sent inside it has gone out, and a later throw, in the same update or in a caller's update it joined, leaves the server with what the realm no longer holds. See [Effects after the update](#effects-after-the-update). ## Answers | Call | Answers | | --- | --- | | `update(realm, (read, write) => ...)` | Runs the recipe atomically. If it throws, every box it wrote gets its old value back. | | `write($box, value)` | Replaces the value. | | `write.modify($box, (draft) => ...)` | Writes the drafted array or object back once. | | `Write` | The type of `write`, for a function an update hands it to. Each of its calls returns `undefined`, so a recipe can end in one. | | `reconcile(previous, next, { keyOf, equals })` | `next`, with each item `equals` finds unchanged replaced by its previous instance; `previous` itself when nothing changed. A key repeated in `next` throws. | | `untracked(realm, (read) => ...)` | What the function returns, read without subscribing. | | `openStage(realm, { name?, conflicts? })` | A new `Stage` over the realm, holding nothing. `conflicts: "fail"` makes `applyStage` refuse when what the stage read changed. | | `openStage(stage, { name? })` | A child stage over `stage`: a savepoint that applies into it. | | `stageUpdate(stage, (read, write) => ...)` | Runs the recipe at once against the stage and keeps it. No box changes. A recipe that throws puts back what it wrote to the stage and is not kept. | | `stageRead(stage, (read) => ...)` | What the function returns, reading through the stage: its own writes, and the realm's current values elsewhere. | | `realmRead(stage, (read) => ...)` | What the function returns, reading the realm's values as `untracked` does, ignoring the stage. These reads are not recorded for the conflict check. | | `applyStage(stage)` | Replays its recipes in order: over a realm, into a fresh overlay, then lands its final state in one update nested in an open one; over a stage, into that stage. A conflict or replay throw drops it; a precondition failure leaves it open. | | `dropStage(stage)` | Closes the stage and its open children, and discards them. No box changes. Does nothing to a closed stage. | | `stageStatus(stage)` | `"open"`, `"applied"`, or `"dropped"`. | | `inspectStage(stage)` | The stage's name, realm, parent, status, and conflict mode; the names of the boxes and collections it wrote; under `{ conflicts: "fail" }`, the names of what it read and `applyStage` checks; and how many recipes and open children it holds. | | `Recipe` | `(read, write) => undefined`: what `update` and `stageUpdate` run. | | `StageClosedError` | Thrown by `stageUpdate`, `stageRead`, `realmRead`, `applyStage`, or `openStage` of a child on a closed stage; `stage` is its name and `status` how it closed. | | `StageConflictError` | Thrown by `applyStage` on a conflict; `changed` names what changed, a named box or collection by its `name`, and `observables` holds it. | ## Effects after the update A watch runs once the outermost update ends, and only for a value that changed. An update that is undone restores every box it wrote, so a watch that reads only boxes does not run; a `write.changed` on an atom is not undone, and a watch that reads the atom runs. An effect that a watch runs from the state it sees is never ahead of the realm. In the sample, `addPair` joins two calls of `addToCart` in one update; when it throws, both writes are undone and nothing is sent, and when it succeeds, one request carries both items. ```ts import { box, update, watch } from "@frondruntime/pinna"; // `sendCart` is the application's request to the server. const $cart = box>(realm, []); // The request goes out from a watch: it runs after the outermost update ends, // and only when the cart changed, so an update that is undone sends nothing. const stopSending = watch( realm, (read) => read($cart), (cart) => { sendCart(cart); }, ); const addToCart = (item: string) => { update(realm, (_read, write) => { write.modify($cart, (cart) => { cart.push(item); }); // A request sent here would go out even when a caller's update throws // later and undoes this write. }); }; const addPair = (first: string, second: string) => { update(realm, () => { addToCart(first); if (second === "") throw new Error("a pair needs two items"); addToCart(second); }); }; ``` An effect that needs no state from the realm, such as closing a dialog, runs in the event handler after its `update` returns, and a throw leaves the handler before it. This holds only for the outermost update: code after an `update` that joined an outer one runs before the outer one ends, and the outer one can still throw. ## Stages A stage holds back the writes of asynchronous work until it succeeds: `applyStage` lands them in one update, and `dropStage` discards them. Until then no box changes, so nothing renders a half-done result and a failure leaves nothing to undo. An optimistic write, one meant to show before the work succeeds, stays a plain `update` that the application undoes by hand. ```ts import { box, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const $balance = box(realm, 100); const $status = box<"idle" | "sent">(realm, "idle"); ``` ```ts import { applyStage, dropStage, openStage, stageUpdate } from "@frondruntime/pinna"; const transfer = async (amount: number, send: (amount: number) => Promise) => { const stage = openStage(realm, { name: "transfer" }); try { stageUpdate(stage, (read, write) => { write($balance, read($balance) - amount); write($status, "sent"); }); // Until applyStage, $balance and $status keep their values and nothing reruns. await send(amount); applyStage(stage); } finally { // Does nothing once applied: a failure anywhere above leaves nothing behind. dropStage(stage); } }; ``` A read through the stage sees the stage's own writes everywhere: a box, a collection's `keys`, `rows`, `row`, and `read.row`, and a computed value, which the stage evaluates over its own values. A refetch stages `write.replaceAll` and decides on the result before anything shows. ```ts import { applyStage, collection, computed, dropStage, openStage, stageUpdate, } from "@frondruntime/pinna"; interface Line { readonly sku: string; readonly price: number; } const $lines = collection(realm, { keyOf: (line) => line.sku }); const $total = computed(realm, (read) => read($lines.rows).reduce((total, line) => total + line.price, 0), ); const refetch = async (load: () => Promise>) => { const stage = openStage(realm); try { const lines = await load(); stageUpdate(stage, (read, write) => { write.replaceAll($lines, lines); // The stage reads its own rows: $total here is the refetched total. if (read($total) > 1000) { write($status, "idle"); } }); applyStage(stage); } finally { dropStage(stage); } }; ``` `realmRead` reads what the realm holds, to compare it with the stage. ```ts import { realmRead, type Stage, stageRead } from "@frondruntime/pinna"; const pendingDebit = (stage: Stage): number => realmRead(stage, (read) => read($balance)) - stageRead(stage, (read) => read($balance)); ``` A function that hands back a change returns a `Recipe`, which `update` and `stageUpdate` both run. ```ts import { box, Model, type Recipe, update } from "@frondruntime/pinna"; class Cart extends Model { readonly $count = box(this.realm, 0); // A change handed back as a Recipe runs in an update or in a stage alike. add(amount: number): Recipe { return (read, write) => write(this.$count, read(this.$count) + amount); } } const cart = new Cart(realm); update(realm, cart.add(1)); ``` A recipe runs once when staged and once per `applyStage` along its path through parent stages to the realm. Row listeners run for each change on each run. Root replay runs in a fresh overlay over the realm's current values under the same recipe guard, then one update lands the final state without user code in its recipe. Anything it creates, an id, a time, a model, is made outside it and closed over, so all runs land the same thing. ```ts import { collection, type Stage, stageUpdate } from "@frondruntime/pinna"; const $orders = collection(realm, { keyOf: (order) => order.id, }); const placeOrder = (stage: Stage) => { // Made outside the recipe: the recipe runs again when the stage is applied, // and a new id or time there would land a different order than the one staged. const order = { id: crypto.randomUUID(), at: Date.now() }; stageUpdate(stage, (_read, write) => { write.upsert($orders, order); }); return order.id; }; ``` A child stage, opened over a stage, is a savepoint: applied, it replays into its parent; dropped, it leaves the parent as it was. ```ts import { applyStage, box, dropStage, openStage, stageUpdate } from "@frondruntime/pinna"; const $note = box(realm, undefined); const transferWithNote = async (amount: number, describe: () => Promise) => { const stage = openStage(realm); try { stageUpdate(stage, (read, write) => { write($balance, read($balance) - amount); }); // A child stage is a savepoint: dropped, it leaves the outer stage as it was. const section = openStage(stage); try { // A note that fails to load leaves the transfer to land without one. const note = await describe(); stageUpdate(section, (_read, write) => { write($note, note); }); applyStage(section); } catch { dropStage(section); } applyStage(stage); } finally { dropStage(stage); } }; ``` A stage opened with `{ conflicts: "fail" }` refuses to land when something it read changed in the realm since. ```ts import { applyStage, box, openStage, type Stage, StageConflictError, stageUpdate, } from "@frondruntime/pinna"; const $price = box(realm, 10); const checkout = (stage: Stage) => { stageUpdate(stage, (read, write) => { write($balance, read($balance) - read($price)); }); }; const land = (stage: Stage): boolean => { try { applyStage(stage); return true; } catch (error) { // Opened with { conflicts: "fail" }: $price changed since the stage read it. if (error instanceof StageConflictError) { return false; } throw error; } }; const priced = openStage(realm, { conflicts: "fail" }); checkout(priced); ``` A host that has its own update open lands the stage inside it, and records a failed replay in the same update. ```ts import { applyStage, box, type Stage, update } from "@frondruntime/pinna"; const $log = box>(realm, []); const landWithLog = (stage: Stage, entry: string) => { update(realm, (_read, write) => { write.modify($log, (log) => { log.push(entry); }); // Nested in this update: watchers see the log entry and the staged writes // once, together. A replay that throws undoes only the stage's writes. try { applyStage(stage); } catch { write.modify($log, (log) => { log.push(`${entry} failed`); }); } }); }; ``` ### Rules - Every call takes the stage first, as `update` takes the realm. The realm keeps no current stage, so `update` and `read` cost the same with stages in use. - A recipe is a function of its `read`. It runs once when staged and once per `applyStage` through its parents to the realm, over the destination's values at that moment, so an id, a time, or an observable it made would differ between runs. Inside a recipe, inside a `stageRead` function, and inside a computed value the stage evaluates, making a box, a computed value, a computed function, an atom, a collection, or a model throws, and so do `update` writing the realm, a `read` or a `write` kept from another place, `untracked`, `watch`, `autorun`, `observe`, `onObserved`, `onRowChange`, and every stage call. The guard covers the stage's own realm; `update(otherRealm, ...)` runs on every recipe run, and its writes survive `dropStage`. Pinna has no development mode, so these checks run in every build. - A read through a stage sees the stage's writes; what it did not write reads the realm's current value. It is not a snapshot: a box the stage did not write can change between two reads with an `await` between them. Once a stage writes a collection it holds that collection's rows and order, so the two agree. - A computed value read through a stage runs its own function against the stage's `read`, outside the graph: it starts no `onObserved` source, and a value nothing observes reads what its boxes hold. The result is cached on the stage until the stage, a parent stage, or the realm changes. - A stage writes boxes (`write`, `write.modify`), collections (`write.upsert`, `write.remove`, `write.replaceAll`), and atoms (`write.changed`, which reruns observers when the stage is applied). A collection write keeps a row equal to the one held, merges a refetched `SchemaModel` into the held instance, and runs `onRowChange` listeners with the stage's `read` and `write`, as in an update. - A schema box or a schema collection checks a staged write at `stageUpdate`, so the work learns of a refused value where it wrote it, and during each `applyStage`'s guarded replay. Landing skips the check already performed by that same box or collection. - `applyStage` replays over the realm's values when it runs. By default it does not detect a conflict: a stage that added 2 to a box at 1 lands 7 when another update moved the box to 5. With `{ conflicts: "fail" }` it throws a `StageConflictError` instead and lands nothing, when a box or collection the stage read, directly or through a computed value, changed since. A `write.modify` counts as a read of its box when its base comes from the realm, as `read` does. A box the stage wrote without reading is the last writer's. Reading two different versions of one box or collection conflicts even if a rollback restores the first version. - `applyStage` replays into a fresh overlay, then lands its final box values, collection rows and order, and atom marks in one update, nested in an update already open. Row listeners run during replay, once per change; landing does not call them again. A replay throw, including a refused write, discards the overlay without changing the realm and reaches the caller; the caller's update keeps its own writes if it catches it. Several stages in one update land in apply order. Final values equal to the realm's values change no version and notify nobody. If an enclosing update rolls back the landing, the stage reads `"dropped"`; stage the work again in a new stage. An empty journal stays `"applied"`, since it had no landing to undo. - A stage closes once, `"applied"` or `"dropped"`, and `stageStatus` says which. A conflict or a replay throw drops it. An `applyStage` precondition failure, such as an open child or a call inside a recipe or computed value, leaves it open. After closing, `stageStatus` and `inspectStage` remain callable outside a recipe; `dropStage` does nothing, so a `finally` drops whether or not the work applied. Every other stage call throws `StageClosedError`. A `read` or a `write` kept past its recipe throws. - Watch effects and autoruns settle after landing. Their errors go to `onError` and the stage stays `"applied"`. - A child stage reads through its parent. `applyStage` replays it into the parent as one `stageUpdate`, and a throw leaves the parent as it was. A parent with an open child does not apply; dropping the parent drops its children. - Staged values are not observable. Nothing subscribes to them, and `stageRead` and `realmRead` throw in a computed value, a watch's select, or a selector, which would go stale on them. `stageUpdate` and `applyStage` throw there as `update` does. - A stage left open holds its overlay until it is collected. A test realm's dispose reports it as `stage "name" still running`, and drops it ([Testing](../guides/testing.md)). `inspectStage` reports its name, parent, status, and what it holds. ## See also - [Boxes and computed](./boxes.md): declaring what an update writes. - [Reacting](./reacting.md): running code when a value changes. - [Schema-checked boxes](../effect/boxes.md): what a write checks when the box has a schema. - [Collections](./collections.md): `write.upsert`, `write.remove`, and `write.replaceAll`. - [Equality and hashing](../effect/equality.md): what `equals` and `reconcile` count as unchanged. - [Live data](../guides/live-data.md): a WebSocket feed and a refetch, written one update per message. --- # Collections URL: https://pinna.frondruntime.dev/docs/state/collections Description: Read when state holds rows by key. Make a keyed collection, add and remove rows, read one row, render one row per key, and write a refetch without rerunning what did not change. ## 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. A key's box is made on the first read of `row(key)` and kept while the key is present, so rows nobody reads alone cost no box. `collection` makes an empty one with no schema; `undefined` rows are rejected. ```tsx import { collection, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); interface Order { readonly id: string; readonly total: number; } const $orders = collection(realm, { keyOf: (order: Order) => order.id, // A refetch builds new objects; an order with the same total is kept. equals: (previous, next) => previous.total === next.total, }); ``` A collection is written inside an update, with `write.upsert` and `write.remove`. ```tsx import { update } from "@frondruntime/pinna"; const addOrder = (order: Order) => { update(realm, (_read, write) => { // Replaces the order under its id, or adds it last. write.upsert($orders, order, { at: "end" }); }); }; const removeOrder = (id: string) => { update(realm, (_read, write) => { write.remove($orders, id); // a missing id changes nothing }); }; ``` `row(key)` tracks that key alone. A write to another row, or a new key, reruns nothing here. ```tsx import { watch } from "@frondruntime/pinna"; // Reruns only when the order under "7" changes, is added, or is removed. const stopRow = watch( realm, (read) => read($orders.row("7"))?.total, (total) => { console.log(total); }, ); ``` Where nothing tracks (an update's recipe, `untracked`, a watch's effect), `read.row($items, key)` reads the row the collection holds and makes no box, so a lookup leaves nothing behind. In a tracked place it is `read($items.row(key))`. ```tsx import { update } from "@frondruntime/pinna"; // Takes 10% off each order under `ids`. A recipe tracks nothing, so // `read.row` makes no box for the orders it looks up. const discountOrders = (ids: ReadonlyArray) => { update(realm, (read, write) => { for (const id of ids) { const order = read.row($orders, id); if (order !== undefined) { write.upsert($orders, { ...order, total: order.total * 0.9 }); } } }); }; ``` `keys` changes only when a key is added, removed, or moved. `rows` changes when any row or the order changes. ```tsx import { computed } from "@frondruntime/pinna"; // Recomputes when an order is added, removed, or moved. const $count = computed(realm, (read) => read($orders.keys).length); // Recomputes when any order or the order of the keys changes. const $sum = computed(realm, (read) => read($orders.rows).reduce((sum, order) => sum + order.total, 0), ); ``` A list component reads `keys` and hands each row its key, so a change to one row rerenders that row alone. ```tsx import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; // Rerenders when an order is added, removed, or moved; never for an order's own change. function OrderList() { const ids = useValue($orders.keys); return (
    {ids.map((id) => ( ))}
); } // Rerenders when the order under its id changes. const OrderRow = memo(function OrderRow({ id }: { readonly id: string }) { const order = useValue($orders.row(id)); return order === undefined ? null : (
  • {order.id}: {order.total}
  • ); }); ``` A refetch writes every row at once with `write.replaceAll`. A row that `equals` finds unchanged is kept, and what read it does not rerun. ```tsx import { update } from "@frondruntime/pinna"; const receiveOrders = (orders: ReadonlyArray) => { update(realm, (_read, write) => { // The rows become `orders`, in their order. An order that `equals` finds // unchanged is kept: what read its row does not rerun. write.replaceAll($orders, orders); }); }; ``` A value kept a row at a time, such as a sum or an index by another key, listens with `onRowChange`. The listener runs inside the update that wrote the row, with that update's `read` and `write`, so what it writes takes effect and rolls back with the row. ```tsx import { box, onRowChange } from "@frondruntime/pinna"; // The sum of every total, kept a row at a time: each write adds what it // changed, instead of a reduce over every order. It takes effect and rolls back // with the write that changed the row. The listener first hears each order // already held, as added, so the sum starts from them. const $runningSum = box(realm, 0); const stopRunningSum = onRowChange($orders, (change, read, write) => { const added = (change.after?.total ?? 0) - (change.before?.total ?? 0); write($runningSum, read($runningSum) + added); }); ``` ## Rules - A collection is written with `write.upsert`, `write.remove`, and `write.replaceAll`, inside an update. An update that throws puts back the keys and every row, as it does a box. - `write.upsert` and `write.replaceAll` reject an `undefined` row with `pinna: a collection row cannot be undefined`, before changing any row. `row(key)` and `read.row` return `undefined` for a missing key, so a present row cannot use that value. The rule also applies to schema collections, even when the schema accepts `undefined`. - `upsert` replaces a held key's row in place and puts a new key first, or last with `{ at: "end" }`. `remove` of a missing key changes nothing. - Adding or removing a key copies the key order, so its cost grows with the collection: about 15 µs at 1,000 rows and 120 µs at 10,000 on Hermes. Replacing the row of a held key costs the same at any size. The order is one immutable array, so a failed update puts back the old one and `keys` answers the same array until a key changes. Many new rows go in through one `write.replaceAll`, which copies once; an `upsert` per row copies once per row, even inside one update. - A row written under a held key is compared with `equals`, `Object.is` without one. A refetch builds new objects, so without `equals` it reruns the readers of every row. - A key that appears twice in `replaceAll` throws `pinna: the collection key appears twice`, and nothing is written. - A list that renders one row per key reads `keys` and `row(key)`. `rows` reruns its reader when any row or the order changes. - `keys` is observed while something reads `keys` or `rows`, or reads `row(key)` for a missing key. `row(key)` of a present key tracks that row alone, so a hook on `keys` misses a reader of one row. A feed that writes the rows only while any of them is read hangs on a private atom that every public reader reads ([Live data](../guides/live-data.md)); a feed for a list alone starts and stops with `keys`, through `onObserved` or, with Effect, `whileObserved`. - `row(key)` returns the same computed value for a present key on every call; for a missing key, only while something observes it. - A lookup where nothing tracks reads through `read.row($items, key)`. `read($items.row(key))` there makes the key's computed value and box, and the collection keeps both until the key is removed. - `read.row` outside every place of its realm throws, as `read` does. - `onRowChange` reports each row `upsert`, `remove`, or `replaceAll` adds, replaces, or removes, `replaceAll` a row at a time, with the row `before` and `after` the write; one is `undefined` for an add or a removal. A write that keeps a row reports nothing. - A listener first hears each row the collection holds, in key order, as added, so what it keeps starts in step with the rows. A throw there adds no listener and reaches the caller of `onRowChange`. If settling watchers throws after replay commits, the listener is removed and the replay's writes stay committed: the caller received no function to remove it. - A listener writes other boxes and collections. A write to the collection it listens to throws, and so does a listener that returns a value: it is synchronous. A listener that throws fails the write, which is put back. - What a listener keeps rolls back when it lives in boxes. A plain `Map` of values the listener fills is not put back when the write fails; a `Map` of boxes is, since it holds the boxes and the boxes are put back. - A listener sees rows the collection replaces, never a write to a box inside a row: a `SchemaModel` row whose box fields alone change is merged in place and reports nothing. A sum over a `BoxField` is a `computed`. - `replaceAll` writes every row, then reports them a row at a time, so a listener that reads the collection sees rows ahead of their reports. - An index by another key deletes an entry only while it still names `change.key`: two rows that swap values report one at a time, and the second report would otherwise delete the first one's new entry. - Each `onRowChange` replays the held rows to its listener, so a host adds a listener once, beside the boxes it fills. A listener added again, as a React effect in strict mode is after its cleanup, counts each row twice unless the host resets its boxes first. - The function `onRowChange` returns removes the listener for good: an update that fails after calling it does not add it back, as with `watch`. - `onRowChange` in a computed value or a watch's select throws, as `update` does there. - A list written one row at a time is a collection. A box of an array is written whole, and every write reruns every reader of the box. A list written whole on each refetch can stay a box written through `reconcile`: see [Updates](./updates.md). ## Answers | Call | Answers | | --- | --- | | `collection(realm, { keyOf, equals?, name? })` | An empty collection with no schema; `undefined` rows are rejected. `equals` defaults to `Object.is`. `name` names its `keys` (`.keys`) and `rows` (`.rows`) for `inspect` and errors, and the collection in a stage's conflict error and `inspectStage`. | | `$items.row(key)` | A computed value of that row, or `undefined`. | | `read.row($items, key)` | That row, or `undefined`: tracked as `read($items.row(key))` in a tracked place, and read without making a box where nothing tracks. | | `$items.keys`, `$items.rows` | Computed values of the keys, and of every row, in order. | | `write.upsert($items, row, { at? })` | Replaces the row under its key, or adds it first, or last with `{ at: "end" }`. | | `write.remove($items, key)` | Removes the row under `key`. | | `write.replaceAll($items, rows)` | Makes `rows` the collection's rows, in their order, keeping each one that is unchanged. | | `onRowChange($items, (change, read, write) => ...)` | Calls the listener for each row a write adds, replaces, or removes, inside that write's update; `change` holds `key`, `before`, and `after`. Returns the function that removes the listener. | ## Row selection The selected key is one box beside the collection, and each row reads a flag of its own from a `computedFunction`. Moving the selection from one row to another changes two flags, so it rerenders the row that lost the selection and the row that gained it, and a first selection changes one; every other row's flag recomputes to the same `false`, and its row does not render. ```tsx import { box, computedFunction, update } from "@frondruntime/pinna"; import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; const $selected = box(realm, undefined); // A flag per id. A row reads its own flag, so a new selection rerenders the // row that lost it and the row that gained it. The flag of an id is dropped // once no mounted row reads it. const isSelected = computedFunction(realm, (read, id: string) => read($selected) === id); const select = (id: string) => { update(realm, (_read, write) => { write($selected, id); }); }; const SelectableRow = memo(function SelectableRow({ id }: { readonly id: string }) { const order = useValue($orders.row(id)); const selected = useValue(isSelected(id)); return order === undefined ? null : (
  • ); }); ``` The flag and the row's own computed value live for different spans. - A flag from `isSelected(id)` lives while something observes it. Once the last row that reads it unmounts, it is dropped, and the next call makes a new one, so a list that mounts and unmounts rows keeps no flag for a row off screen. - `$orders.row(id)` returns the same computed value while the key is held, whether a row reads it or not, and the collection keeps the key's box until the key is removed. ## Sorted rows Rows in sorted order sit in one box, and `onRowChange` places each change by binary search. A `computed` that sorts `rows` sorts every row on each change. `$orders` and `Order` are the ones from [Indexes and sets](../guides/row-indexes.md). ```ts import { box, computed, onRowChange } from "@frondruntime/pinna"; // Largest first; the id breaks a tie, so every order has one place. const compareByAmount = (a: Order, b: Order): number => b.cents - a.cents || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); // The first index whose order sorts at or after `order`. const placeOf = (orders: ReadonlyArray, order: Order): number => { let low = 0; let high = orders.length; while (low < high) { const middle = (low + high) >>> 1; const held = orders[middle]; if (held !== undefined && compareByAmount(held, order) < 0) { low = middle + 1; } else { high = middle; } } return low; }; // Each change finds its place by binary search, instead of a sort of every // order. The box holds the rows as they were reported: `before` is found by // the amount it was sorted under. const $byAmount = box>(realm, []); const stopByAmount = onRowChange($orders, ({ before, after }, read, write) => { const orders = [...read($byAmount)]; if (before !== undefined) { orders.splice(placeOf(orders, before), 1); } if (after !== undefined) { orders.splice(placeOf(orders, after), 0, after); } write($byAmount, orders); }); // The ten largest orders. A change below the tenth leaves the same ten rows, // and `equals` keeps what reads them from rerunning. const $largest = computed(realm, (read) => read($byAmount).slice(0, 10), { equals: (previous, next) => previous.length === next.length && previous.every((order, index) => order === next[index]), }); ``` - Give the order a tie-breaker, such as the key. Binary search then finds one place for each row, and removing `before` removes that row and not another with the same amount. - Find `before` by the value it was reported with, never by reading the collection: `replaceAll` writes every row before its first report. The box holds the rows as reported for this reason. - Each change copies the sorted array. A `replaceAll` that adds n rows reports n adds, so filling the box from empty copies O(n²) rows. Where that cost shows, a persistent balanced tree in the box copies one path, O(log n), per change. ## See also - [Updates](./updates.md): the update every write runs in, and `reconcile`. - [Indexes and sets](../guides/row-indexes.md): a set of keys, an index by another key, and a sum per group, kept with `onRowChange`. - [Hooks](../react/hooks.md): every way a component reads. - [Collection fields](../effect/collections.md): a collection as a field of a `SchemaModel`, each row checked against a schema. - [Equality and hashing](../effect/equality.md): what `equals` counts as an unchanged row. --- # Reacting URL: https://pinna.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 The samples on this page use the realm and the box `$tags` of [Updates](./updates.md). ```ts import { box, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const $tags = box>(realm, []); ``` `watch` runs its effect when the select's result changes, not on the first run. The effect gets the value and the one before it. ```ts import { watch } from "@frondruntime/pinna"; const stop = watch( realm, (read) => read($tags).length, (count, previous) => { console.log(`${previous} → ${count} tags`); }, ); ``` `autorun` runs at once, and again when what its last run read changes. ```ts import { autorun } from "@frondruntime/pinna"; const stopTitle = autorun(realm, (read) => { document.title = `${read($tags).length} tags`; }); ``` A function an autorun returns is its cleanup. ```ts import { autorun, box, update } from "@frondruntime/pinna"; const $editing = box(realm, false); const stopEscape = autorun(realm, (read) => { if (!read($editing)) return undefined; const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") { update(realm, (_read, write) => write($editing, false)); } }; window.addEventListener("keydown", onKey); // Runs before the next run, and when the autorun stops. return () => window.removeEventListener("keydown", onKey); }); ``` An autorun's body may call `update`. The recipe runs untracked, so its reads of what it writes do not subscribe the autorun. ```ts import { autorun, box, update } from "@frondruntime/pinna"; const $selected = box(realm, 0); // Keeps the selection inside the list as it shrinks. const stopClamp = autorun(realm, (read) => { const last = Math.max(read($tags).length - 1, 0); update(realm, (read, write) => { if (read($selected) > last) { write($selected, last); } }); }); ``` ## Rules - Prefer a computed value to an autorun that writes a box: derived state is computed, not copied. - A watch's select only reads: an update there throws. Its effect runs untracked and writes through `update`. - An autorun that writes what it read runs again, until what it read stops changing. One that never settles stops after 100 rounds, and `pinna: watchers did not settle after 100 rounds` goes to `onError`. - A watch's effect returns `undefined`, so an async function does not type-check. The refusal is in the types only: at run time the returned promise is dropped, and its rejection is unhandled, reaching neither the caller nor `onError`. Start async work from the effect and handle its errors there. - An error from the first run of either is thrown to the caller, and nothing is watched. A later one goes to the realm's `onError`. - Both return a stop function. Stopping twice does nothing, and once stopped, the effect never runs again. - In React, read with the hooks instead: [Hooks](../react/hooks.md). ## Answers | Call | Answers | | --- | --- | | `watch(realm, (read) => ..., (value, previous) => ..., { name?, equals? })` | The stop function. `equals` decides what counts as a change; `Object.is` by default. | | `autorun(realm, (read) => ...)` | The stop function. | ## See also - [Updates](./updates.md): writing from an effect. - [Lifecycles](./lifecycles.md): what a watch or an autorun holds observed. - [Programs](../effect/programs.md): `watchScoped` and `changes` as Effect programs. - [Live data](../guides/live-data.md): a watch that refetches when its input changes. --- # Lifecycles URL: https://pinna.frondruntime.dev/docs/state/lifecycles Description: Read when state comes from outside Pinna. Start a listener when a value gains its first observer and stop it after the last, stand for outside state with an atom, and hold a value observed. ## Example An observable is observed while something holds it: a watch, an autorun, a mounted `useValue`, `observe`, or an observed computed value that read it. `onObserved` runs on the first observer, and its cleanup after the last. ```ts import { box, createRealm, onObserved, update } from "@frondruntime/pinna"; const realm = createRealm(); const $online = box(realm, true); // Listens to the browser only while something observes $online. onObserved($online, () => { const sync = () => { update(realm, (_read, write) => write($online, navigator.onLine)); }; sync(); // the value may have changed while no one listened window.addEventListener("online", sync); window.addEventListener("offline", sync); return () => { window.removeEventListener("online", sync); window.removeEventListener("offline", sync); }; }); ``` An atom stands for state kept outside Pinna. `read($atom)` subscribes; `write.changed($atom)`, inside an update, reruns what observed it. ```ts import { atom, computed, onObserved, update } from "@frondruntime/pinna"; // The clock is state kept outside Pinna: the atom stands for it. const $clock = atom(realm); onObserved($clock, () => { const timer = setInterval(() => { update(realm, (_read, write) => write.changed($clock)); }, 1000); return () => clearInterval(timer); }); const $time = computed(realm, (read) => { read($clock); return new Date().toLocaleTimeString(); }); ``` `observe` holds a value observed with nothing rendered. ```ts import { observe } from "@frondruntime/pinna"; // The clock ticks, and $time stays cached, until release runs. const release = observe($time); ``` ## Rules - A hook may write, in an update. It runs once every link of the call that observed is in place, before that call returns. Inside an update, hooks start and stop once the recipe returns, never in the middle of it. - An observer holds what it read until it stops: a watch or an autorun until its stop function runs or its next run stops reading the value, `observe` until its release runs, `useValue` and `useValues` until the component unmounts, `watchScoped`, `observeScoped`, and `changes` until the scope closes or the stream stops, and an observed computed value until it is no longer observed or a recompute stops reading the value. `untracked` and an update read without observing. - A source lost and gained within one call or one update fires nothing, so a watcher that swaps its sources does not restart a subscription. - A hook's error, or its cleanup's, goes to the realm's `onError`, never to the caller. The caller always gets its release. - Nothing reports what outside state did while no one observed it, so a hook syncs the state when it starts, as `sync()` does above. - An atom nothing observes counts as changed on every check. A computed value that reads such an atom recomputes on every read; observed, it recomputes only after `write.changed`. ## Answers | Call | Answers | | --- | --- | | `onObserved($x, () => cleanup)` | The function that removes the hook. The function passed in returns the cleanup. | | `atom(realm)` | An atom. `read($atom)` returns `undefined`. | | `write.changed($atom)` | Reruns what observed the atom. | | `observe($x)` | A release. Until it runs, `$x`'s hooks stay started and a computed value stays cached. | ## See also - [Reacting](./reacting.md): watches and autoruns. - [Programs](../effect/programs.md): `fromStream`, a value fed by a stream while observed. - [Live data](../guides/live-data.md): a WebSocket opened while something observes the feed. --- # Hooks URL: https://pinna.frondruntime.dev/docs/react/hooks Description: Read when showing state in React. Pick between useValue, useValues, and useSelect, read in a handler, give a component its own box, render a model from pinna-effect, and defer a slow render after a write. ## Example The samples on this page share one realm and these boxes. ```tsx import { box, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const $first = box(realm, "Ada"); const $last = box(realm, "Lovelace"); const $starred = box>(realm, []); const $query = box(realm, ""); const names: ReadonlyArray = ["Ada", "Grace", "Barbara"]; ``` `useValue` reads one observable. Under `memo`, the component rerenders only when that value changes. ```tsx import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; const FirstName = memo(function FirstName() { const first = useValue($first); return {first}; }); ``` `useValues` reads several, as a typed array. ```tsx import { useValues } from "@frondruntime/pinna-react"; function FullName() { const [first, last] = useValues([$first, $last]); return ( {first} {last} ); } ``` `useSelect` runs view logic over observables, in the realm of the nearest `RealmProvider`. ```tsx import { useSelect } from "@frondruntime/pinna-react"; function Star({ id }: { readonly id: string }) { const starred = useSelect((read) => read($starred).includes(id)); return {starred ? "★" : "☆"}; } ``` A component's own state is a box in the provider's realm. ```tsx import { box, update } from "@frondruntime/pinna"; import { useRealm, useValue } from "@frondruntime/pinna-react"; import { useState } from "react"; function Draft() { const local = useRealm(); const [$text] = useState(() => box(local, "")); const text = useValue($text); const onChange = (value: string) => { update(local, (_read, write) => { write($text, value); }); }; return onChange(event.target.value)} />; } ``` An event handler reads through `untracked` and writes through `update`. ```tsx import { untracked } from "@frondruntime/pinna"; function SaveButton() { // A handler reads without subscribing; the component does not rerender for it. const onClick = () => { const first = untracked(realm, (read) => read($first)); console.log("saving", first); }; return ( ); } ``` `RealmProvider` gives the components under it a realm. Only `useSelect` and `useRealm` need it: `useValue` and `useValues` read the realm of the observables they are handed. ```tsx import { RealmProvider } from "@frondruntime/pinna-react"; function App() { return ( ); } ``` ## Rules - There is no `observer` wrapper. The hooks work with the React Compiler as they are. - A read in a render body does not type-check: render has no `read`. The hooks are the only way in. - Prefer `useValue` and `useValues`. `useSelect` costs a layout effect per render; a value several components need is a computed value on the model. - `useValues` compares the input array's elements on each render and keeps its own copy when they change. Replacing or removing an observable in the same input array takes effect on the next render, so reads and the subscription follow the same observables. - To rerender less, move the read into a small component under `memo`. For control flow, use plain JSX. `memo` skips a render only when every prop is the same as before, so the parent passes values it does not rebuild each render. See [Render scopes](#render-scopes). - A list of a collection reads `keys` and hands each row its key. Reading `rows` rerenders the whole list when any row changes. - In an event handler, read inside `untracked` and write through a method that calls `update`. - A slow render after a write reads a deferred value: `useDeferredValue(useValue($x))`. A `startTransition` around the write changes nothing, since 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. | | `` | Gives the components under it a realm. | | `useRealm()` | The nearest provider's realm. Throws without a provider. | ## Transitions A write renders at once, at full priority, even inside `startTransition`. The hooks read through `useSyncExternalStore`, and React renders a change of an outside store as a blocking update. A slow part of the page reads the value through `useDeferredValue` instead: the input renders the new value first, and the results render it after, in a render React can interrupt. Under `memo`, the results skip the first render, which still passes them the old value. ```tsx import { update } from "@frondruntime/pinna"; import { useValue } from "@frondruntime/pinna-react"; import { memo, useDeferredValue } from "react"; // Under `memo`, the results skip the urgent render, which still passes them the old `query`. const Results = memo(function Results({ query }: { readonly query: string }) { const found = names.filter((name) => name.includes(query)); return (
      {found.map((name) => (
    • {name}
    • ))}
    ); }); function Search() { const query = useValue($query); const deferred = useDeferredValue(query); const onChange = (value: string) => { update(realm, (_read, write) => { write($query, value); }); }; return ( <> onChange(event.target.value)} /> ); } ``` The same holds under `Suspense`. A write that makes a component suspend shows the nearest fallback in place of the content on screen. A component that suspends on a deferred value keeps the content on screen until the next one loads. Under ``, the hooks unsubscribe: an `onObserved` hook stops, and a write renders nothing there. Shown again, the component subscribes and renders the current value. ## Render scopes A component rerenders when a value it reads through a hook changes, and, under `memo`, when a prop is not `Object.is` the one it had. - A value that changes often, such as a status line, is read by a small component of its own. Read in the list's component, it rerenders the list on every change of status. - The props a parent passes are the same values from render to render: an observable, a key, or data made once. An array built in the render, such as `names.filter(...)`, or an object or function written inline, is new each time, and `memo` renders the child anyway. ```tsx import { box } from "@frondruntime/pinna"; import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; const $saving = box(realm, false); // Reads $saving alone: a change of status rerenders this line, not the list. const SavingStatus = memo(function SavingStatus() { const saving = useValue($saving); return

    {saving ? "Saving…" : "Saved"}

    ; }); const NameList = memo(function NameList({ names }: { readonly names: ReadonlyArray }) { return (
      {names.map((name) => (
    • {name}
    • ))}
    ); }); // `names` is made once, in module code, so NameList gets the same array on // every render and `memo` skips it. `names.filter(...)` here would hand it a // new array each time. function Panel() { return ( <> ); } ``` - A computed value that builds the object a component shows returns a new object on each recompute, and `useValue` compares with `Object.is`, so a change to any field the computed value reads renders the component, shown or not. Its `equals` compares the fields the screen shows and leaves out the rest, such as the time a quote arrived; a recompute that `equals` finds unchanged keeps the previous object, and nothing renders. ```tsx import { box, computed } from "@frondruntime/pinna"; import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; interface Quote { readonly symbol: string; readonly price: number; readonly receivedAt: number; } const $quote = box(realm, { symbol: "ACME", price: 10, receivedAt: 0 }); // What the card shows. Each recompute builds a new object, so `equals` // compares the shown fields: a tick that changes only `receivedAt` keeps the // previous object, and the card does not rerender. const $quoteCard = computed( realm, (read) => { const quote = read($quote); return { symbol: quote.symbol, price: quote.price.toFixed(2) }; }, { equals: (previous, next) => previous.symbol === next.symbol && previous.price === next.price }, ); const QuoteCard = memo(function QuoteCard() { const card = useValue($quoteCard); return (

    {card.symbol} {card.price}

    ); }); ``` ## With Effect A model from `pinna-effect` is read the same way, with the same hooks. A list reads a collection's `keys`, and each row reads its own `row(key)`. Toggling one todo rerenders one `TodoLabel`. The `TodoList` is the one from [Collection fields](../effect/collections.md). ```tsx import { useValue } from "@frondruntime/pinna-react"; import { memo } from "react"; import type { Todo, TodoList } from "./models.ts"; // Rerenders when a key is added, removed, or moved; never for a row's own change. function TodoRows({ list }: { readonly list: TodoList }) { const ids = useValue(list.$items.keys); return (
      {ids.map((id) => ( ))}
    ); } // Rerenders when the row under its key is replaced. const TodoRow = memo(function TodoRow({ list, id, }: { readonly list: TodoList; readonly id: string; }) { const todo = useValue(list.$items.row(id)); return todo === undefined ? null : ; }); // Rerenders when its own label changes. const TodoLabel = memo(function TodoLabel({ todo }: { readonly todo: Todo }) { const label = useValue(todo.$label); return (
  • ); }); ``` ## See also - [Start](../start/index.md): a counter from box to button. - [Classes](../effect/classes.md): the models these components read. - [Collections](../state/collections.md): `keys` and `row(key)`, and a list that rerenders one row. - [Testing](../guides/testing.md): a realm per test, for the models a component reads. --- # Schema-checked boxes URL: https://pinna.frondruntime.dev/docs/effect/boxes Description: Read when an app already uses Effect. Import the core's calls from pinna-effect, make a box that checks an Effect Schema on every write, and know what a schema adds to a write. The Effect pages are for applications that already use Effect. `@frondruntime/pinna-effect` has the same calls as `@frondruntime/pinna`, on Effect Schema, and `effect` is its peer dependency. It adds what the core lacks: boxes that check a schema on every write, models as [classes](./classes.md) decoded from the wire, with boxes and [collections](./collections.md) as fields, and [programs](./programs.md) that run with a scope. An application without Effect needs none of it: start at [Start](../start/index.md). ## Example `schemaBox` takes a schema before the initial value. The other calls, and the hooks of `@frondruntime/pinna-react`, are the core's. ```ts import { createRealm, schemaBox } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); const $price = schemaBox(realm, Schema.Number, 10, { name: "price" }); const $tags = schemaBox(realm, Schema.Array(Schema.String), [], { name: "tags" }); ``` A write equal to the current value notifies nobody. A box compares with its schema's equivalence, so an equal array or object counts as unchanged. ```ts import { update } from "@frondruntime/pinna-effect"; const tagSale = () => { update(realm, (_read, write) => { // A new array each time, equal under the schema after the first: // the second call notifies nobody. write($tags, ["sale"]); }); }; ``` A write the schema rejects throws from the update, and every write before it in the same update is undone. ```ts import { schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const $quantity = schemaBox(realm, Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), 1); const $note = schemaBox(realm, Schema.String, ""); const take = (amount: number) => { update(realm, (read, write) => { write($note, `took ${amount}`); write($quantity, read($quantity) - amount); // throws below zero, and $note is undone too }); }; ``` `write.modify` drafts an array or a plain object, then writes it back once, checked against the schema. ```ts import { update } from "@frondruntime/pinna-effect"; const addTag = (tag: string) => { update(realm, (_read, write) => { // The drafted array is checked against the schema once, when the recipe ends. write.modify($tags, (tags) => { tags.push(tag); }); }); }; ``` ## Rules - `pinna-effect` re-exports every name of `pinna` as it is. Its `box` and `collection` check nothing and compare with `Object.is` unless given `{ equals }`, and its `reconcile` checks nothing and takes the `equals` it is given. The names it adds say they use a schema: `schemaBox`, `SchemaModel` with `BoxField` and `CollectionField`, and `reconcileSchema`. An application imports from one package. - `box` given a schema throws and names `schemaBox`, so a box meant to check a schema never silently checks nothing. - A box of a plain `Schema.Array(element)` checks only the elements a write put there: a push onto 10,000 rows checks one. 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 `schemaBox` compares with its schema's equivalence unless `{ equals }` says otherwise. What each schema counts as equal is on [Equality and hashing](./equality.md). - `schemaBox` throws when `initial` does not fit the schema. - A value the schema accepts is plain data, `readonly` in the types. A value changed in place is checked by no schema. ## Answers | Call | Answers | | --- | --- | | `schemaBox(realm, schema, initial, { name?, equals? })` | A box of the values `schema` accepts. Throws when `initial` does not fit. | | `write($box, value)` | Replaces the value, checked against the schema. | | `write.modify($box, (draft) => ...)` | Writes the drafted array or object back once, checked. | ## Checks and rules A check runs when a value is written, on that value alone, and never again (a write of the value the box holds runs none): a read, a recompute, or a change elsewhere does not run it. So a check holds only what the value itself decides. - Terms that must agree, such as the two dates of a stay, are one schema value with one check. A `BoxField`'s check sees its own value and no sibling field, and a check on the `SchemaModel` as a whole runs when an instance is made, decoded, or written to a schema box, never when a box of the instance changes. A filter made with `Schema.makeFilter` that returns a string fails with that string as its message: see [Errors](../guides/errors.md#fields-a-schema-refuses). ```ts import { BoxField, decode, SchemaModel } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; // Both dates are one value, so one check sees them together. const Stay = Schema.Struct({ checkIn: Schema.String, checkOut: Schema.String }).check( Schema.makeFilter((stay) => stay.checkIn < stay.checkOut || "Check out after checking in"), ); class Booking extends SchemaModel("Booking")({ id: Schema.String, // As two fields, $checkIn and $checkOut, each check would see its own // date alone, and a write to one would never see the other. $stay: BoxField(Stay), }) {} const booking = decode( realm, Booking, )({ id: "b1", stay: { checkIn: "2026-05-01", checkOut: "2026-05-03" }, }); ``` - A rule that depends on time, such as a date that must be after today, or on another box's value, is no check of the box: the value it judged would stay in the box after today moves past it. It is checked where the input is accepted, in the update that writes it, and what it allows from then on is a computed value that follows both. ```ts import { box, computed, update } from "@frondruntime/pinna-effect"; // Today changes with no write to the stay, so no check on the stay sees it. const $today = box(realm, "2026-04-20"); // Checked once, as the input arrives. const changeStay = (stay: typeof Stay.Type) => { update(realm, (read, write) => { if (stay.checkIn <= read($today)) { throw new Error("Check in after today"); } write(booking.$stay, stay); }); }; // Whether the stay can still change is derived, so it follows today. const $changeable = computed(realm, (read) => read($today) < read(booking.$stay).checkIn); ``` ## See also - [Boxes and computed](../state/boxes.md): the core's box, with no schema. - [Updates](../state/updates.md): what an update undoes when it throws. - [Classes](./classes.md): boxes as fields of a model decoded from the wire. - [Errors and debugging](../guides/errors.md#with-effect): the errors a schema adds, and the path and message of each field it refuses. - [Equality and hashing](./equality.md): what each schema counts as the same value, and a class's own `Equal`. --- # Classes URL: https://pinna.frondruntime.dev/docs/effect/classes Description: Read when modeling domain data. Declare a SchemaModel 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 `SchemaModel`: a `Schema.Class` whose instances hold a realm that its wire form never carries. A field whose name starts with `$` is a `BoxField`, or a `CollectionField` of rows by key ([Collection fields](./collections.md)), and its wire key drops the `$`. A field without `$` is plain, `readonly` data. The class keeps `check` and `annotate`, and seals `extend`, `mapFields`, `makeOption`, and `makeEffect`. ```ts import { BoxField, computed, createRealm, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); class Todo extends SchemaModel("Todo")({ id: Schema.String, title: Schema.String, $done: BoxField(Schema.Boolean), // a box field; the wire key is "done" }) { readonly $label = computed(this.realm, (read) => read(this.$done) ? `✓ ${this.title}` : this.title, ); toggle(): void { update(this.realm, (read, write) => { write(this.$done, !read(this.$done)); }); } } ``` - A derived value is a `$` property of the class body, made with `computed(this.realm, ...)`. It is not a schema field, so it is not on the wire. - A method that writes calls `update(this.realm, ...)`. `decode(realm, Todo)` makes instances from wire data. Every instance and every box inside it belongs to the realm `decode` is given, the one made above the class. ```ts import { decode, untracked } from "@frondruntime/pinna-effect"; // Throws the SchemaError when the input does not fit. const todo = decode(realm, Todo)({ id: "1", title: "Write the docs", done: false }); todo.toggle(); const label = untracked(realm, (read) => read(todo.$label)); // "✓ Write the docs" ``` A `FromContext` field holds a value of the caller's own, such as a formatter or a client: the service of an Effect `Context.Service` tag. `decode` takes it from the `Context` it is given; it is never on the wire. ```ts import { BoxField, computed, decode, FromContext, SchemaModel } from "@frondruntime/pinna-effect"; import { Context, Schema } from "effect"; interface MoneyFormat { readonly format: (amount: number) => string; } // An Effect service: the field requires it, and the caller provides it. class Money extends Context.Service()("app/Money") {} class Price extends SchemaModel("Price")({ $amount: BoxField(Schema.Number), money: FromContext(Money), // the caller's own value, never on the wire }) { readonly $label = computed(this.realm, (read) => this.money.format(read(this.$amount))); } const euros: MoneyFormat = { format: (amount) => `€${amount.toFixed(2)}` }; const price = decode(realm, Price, Context.make(Money, euros))({ amount: 12 }); ``` An Effect program decodes the same class with `Schema.decodeUnknownEffect`. The tag is one of its requirements, provided as any service is, with `Effect.provideService` or a `Layer`. The realm comes from `RealmService`, as for every Effect program. ```ts import { RealmService } from "@frondruntime/pinna-effect"; import { Effect, Schema } from "effect"; // Money is a requirement like any service: Effect. const loadPrice = (json: unknown) => Schema.decodeUnknownEffect(Price)(json); const loaded = Effect.runSync( loadPrice({ amount: 12 }).pipe( Effect.provideService(Money, euros), Effect.provideService(RealmService, realm), ), ); ``` ## Rules - Make instances with `decode(realm, Todo)(json)`. Every instance has a `realm` field, never on the wire: `decode` fills it, and field initializers use `this.realm`. - `Todo.make({ id, title, done: false, realm })` builds an instance from values already in hand. It takes each `$` field's starting value under its wire key, and builds the box in the instance's realm. A box under the `$` key throws `pinna: Todo.make takes the value of $done under "done", never a box under "$done"`, so a spread instance never shares its box with the new one. - `make` checks each `$` field's value even under `{ disableChecks: true }`, which skips only the plain fields' checks: the box checks every value it holds, its first included. - A model in another schema's `make` is an instance. A plain object in its place throws `pinna: a Todo field of another schema takes an instance; build it with Todo.make or decode`, because its boxes would be another instance's, or none. - A field list that breaks a naming rule makes `SchemaModel` throw when the class is defined, so no instance is ever half-declared: - two fields with one wire key, such as `$count` and `count`: `pinna: Counter.$count and Counter.count both read "count"; rename one`; - a field whose wire key is `realm`: `pinna: Counter.realm reads "realm", the realm the instance belongs to; rename the field`; - a `$` field that is not a `BoxField` or a `CollectionField`: `pinna: Counter.$count is named as a box; declare it BoxField(...) or CollectionField(...)`; - a `BoxField` or a `CollectionField` without `$`: `pinna: Counter.count holds a box; name it $count`. - `BoxField` and `CollectionField` are fields of a `SchemaModel` only. In any other schema they fail to decode and encode with `pinna: BoxField is a SchemaModel field; declare it in SchemaModel(...), never in another schema` (or `CollectionField`), because the `$` key would go on the wire. - `extend`, `mapFields`, `makeOption`, and `makeEffect` throw and do not compile on a `SchemaModel`: the first two would declare fields without its checks, and the last two would take boxes where `make` takes values. The call throws `pinna: Todo.extend is not supported; declare another SchemaModel with every field it needs`, and the same for `mapFields`; `makeOption` and `makeEffect` throw `pinna: Todo.makeOption is not supported; call make, which throws the schema error, or decode`. - A plain getter has no `read` to call, and a method that takes `read` is not cached. A value several components need is a computed field. - A context field's tag is a requirement of the decode, at any depth: `decode` without a `Context` holding the tag does not compile, and neither does running a `Schema.decodeUnknownEffect` that nothing provides it to. A `Context` holding more tags compiles. A schema with no context field takes no `Context`. `Schema.decodeUnknownSync` does not compile on such a schema, because it runs without services. - The `Context` given to `decode` may hold any Effect service, such as a `Clock`, and the schema's own transformations read them from Effect. - A field reads its tag from the Effect context, so the innermost provider wins, as for any service: an Effect decode inside a `decode`'s transformation that provides a tag the outer `decode` also holds reads its own value. - Plain fields are never written after `decode`. A value that changes is a `$` field. - Encoding an instance, as `Schema.encodeSync(Todo)(todo)`, gives the schema's wire fields and nothing else, each `$` field's current value under its wire key. The `realm`, a `FromContext` field, computed fields, and other instance properties stay off the wire, so what is sent is the schema's encoded form. - Declare a class with no `$` field as a plain `Schema.Class`. A `SchemaModel` without one still has a `realm` field, so decoding it needs a realm, and `RealmService` in an Effect program, for nothing to observe. ## Answers | Call | Answers | | --- | --- | | `SchemaModel(identifier)(fields)` | A class whose `$` fields are boxes or collections, checked by its schema. | | `BoxField(schema)` | A field that is a box of `schema`, under the wire key without the `$`. | | `CollectionField(rowSchema, { keyOf })` | A field that is a collection of rows by key, each row checked against `rowSchema` and compared with its equivalence: see [Collection fields](./collections.md). | | `decode(realm, schema, context?)(input)` | The decoded value, or throws `Schema.SchemaError`. | | `FromContext(tag)` | A field holding the service of `tag`, never on the wire, that puts `tag` in the schema's requirements. | | `Todo.make({ ...values, realm })` | An instance from values in hand, each `$` field's value under its wire key. | ## See also - [Schema-checked boxes](./boxes.md): what a `$` field checks on a write. - [Errors](../guides/errors.md#fields-a-schema-refuses): the path and message of each field `decode` refuses. - [Collection fields](./collections.md): rows by key, as a `$` field. - [Boxes and computed](../state/boxes.md): what a `$` field and a computed field are. - [Updates](../state/updates.md): what a write checks, and when it is undone. - [Hooks](../react/hooks.md): reading a model in a component. - [Equality and hashing](./equality.md): when two instances of a model are equal, and a class's own `Equal`. - [Coming from MobX](../start/mobx.md): a MobX store as a `SchemaModel`. --- # Collection fields URL: https://pinna.frondruntime.dev/docs/effect/collections Description: Read when a model holds rows by key. Declare a CollectionField, decode it from a plain array, write a refetch that keeps rows equal under the schema, and reconcile a schema-checked box of an array. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). A `CollectionField` is the core's [collection](../state/collections.md) as a field of a `SchemaModel`: it is read with `row(key)`, `read.row`, `keys`, and `rows`, and written with `write.upsert`, `write.remove`, and `write.replaceAll`, as that page shows. ## Example A `CollectionField` holds rows by key, each row checked against the row schema. On the wire it is a plain array. The rows here are the `Todo` of [Classes](./classes.md): ```ts import { BoxField, computed, createRealm, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); class Todo extends SchemaModel("Todo")({ id: Schema.String, title: Schema.String, $done: BoxField(Schema.Boolean), // a box field; the wire key is "done" }) { readonly $label = computed(this.realm, (read) => read(this.$done) ? `✓ ${this.title}` : this.title, ); toggle(): void { update(this.realm, (read, write) => { write(this.$done, !read(this.$done)); }); } } ``` ```ts import { CollectionField, computed, SchemaModel, update } from "@frondruntime/pinna-effect"; class TodoList extends SchemaModel("TodoList")({ $items: CollectionField(Todo, { keyOf: (todo) => todo.id }), }) { readonly $open = computed( this.realm, (read) => read(this.$items.rows).filter((todo) => !read(todo.$done)).length, { name: "TodoList.open" }, ); add(todo: Todo): void { update(this.realm, (_read, write) => { write.upsert(this.$items, todo, { at: "end" }); }); } remove(id: string): void { update(this.realm, (_read, write) => { write.remove(this.$items, id); }); } } ``` ```ts import { decode, untracked } from "@frondruntime/pinna-effect"; // On the wire, a collection is a plain array. const items = [ { id: "1", title: "Write the docs", done: false }, { id: "2", title: "Read them", done: true }, ]; const list = decode(realm, TodoList)({ items }); const open = untracked(realm, (read) => read(list.$open)); // 1 ``` A refetch writes every row at once with `write.replaceAll`. A row equal under the schema to the one held is kept, and what read it does not rerun. A `SchemaModel` row with a `$` field is merged: the held row stays, and its boxes take the refetched values. ```ts import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; // No `$` field, so it is declared as a plain Schema.Class. class Quote extends Schema.Class("Quote")({ symbol: Schema.String, price: Schema.Number, }) {} class Market extends SchemaModel("Market")({ $quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }), }) { receive(quotes: ReadonlyArray): void { update(this.realm, (_read, write) => { // A quote equal to the one held is kept: what read its row does not rerun. write.replaceAll(this.$quotes, quotes); }); } } const market = decode(realm, Market)({ quotes: [] }); const receiveQuotes = (json: unknown) => { market.receive(decode(realm, Schema.Array(Quote))(json)); }; ``` `reconcile` takes `equals`, here the item schema's equivalence, so a `schemaBox` of a plain array keeps the previous object of every item that did not change. `reconcileSchema` takes no schema, and works `equals` out from each pair of items when it is left out, as [Equality and hashing](./equality.md) lists. A plain `Schema.Struct` row compares with Effect's `Equal.equals`, which never sees a schema, so a `toEquivalence` annotation on a Struct is not used there. ```ts import { computedFunction, decode, reconcile, schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const Rate = Schema.Struct({ currency: Schema.String, rate: Schema.Number }); const sameRate = Schema.toEquivalence(Rate); const $rates = schemaBox(realm, Schema.Array(Rate), []); const rateOf = computedFunction(realm, (read, currency: string) => read($rates).find((rate) => rate.currency === currency), ); const receiveRates = (json: unknown) => { const next = decode(realm, Schema.Array(Rate))(json); update(realm, (read, write) => { // An unchanged rate keeps its previous object, so rateOf for it // returns the same value and its readers do not rerun. write( $rates, reconcile(read($rates), next, { keyOf: (rate) => rate.currency, equals: sameRate }), ); }); }; ``` `reconcileSchema` takes arrays only. One refetched model is a list of one on each side, under any key, such as a constant: the result is the held instance, its boxes set to the refetched values, or the refetched instance when a plain field differs. ```ts import { decode, reconcileSchema } from "@frondruntime/pinna-effect"; // One model, refetched: a list of one on each side. With one item, any key // does, such as a constant. const refreshTodo = (held: Todo, json: unknown): Todo => { const fresh = decode(realm, Todo)(json); const [next = fresh] = reconcileSchema([held], [fresh], { keyOf: () => "todo" }); return next; // `held`, its $done set to the refetched value, or `fresh` }; ``` `schemaCollection` is the collection a `CollectionField` holds, with no model around it: for rows a service or a feed owns, such as the trades a feed writes. It starts empty and checks and compares rows as the field does. ```ts import { decode, schemaCollection, update } from "@frondruntime/pinna-effect"; // The collection a CollectionField holds, with no model around it. const $quotes = schemaCollection(realm, Quote, { keyOf: (quote) => quote.symbol }); const receiveQuote = (json: unknown) => { // decode checks the wire data; upsert checks the row again as it lands. const quote = decode(realm, Quote)(json); update(realm, (_read, write) => { write.upsert($quotes, quote); }); }; ``` ## Rules - A `CollectionField` checks each row against the row schema when it lands: on `decode`, `write.upsert`, and `write.replaceAll`. A row the schema rejects throws from the update, which rolls back. A `schemaCollection` checks on `write.upsert` and `write.replaceAll` the same way. - An `undefined` row is rejected with `pinna: a collection row cannot be undefined`, even when the row schema accepts it: `row(key)` and `read.row` use `undefined` for a missing key. `decode` throws a `Schema.SchemaError` with that message and an Effect decode fails with it, before `keyOf` runs; `make` throws its schema error; `write.upsert` and `write.replaceAll` throw the message before changing any row. - A row written under a held key is compared with the row schema's equivalence, so a refetch of equal rows reruns nothing. - A key names one row. A repeated key fails the `decode` and throws from `write.replaceAll`, both with `pinna: the collection key appears twice`. `reconcile` and `reconcileSchema` throw `pinna: reconcile: the key appears twice`. - A row with a `$` field is a new instance after every `decode`, with new boxes. `replaceAll`, `upsert`, and `reconcileSchema` merge it into the row held under its key, so only the readers of a changed box rerun. When they merge is on [Equality and hashing](./equality.md). ## Answers | Call | Answers | | --- | --- | | `CollectionField(schema, { keyOf, name? })` | A field of rows by key, each checked against `schema`, a plain array on the wire. `name` names every instance's collection, as `collection`'s does. | | `schemaCollection(realm, schema, { keyOf, equals?, name? })` | An empty collection of rows `schema` accepts, the one a `CollectionField` holds. A row is compared with `equals`, the schema's equivalence by default, and a `SchemaModel` row is merged into the held one. | | `reconcileSchema(previous, next, { keyOf, equals? })` | As `reconcile` on [Updates](../state/updates.md), with `equals` optional and a `SchemaModel` item merged into the held one. | ## See also - [Collections](../state/collections.md): reading and writing a collection, and rendering one row per key. - [Classes](./classes.md): the model a collection field lives on. - [Updates](../state/updates.md): the update every write runs in. - [Hooks](../react/hooks.md): a row component that rerenders alone. - [Equality and hashing](./equality.md): a row class's own `Equal`, and what each schema counts as equal. - [Live data](../guides/live-data.md): a refetch and a feed written into a collection field. --- # Equality and hashing URL: https://pinna.frondruntime.dev/docs/effect/equality Description: Read when a write, a refetch, or a reconcile keeps or replaces a value. Know what each box, collection, and reconcile compares with by default, why two decodes of a model with a box are not equal unless the class defines its own Equal, what Effect's Equal.equals and HashSet see, and how a class defines its own Equal and Hash. Pinna compares a value written over the one held. When the two are equal, the held value stays, and nothing that read it reruns. What counts as equal depends on what holds the value. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). ## Example A `schemaBox` compares as `Schema.toEquivalence` of its schema does. An equal write keeps the object the box holds. ```ts import { createRealm, schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const realm = createRealm(); const Reading = Schema.Struct({ at: Schema.Date, value: Schema.Number }); type Reading = typeof Reading.Type; const $reading = schemaBox(realm, Reading, { at: new Date(0), value: 1 }); const record = (reading: Reading) => { update(realm, (_read, write) => { // A Date compares by its time: an equal reading keeps the object // the box holds, and nobody reruns. write($reading, reading); }); }; ``` A `SchemaModel` without its own Equal compares its boxes and its realm by identity, so two decodes of the same JSON are not equal when the class has a `$` field. ```ts import { BoxField, decode, SchemaModel } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; class Position extends SchemaModel("Position")({ id: Schema.String, $size: BoxField(Schema.Number), }) {} const samePosition = Schema.toEquivalence(Position); const first = decode(realm, Position)({ id: "a", size: 1 }); const again = decode(realm, Position)({ id: "a", size: 1 }); // false: each decode makes its own $size box, and boxes compare by identity. const positionsEqual = samePosition(first, again); ``` A refetch through `write.replaceAll` keeps each plain row that did not change. ```ts import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; // No `$` field, so a plain Schema.Class. class Quote extends Schema.Class("Quote")({ symbol: Schema.String, price: Schema.Number, }) {} class Market extends SchemaModel("Market")({ $quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }), }) {} const market = decode(realm, Market)({ quotes: [] }); const receiveQuotes = (json: unknown) => { const quotes = decode(realm, Schema.Array(Quote))(json); update(realm, (_read, write) => { // A quote equal under Quote's schema is kept, and what read its row does not rerun. write.replaceAll(market.$quotes, quotes); }); }; ``` A refetched `SchemaModel` row is merged into the held one, so a component that reads the row reruns only when a plain field changes, and one that reads `$size` reruns when the size does. ```ts import { decode, reconcileSchema, schemaBox, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const $positions = schemaBox(realm, Schema.Array(Position), []); const receivePositions = (json: unknown) => { const fresh = decode(realm, Schema.Array(Position))(json); update(realm, (read, write) => { // A held id keeps its Position, and the new size goes into its $size box. write( $positions, reconcileSchema(read($positions), fresh, { keyOf: (position) => position.id }), ); }); }; ``` A `SchemaModel` that defines `[Equal.symbol]` decides its own equality. A refetched rate under a held pair is merged, and its box takes the new bid. ```ts import { BoxField, decode, reconcileSchema, SchemaModel, schemaBox, update, } from "@frondruntime/pinna-effect"; import { Equal, Hash, Schema } from "effect"; class Rate extends SchemaModel("Rate")({ pair: Schema.String, $bid: BoxField(Schema.Number), }) { // One rate per pair. Plain fields only: Effect caches what Equal.equals answers. [Equal.symbol](that: unknown): boolean { return that instanceof Rate && that.realm === this.realm && this.pair === that.pair; } [Hash.symbol](): number { return Hash.string(this.pair); } } const $rates = schemaBox(realm, Schema.Array(Rate), []); const receiveRates = (json: unknown) => { const fresh = decode(realm, Schema.Array(Rate))(json); update(realm, (read, write) => { // A pair already held keeps its rate, and the new bid goes into that rate's box. write($rates, reconcileSchema(read($rates), fresh, { keyOf: (rate) => rate.pair })); }); }; ``` `{ equals }` replaces the default of any box. ```ts import { schemaBox } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; const Row = Schema.Struct({ id: Schema.String, price: Schema.Number }); // Every new array is a change, even one equal part by part. const $log = schemaBox(realm, Schema.Array(Schema.String), [], { equals: Object.is }); // The same row while the id is the same, whatever the price. const $selected = schemaBox( realm, Row, { id: "a", price: 1 }, { equals: (held, next) => held.id === next.id }, ); ``` ## Rules - The core's `box`, `collection`, and `computed` compare with `Object.is` unless `{ equals }` says otherwise, so a new array or object is a change. A computed value compares with `Object.is` in `pinna-effect` too, even when what it reads is a `schemaBox`. - A `schemaBox` and a `BoxField` compare with the schema's equivalence, with the answers of `Schema.toEquivalence`. An equal write keeps the value held and notifies nobody, so a refetch of the same data reruns nothing. - Under a schema's equivalence a primitive equals the same value, `NaN` equals `NaN`, and `0` equals `-0`. A `Date` equals one with the same time, and two invalid Dates are equal. An array or a struct compares part by part. A schema with an equivalence annotation, such as `Schema.overrideToEquivalence`, compares with it. - A box of `Schema.Unknown`, `Schema.Any`, or `Schema.ObjectKeyword` compares with `Object.is`: such a schema says nothing of the value's shape, and a structural compare would hash the whole value on every write. An `Unknown` field inside a struct compares structurally. - `{ equals }` replaces the schema's equivalence: `Object.is` counts every new array or object as a change, even one equal part by part, and a function by id counts a row with a new price as unchanged. - A `SchemaModel` instance without its own `Equal` compares its plain fields by value and its boxes and its realm by identity. Every `decode` makes new boxes, so a refetched instance with a `$` field is not equal to the one held, and neither is an instance from another realm. - A `SchemaModel` with its own `[Equal.symbol]` is compared by that method wherever Pinna compares with the class's schema, as in a `schemaBox` and in `reconcileSchema`, on every comparison, with no answer cached. A plain `Schema.Class` ignores its own `[Equal.symbol]` there, as Effect's schema does, and compares field by field. - A refetched `SchemaModel` instance under a held key is merged into the held one when both are of the same class and realm and their plain fields are equal, or the class's own `[Equal.symbol]` finds them equal, even when a plain field differs. The held instance stays; each `BoxField` takes the refetched value, compared with its schema, and each `CollectionField` merges its rows the same way, so a refetch reruns only the readers of a box that changed. A plain field that holds a model is compared, not merged. Any other difference replaces the instance. - `reconcileSchema`, `write.replaceAll`, and `write.upsert` merge. A `schemaBox` of an array compares by index and does not. - A `CollectionField` merges a `SchemaModel` row written under a held key and compares any other row with the row schema's equivalence: `replaceAll` and `upsert` keep every equal or merged row, and notify nobody when nothing changed. - `reconcile` takes `equals` and has no default: a refetch builds new objects, and the comparison is the caller's choice. - `reconcileSchema` keeps a row that is the same instance, merges a `SchemaModel` row, compares any other instance of a `Schema.Class` with its class's equivalence, and anything else with Effect's `Equal.equals`. A key repeated in the new array throws before any box is written. The merge writes in the open update, or in one of its own; a refetch that changes no box opens none, so it runs inside a computed value too. `equals` replaces all of it. - Effect's `Equal.equals`, which `HashSet` and `HashMap` look values up with, is not the schema's equivalence. It compares `Hash.hash` first, caches each object's hash, caches its answer for a pair of objects, and compares an instance by every own property. The two agree on a plain `Schema.Class` and on a `SchemaModel` whose fields are all plain: two decodes of the same JSON into one realm are equal, and `HashSet.has` finds either. They part on two cases: - A `$` property of the class body, such as a computed value, is no schema field. The schema's equivalence ignores it; `Equal.equals` compares it by identity, so two instances are not equal under Effect. - A `SchemaModel` with `[Equal.symbol]` and no `[Hash.symbol]` is equal under the schema's equivalence and not under `Equal.equals`, which compares hashes first. Define both, on plain fields only, such as the key, since Effect caches the hash. - Under Effect's `Equal.equals`, a box, a computed value, an atom, and a realm equal only themselves. A plain object holding them compares them by identity, never by their contents. ## Answers | Call | Compares a new value with the held one by default with | | --- | --- | | `box(realm, initial, { equals? })` | `Object.is`. | | `collection(realm, { keyOf, equals? })` | `Object.is`, row by row. | | `computed(realm, compute, { equals? })` | `Object.is`. | | `schemaBox(realm, schema, initial, { equals? })` | The schema's equivalence. | | `BoxField(schema)` | The schema's equivalence. | | `CollectionField(schema, { keyOf })` | A merge for a `SchemaModel` row, the row schema's equivalence otherwise, row by row. | | `reconcile(previous, next, { keyOf, equals })` | `equals`, required. | | `reconcileSchema(previous, next, { keyOf, equals? })` | A merge for a `SchemaModel` row, the class's equivalence for another schema class instance, `Equal.equals` otherwise. | ## 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. - [Boxes and computed](../state/boxes.md): the core's box and its `equals`. - [Collections](../state/collections.md): the core's collection and its `equals`. --- # Programs URL: https://pinna.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. The Effect pages are for applications that already use Effect: see [Schema-checked boxes](./boxes.md). The functions on this page are for apps written as Effect programs, and `@frondruntime/pinna-effect` exports them next to the rest. Models and components need none of them. `watchScoped` and `observeScoped` end in `Scoped`, Effect's suffix for a call that lives for the caller's scope, because the plain `watch` and `observe` keep their names and return a stop function instead. ## Example No program requires a service for the realm. `watchScoped` and `fromStream` take it first, as `watch` does, and `changes`, `observeScoped`, and `whileObserved` take it from the observable, so a program that refuses every requirement but `Scope` runs each of them. ```ts import { createRealm } from "@frondruntime/pinna-effect"; // Every program below takes the realm, or an observable that carries it, // so none requires a service for it; a test makes a realm of its own. const realm = createRealm(); ``` `watchScoped` runs an effect for each change of what the select reads, in the caller's scope. A new value interrupts the running effect: the latest value wins. `search` stands for the application's own effect. ```ts import { schemaBox, update, watchScoped } from "@frondruntime/pinna-effect"; import { Effect, Schema } from "effect"; const $query = schemaBox(realm, Schema.String, ""); const $results = schemaBox(realm, Schema.Array(Schema.String), []); const searchAsTyped = watchScoped( realm, (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* search(query); update(realm, (_read, write) => write($results, results)); }), ); ``` `changes` is a stream of the current value, then each change. ```ts import { changes } from "@frondruntime/pinna-effect"; import { Effect, Stream } from "effect"; // The query now, then each change; a slow consumer skips to the newest. const logQueries = changes($query).pipe( Stream.runForEach((query) => Effect.log(`query: ${query}`)), ); ``` `fromStream` is a read-only value fed by a stream. The stream runs only while the value is observed. When the last observer leaves, the value resets to `initial` synchronously. Each run starts from `initial` until its first element arrives. `fetchRate` stands for the application's own effect. ```ts import { computed, fromStream, schemaBox } from "@frondruntime/pinna-effect"; import { Effect, Schedule, Schema, Stream } from "effect"; const $price = schemaBox(realm, Schema.Number, 10); const priceInEuros = Effect.gen(function* () { // No rate until the stream emits, then its latest rate. The poll runs // only while $rate is observed. Losing the last observer resets $rate // to undefined, so a stale rate never shows as current. const $rate = yield* fromStream( realm, Stream.fromEffectSchedule(fetchRate, Schedule.spaced("1 minute")), undefined, ); return computed(realm, (read) => { const rate = read($rate); return rate === undefined ? undefined : read($price) * rate; }); }); ``` `whileObserved` runs a program while an observable is observed: from the start when the first observer arrives, interrupted when the last one leaves. It is how a feed writes the rows of a collection only while a list shows them: a list reads `keys`, and a reader of one present row does not. `fromStream` is the same lifetime around a single value. A row checked against a schema lands in a `schemaCollection` ([Collection fields](./collections.md)). `fetchTrades` and `tradeUpdates` stand for the application's own snapshot and updates. ```ts import { Schema } from "effect"; class Trade extends Schema.Class("Trade")({ id: Schema.String, notional: Schema.Number.check(Schema.isGreaterThan(0)), }) {} ``` ```ts import { box, schemaCollection, update, whileObserved } from "@frondruntime/pinna-effect"; import { Effect, Stream } from "effect"; const $trades = schemaCollection(realm, Trade, { keyOf: (trade) => trade.id }); // Only the app knows when its snapshot is complete, so the flag is its own. const $loaded = box(realm, false); // A list observes the keys; a reader of one present row does not, so this // feed runs while a list shows the trades. const tradeFeed = whileObserved( $trades.keys, Effect.gen(function* () { const trades = yield* fetchTrades; update(realm, (_read, write) => { write.replaceAll($trades, trades); write($loaded, true); }); // The run ends when the last reader leaves, so it must not end before: // it runs the updates for as long as it is observed. yield* tradeUpdates.pipe( Stream.runForEach((trade) => Effect.sync(() => update(realm, (_read, write) => write.upsert($trades, trade))), ), ); }).pipe( // Not loaded once nobody reads it: the next reader waits for a new snapshot. Effect.ensuring(Effect.sync(() => update(realm, (_read, write) => write($loaded, false)))), ), ); ``` `observeScoped` holds a value observed until the scope closes, so the stream behind it keeps running with nothing rendered. ```ts import { observeScoped } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const keepRateFresh = Effect.gen(function* () { const $euros = yield* priceInEuros; // Observed until the scope closes, rendered or not: // the poll keeps running, and $euros stays cached. yield* observeScoped($euros); return $euros; }); ``` Each of them stops when its scope closes. ```ts import { Effect } from "effect"; const main = Effect.gen(function* () { yield* searchAsTyped; yield* Effect.forkScoped(logQueries); yield* keepRateFresh; yield* tradeFeed; }); // Every watch, stream, and hold above stops when the scope // closes: here, when the fiber is interrupted. const start = () => Effect.runFork(main.pipe(Effect.andThen(Effect.never), Effect.scoped)); ``` ## Rules - Pass the realm, as `watch` takes it. A test makes a realm of its own. `RealmService` is for a `SchemaModel` decoded inside an Effect program ([Classes](./classes.md)). - A watch's effect has no error channel. A defect is a bug: it is logged at the error level, and the watch keeps running. A stream behind `fromStream` logs a defect too. - While observed, a `fromStream` value is the last element of the current run, or `initial` before the first; while unobserved, it is `initial`. A stream that completes or dies leaves the value as it is until the last observer leaves. A failure the screen must show is an element the stream gives, such as a status beside the rate: see [Failures as values](#failures-as-values). - A watch's select is tracked and must not write. Its effect writes through `update`. - `watchScoped` runs for changes, not for the current value. `changes` starts with the current value. - `changes`, `observeScoped`, and `whileObserved` take the realm from the observable. A host whose programs require nothing but `Scope` watches a box with `changes` while its work awaits. - A `whileObserved` program runs in a scope of its own, closed when the run ends, so a fiber it forks into that scope stops with it. A program that returns ends its run while the value is still observed, and the next run starts only after the last observer leaves and another arrives: a feed ends on the stream it runs. - `whileObserved` and `fromStream` keep the services of the program that called them, not of the code that observes later. Provide a service before the call. - A program that writes more than one value per element runs on `whileObserved` and writes them in one update. `fromStream` publishes each element in an update of its own, so a box written from inside its stream lands one update earlier, and a reader of both sees them disagree. - Whether a feed has loaded is the application's own box. Pinna cannot tell when a snapshot is complete. The program writes the flag in the same update as the rows, so no reader sees it loaded with the rows missing. - `watchScoped` and `fromStream` compare with `Object.is` unless given `{ equals }`, as the core's `watch` and `box` do: a value from a stream or a select has no schema to compare by, unlike a `schemaBox`. `changes` takes no options and compares with `Object.is`. - Stop a program by closing its scope, not by keeping stop functions. ## Answers | Call | Answers | | --- | --- | | `watchScoped(realm, (read) => ..., (value, previous) => effect, { equals?, name? })` | An effect that starts the watch in the caller's scope. A result equal under `equals`, `Object.is` by default, is no change, so it neither runs nor interrupts the effect. `name` names the watch in its errors. | | `changes($x)` | A stream of `$x`'s current value, then each change; a slow consumer skips to the newest. Takes a box or a computed value, not an atom. | | `observeScoped($x)` | An effect that holds `$x`, a box, a computed value, or an atom, observed until the scope closes. | | `whileObserved($x, program)` | An effect that runs `program` while `$x`, a box, a computed value, or an atom, is observed, each run in a scope of its own. A defect is logged at the error level, and the next observation starts the program again. Closing the caller's scope interrupts a run and waits for it; later observation does not start it again. | | `fromStream(realm, stream, initial, { equals?, name? })` | A read-only value: `initial`, then the stream's latest element; needs the stream's services. The stream runs with the services of the program that made the value, and restarts each time the value is observed again. The value resets to `initial` when the last observer leaves or the scope closes; closing the scope stops the stream for good. An element equal under `equals`, `Object.is` by default, notifies nobody; `name` names the value for `inspect`. | | `withStage(realm, (stage) => section, { name?, conflicts? })` | The section's value, with its stage applied; a section failure, defect, or interruption drops the stage and the outcome stands. A conflict fails with `StageConflict`; a recipe that throws on replay is a defect. An interruption once landing began leaves the stage applied; the exit still contains `Interrupt`. | | `withStage(stage, (child) => section, { name? })` | A savepoint over `stage`, with the same success and failure behavior. The child inherits its root's conflict mode, takes no `conflicts` option, and never fails with `StageConflict`: its root checks what the child read. | | `StageConflict` | The tagged error `withStage` fails with when a stage opened with `{ conflicts: "fail" }` finds that what it read changed: `stage`, `changed`, and `observables`, as on `StageConflictError`. | ## Lifetimes Three owners run an effect, and the owner decides what stops it. - Observation owns the stream of a `fromStream` value and a `whileObserved` program: each runs from the first observer to the last, and starts again with the next. This fits data that matters only while something shows it, such as a rate or a search result: the last observer leaving stops the work, and the value resets to `initial`, so a stale rate never shows as current. - A fiber owns a feed whose data is kept whether shown or not, such as the quotes of a board that several screens and watches read from one collection. The feed runs until the fiber is interrupted, with nothing observing it ([Live data](../guides/live-data.md#with-effect)). - A scope owns a command, such as an order sent or a file saved. It runs to its end whatever the screen does, and only closing the scope interrupts it. This fits work a person started and expects finished. A `fromStream` value keeps the context of the program that made it, and its stream runs with that context on every observation. A service the stream needs is provided where the value is made, not where it is observed. The stream's type lists the services it needs but not the clock, so a stream that polls or sleeps keeps the clock of the program that made the value: a test on `TestClock` provides it before the value is made ([Testing](#testing)). ```ts import { fromStream } from "@frondruntime/pinna-effect"; import { Context, Effect, Schedule, Stream } from "effect"; class Rates extends Context.Service }>()("Rates") {} // The stream needs Rates, so making the value needs it: fromStream keeps the // context of the program that makes the value, and the stream runs with it // on every observation, whatever program observes the value later. const makeRate = fromStream( realm, Stream.fromEffectSchedule( Effect.gen(function* () { const rates = yield* Rates; return yield* rates.latest; }), Schedule.spaced("1 minute"), ), undefined, ); const rate = makeRate.pipe(Effect.provideService(Rates, { latest: fetchRate })); ``` A command that an event handler starts runs in a scope made once for the application. `Effect.forkIn` runs it in that scope, and `Effect.runForkWith(context)` gives it the application's services, the clock among them, so a test's `TestClock` reaches the command too. ```ts import { box, update } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; type OrderStatus = "idle" | "sending" | "sent"; const $orderStatus = box(realm, "idle"); const sendOrder = (amount: number) => Effect.gen(function* () { update(realm, (_read, write) => write($orderStatus, "sending")); yield* submit(amount); update(realm, (_read, write) => write($orderStatus, "sent")); }); // Made once, in the application's scope. An event handler calls `send`; the // order runs in that scope, so unmounting the component that sent it, or the // last observer of $orderStatus leaving, interrupts nothing. Closing the // application's scope interrupts it. The order runs with the services the // application was given, its clock among them. const orders = Effect.gen(function* () { const scope = yield* Effect.scope; const context = yield* Effect.context(); const send = (amount: number): void => { Effect.runForkWith(context)(Effect.forkIn(sendOrder(amount), scope)); }; return { send }; }); ``` `Effect.forkScoped` schedules its fiber and returns before the fiber runs, so the next line cannot count on what the fiber writes. `{ startImmediately: true }` runs the fiber up to its first wait at once. ```ts import { untracked } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const sendAndRead = Effect.gen(function* () { // The fiber runs up to its first wait before the next line, so the read // sees "sending". Without startImmediately, it starts later, and the read // sees "idle". yield* Effect.forkScoped(sendOrder(10), { startImmediately: true }); return untracked(realm, (read) => read($orderStatus)); }); ``` ## Failures as values `fromStream` takes a stream whose error type is `never`, because a value has no channel for a failure. A typed failure the screen shows is mapped into the value's own type: the good elements and the failure become members of one union, and `Stream.catch` turns the failure into the last element. ```ts import { fromStream } from "@frondruntime/pinna-effect"; import { Data, Stream } from "effect"; // The transport's typed failure. class RateUnavailable extends Data.TaggedError("RateUnavailable")<{ readonly reason: string }> {} // What the screen shows: a rate, or why there is none. type RateState = | { readonly _tag: "Loading" } | { readonly _tag: "Rate"; readonly rate: number } | { readonly _tag: "Unavailable"; readonly reason: string }; const showRate = (rates: Stream.Stream) => fromStream( realm, rates.pipe( Stream.map((rate): RateState => ({ _tag: "Rate", rate })), // The failure becomes the last element: the stream ends on it, and the // value shows it until the last observer leaves. Stream.catch((error) => Stream.succeed({ _tag: "Unavailable", reason: error.reason }), ), ), { _tag: "Loading" }, ); ``` The stream ends on the failure, and the value shows it until the last observer leaves. The next observer starts the stream again, from `initial`. ## Testing A program that polls or sleeps is tested on `TestClock`, from `effect/testing`, so the test moves time instead of waiting for it. The test realm is as on [Testing](../guides/testing.md). - Provide `TestClock.layer()` around the program that makes a `fromStream` value, not only around the one that observes it. The value keeps the clock of the program that made it, and a value made on the live clock polls on the live clock whatever the observer provides. - Hold the value observed with `observeScoped`. Its stream runs only while something observes the value, so an unobserved poll never runs and the value stays `initial`. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { fromStream, observeScoped, RealmService, untracked } from "@frondruntime/pinna-effect"; import { Effect, Schedule, Stream } from "effect"; import { TestClock } from "effect/testing"; test("a poll advances with the test clock", async () => { using realm = testRealm(); let polls = 0; const poll = Effect.sync(() => ++polls); const latest = await Effect.gen(function* () { // Made under TestClock: fromStream keeps the clock of the program that // makes the value, and the poll waits on it. const $polls = yield* fromStream( realm, Stream.fromEffectSchedule(poll, Schedule.spaced("1 minute")), 0, ); // The poll runs only while something observes the value. yield* observeScoped($polls); yield* TestClock.adjust("2 minutes"); return untracked(realm, (read) => read($polls)); }).pipe( Effect.scoped, Effect.provideService(RealmService, realm), Effect.provide(TestClock.layer()), Effect.runPromise, ); expect(latest).toBe(3); }); ``` `TestClock.adjust` is not a completion signal. It runs the sleeps that fall due and waits for the fibers it woke to suspend; work that no sleep holds, such as a load that yields between rows, can still be running when it returns, and `TestClock.adjust(0)` wakes nothing at all. A test waits on a value the program publishes when its work is done: a `Deferred`, or a box read through `changes`. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { box, changes, RealmService, untracked, update } from "@frondruntime/pinna-effect"; import { Effect, Stream } from "effect"; import { TestClock } from "effect/testing"; test("a test waits on what the program publishes, not on the clock", async () => { using realm = testRealm(); const $loadedRows = box(realm, 0); const $loaded = box(realm, false); // Yields between rows; no sleep holds it, so the clock has nothing to wait for. const load = Effect.gen(function* () { for (let row = 1; row <= 100; row++) { yield* Effect.yieldNow; update(realm, (_read, write) => write($loadedRows, row)); } update(realm, (_read, write) => write($loaded, true)); }); const loaded = await Effect.gen(function* () { yield* Effect.forkScoped(load); yield* changes($loaded).pipe( Stream.filter((done) => done), Stream.runHead, ); return untracked(realm, (read) => read($loadedRows)); }).pipe( Effect.scoped, Effect.provideService(RealmService, realm), Effect.provide(TestClock.layer()), Effect.runPromise, ); expect(loaded).toBe(100); }); ``` A helper that runs a program and declares its realm with `using` is `async` and awaits the run before it returns. Returning the promise without `await` disposes the realm while the program's scope is still open, and the dispose throws `The test realm is not at rest: watch still running.`, one entry per watch the program holds. The dispose stops each watch first, so no watch reruns in the next test, but a fiber the program forked runs on until its scope closes; the fix is `return await`. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { RealmService, schemaBox, update, watchScoped } from "@frondruntime/pinna-effect"; import { Deferred, Effect, Schema } from "effect"; // `async` and `return await`: the realm is disposed after the program's scope // closes. A helper that returns the promise without awaiting it disposes the // realm while the program's watch still runs. const searchOnce = async (query: string): Promise => { using realm = testRealm(); const $query = schemaBox(realm, Schema.String, ""); return await Effect.gen(function* () { const searched = yield* Deferred.make(); yield* watchScoped( realm, (read) => read($query), (value) => Deferred.succeed(searched, value), ); update(realm, (_read, write) => write($query, query)); return yield* Deferred.await(searched); }).pipe(Effect.scoped, Effect.provideService(RealmService, realm), Effect.runPromise); }; test("a helper awaits its program before its realm is disposed", async () => { expect(await searchOnce("pinna")).toBe("pinna"); }); ``` | Call | Answers | | --- | --- | | `Effect.provide(TestClock.layer())` | A program whose sleeps and schedules wait on the test clock. | | `TestClock.adjust(duration)` | Moves the test clock and runs the sleeps that fall due; not a signal that other work finished. | ## Stages `withStage` holds a section's writes in a stage ([Updates](../state/updates.md#stages)) and lands them when the section succeeds. A section failure, defect, or interruption drops them, so nothing the section staged reaches the realm. An interruption once landing began leaves the stage applied; the exit still contains `Interrupt`. ```ts import { box, stageUpdate, withStage } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const $balance = box(realm, 100); const $status = box<"idle" | "sent">(realm, "idle"); const transfer = (amount: number) => withStage(realm, (stage) => Effect.gen(function* () { stageUpdate(stage, (read, write) => { write($balance, read($balance) - amount); write($status, "sent"); }); // Nothing shows until send succeeds; a failure or an interruption drops it. yield* send(amount); }), ); ``` Over a stage, `withStage` is a savepoint. A section that fails and is caught leaves the outer stage as it was, and each attempt of an `Effect.retry` opens a fresh child. ```ts import { box, stageUpdate, withStage } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const $notes = box>(realm, []); const transferWithNote = (amount: number, note: string) => withStage(realm, (stage) => Effect.gen(function* () { stageUpdate(stage, (read, write) => { write($balance, read($balance) - amount); }); // A child stage: when the section fails, its writes never reach the outer // stage, and each retry starts from a fresh child. yield* withStage(stage, (section) => Effect.gen(function* () { const text = yield* describeTransfer(note); stageUpdate(section, (_read, write) => { write.modify($notes, (notes) => { notes.push(text); }); }); }), ).pipe( Effect.retry({ times: 2 }), Effect.catch(() => Effect.void), ); yield* send(amount); }), ); ``` With `{ conflicts: "fail" }`, a stage whose reads changed before it landed fails with `StageConflict`, and `Effect.retry` runs the section again over the new values. ```ts import { box, StageConflict, stageUpdate, withStage } from "@frondruntime/pinna-effect"; import { Effect } from "effect"; const $price = box(realm, 10); const $total = box(realm, 0); const checkout = withStage( realm, (stage) => Effect.sync(() => { stageUpdate(stage, (read, write) => { write($total, read($price) * 2); }); }), { conflicts: "fail" }, ).pipe( // The price changed after the stage read it: run the section again over the new one. Effect.retry({ while: (error) => error instanceof StageConflict, times: 3 }), ); ``` - `withStage` applies the stage after the section succeeds, synchronously, so nothing runs between the section's last write and the landing. - The release drops the stage whether or not it applied: `dropStage` does nothing to a closed stage. An `applyStage` precondition failure leaves the stage open and becomes a defect in `withStage`; the release then drops it and its open children. A conflict or replay throw drops it before the release. - Retrying reruns the section, requests included. Retry only a section that is safe to repeat; `withStage` never retries on its own. - A host that lands a stage inside its own update, or applies only on a condition, calls `openStage`, `applyStage`, and `dropStage` itself, with `Effect.acquireUseRelease`. ## See also - [Reacting](../state/reacting.md): `watch` and `autorun` without Effect. - [Classes](./classes.md): `decode`, JSON in and a checked model out. - [Live data](../guides/live-data.md): a WebSocket feed and a refetch as Effect programs. - [Testing](../guides/testing.md): a test realm, and a program run in it. --- # Live data URL: https://pinna.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 message in one update, refetch without losing row identity, and run the same feed as an Effect stream. ## Example A quote feed keeps one row per symbol, written from a WebSocket. The server sends a snapshot of every quote when the socket opens, then one change per message. The parser checks each message by hand, builds new objects with the fields a quote has, and returns `undefined` for anything else. ```ts interface Quote { readonly symbol: string; readonly bid: number; readonly ask: number; } type QuoteMessage = | { readonly type: "snapshot"; readonly quotes: ReadonlyArray } | { readonly type: "upsert"; readonly quote: Quote } | { readonly type: "delete"; readonly symbol: string }; const isRecord = (value: unknown): value is Readonly> => typeof value === "object" && value !== null; const isPrice = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value); // A new object with a quote's fields alone, or undefined. const toQuote = (value: unknown): Quote | undefined => { if (!isRecord(value)) { return undefined; } const { symbol, bid, ask } = value; return typeof symbol === "string" && isPrice(bid) && isPrice(ask) ? { symbol, bid, ask } : undefined; }; // The message in `data`, or undefined. A snapshot that repeats a symbol is // no message: `write.replaceAll` would throw on it. const parseMessage = (data: unknown): QuoteMessage | undefined => { let value: unknown; try { value = JSON.parse(String(data)); } catch { return undefined; } if (!isRecord(value)) { return undefined; } const { type, quotes, quote, symbol } = value; if (type === "snapshot" && Array.isArray(quotes)) { const parsed: Array = []; const seen = new Set(); for (const item of quotes) { const next = toQuote(item); if (next === undefined || seen.has(next.symbol)) { return undefined; } seen.add(next.symbol); parsed.push(next); } return { type, quotes: parsed }; } if (type === "upsert") { const next = toQuote(quote); return next === undefined ? undefined : { type, quote: next }; } if (type === "delete" && typeof symbol === "string") { return { type, symbol }; } return undefined; }; ``` The socket is open while something observes the feed. A private atom stands for the socket, and `$status`, `$symbols`, and each `quote(symbol)` read it, so the first observer of any of them runs `connect`, and the last one leaving runs its cleanup, which closes the socket and cancels a pending reconnect. A hook on `keys` would miss a reader of one row: `row(key)` never reads `keys`. ```ts import { atom, box, collection, computed, computedFunction, Model, onObserved, type Realm, update, } from "@frondruntime/pinna"; type Status = "connecting" | "open" | "closed"; const quotesUrl = "wss://example.com/quotes"; class QuoteFeed extends Model { // Stands for the socket: observing any public field below opens it. private readonly $socket = atom(this.realm); private readonly $state = box(this.realm, "closed"); private readonly $rows = collection(this.realm, { keyOf: (quote: Quote) => quote.symbol, // A snapshot builds new objects; a quote with the same prices is kept. equals: (previous, next) => previous.bid === next.bid && previous.ask === next.ask, }); readonly $status = computed(this.realm, (read) => { read(this.$socket); return read(this.$state); }); readonly $symbols = computed(this.realm, (read) => { read(this.$socket); return read(this.$rows.keys); }); readonly quote = computedFunction(this.realm, (read, symbol: string) => { read(this.$socket); return read.row(this.$rows, symbol); }); constructor(realm: Realm) { super(realm); onObserved(this.$socket, () => this.connect()); } // 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 a message arrives. // Returns what closes it. The state lives in this call, so a socket from // an earlier observation never schedules a reconnect. private connect(): () => void { let socket: WebSocket | undefined; let timer: ReturnType | undefined; let attempt = 0; const open = () => { this.setStatus("connecting"); const next = new WebSocket(quotesUrl); next.onopen = () => { this.setStatus("open"); }; next.onmessage = (event: MessageEvent) => { attempt = 0; this.receive(event.data); }; next.onclose = () => { this.setStatus("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(); } }; } private setStatus(status: Status): void { update(this.realm, (_read, write) => write(this.$state, status)); } private receive(data: unknown): void { const message = parseMessage(data); if (message === undefined) { // The host's error sink, which a realm made without onError uses too. reportError(new TypeError("quotes: dropped a message that is not one")); return; } // One update per message: a reader sees all of it or none of it. update(this.realm, (_read, write) => { switch (message.type) { case "snapshot": // A quote equal to the one held keeps its row and notifies nobody. return write.replaceAll(this.$rows, message.quotes); case "upsert": return write.upsert(this.$rows, message.quote, { at: "end" }); case "delete": return write.remove(this.$rows, message.symbol); } }); } } ``` A watch, an autorun, `observe`, or a mounted `useValue(feed.$symbols)` opens the socket. ```ts import { createRealm, watch } from "@frondruntime/pinna"; const realm = createRealm(); const feed = new QuoteFeed(realm); // The first observer opens the socket; stopping the last one closes it. const stop = watch( realm, (read) => read(feed.$status), (status) => { console.log(`quotes: ${status}`); }, ); ``` A request is the same shape without a socket. An `AbortController` cancels the request a newer one replaces, and `reconcile` keeps each unchanged row's instance, so a refetch that changed nothing notifies nobody. The parser reuses `isRecord` and `isPrice` from the first sample and throws on a body that does not fit, and the status ends in `"failed"`. ```ts import { box, Model, reconcile, update } from "@frondruntime/pinna"; interface Position { readonly id: string; readonly symbol: string; readonly quantity: number; } type Load = | { readonly state: "loading" } | { readonly state: "loaded" } | { readonly state: "failed"; readonly error: unknown }; const positionsUrl = "https://example.com/positions"; const toPosition = (value: unknown): Position => { if (isRecord(value)) { const { id, symbol, quantity } = value; if (typeof id === "string" && typeof symbol === "string" && isPrice(quantity)) { return { id, symbol, quantity }; } } throw new TypeError("positions: a row is not a position"); }; class Positions extends Model { readonly $rows = box>(this.realm, []); readonly $load = box(this.realm, { state: "loading" }); private controller: AbortController | undefined; // Loads the account's positions. A newer call aborts this one, and an // aborted call writes nothing, so the last call wins. The rows stay on // screen while the next ones load. async refresh(account: string): Promise { this.controller?.abort(); const controller = new AbortController(); this.controller = controller; update(this.realm, (_read, write) => write(this.$load, { state: "loading" })); try { const response = await fetch(`${positionsUrl}/${encodeURIComponent(account)}`, { signal: controller.signal, }); if (!response.ok) { throw new Error(`positions: the server answered ${response.status}`); } const body: unknown = await response.json(); if (!Array.isArray(body)) { throw new TypeError("positions: the body is not a list"); } const next = body.map(toPosition); if (controller.signal.aborted) { return; } update(this.realm, (read, write) => { // Unchanged positions keep their instance; nothing changed keeps the array. write( this.$rows, reconcile(read(this.$rows), next, { keyOf: (position) => position.id, equals: (previous, current) => previous.symbol === current.symbol && previous.quantity === current.quantity, }), ); write(this.$load, { state: "loaded" }); }); } catch (error) { // An aborted fetch rejects too; the newer call owns the status. if (controller.signal.aborted) { return; } update(this.realm, (_read, write) => write(this.$load, { state: "failed", error })); } } } ``` ## Rules - Write each message in one update. A reader then sees a snapshot whole or not at all; a write per row would show every row in between. - Write a snapshot through `write.replaceAll` on a collection with `equals`. An unchanged row keeps its instance, so a reconnect that sends the same quotes reruns no reader. `write.replaceAll` throws on a repeated key and writes nothing, so reject one at the boundary. - Await a request, then write its result in an update of its own: an update is synchronous ([Updates](../state/updates.md)). - Check that a request was not aborted before writing its result or its failure. An aborted `fetch` rejects, and without the check the older request's failure overwrites the newer one's `"loading"`. - The hook writes `"connecting"`, in an update. The cleanup writes nothing, so rows and status stay as last written while nothing observes the feed, and the next snapshot replaces the rows. - Keep a connection's state inside the call that opens it, and detach the socket's `onclose` before closing it, so a socket from an earlier observation schedules no reconnect. - A message the parser drops goes to the host's `reportError`, where a realm made without `onError` also reports. A realm made with `onError` does not see it. `onObserved` and atoms are on [Lifecycles](../state/lifecycles.md), the writes to a collection on [Collections](../state/collections.md), and `reconcile` on [Updates](../state/updates.md). ## With Effect The same feed as an Effect program. `Schema.fromJsonString` parses and checks a message in one step, and fails with a `SchemaError` for anything that does not fit. ```ts import { Schema } from "effect"; const Quote = Schema.Struct({ symbol: Schema.String, bid: Schema.Finite, ask: Schema.Finite, }); type Quote = typeof Quote.Type; const QuoteMessage = Schema.Union([ Schema.Struct({ type: Schema.Literal("snapshot"), quotes: Schema.Array(Quote) }), Schema.Struct({ type: Schema.Literal("upsert"), quote: Quote }), Schema.Struct({ type: Schema.Literal("delete"), symbol: Schema.String }), ]); type QuoteMessage = typeof QuoteMessage.Type; // Parses the JSON and checks it in one step; fails with a SchemaError. const decodeMessage = Schema.decodeUnknownEffect(Schema.fromJsonString(QuoteMessage)); ``` The watchlist is a `BoxField`, checked on every write: people type it, and it is saved with the board. The quotes are a plain collection and the status a plain box, written only from messages the decode checked, so nothing checks them twice ([Plain or schema boxes](../start/index.md#plain-or-schema-boxes)). Loosening a field's schema to make the feed fast would leave every other writer of that field unchecked; the hot rows go in a plain collection instead. ```ts import { BoxField, box, collection, SchemaModel, update } from "@frondruntime/pinna-effect"; import { Schema } from "effect"; type Status = "connecting" | "open" | "closed"; class QuoteBoard extends SchemaModel("QuoteBoard")({ // Typed by people and saved with the board: every write is checked. $watchlist: BoxField(Schema.Array(Schema.String)), }) { // Written by the feed alone, from messages the decode checked: checked nowhere else. readonly $quotes = collection(this.realm, { keyOf: (quote: Quote) => quote.symbol, equals: Schema.toEquivalence(Quote), }); readonly $status = box(this.realm, "closed"); setStatus(status: Status): void { update(this.realm, (_read, write) => write(this.$status, status)); } add(symbol: string): void { update(this.realm, (read, write) => write(this.$watchlist, [...read(this.$watchlist), symbol])); } // One update per message: a reader sees all of it or none of it. receive(message: QuoteMessage): void { update(this.realm, (_read, write) => { switch (message.type) { case "snapshot": return write.replaceAll(this.$quotes, message.quotes); case "upsert": return write.upsert(this.$quotes, message.quote, { at: "end" }); case "delete": return write.remove(this.$quotes, message.symbol); } }); } } ``` `Stream.callback` turns the socket's callbacks into a stream. The socket opens in `Effect.acquireRelease`, so closing the stream's scope closes it, and a drop fails the stream with `SocketClosed`. ```ts import { Cause, Data, Effect, Queue, Stream } from "effect"; class SocketClosed extends Data.TaggedError("SocketClosed")<{ readonly code: number }> {} // Each message the socket receives. The stream fails with SocketClosed when // the socket closes, and closing the stream's scope closes the socket. const socket = (url: string, onOpen: () => void): Stream.Stream => Stream.callback((queue) => Effect.acquireRelease( Effect.sync(() => { const next = new WebSocket(url); next.onopen = onOpen; next.onmessage = (event: MessageEvent) => { Queue.offerUnsafe(queue, String(event.data)); }; next.onclose = (event: CloseEvent) => { Queue.failCauseUnsafe(queue, Cause.fail(new SocketClosed({ code: event.code }))); }; return next; }), (next) => Effect.sync(() => { next.onclose = null; next.close(); }), ), ); ``` `changes` streams the watchlist, and `Stream.switchMap` closes the socket of the previous list and opens one for the new list. `Stream.retry` reopens the socket after a drop, and its schedule resets once a message passes through. Each message is decoded, then written in one update; a message that fails either step is logged and dropped. ```ts import { changes } from "@frondruntime/pinna-effect"; import { Effect, Schedule, Stream } from "effect"; const quotesUrl = "wss://example.com/quotes"; // 0.5 s after a drop, doubling up to 30 s; a message that arrives resets it. const reconnect = Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("30 seconds")]); // Follows the board's watchlist: a new list closes the socket and opens one for it. const follow = Effect.fn("follow")(function* (board: QuoteBoard) { yield* changes(board.$watchlist).pipe( Stream.switchMap((symbols) => { const url = `${quotesUrl}?symbols=${symbols.map(encodeURIComponent).join(",")}`; return socket(url, () => board.setStatus("open")).pipe( Stream.onStart(Effect.sync(() => board.setStatus("connecting"))), Stream.tapError(() => Effect.sync(() => board.setStatus("closed"))), Stream.retry(reconnect), ); }), Stream.runForEach((data) => decodeMessage(data).pipe( // A write that throws, such as a snapshot that repeats a symbol, is undone. Effect.flatMap((message) => Effect.try(() => board.receive(message))), Effect.catch((error) => Effect.logWarning("quotes: dropped a message", error)), ), ), ); }); ``` A layer provides the realm. The fiber owns the feed: the socket is open while the fiber runs, whether or not anything observes the board, and interrupting the fiber closes it. A value that should run only while a screen shows it is owned by observation instead, through `fromStream` ([Programs](../effect/programs.md#lifetimes)). ```ts import { createRealm, decode, RealmService } from "@frondruntime/pinna-effect"; import { Effect, Fiber, Layer } from "effect"; const realm = createRealm(); const RealmLive = Layer.succeed(RealmService, realm); // Throws the SchemaError when the saved board does not fit. const board = decode(realm, QuoteBoard)({ watchlist: ["ACME", "GLOBEX"] }); // The socket is open while the fiber runs. const fiber = Effect.runFork(follow(board).pipe(Effect.provide(RealmLive))); // Interrupting the fiber closes the socket. const close = () => Effect.runFork(Fiber.interrupt(fiber)); ``` - Wrap the write in `Effect.try`. A throw inside `Effect.sync` is a defect, and a defect in `Stream.runForEach` ends the program, socket and all. `Effect.try` makes it an error the program logs; the update has already undone the write. - Write each status in the stage that knows it: `Stream.onStart` for `"connecting"`, the socket's `onopen` for `"open"`, and `Stream.tapError`, before `Stream.retry`, for `"closed"`. Without `Stream.tapError`, the status stays `"open"` through every reconnect wait. ## See also - [Lifecycles](../state/lifecycles.md): `onObserved`, atoms, and `observe`. - [Collections](../state/collections.md): `keys`, `row(key)`, and `equals`. - [Updates](../state/updates.md): what an update undoes when it throws. - [Programs](../effect/programs.md): `changes`, `watchScoped`, `fromStream`, and who owns a feed. - [Classes](../effect/classes.md): `SchemaModel`, `BoxField`, and `decode`. - [Hooks](../react/hooks.md): `useValue` and a list that rerenders one row. --- # Indexes and sets URL: https://pinna.frondruntime.dev/docs/guides/row-indexes Description: Read when a value follows a collection a row at a time. Keep a set of keys, the keys of each group, and a sum per group, with collections, boxes, and onRowChange. ## Example Each structure on this page takes a few lines over the calls on [Collections](../state/collections.md); Pinna has no call for any of them. `onRowChange` keeps a structure in step with a collection a row at a time. The samples share one collection of orders, with amounts in whole cents. ```ts import { collection, createRealm } from "@frondruntime/pinna"; const realm = createRealm(); interface Order { readonly id: string; readonly customer: string; /** Whole cents, so a sum kept by adding and subtracting stays exact. */ readonly cents: number; } const $orders = collection(realm, { keyOf: (order: Order) => order.id, equals: (previous, next) => previous.customer === next.customer && previous.cents === next.cents, }); ``` A set of keys is a collection keyed by the key itself. `read.row` tracks one key, so a row that asks whether it is selected reruns only when its own key joins or leaves the set. An array in a box reruns every such reader on each change, and each one scans the array. ```ts import { collection, computedFunction, update } from "@frondruntime/pinna"; // A set of order ids: a collection keyed by the id itself. const $selected = collection(realm, { keyOf: (id: string) => id }); const toggleSelected = (id: string) => { update(realm, (read, write) => { if (read.row($selected, id) === undefined) { write.upsert($selected, id); } else { write.remove($selected, id); } }); }; // Tracks one id: selecting another order reruns nothing here. const isSelected = computedFunction( realm, (read, id: string) => read.row($selected, id) !== undefined, ); ``` A value per group, such as its keys or its sum, is one box per group, made on the first ask. A map of groups in one box copies every group on each change and reruns every reader of every group. ```ts import { type Box, box, type Realm } from "@frondruntime/pinna"; // One box per key, made on the first ask. The map holds boxes, never values, // so a write that fails puts back what the boxes hold and leaves at most an // empty box behind. const boxPerKey = (realm: Realm, initial: Value) => { const boxes = new Map>(); return (key: Key): Box => { let $value = boxes.get(key); if ($value === undefined) { $value = box(realm, initial); boxes.set(key, $value); } return $value; }; }; ``` The ids of each customer's orders. `onRowChange` reports a row `before` and `after` the write, so an order that moves to another customer leaves one group and joins the other in the same report. ```ts import { onRowChange } from "@frondruntime/pinna"; // The ids of each customer's orders. A write to one customer's orders reruns // the readers of that customer alone. const ordersOf = boxPerKey>(realm, []); const stopOrdersOf = onRowChange($orders, ({ key, before, after }, read, write) => { if (before?.customer === after?.customer) { return; // a new amount under the same customer moves no id } if (before !== undefined) { const $ids = ordersOf(before.customer); write( $ids, read($ids).filter((id) => id !== key), ); } if (after !== undefined) { const $ids = ordersOf(after.customer); write($ids, [...read($ids), key]); } }); ``` A sum per customer subtracts the row `before` and adds the row `after`: two writes per change, however many orders the customer has. ```ts import { onRowChange } from "@frondruntime/pinna"; // The sum of each customer's orders, in cents. const totalOf = boxPerKey(realm, 0); const stopTotalOf = onRowChange($orders, ({ before, after }, read, write) => { if (before !== undefined) { const $total = totalOf(before.customer); write($total, read($total) - before.cents); } if (after !== undefined) { const $total = totalOf(after.customer); write($total, read($total) + after.cents); } }); ``` A graph is a collection of edges with two such indexes, one by source and one by target. A walk over it, such as every key reachable from one key, is a function that reads them, run in a `computed` or an update, and reruns in full on each change it reads. Rows kept in sorted order are on [Collections](../state/collections.md#sorted-rows). ## Rules - Keep what a listener builds in boxes and collections, so a failed write puts it back with the row ([Collections](../state/collections.md)). - Skip a report that leaves a row's group as it was. Removing the key and adding it again moves it to the end of its group and reruns that group's readers for nothing. - Keep amounts as integers. Each floating-point add and subtract rounds, so a sum kept that way drifts from the sum of its rows. - A change copies the group it writes, as a collection copies its key order when a key is added or removed. - A `computed` over `rows` derives the same values with no listener, and reruns over every row on each change. It fits a collection that is small or rarely written. ## See also - [Collections](../state/collections.md): `onRowChange`, `read.row`, what each write reports, and sorted rows. - [Updates](../state/updates.md): the update a listener runs in, and what a failed one puts back. - [Collection fields](../effect/collections.md): a collection as a field of a `SchemaModel`. --- # Saving state URL: https://pinna.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 a burst of changes once, skip a save that changes nothing, keep a storage error as state, and write a pending save on dispose. ## Example A workspace keeps a theme and whether the sidebar is open across reloads, in `localStorage`. The storage is passed in, so a test hands the model one that keeps the saves in memory, or one that refuses them. ```ts interface SettingsStorage { readonly load: () => string | undefined; // Throws when the storage refuses the write, as a full localStorage does. readonly save: (text: string) => void; } const browserStorage: SettingsStorage = { load: () => localStorage.getItem("workspace") ?? undefined, save: (text) => localStorage.setItem("workspace", text), }; ``` The model saves a computed projection: `$saved` is the text to store, built from the boxes that are saved and from nothing else. `$hovered` is shown on screen and never saved: `$saved` does not read it, so a write to it neither recomputes `$saved` nor runs the watch. The constructor and `flush` read `$saved` through `untracked`, which reads without subscribing. ```ts import { box, computed, Model, type Realm, untracked, update, watch } from "@frondruntime/pinna"; type Theme = "light" | "dark"; class Workspace extends Model implements Disposable { readonly $theme = box(this.realm, "light"); readonly $sidebarOpen = box(this.realm, true); // Shown, never saved: a restart begins with nothing hovered. readonly $hovered = box(this.realm, undefined); readonly $storageError = box(this.realm, undefined); // The text to save, and nothing else: it never reads $hovered, so a write // to $hovered leaves it, and the watch below, untouched. private readonly $saved = computed(this.realm, (read) => JSON.stringify({ theme: read(this.$theme), sidebarOpen: read(this.$sidebarOpen) }), ); private readonly storage: SettingsStorage; private readonly stopSaving: () => void; private queued = false; private lastSaved: string; constructor(realm: Realm, storage: SettingsStorage) { super(realm); this.storage = storage; // Restored before the watch starts, so restoring saves nothing back. this.restore(); this.lastSaved = untracked(realm, (read) => read(this.$saved)); this.stopSaving = watch( realm, (read) => read(this.$saved), () => { this.queue(); }, ); } private restore() { const text = this.storage.load(); if (text === undefined) return; let saved: { readonly theme?: unknown; readonly sidebarOpen?: 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. update(this.realm, (_read, write) => { if (saved?.theme === "light" || saved?.theme === "dark") write(this.$theme, saved.theme); if (typeof saved?.sidebarOpen === "boolean") write(this.$sidebarOpen, saved.sidebarOpen); }); } // 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 = untracked(this.realm, (read) => read(this.$saved)); if (text === this.lastSaved) return; // the burst ended where it began try { this.storage.save(text); this.lastSaved = text; 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); update(this.realm, (_read, write) => write(this.$storageError, message)); } } [Symbol.dispose]() { this.stopSaving(); this.flush(); // a save still queued is written now, not lost } } ``` The workspace is made once, in module code. ```ts import { createRealm } from "@frondruntime/pinna"; const realm = createRealm(); const workspace = new Workspace(realm, browserStorage); ``` ## Rules - Save a `computed` that builds the stored text, not the boxes one by one. The watch runs only when that text changes, so state the screen shows but the save leaves out, such as a hover or a selection, writes nothing to the storage. - Restore before starting the watch, and set the last saved text from the restored state. A restore after the watch starts writes boxes the watch reads, which queues a save of what the restore loaded. - Take each restored field only when it is valid, and keep the default for the rest. A save written by an older version, or edited by hand, then loses one field, not the whole workspace; text that does not parse starts from the defaults. - Queue the save with `queueMicrotask`, read the text when it runs, and skip it when the text equals the last one written. A watch runs once per outermost update, so an event handler that makes several updates runs it several times; the queued save runs once, after the handler returns, and a burst that ends where it began, such as a toggle clicked twice, writes nothing. - Catch a storage error in `flush` and write it to a box. `flush` runs from a microtask, where a throw reaches no caller; as state, the screen shows it. The last saved text stays as it was, so the next change saves again. - Dispose with `using` or `[Symbol.dispose]()`: it stops the watch, then writes a save still queued, at once. A workspace made right after the dispose loads what it saved, and a test realm's dispose finds no watch still running. ## With Effect Stored text comes from outside the program: an older version wrote it, or a person edited it. With Effect, `restore` decodes it through a schema instead of checking each field by hand, so the check and the type come from one declaration and cannot drift apart. Each field recovers from a refusal with `Schema.catchDecoding` and decodes to no field at all, so one bad field keeps its default and the others still restore. ```ts import { Effect, Option, Schema } from "effect"; // 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)), ), sidebarOpen: Schema.optionalKey( Schema.Boolean.pipe(Schema.catchDecoding(() => Effect.succeedNone)), ), }), ); // Text that does not parse decodes to no fields, so the workspace keeps its defaults. const readSaved = (text: string): typeof SavedSettings.Type => Schema.decodeUnknownOption(SavedSettings)(text).pipe(Option.getOrElse(() => ({}))); ``` `restore` writes each field `readSaved` returns, in one update. The boxes stay plain: the workspace writes them itself, so only the restore needs the check. ## See also - [Reacting](../state/reacting.md): `watch` and when its effect runs. - [Updates](../state/updates.md): an effect that cannot be taken back runs after the update. - [Boxes and computed](../state/boxes.md): a `Model` and its `$` fields. - [Testing](./testing.md): `testRealm`, and the dispose that finds a watch still running. - [Errors](./errors.md#fields-a-schema-refuses): what a schema reports for a field it refuses. --- # Testing URL: https://pinna.frondruntime.dev/docs/guides/testing Description: Read when writing tests. Make a test realm per test, read and write as application code does, record what a select changed to, check what a collection still holds, and test models and programs with Effect. ## Example The state under test is a model: a class that extends `Model`, so each test can make one in a realm of its own. ```ts import { box, computed, Model, update } from "@frondruntime/pinna"; // The state under test: a count of open todos and the method that closes one. class Todos extends Model { readonly $open = box(this.realm, 2); readonly $label = computed(this.realm, (read) => `${read(this.$open)} open`); close(): void { update(this.realm, (read, write) => { if (read(this.$open) === 0) throw new Error("nothing is open"); write(this.$open, read(this.$open) - 1); }); } } ``` A test makes its own realm with `testRealm` from `@frondruntime/pinna/testing` and builds its state in it. It reads through `untracked` and writes through the methods that call `update`, as an event handler does. Held with `using`, the realm is disposed when the test ends, and its dispose throws if a watch, an autorun, an `observe`, an `onRowChange` listener, or a stage is still running. ```ts import { expect, test } from "bun:test"; import { untracked } from "@frondruntime/pinna"; import { testRealm } from "@frondruntime/pinna/testing"; test("closing a todo updates the label", () => { // A realm per test: nothing one test made is seen by the next. Its dispose, // when the test ends, throws if a watch or an autorun is still running. using realm = testRealm(); const todos = new Todos(realm); todos.close(); expect(untracked(realm, (read) => read(todos.$label))).toBe("1 open"); }); ``` `record` keeps each value a select changes to, in `values`, and stops when its `using` scope ends. Each update reruns it once, after the update ends, and only when the value changed, so `values.length` counts the changes. ```ts import { expect, test } from "bun:test"; import { update } from "@frondruntime/pinna"; import { record, testRealm } from "@frondruntime/pinna/testing"; test("closing two todos in one update records one change", () => { using realm = testRealm(); const todos = new Todos(realm); // Declared after the realm, so it stops before the realm checks. using labels = record(realm, (read) => read(todos.$label)); update(realm, () => { todos.close(); todos.close(); }); expect(labels.values).toEqual(["0 open"]); }); ``` An update that throws leaves the realm as it was. ```ts import { expect, test } from "bun:test"; import { untracked, update } from "@frondruntime/pinna"; import { testRealm } from "@frondruntime/pinna/testing"; test("an update that throws leaves the realm as it was", () => { using realm = testRealm(); const todos = new Todos(realm); expect(() => update(realm, () => { todos.close(); todos.close(); todos.close(); // nothing is open: throws, and the two before it are undone }), ).toThrow("nothing is open"); expect(untracked(realm, (read) => read(todos.$open))).toBe(2); }); ``` `retainedKeys` names the keys a collection still keeps something for: a row, or the box and computed value a reader made for a key. A test of a feed that removes rows checks that this set is exactly the keys that remain, so a removed row that stays in memory fails the test, which a count of the rows would not show. ```ts import { expect, test } from "bun:test"; import { collection, observe, update } from "@frondruntime/pinna"; import { retainedKeys, testRealm } from "@frondruntime/pinna/testing"; test("a refetch lets go of the rows it drops", () => { using realm = testRealm(); const $trades = collection(realm, { keyOf: (trade: { readonly id: string }) => trade.id }); update(realm, (_read, write) => { write.replaceAll($trades, [{ id: "a" }, { id: "b" }, { id: "c" }]); }); // A reader of a row makes a box and a computed value for its key. const release = observe($trades.row("c")); update(realm, (_read, write) => { write.replaceAll($trades, [{ id: "a" }]); }); // "c" is gone with its box and computed value, though still observed. expect(retainedKeys($trades)).toEqual(new Set(["a"])); release(); }); ``` ## 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 `untracked(realm, (read) => ...)`, write with `update` or a model method that calls it. The testing entry adds no reader or writer, so a test goes through the same calls as application code. - A watch's effect runs after the outermost update ends, so a test that records values asserts after the update returns. - Declare the realm before the recordings: `using` disposes in reverse order, so each recording stops before the realm checks. - Stop every watch, autorun, `observe`, and `onRowChange` listener a test starts, and apply or drop every stage. One left running keeps its values cached and its `onObserved` hooks started, and a stage left open holds its overlay, so the test realm's dispose throws, naming each by its `name`, or `watch`, `autorun`, `onRowChange`, or `stage`, and stops it so the next test starts clean; a stage is dropped. A React component's subscription is not counted. - Hold each one in `using`: a watch through `record`, the rest through `held`, as in `using _ = held(autorun(realm, ...))`. A stop function called at the end of the test is skipped when an assertion fails, the dispose then throws too, and Bun 1.4.4 prints the resulting `SuppressedError` without either error, so the assertion's diff is lost. - Check what a collection holds with `retainedKeys`, never through its private fields: they are not part of the API and change without notice. ## Answers | Call | Answers | | --- | --- | | `testRealm(options?)` | A realm of the test's own; its dispose throws if a watch, an autorun, an `observe`, an `onRowChange` listener, or a stage is still running. | | `record(realm, select, options?)` | `values`, each value `select` changed to, oldest first; `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; every one is a present key. Throws for a value that is not a collection Pinna made. | ## With Effect A model decoded from `pinna-effect` is tested the same way. The `TodoList` and its wire data, `items`, are the ones from [Collection fields](../effect/collections.md). ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { decode, untracked } from "@frondruntime/pinna-effect"; import { TodoList } from "./models.ts"; test("toggling a todo closes it", () => { // A realm per test: nothing one test made is seen by the next. using realm = testRealm(); const list = decode(realm, TodoList)({ items }); const first = untracked(realm, (read) => read(list.$items.row("1"))); first?.toggle(); expect(untracked(realm, (read) => read(list.$open))).toBe(0); }); ``` A watch on the model and a write the schema rejects behave as above: one rerun per update, and a rejected write leaves the realm as it was. An Effect program takes the test's realm: `watchScoped(realm, ...)` and `fromStream(realm, ...)` take it first, and `changes`, `observeScoped`, and `whileObserved` take it from the observable. A `SchemaModel` decoded inside an Effect program reads it from `RealmService`, which the test provides. A `Deferred` waits for the watch's effect without a sleep. Close every program's scope: a program left running keeps its values cached and its `onObserved` hooks started, and the test realm's dispose throws for its watch. ```ts import { expect, test } from "bun:test"; import { testRealm } from "@frondruntime/pinna/testing"; import { RealmService, schemaBox, update, watchScoped } from "@frondruntime/pinna-effect"; import { Deferred, Effect, Schema } from "effect"; test("a program reads the test's realm", async () => { using realm = testRealm(); const $query = schemaBox(realm, Schema.String, ""); const program = Effect.gen(function* () { const searched = yield* Deferred.make(); yield* watchScoped( realm, (read) => read($query), (query) => Deferred.succeed(searched, query), ); update(realm, (_read, write) => write($query, "pinna")); return yield* Deferred.await(searched); }); const query = await Effect.runPromise( program.pipe(Effect.scoped, Effect.provideService(RealmService, realm)), ); expect(query).toBe("pinna"); }); ``` | Call | Answers | | --- | --- | | `decode(realm, Model)(json)` | A model in the test's realm. | | `Effect.provideService(RealmService, realm)` | A `SchemaModel` decoded inside the program lands in the test's realm. | A program that polls or sleeps runs on `TestClock`: [Programs](../effect/programs.md#testing) shows where to provide it and what a test waits on instead of the clock. ## See also - [Updates](../state/updates.md): what an update undoes when it throws. - [Reacting](../state/reacting.md): when a watch reruns. - [Programs](../effect/programs.md): `watchScoped`, `withStage`, and testing a program on `TestClock`. - [Errors and debugging](./errors.md): what throws, and where the rest goes. --- # Errors and debugging URL: https://pinna.frondruntime.dev/docs/guides/errors Description: Read when something throws or reruns unexpectedly. Know which errors reach the caller and which go to onError, how a computed value keeps its error, find why a value recomputed with inspect and names, and know the errors Effect adds. ## Example A realm takes `onError`: where an error goes when there is no caller to throw to. `report` stands for the application's own error reporter. ```ts import { createRealm } from "@frondruntime/pinna"; // Errors with no caller to throw to: a watch effect's, an autorun's after // its first run, an onObserved hook's. The host's reportError by default. const realm = createRealm({ onError: (error) => report(error) }); ``` A computed value that throws keeps the error as its value. Every read rethrows it, and it computes again only when what it read changes. ```ts import { box, computed, update } from "@frondruntime/pinna"; const $count = box(realm, 1, { name: "count" }); const $inverse = computed( realm, (read) => { const count = read($count); if (count === 0) throw new Error("no inverse of zero"); return 1 / count; }, { name: "inverse" }, ); update(realm, (_read, write) => write($count, 0)); // Every read of $inverse throws "no inverse of zero" until $count changes. ``` A watch effect runs after the write has landed, so its error goes to `onError`, not to the writer. ```ts import { update, watch } from "@frondruntime/pinna"; const stop = watch( realm, (read) => read($count), (count) => { if (count > 10) throw new Error(`too many: ${count}`); }, ); // The write lands; the effect's error goes to onError, and the watch keeps running. update(realm, (_read, write) => write($count, 11)); ``` `inspect` reports what a value last read, how many observe it, and, for a named computed value, why it last recomputed. It reports one level; inspect a dependency to go further. ```ts import { inspect, update, watch } from "@frondruntime/pinna"; update(realm, (_read, write) => write($count, 2)); const stopInverse = watch( realm, (read) => read($inverse), () => undefined, ); update(realm, (_read, write) => write($count, 4)); inspect($inverse); // { name: "inverse", realm: undefined, dependencies: ["count"], observers: 1, // lastReason: "count changed" } ``` ## Rules - Errors with a caller throw to it: every misuse throws from the call that made it, and an update that throws rolls back. An `onError` that throws while a write's watchers run throws to the writer, with the writes in place. - Errors without one go to `onError`: a watch effect's, an autorun's after its first run, an `onObserved` hook's or cleanup's, and watchers that never settle. The first run of a `watch` or `autorun` throws to the caller, and nothing is watched. - Name what gets debugged: `{ name }` on a box or a computed value. A named computed value keeps why it last recomputed, and its errors name it. An unnamed one costs nothing for names. - Pinna has no development mode. Every check runs in every build. ## Answers | Call | Answers | | --- | --- | | `inspect($x)` | `{ name, realm, dependencies, observers, lastReason }`. `realm` is the name of the realm that made the value, `undefined` for an unnamed realm. | Every message Pinna throws, with its cause and fix, is on [Error messages](../reference/errors.md). ## With Effect A schema adds errors with a caller, and a program has a place for defects. - A write the schema of a [`schemaBox`](../effect/boxes.md) or a `BoxField` refuses throws from the write, and the update rolls back. The error's `cause` is the `Schema.SchemaError` that says what did not fit. A row a [collection field](../effect/collections.md) refuses throws the same error. - `decode` throws `Schema.SchemaError` for input that does not fit the schema. - A [program's](../effect/programs.md) defect is logged at the error level through Effect's logger. A `watchScoped` watch keeps running; a `fromStream` stream or a `whileObserved` run ends, and the next observation starts it again. Their messages are on [Error messages](../reference/errors.md#with-effect). ### Fields a schema refuses A form shows each refused field beside its input, so it needs the field's path and a message, not the error's text. A filter made with `Schema.makeFilter` gives its own message when it returns a string in place of `false`. ```ts import { Schema } from "effect"; // A filter that returns a string fails with that string as its message. const Password = Schema.String.check( Schema.makeFilter((password) => password.length >= 8 || "Use at least 8 characters"), ); const Signup = Schema.Struct({ email: Schema.String, password: Password }); ``` The `Schema.SchemaError` holds an `issue`, and `SchemaIssue.makeFormatterStandardSchemaV1()` turns it into a list of `{ path, message }`. `decode` throws the `SchemaError` itself; a write a box refuses throws an `Error` whose `cause` is the `SchemaError`. ```ts import { Schema, SchemaIssue } from "effect"; const toStandard = SchemaIssue.makeFormatterStandardSchemaV1(); // Each refused field's path and message. `decode` throws the SchemaError; a // write a box refuses throws an Error whose `cause` is the SchemaError. // Anything else is not a schema's refusal, and is thrown again. const issuesOf = (error: unknown) => { const schemaError = error instanceof Error && !Schema.isSchemaError(error) ? error.cause : error; if (!Schema.isSchemaError(schemaError)) { throw error; } return toStandard(schemaError.issue).issues; }; ``` ```ts import { createRealm, decode, schemaBox, update } from "@frondruntime/pinna-effect"; const realm = createRealm(); const $signup = schemaBox(realm, Signup, { email: "", password: "correct horse" }); const submit = (input: unknown) => { try { return { signup: decode(realm, Signup)(input), issues: [] }; } catch (error) { // [{ path: ["password"], message: "Use at least 8 characters" }] return { signup: undefined, issues: issuesOf(error) }; } }; const editPassword = (password: string) => { try { update(realm, (read, write) => { write($signup, { ...read($signup), password }); }); return []; } catch (error) { return issuesOf(error); } }; ``` - `decode` stops at the first field it refuses, so for a struct such as `Signup` the list holds one issue: input with two bad fields reports the first. A union, or a filter that returns several issues, reports more. - A field that is absent reads as `Missing key` at its path, and a value of the wrong type as `Expected` and the type, such as `Expected string`. - A refused write leaves the box as it was, as every update that throws does, so the form keeps the last value that fit. - An error that is neither is no schema's refusal, such as a failed request, and is thrown again rather than shown as a field's message. ## See also - [Updates](../state/updates.md): what an update undoes when it throws. - [Reacting](../state/reacting.md): watch and autorun, and their first run. - [Programs](../effect/programs.md): how a program reports a defect. - [Error messages](../reference/errors.md): every message, its cause, and the fix. - [Testing](./testing.md): asserting on a rejected write. - [Schema-checked boxes](../effect/boxes.md): what a box checks, and when. --- # Error messages URL: https://pinna.frondruntime.dev/docs/reference/errors Description: Read when Pinna throws or logs a message. Every message Pinna and pinna-effect throw or log, what caused it, and the fix. This page lists every message Pinna and `@frondruntime/pinna-effect` throw or log, grouped by the call that causes it, with the cause and the fix. [Errors and debugging](../guides/errors.md) covers where an error goes and how to find why a value recomputed. ## Rules - Every message starts with `pinna: `, 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` or a `write` message prints `$observable`, and a message from a computed value prints `a derived value`. - A `read` or a `write` message puts the name in quotes, such as `read("count")`. ## Answers ### Reading and writing | Error | Answers | | --- | --- | | `pinna: read() runs outside a place. ...` | A `read` used outside every place of its realm, such as one kept in a closure. Pass `read` down instead. | | `pinna: read.row($collection, key) runs outside a place. ...` | The same, for `read.row`. | | `pinna: write inside update` | A `write` kept past its update. | | `pinna: () is handed an observable of another 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 `createRealm({ name })` is named in the message, such as `(realm "quotes", not "ui")`. Build each observable from the realm that reads it. | | `pinna: needs a box, a computed value, or an atom` | `onObserved`, `observe`, or `inspect` given a value Pinna did not make. | | `pinna: expected a box, a computed value, or an atom` | `useValues` given a value Pinna did not make. | ### Updates | Error | Answers | | --- | --- | | `pinna: update cannot run in a computed value; ...` | An update inside a computed value or a computed function's value. Write from an event, a watch's effect, or an autorun. `onRowChange` called there says `onRowChange` in place of `update`. | | `pinna: update cannot run in a watch's select or a selector; ...` | An update inside a watch's select or a `useSelect` function. Write from an event, a watch's effect, or an autorun. `onRowChange` called there says `onRowChange` in place of `update`. | | `pinna: update recipes are synchronous; await outside, then update` | A recipe that returned a promise. The update is undone. Await outside, then update. | | `pinna: an update recipe returns nothing` | A recipe that returned a value other than `undefined` or a promise. The update is undone. | | `pinna: cannot write while it computes` | A computed value that wrote, through a `write` kept from an update. | ### Stages | Error | Answers | | --- | --- | | `pinna: runs on a stage after it was ; ...` | A `StageClosedError`: a stage call after `applyStage` or `dropStage` closed it. `` is `stageUpdate`, `stageRead`, `realmRead`, `applyStage`, or `openStage` of a child; a named stage reads `the stage ""`. `stageStatus` and `inspectStage` remain callable outside a recipe after closing. `dropStage` on a closed stage does nothing. | | `pinna: applyStage finds that changed since the stage read ; nothing lands` | A `StageConflictError`: a stage opened with `{ conflicts: "fail" }` read a box or a collection that changed in the realm before it landed. `` names each by its `{ name }`: an unnamed box is ``, an unnamed collection `a collection`. The stage is dropped. Retry the work over the new values, or open the stage without the option to replay over them. | | `pinna: of a stage runs after its recipe returned; ...` | 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`. | | `pinna: runs inside a stage recipe, ...` | A stage call, `onObserved`, or `onRowChange` on the stage's realm inside a recipe, a `stageRead` function, or a computed value the stage evaluates. Call it outside the recipe or evaluation. | | `pinna: a stage recipe writes the realm, through update or a write kept from one; ...` | A realm write inside a stage recipe, which would show at once and survive a drop. Write through the recipe's own `write`. | | `pinna: read() of the realm runs inside a stage recipe, ...` | A `read` of the stage's realm, kept from another place, inside a recipe, a `stageRead` function, or a computed value the stage evaluates, where it would skip the stage's values. `read.row` and `untracked` say so in its place. Read through the stage's `read`. | | `pinna: is made inside a stage 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 `stageRead` function, or a computed value the stage evaluates; replay would make it again. Make it outside and close over it. | | `pinna: a stage recipe cannot observe or release while it computes` | A `watch`, an `autorun`, or an `observe` started inside a stage recipe. | | `pinna: runs in stageRead, which writes nothing; write in stageUpdate` | A write inside a `stageRead` function, such as a `reconcileSchema` merge. | | `pinna: applyStage runs on a stage while a child stage of it is open; ...` | A precondition failure: the stage stays open. Apply or drop the child first. | | `pinna: conflicts is "replay" or "fail", not ` | `openStage` given another `conflicts` value, from code the types did not check. | | `pinna: a child stage takes no conflicts option; ...` | `openStage(stage, { conflicts })`. The root stage's option covers what its children read. | | `pinna: is read while a stage evaluates it (cycle)` | A computed value that reads itself, read through a stage. | | `pinna: stageUpdate cannot run in a computed value; ...` | As for `update`, with `stageUpdate` or `applyStage` in its place, and the same for a watch's select or a selector. This precondition failure leaves the stage open. | | `pinna: stageRead cannot run in a computed value; ...` | `stageRead` or `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. | | `pinna: stageUpdate recipes are synchronous; await outside, then stageUpdate` | A `stageUpdate` recipe that returned a promise. Its writes to the stage are put back. | | `pinna: a stageUpdate recipe returns nothing` | A `stageUpdate` recipe that returned a value other than `undefined` or a promise. | | `StageConflict` | Not thrown: `withStage` fails with this tagged error on a conflict, in the error channel, where `Effect.catchTag` and `Effect.retry` take it. | ### Drafts | Error | Answers | | --- | --- | | `pinna: write.modify drafts arrays and plain objects; ...` | `write.modify` on a box holding another kind of value. Write it whole with `write($box, value)`. | | `pinna: a modify recipe returns nothing; write through the draft` | A `write.modify` recipe that returned a value. | | `pinna: a draft is used after its recipe returned` | A draft kept past its recipe. | | `pinna: write.modify left an object it wrote under 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. | | `pinna: a draft does not take defineProperty; assign instead` | `Object.defineProperty` on a draft. | | `pinna: a draft cannot change its prototype` | `Object.setPrototypeOf` on a draft. | ### Declaring | Error | Answers | | --- | --- | | `pinna: a name is a non-empty string` | `{ name: "" }`. | | `pinna: box takes a value, not a schema; ...` | `box` given an Effect schema. A box that checks a schema is `schemaBox` from `@frondruntime/pinna-effect`. | ### Computed values and watchers | Error | Answers | | --- | --- | | `pinna: is read while it computes (cycle)` | A computed value that reads itself, directly or through others. | | `pinna: cannot observe or release while it computes` | A `watch`, an `autorun`, an `observe`, or a release inside a computed value. | | `pinna: watchers did not settle after 100 rounds` | 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. | | `pinna: onObserved hooks did not settle after 100 passes` | Sent to `onError`: hooks kept starting other hooks. The hooks still due wait for the next settle. | ### Collections | Error | Answers | | --- | --- | | `pinna: the collection key appears twice` | A [collection](../state/collections.md)'s `write.replaceAll` given two rows of one key. Nothing is written. | | `pinna: reconcile: the key appears twice` | `reconcile` given two items of one key in `next`. | | `pinna: on the collection an onRowChange listener is reporting; ...` | A listener that wrote the collection it listens to. `` is `write.upsert`, `write.remove`, or `write.replaceAll`. The write fails and is put back. | | `pinna: onRowChange on the collection an onRowChange listener is reporting` | A listener that added another listener to the collection it listens to. | | `pinna: an onRowChange listener is synchronous and returns nothing` | A listener that returned a value, such as a promise. The write fails and is put back. | | `pinna: onRowChange needs a collection made by Pinna` | `onRowChange` given a value Pinna did not make. | ### React | Error | Answers | | --- | --- | | `pinna: useRealm and useSelect need a RealmProvider above the component` | `useRealm` or `useSelect` with no `RealmProvider` above. `useValue` and `useValues` need none. | | `pinna: expected a realm made by createRealm()` | `useSelect` under a `RealmProvider` given something other than a realm. | | `pinna: useValues takes observables of one realm` | `useValues` given observables of two realms; named realms are named in the message. | ## With Effect | Error | Answers | | --- | --- | | `pinna: the box rejects this value: ...` | A write the schema refused, with the `Schema.SchemaError` as its `cause`. The update rolled back. | | `pinna: Todo.a and Todo.b both read "key"; rename one` | Two fields under one wire key, thrown when the class is defined. The other naming errors are on [Classes](../effect/classes.md). | | `pinna: the collection key appears twice` | Also a `decode` of a [collection field](../effect/collections.md) given two rows of one key, inside the `Schema.SchemaError`. | | `pinna: a watch effect died`, `pinna: a stream into a value died`, `pinna: a program run while observed died` | Logged at the error level, with the defect as its cause: a `watchScoped` effect, a `fromStream` stream, or a `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. | | `Schema.SchemaError` | `decode` input that does not fit the schema. | ## See also - [Errors and debugging](../guides/errors.md): which errors reach the caller, which go to `onError`, and `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 `SchemaModel` throws when it is defined.