xmachines-runtime 2.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
#![doc = include_str!("../README.md")]

mod actor;
pub mod core;
mod delay;
mod error;
mod event;
pub mod host;
mod interp;
mod load;
mod machine;
pub mod migrate;
pub mod ops;
mod registry;
pub mod step;
pub mod system;

use serde::de::DeserializeOwned;
use serde_json::Value;

pub use actor::{Actor, RestoreOptions};
pub use error::{LoadError, LoadErrorKind};
pub use event::{js_numbers, Ev, EventType};
pub use load::{Reference, References};
pub use machine::{Machine, NodeId};
pub use migrate::Migration;
pub use registry::{
    Code, CodeKind, ContextArgs, Enq, Evaluator, ExprArgs, GuardArgs, HostEvaluator, Registry, Scope, Slot,
    SpawnOptions,
};
pub use system::{
    ActorRef, Effect, EffectKind, ExternalEffect, InitOptions, Logic, Status, System, SystemError, SystemLogic,
    DEFAULT_MAX_STEPS,
};

/// What code generated by `xmachines-build` refers to. Not a stable API.
#[doc(hidden)]
pub mod __codegen {
    pub use crate::{
        Actor, Ev, Evaluator, EventType, ExprArgs, GuardArgs, LoadError, Logic, Machine, Registry, Status, SystemError,
    };
    pub use indexmap::IndexMap;
    pub use serde;
    pub use serde_json;
}

/// Includes the module `xmachines-build` generated for a machine bundle, by
/// module name (the bundle's file name without `.machine.json`):
///
/// ```ignore
/// pub mod checkout {
///     xmachines_runtime::include_machine!("checkout");
/// }
/// ```
#[macro_export]
macro_rules! include_machine {
    ($name:literal) => {
        include!(concat!(env!("OUT_DIR"), "/xstate/", $name, ".rs"));
    };
}

impl<C, E> Machine<C, E>
where
    C: DeserializeOwned + 'static,
    E: EventType + 'static,
{
    /// Compiles a `MachineJSON` definition. Every referenced guard, action and
    /// named delay must be in `registry` (or defined in the JSON itself). A
    /// macrostep is unbounded unless the definition sets
    /// `options.maxIterations`, as `machineToJSON` writes it.
    pub fn from_json(json: &Value, registry: &Registry<C, E>) -> Result<Self, LoadError> {
        load::load(json, registry)
    }

    /// Validates a definition and lists the guards, actions, delays and
    /// actors it needs from the host (everything not defined in the JSON or
    /// built in), with their JSON paths and params. Used by code generation.
    pub fn references(json: &Value) -> Result<References, LoadError> {
        load::references(json)
    }

    /// Parses and compiles a definition from a JSON string. Key order is
    /// preserved, which transition priority depends on.
    pub fn from_json_str(json: &str, registry: &Registry<C, E>) -> Result<Self, LoadError> {
        let value: Value = serde_json::from_str(json)
            .map_err(|e| LoadError::new(LoadErrorKind::Invalid, "$", format!("invalid JSON: {e}")))?;
        Self::from_json(&value, registry)
    }
}