Skip to content

Events

Both Fsm and BehavioralFsm emit lifecycle events throughout the input-handling and transition cycle. Subscribe with on(), which returns a { off() } subscription object.

const sub = fsm.on("transitioned", ({ fromState, toState }) => {
    console.log(`${fromState} -> ${toState}`);
});

sub.off(); // unsubscribe

on() is safe to call multiple times with the same callback, because the underlying Set deduplicates. To remove a specific listener, call off() on the returned Subscription. machina doesn’t provide an off(eventName, callback) API.

Event Payload Fired when
transitioning { fromState, toState } A transition is about to occur
transitioned { fromState, toState } A transition completed
handling { inputName } An input is about to be dispatched
handled { inputName } An input was successfully handled
nohandler { inputName, args } No handler found in current state
invalidstate { stateName } Transition targeted a nonexistent state
deferred { inputName } An input was deferred

Events follow a grammatical pattern: present participle (transitioning, handling) means “about to happen”; past participle (transitioned, handled) means “just happened”.

BehavioralFsm shares the same event names, and each built-in payload is intersected with a client field identifying which client the event pertains to:

connFsm.on("transitioned", ({ client, fromState, toState }) => {
    console.log(client.url, `${fromState} -> ${toState}`);
});

The field is necessary because one BehavioralFsm instance manages many independent clients. Without client in the payload, you couldn’t tell whose event just fired.

Custom events emitted with emit() pass through with the payload you supply, and machina doesn’t add a client field to them. An Fsm removes the client field from the seven built-in payloads only. A custom payload with its own client key arrives intact.

Subscribe to "*" to receive every event. The callback signature differs from named subscriptions: the first argument is the event name, the second is the payload.

fsm.on("*", (eventName, data) => {
    console.log(eventName, data);
});

Wildcard listeners fire before named listeners for the same event. The ordering is intentional: it lets relay listeners observe each event before specific subscribers react.

Handlers can emit custom events via the emit argument on the handler args object. The engine emits built-in lifecycle events automatically, and emit is for user-defined events. Subscribe to a custom event by name, the same way you subscribe to a built-in one.

const fsm = createFsm({
    id: "connectivity",
    initialState: "checking",
    context: { checkCount: 0 },
    states: {
        checking: {
            _onEnter({ ctx, emit }) {
                ctx.checkCount++;
                emit("checkCountUpdated", { checkCount: ctx.checkCount });
            },
        },
    },
});

fsm.on("checkCountUpdated", data => {
    const { checkCount } = data as { checkCount: number };
    console.log("check count:", checkCount);
});

The payload of a custom event is unknown until you narrow it, because this FSM doesn’t declare an event map. The next section adds that declaration. The "*" wildcard still receives custom events along with the built-in ones.

An event map declares each custom event’s payload once. The declaration types emit inside handlers and on() on the instance, so a misspelled event name or a wrong payload is a compile error on both sides.

The map goes in the same curried slot as the input payload map, as the events member of a vocabulary bag:

import { createFsm } from "machina";

type ConnectivityEvents = {
    checkCountUpdated: { checkCount: number };
    maxChecksReached: undefined; // payload-free
};

const fsm = createFsm<{ events: ConnectivityEvents }>()({
    id: "connectivity",
    initialState: "checking",
    context: { checkCount: 0 },
    states: {
        checking: {
            _onEnter({ ctx, emit }) {
                ctx.checkCount++;
                emit("checkCountUpdated", { checkCount: ctx.checkCount }); // payload checked
                emit("maxChecksReached"); // payload optional: the type admits undefined
                emit("checkCountUpdate", {}); // error: not in the map
            },
        },
    },
});

fsm.on("checkCountUpdated", ({ checkCount }) => {
    console.log("check count:", checkCount); // number
});
fsm.on("transitioned", ({ toState }) => {}); // built-ins stay typed
fsm.on("checkCountUpdate", () => {}); // error: not in the map

A payload is required unless its declared type admits undefined. Declare a payload-free event as undefined.

A declared name can’t be one of the seven built-in names. The engine owns those payloads, so events: { transitioned: { trackingId: string } } fails on the type argument with TS2344. A misspelled bag member fails the same way, with or without a valid member beside it.

To declare inputs and events together, give the bag both members. A bare input map in the slot keeps its meaning:

createFsm<ConnectivityInputs>()({ ... }); // inputs only, unchanged
createFsm<{ events: ConnectivityEvents }>()({ ... }); // events only
createFsm<{ inputs: ConnectivityInputs; events: ConnectivityEvents }>()({ ... }); // both

For a BehavioralFsm, the bag is the second type argument, after the client type:

const connFsm = createBehavioralFsm<Connection, { events: ConnectionEvents }>()({ ... });

A custom event’s payload is exactly the declared type. The engine doesn’t add a client field to it, on either class. A subscriber that needs the client for a custom event reads it from the payload, so include the client or its id when you emit.

onDispose and the public fsm.emit() are checked against the same map. The map is type-only. The engine never reads it, and the untyped forms keep working as before.

The built-in event payloads are fully typed via FsmEventMap and BehavioralFsmEventMap. You won’t normally need to reference these directly, because on() is already typed through the FSM instance. They’re exported for callbacks defined outside the on() call.

import type { FsmEventMap, BehavioralFsmEventMap } from "machina";

// Extracting the payload type for a specific event:
type TransitionedPayload = FsmEventMap["transitioned"];
// => { fromState: string; toState: string }

// With state names narrowed to your actual states:
type NarrowedPayload = FsmEventMap<"green" | "yellow" | "red">["transitioned"];
// => { fromState: "green" | "yellow" | "red"; toState: "green" | "yellow" | "red" }

A custom event’s payload comes from the FSM’s event map when it declares one, and is unknown otherwise. The wildcard path is always unknown. EventMapOfInstance extracts the declared map from an instance, for code that types callbacks outside the on() call:

import type { EventMapOfInstance } from "machina";

type CheckCountPayload = EventMapOfInstance<typeof fsm>["checkCountUpdated"];
// => { checkCount: number }