Entity / Laws
Choosing the right rule in authoring order
Reach for the simplest declaration that can express the constraint, because earlier steps require less machinery and catch mistakes earlier:
1. A Schema for a single value
When a single field determines validity (an enum, an integer, a minimum length), express it directly in the field's Schema. Every decoder enforces it automatically.
2. Variants for case-specific fields
When the fields a row carries depend on its state, model the cases with Entity.defineVariants instead of writing nullability invariants:
const DomainName = { id: Schema.String, name: Schema.String }
const Domain = Entity.defineVariants('Domain', {
Available: { ...DomainName, price: Schema.Finite, years: Schema.Int },
Unconfirmed: DomainName,
})Each variant automatically generates invariants and SQL CHECK constraints ensuring Available rows carry price and years while Unconfirmed rows omit them.
3. Derived facts for cross-row summaries
Counts and existence flags calculated from other rows stay accurate when declared as derived members rather than stored columns:
import { Derived, Relation } from 'foldkit-entity'
const Author = Entity.define('Author', Schema.Struct({ id: Schema.String }))
const Post = Entity.define('Post', Schema.Struct({ id: Schema.String, title: Schema.String }))
const Comment = Entity.define('Comment', Schema.Struct({ id: Schema.String }))
const Blog = Entity.relate(
{ Author, Post, Comment },
{ Comment: { post: Relation.one(Post), author: Relation.one(Author) } },
)
const CountedPost = Blog.Post.pipe(
Entity.derived({ commentCount: Derived.count(Blog.Comment.relations.post) }),
)4. Invariants for what every row and transition holds
Use Entity.invariant when a rule connects multiple fields on a row (like reservedWithinStock above) or compares before and after on an update:
const OrderFields = Entity.define(
'Order',
Schema.Struct({ id: Schema.String, status: Schema.Literals(['placed', 'shipped']) }),
)
const Order = OrderFields.pipe(
Entity.invariant(
'shippedStaysShipped',
({ before, after }) =>
Expr.or(Expr.not(Expr.eq(before.status, 'shipped')), Expr.eq(after.status, 'shipped')),
{ message: 'A shipped order stays shipped', path: ['status'] },
),
)Entity.judge(Order, { before, after }) evaluates invariants purely in memory and returns Valid, Invalid, or Undecided. State invariants (after only) judge inserts, updates, and deletes; transition invariants (before and after) judge updates only. A null operand fails an invariant, and an update on an already-broken row lands only if the row it leaves satisfies the rule.
5. Preconditions for a single write
When a rule restricts when one specific operation may run rather than every write on the Entity, attach when to Write.update:
const Publish = Mutation.write(
'Publish',
Write.update(
Entity.input(
Product,
Schema.Struct({ id: Schema.String, status: Schema.Literal('published') }),
),
{ id: 'id', when: () => Expr.eq(Product.fields.status, 'draft') },
),
)The writer checks when in the same SQL statement that applies the update and returns Unmet if it fails. Other writes on Product remain free of Publish's precondition.
6. Named states for lifecycles (from and becomes)
When multiple queries and writes share a condition such as "the product is a draft", name it once with Entity.refine:
const Draft = Entity.refine(Product, 'Draft', { status: 'draft' })
const Published = Entity.refine(Product, 'Published', { status: 'published' })
const Release = Mutation.write(
'Release',
Write.update(
Entity.input(
Product,
Schema.Struct({ id: Schema.String, status: Schema.Literal('published') }),
),
{ id: 'id', from: Draft, becomes: Published },
),
)from: Draftappends the state predicate to the write'swhen, refusing rows in other states asUnmet.becomes: Publishedchecks at declaration time (over finite states) or at commit time (via a postcondition over numeric fields, refusing asInvalid) that every successful write leaves the row inPublished.Query.from(Draft)andDraft.is(row)reuse the exact same state predicate in queries and type guards.
Note that from and becomes predicates must read only their own row so the writer can enforce them inside one statement; cross-row conditions (Expr.exists, Expr.path) belong in queries and guards.
7. Guards for who may act
Authority belongs in foldkit-guard so Forbidden runs before state checks and reveals nothing about hidden rows:
import { Guards } from 'foldkit-guard'
const User = Schema.Struct({ id: Schema.String })
const OwnedFields = Entity.define(
'Owned',
Schema.Struct({ id: Schema.String, ownerId: Schema.String, name: Schema.String }),
)
const Shop = Guards.declare(
'Shop',
User,
guard => ({
isOwner: guard.row(OwnedFields, user => Expr.eq(OwnedFields.fields.ownerId, user.id)),
}),
{ key: user => user.id, unguarded: 'allow' },
)
const Owned = OwnedFields.pipe(
Guards.attach(Shop, { row: { Read: [Shop.isOwner], Update: [Shop.isOwner] } }),
)8. Document laws for shared Sync state
For a foldkit-sync document, declare laws on forApplication(...).make to enforce constraints across the shared snapshot after every durable Message:
import { defineMessageUnion } from 'foldkit/message'
import { modifyFields } from 'foldkit/struct'
import type * as Update from 'foldkit/update'
import { Evidence, Graph, MessageSet, Module, Projection, Surface } from 'foldkit-surface'
import { DocumentId, forApplication } from 'foldkit-sync'
const BoardModel = Schema.Struct({
todos: Schema.Array(Schema.Struct({ id: Schema.String, title: Schema.String })),
})
type BoardModel = typeof BoardModel.Type
const BoardMessage = defineMessageUnion({
CreatedTodo: { id: Schema.String, title: Schema.String },
DuplicatedTodo: { id: Schema.String, copyId: Schema.String },
})
type BoardMessage = typeof BoardMessage.Type
type Return = Update.Return<BoardModel, BoardMessage>
const update = (model: BoardModel, message: BoardMessage): Return =>
BoardMessage.match<Return>(message, {
CreatedTodo: ({ id, title }) => ({
model: modifyFields(model, { todos: () => [...model.todos, { id, title }] }),
}),
DuplicatedTodo: ({ id, copyId }) => ({
model: modifyFields(model, {
todos: () =>
model.todos.flatMap(todo => (todo.id === id ? [todo, { ...todo, id: copyId }] : [todo])),
}),
}),
})
const BoardApp = Surface.application({
Model: BoardModel,
Message: BoardMessage,
initial: { todos: [] },
update,
})
const Board = forApplication(BoardApp).make({
documentId: DocumentId.make('capped-board'),
shared: Projection.pick(BoardApp.model.todos),
durable: MessageSet.make(BoardApp, [BoardMessage.CreatedTodo, BoardMessage.DuplicatedTodo]),
laws: {
atMost100Todos: {
holds: ({ after }) => after.todos.length <= 100,
message: 'A board holds 100 todos',
path: ['todos'],
},
},
})The server journal evaluates holds after folding the operation and rejects violations as Invalid with the law ID. Replicas evaluate the same rule optimistically (LawBrokenError), while authorize controls who may append each Message.