New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

hsm_ts

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hsm_ts

Hierarchical State Machine implementation in TypeScript

latest
Source
npmnpm
Version
1.0.2
Version published
Maintainers
1
Created
Source

Hierarchical State Machine (HSM) Implementation

A TypeScript implementation of a Hierarchical State Machine (HSM) that provides a robust way to manage complex state transitions and behaviors in your applications.

Features

  • Hierarchical state management

  • Concurrent states

  • Event handling

  • Guard conditions

  • Entry/exit actions

  • Type-safe configuration

  • Function registry for handlers, guards, and actions

Roadmap

  • Choice states
  • History states (shallow and deep)
  • Fork and Join states

Installation

yarn add hsm_ts

Usage

Basic Example

import { HSM } from './src/core/HSM';
import { parseHSMConfig } from './src/utils/parser';
import { FunctionRegistry } from './src/types/hsm';

// Create a registry with your handler functions
const registry: FunctionRegistry = {
  guards: {
    canTransition: () => true
  },
  actions: {
    logTransition: () => console.log('Transitioning...')
  },
  handlers: {
    enterState: () => {
      console.log('Entering state');
      return { propagate: false };
    }
  }
};

// Define your state machine configuration
const config = {
  id: "simple",
  initial: "idle",
  states: {
    idle: {
      id: "idle",
      handlerReferences: {
        enter: "enterState"
      },
      transitions: [
        {
          event: "START",
          target: "active",
          guard: "canTransition",
          action: "logTransition"
        }
      ]
    },
    active: {
      id: "active",
      handlerReferences: {
        enter: "enterState"
      }
    }
  }
};

// Create and use the state machine
const hsm = new HSM(parseHSMConfig(config, registry));
hsm.deliverEvent({ type: "START" });

History States Example

const registry: FunctionRegistry = {
  handlers: {
    enterChild1: () => {
      console.log("Entering child1");
      return { propagate: false };
    },
    enterChild2: () => {
      console.log("Entering child2");
      return { propagate: false };
    }
  }
};

const config = {
  id: "historyExample",
  initial: "parent",
  states: {
    parent: {
      id: "parent",
      history: true,
      initial: "child1",
      states: {
        child1: {
          id: "child1",
          handlerReferences: {
            enter: "enterChild1"
          },
          transitions: [
            {
              event: "NEXT",
              target: "child2"
            }
          ]
        },
        child2: {
          id: "child2",
          handlerReferences: {
            enter: "enterChild2"
          }
        }
      }
    }
  }
};

Concurrent States Example

const registry: FunctionRegistry = {
  handlers: {
    enterStateA: () => {
      console.log("Entering state A");
      return { propagate: false };
    },
    enterStateB: () => {
      console.log("Entering state B");
      return { propagate: false };
    }
  }
};

const config = {
  id: "concurrent",
  initial: "parent",
  states: {
    parent: {
      id: "parent",
      type: "concurrent",
      childMachines: [
        {
          id: "machineA",
          initial: "stateA",
          states: {
            stateA: {
              id: "stateA",
              handlerReferences: {
                enter: "enterStateA"
              }
            }
          }
        },
        {
          id: "machineB",
          initial: "stateB",
          states: {
            stateB: {
              id: "stateB",
              handlerReferences: {
                enter: "enterStateB"
              }
            }
          }
        }
      ]
    }
  }
};

Function Registry

The HSM uses a function registry to manage all handlers, guards, and actions. This provides several benefits:

  • Type safety - all functions are properly typed
  • No eval-like behavior - functions are referenced directly
  • Better security - no string evaluation
  • Easier testing - functions can be mocked
  • Better IDE support - proper code completion and type checking

Registry Structure

interface FunctionRegistry {
  guards: {
    [key: string]: (event: Event) => boolean;
  };
  actions: {
    [key: string]: (event: Event) => void;
  };
  handlers: {
    [key: string]: (event: Event) => EventHandlingResult;
  };
}

Using the Registry

  • Define your functions in the registry
  • Reference them by name in your state configuration
  • Pass the registry to parseHSMConfig
const registry: FunctionRegistry = {
  guards: {
    canTransition: (event) => event.type === "START"
  },
  actions: {
    logTransition: (event) => console.log(`Transitioning on ${event.type}`)
  },
  handlers: {
    enterState: (event) => {
      console.log(`Entering state on ${event.type}`);
      return { propagate: false };
    }
  }
};

Functions can also be added manually to different transitions or states in the JS files as needed.

API Reference

HSM Class

  • constructor(config: HSMConfig)
  • deliverEvent(event: Event): void
  • getActiveState(): StateId
  • getActiveStates(): Set<StateId>

Event Handling

Events can be handled at any level of the state hierarchy. The propagate flag in the EventHandlingResult determines whether the event should continue propagating up the hierarchy.

interface EventHandlingResult {
  propagate: boolean;
}

State Types

  • normal - Standard state
  • concurrent - State that can have multiple active child states
  • history - State that remembers its last active child state

Contributing

  • Fork the repository
  • Create your feature branch
  • Commit your changes
  • Push to the branch
  • Create a new Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Keywords

state-machine

FAQs

Package last updated on 07 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts