A workflow: statuses that only move forward#
oneOf is a choice of names. A step law is about one step: when narrows the
request, and after reads the state after it.
import {oneOf, proveSteps, rule, when} from 'gdp-wired'
const order = rule('order')
.inputs({op: oneOf('pay', 'ship', 'refund')})
.state({status: oneOf('new', 'paid', 'shipped', 'refunded').from('new')})
.flags(({op, status}) => ({
paying: op.is('pay').and(status.is('new')),
shipping: op.is('ship').and(status.is('paid')),
refunding: op.is('refund').and(status.is('paid')),
}))
.step(({paying, shipping, refunding, status}) => ({
status: when(paying, 'paid', when(shipping, 'shipped', when(refunding, 'refunded', status))),
}))
const neverRefunded = order.stepLaw('a shipped order is never refunded',
(_, after) => after.status.is('refunded').not(), ({status}) => status.is('shipped'))
const paidFirst = order.stepLaw('only a paid order ships',
({status}, after) => after.status.is('shipped').implies(status.is('paid').or(status.is('shipped'))),
)
proveSteps(order, [], [neverRefunded, paidFirst]) // {proven: true, checked: true}
The same workflow as a statechart#
When a workflow has more than a few states, write it as a table. chart takes nested states, parallel
regions, guards (when), extended state (context and set) and a
compound's history, and compiles them to the same kind of rule. check() answers what a
chart's author asks first: every state is reached (with the run that reaches it, or a proof that none does), no
state is stuck, and no event is ambiguous.
import {chart} from 'gdp-wired'
const order = chart('order')
.states({
new: {},
active: {states: {paid: {}, shipped: {}}},
refunded: {final: true},
delivered: {final: true},
})
.on('pay', {from: 'new', to: 'active'}) // enters active.paid, its first state
.on('ship', {from: 'active.paid', to: 'active.shipped'})
.on('refund', {from: 'active.paid', to: 'refunded'})
.on('deliver', {from: 'active.shipped', to: 'delivered'})
order.check()
// {ok: true, stuck: [], ambiguous: [],
// reached: {'active.shipped': {run: [{event: 'pay'}, {event: 'ship'}]}, ...}}
const neverAfterShipping = order.stepLaw('a shipped order is never refunded',
(_, after) => after.in('refunded').not(), before => before.in('active.shipped'))
order.prove([], [neverAfterShipping]) // {proven: true, checked: true}
Already ship an XState machine, or want to test the real app around this chart?
Continue to With XState, and model-based tests for fromXState,
conforms, toLogic with @xstate/graph, and offline JSONL trace conformance.