A lightweight, type-safe finite state machine (FSM) library for TypeScript and Node.js.
- Zero runtime dependencies
- Immutable context
- Guards and lifecycle hooks
- Snapshot/restore support
- Fully typed API
npm install state-flow-engineimport { createMachine } from "state-flow-engine";
type State = "idle" | "loading" | "success" | "failure";
type Event = "FETCH" | "RESOLVE" | "REJECT" | "RESET";
const machine = createMachine({
initial: "idle",
context: {
attempts: 0,
data: null as string | null,
},
states: {
idle: {},
loading: {},
success: {
terminal: true,
},
failure: {},
},
transitions: {
FETCH: [
{
from: "idle",
target: "loading",
},
],
RESOLVE: [
{
from: "loading",
target: "success",
reduce: () => ({
data: "payload",
}),
},
],
REJECT: [
{
from: "loading",
target: "failure",
},
],
RESET: [
{
from: "failure",
target: "idle",
},
],
},
});
machine.send("FETCH");
machine.send("RESOLVE");
console.log(machine.getState()); // success
console.log(machine.isDone()); // true- Typed states and events
- Transition guards
- Immutable context updates
- Lifecycle hooks (
onEntry,onExit) - Snapshot and restore support
- Strict and non-strict modes
- ESM-compatible
Creates a new machine instance.
| Method | Description |
|---|---|
send(event) |
Attempts a transition |
getState() |
Returns current state |
getContext() |
Returns immutable context |
can(event) |
Checks if transition is possible |
availableEvents() |
Lists valid events |
isDone() |
Checks terminal state |
subscribe(listener) |
Registers transition listener |
snapshot() |
Creates serializable snapshot |
restore(snapshot) |
Restores machine from snapshot |
const paymentMachine = createMachine({
initial: "pending",
context: {
paid: false,
},
states: {
pending: {},
completed: {
terminal: true,
},
},
transitions: {
PAY: [
{
from: "pending",
target: "completed",
guard: ctx => ctx.paid === true,
},
],
},
});MIT