npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@state-machine/core

v0.1.3

Published

Fully typesafe finite state machine

Downloads

61

Readme

A finite state machine implemented in typescript

Features:

  • React integration(coming soon).
  • 100% typesafe without any manual casting needed.
  • States and events automatic inferred from machine definition.
  • Simple API.
  • Composability through machine composition.

Machine creation

To create a new machine we should use createMachine function:

// DENO import
import { createMachine } from "https://deno.land/x/state_machine_core/mod.ts";

// NODE import
import { createMachine } from "@state-machine/core";

Example:

fetch-machine

Let's create a simple state machine that represent a fetch request:

const requestMachine = createMachine({
    type: 'D',
    initial: 'idle',
    states: {
        idle: {
            on:{
                FETCH: () => 'loading'
            }
        },
        loading: {
            on: {
                RESOLVE: () => 'success',
                REJECT: () => ({ target: 'failure' })
            }
        },
        failure: {
            on: {
                RETRY: () => 'loading',
            }
        },
        success: {}
    }
})

In the machine definition object we find:

  • type: this is the machine type it could be D for a deterministic machine or ND for a non-deterministic machine.
  • initial: this is a string the specify the machine initial state.
  • states: object where every key represent a machine state.

State definition

In the example above we see that each state should have a property on, which is an object where every key of it define an event supported in the current state. For every event key we have a transition function defining the next machine after this event. For example:

idle: {
    on:{
        FETCH: () => 'loading'
    }
},

this means that on idle state we can receive FETCH event, after it we go from idle to loading state.

Querying machine state

requestMachine.state() // idle

Every machine has a state() function that returns at any moment in which state is the machine currently

Sending machine events

The state machine supports different events, by sending them we allow transitions between different states

requestMachine.state() // initial state 'idle'

requestMachine.send({ event: 'FETCH' });

requestMachine.state(); // next state 'loading'

Machine non-deterministic

Above was mentioned that a machine could be either deterministic or non-deterministic. A non-deterministic machine of type: 'ND' supports an internal context which can store information that can be used internally by the machine during some state transition, a machine that rely on the context information to execute a transition could go from state S1 to states S2 or S3 depending on the context, for that reason they are considered non-deterministic.

Let's see an example of this kind of machine, we will have a counterMachine which could have two possible states empty or non-empty:

counter-machine

Before see the code for the definition of the previous machine let's take a closer look to our not-empty state.

This state support events INC and DEC, in the case of INC we remain in the same state whenever it is emitted, but for DEC event we could go either to empty state or keep the machine as not-empty, the next state after DEC event doesn't depends only in the current machine state but also in the internal machine context, for this reason this machine is considered non-deterministic.

const counterMachine = createMachine({
        type: "ND",
        context: {
            count: 0,
        },
        initial: "empty",
        states: {
            empty: {
                on: {
                    INC: ({ context }) => {
                        context.count++;
                        return "not_empty";
                    },
                },
            },
            not_empty: {
                on: {
                    INC: ({ context }) => {
                        context.count++;
                        return { target: "not_empty" };
                    },
                    DEC: ({ context }) => {
                        context.count--;
                        return context.count === 0
                            ? "empty"
                            : { target: "not_empty" };
                    },
                },
            },
        },
    });
}

From the prvious machine definition we could see that the main differences compared to machines of type: 'D', are the context property as part of the machine declaration, and the context parameter passed to every transition function. As we mentioned before during the DECevent our machine depends on the context data to decide which is the new machine state.

Machines combination

// DENO import
import { combineMachines } from "https://deno.land/x/state_machine_core/mod.ts";

// NODE import
import { combineMachines } from "@state-machine/core";

Is possible combine two or more different state machines to create a new one composed from them.

Let's say we have the following traffic light machine:

traffic-light-machien

This machine model a traffic with initial state red and support one a CHANGE event, the following code create the previous machine:

const trafficLightMachine = createMachine({
    type: 'D',
    initial: 'red',
    states: {
        red: {
            on: {
                CHANGE: () => 'red_yellow',
            }
        },
        red_yellow: {
            on: {
                CHANGE: () => 'green',
            }
        },
        green: {
            on: {
                CHANGE: () => 'yellow',
            }
        },
        yellow: {
            on: {
                CHANGE: () => 'red',
            }
        }
    }
})

We can combine this machine with our previous fetchMachine to build a new one like:

const m = combineMachines({
        trafficLight: trafficLightMachine,
        request: requestMachine
    });

After this our new m machine have the following state:

m.state(); // { trafficLight: 'red', request: 'idle' }

It supports events either for requestMachine or trafficLightMachine:

m.send({ event: 'CHANGE' });

m.state(); // { trafficLight: 'red_yellow', request: 'idle' }

m.send({ event: 'FETCH' });

m.state(); // { trafficLight: 'red_yellow', request: 'loading' }

m.send({ event: 'CHANGE' });

m.state(); // { trafficLight: 'green', request: 'loading' }