Skip to content

martemantas/state-flow-engine

Repository files navigation

State-Flow-Engine

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

Installation

npm install state-flow-engine

Quick Example

import { 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

Features

  • Typed states and events
  • Transition guards
  • Immutable context updates
  • Lifecycle hooks (onEntry, onExit)
  • Snapshot and restore support
  • Strict and non-strict modes
  • ESM-compatible

API

createMachine(schema, options?)

Creates a new machine instance.

Machine methods

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

Advanced Example

const paymentMachine = createMachine({
  initial: "pending",

  context: {
    paid: false,
  },

  states: {
    pending: {},
    completed: {
      terminal: true,
    },
  },

  transitions: {
    PAY: [
      {
        from: "pending",
        target: "completed",
        guard: ctx => ctx.paid === true,
      },
    ],
  },
});

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors