A lightweight, type-safe state machine library for JavaScript/TypeScript with production-ready performance and clean architecture. Features declarative state management, comprehensive error handling, and server-scale performance testing.
- π― Declarative API - Clean, intuitive syntax for state definitions
- π Type Safety - Full TypeScript support with strict type checking
- ποΈ Builder Pattern - Fluent API with method chaining
- β‘ Production Ready - Optimized bundle (~45KB) with tree-shaking support
- π‘οΈ Guard Conditions - Conditional transition logic (sync & async)
- π Actions - State entry, exit, and transition actions (sync & async)
- π§ Middleware Pipeline System - Powerful middleware system with BaseMiddleware class and extensible architecture
- π Async Transactions - Database transactions with automatic rollback
- π¨ Error Handling - Comprehensive error types with rollback support
- π Observability - Built-in statistics, history, and event tracking
- π Performance - Stateless definitions for zero per-object overhead
- π Scalable - Efficient pattern for millions of objects
- π§ͺ Testing - Comprehensive test suite
npm install @jewel998/state-machinepnpm add @jewel998/state-machineyarn add @jewel998/state-machineimport { StateMachine } from '@jewel998/state-machine';
// 1. Create ONE shared definition (zero per-object overhead)
const orderWorkflow = StateMachine.definitionBuilder()
.initialState('PENDING')
.state('PENDING')
.state('APPROVED')
.state('SHIPPED')
.transition('PENDING', 'APPROVED', 'approve')
.transition('APPROVED', 'SHIPPED', 'ship')
.buildDefinition();
// 2. Objects just track their state
class Order {
constructor(id) {
this.id = id;
this.state = 'PENDING'; // Just the state value - no machine instance!
}
processEvent(event) {
const result = orderWorkflow.processEvent(this.state, event, this);
if (result.success) {
this.state = result.newState;
}
return result.success;
}
}
// 3. Scale to millions with shared definition
const orders = Array.from({ length: 1000000 }, (_, i) => new Order(`ORD-${i}`));
orders.forEach((order) => order.processEvent('approve'));
console.log('Processed 1M orders with ONE shared definition!');const orderWorkflow = StateMachine.definitionBuilder()
.initialState('DRAFT')
.state('DRAFT')
.state('INVENTORY_RESERVED')
.state('PAYMENT_PROCESSED')
.state('CONFIRMED')
// Reserve inventory with automatic rollback on failure
.transition('DRAFT', 'INVENTORY_RESERVED', 'reserve_inventory')
.transaction(
async (context) => {
await database.reserveInventory(context.orderId, context.quantity);
await database.updateOrderStatus(context.orderId, 'RESERVED');
},
async (context, error) => {
// Automatic rollback on any failure
await database.rollbackInventory(context.orderId, context.quantity);
}
)
// Process payment with rollback
.transition('INVENTORY_RESERVED', 'PAYMENT_PROCESSED', 'process_payment')
.transaction(
async (context) => {
await paymentService.charge(context.orderId, context.amount);
},
async (context, error) => {
// Rollback both payment and inventory
await paymentService.refund(context.orderId, context.amount);
await database.rollbackInventory(context.orderId, context.quantity);
}
)
.buildDefinition();
// Use async processing
class Order {
async processEvent(event) {
const result = await orderWorkflow.processEventAsync(this.state, event, this);
if (result.success) {
this.state = result.newState;
} else if (result.rollbackExecuted) {
console.log('Transaction rolled back automatically');
}
return result.success;
}
}const workflow = StateMachine.definitionBuilder()
.initialState('IDLE')
.state('PROCESSING')
.state('COMPLETED')
.transition('IDLE', 'PROCESSING', 'start')
.guard(async (context) => {
// Async guard - check permissions from database
return await permissionService.hasAccess(context.userId);
})
.action(async (context) => {
// Async action
await auditService.log('Processing started', context);
})
.onStateEntry('PROCESSING', async (context) => {
await context.startTimer();
})
.buildDefinition();interface OrderContext {
orderId: string;
amount: number;
approved: boolean;
}
type OrderState = 'PENDING' | 'APPROVED' | 'REJECTED' | 'SHIPPED';
type OrderEvent = 'approve' | 'reject' | 'ship';
const orderMachine = StateMachine.builder<OrderContext, OrderState, OrderEvent>()
.initialState('PENDING')
.state('PENDING')
.state('APPROVED')
.state('REJECTED')
.state('SHIPPED')
.transition('PENDING', 'APPROVED', 'approve')
.guard((context) => context.amount < 10000)
.transition('PENDING', 'REJECTED', 'reject')
.transition('APPROVED', 'SHIPPED', 'ship')
.build();Create powerful, composable middleware with the new pipeline architecture:
import { StateMachine, BaseMiddleware } from '@jewel998/state-machine';
// Create custom middleware extending BaseMiddleware
class LoggingMiddleware extends BaseMiddleware<OrderContext, OrderState> {
constructor() {
super('logging', { priority: 100 });
}
async onAction(context, next, originalAction) {
console.log(`Processing order ${context.currentContext.orderId}`);
const result = await next();
console.log('Order processing completed');
return result;
}
async onBeforePipeline(context) {
console.log(`Pipeline ${context.pipelineId} starting`);
}
}
class ValidationMiddleware extends BaseMiddleware<OrderContext, OrderState> {
constructor() {
super('validation', { priority: -100 }); // Run first
}
async onGuard(context, next, originalGuard) {
if (context.currentContext.amount <= 0) {
return false; // Stop pipeline
}
return await next();
}
}
// Build state machine with middleware pipeline
const definition = StateMachine.definitionBuilder<OrderContext, OrderState, OrderEvent>()
.initialState('PENDING')
.state('PENDING')
.state('APPROVED')
.transition('PENDING', 'APPROVED', 'approve')
.action((context) => {
context.approved = true;
context.approvedAt = Date.now();
})
// Add middleware - executes in priority order
.addMiddleware(new ValidationMiddleware()) // Priority: -100 (first)
.addMiddleware(new LoggingMiddleware()) // Priority: 100 (second)
.buildDefinition();
// Use async methods for full middleware support
const result = await definition.processEventAsync('PENDING', 'approve', orderContext);Key Features:
- Complete Pipeline Implementation - All middleware methods fully functional
- BaseMiddleware Class - Type-safe base class for easy custom middleware
- Pipeline Context - Access to execution order, pipeline ID, and previous results
- Backward Compatibility - Existing middleware configurations work unchanged
- Error Handling - Comprehensive error handling and recovery mechanisms
Check out the comprehensive examples in the examples/ directory:
stateless-pattern.js- Efficient stateless pattern with 1M objectsasync-transactions.js- Database transactions with automatic rollbacksadvanced-features.js- Complex workflows with guards and actions
# Run the stateless pattern demo
node examples/stateless-pattern.js
# Run async transaction demo
node examples/async-transactions.js
# Run advanced features demo
node examples/advanced-features.jsCreates a new stateless definition builder instance.
.initialState(state)- Set the initial state.state(state)- Define a state.transition(from, to, event)- Define a transition.guard(condition)- Add guard condition (sync or async).action(callback)- Add action (sync or async).transaction(callback, rollback)- Add async transaction with rollback.onStateEntry(state, callback)- Add state entry action.onStateExit(state, callback)- Add state exit action.buildDefinition()- Create the stateless definition
.processEvent(currentState, event, context)- Process event synchronously.processEventAsync(currentState, event, context)- Process event asynchronously.canTransition(currentState, event, context)- Check if transition is possible.canTransitionAsync(currentState, event, context)- Check transition asynchronously.getAvailableEvents(currentState, context?)- Get available events for state.getInitialState()- Get the initial state.getAllStates()- Get all defined states
The library provides comprehensive error handling with specific error types:
import {
StateMachine,
InvalidTransitionError,
GuardConditionError,
ActionExecutionError,
} from '@jewel998/state-machine';
try {
machine.sendEventStrict('invalid_event');
} catch (error) {
if (error instanceof InvalidTransitionError) {
console.log(`Available events: ${error.availableEvents}`);
} else if (error instanceof GuardConditionError) {
console.log(`Guard failed: ${error.fromState} -> ${error.toState}`);
} else if (error instanceof ActionExecutionError) {
console.log(`Action failed: ${error.actionType} in ${error.state}`);
}
}- Workflow Management - Model business processes and approval workflows
- Game Development - Manage game states, character states, and UI flows
- Form Validation - Handle multi-step forms with complex validation rules
- API Integration - Manage request/response cycles and error handling
- UI Components - Control component behavior and user interactions
# Setup development environment
npm run setup
# Run tests
npm test
# Run stateless performance tests
npm run perf:quick
# Development workflow
npm run dev helpnpm run setup- Complete development setupnpm run test:all- Comprehensive test suitenpm run perf:quick- Quick stateless performance testsnpm run perf:server- Server-scale performance tests (millions of ops)npm run ci- CI/CD pipeline simulationnpm run dev <command>- Development workflow automation
Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
See CHANGELOG.md for a detailed history of changes.
- π Documentation
- π Issue Tracker
- π¬ Discussions