xmachines-runtime 6.0.0

XState v6 semantics in Rust: a port of XState's interpreter and actor runtime; not affiliated with Stately
Documentation
use std::fmt;

/// What went wrong while loading a machine definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadErrorKind {
    /// The definition is not valid JSON, or a value has the wrong shape.
    Invalid,
    /// A `{"@code": ...}` or `{"@expr": ...}` node that is malformed, or in a language with no evaluator.
    Code,
    /// A key that `machineFromJSON` does not accept.
    UnknownKey,
    /// A v6 feature this runtime does not support (yet).
    Unsupported,
    /// A transition target, `initial`, history target or `stateIn` id that does not resolve.
    InvalidTarget,
    /// A guard, action or delay referenced by name with no implementation.
    MissingImplementation,
    /// An implementation rejected the `params` it was given.
    InvalidParams,
    /// Two states share an id.
    DuplicateId,
}

/// An error raised while parsing, validating or compiling a machine definition.
///
/// `path` is a JSON path in the style XState uses, for example
/// `$.states.idle.on.go[0].guard`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadError {
    pub kind: LoadErrorKind,
    pub path: String,
    pub message: String,
}

impl LoadError {
    pub(crate) fn new(kind: LoadErrorKind, path: impl Into<String>, message: impl Into<String>) -> Self {
        Self { kind, path: path.into(), message: message.into() }
    }
}

impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at {}", self.message, self.path)
    }
}

impl std::error::Error for LoadError {}

/// One value of an XState error code's message: a string, quoted as
/// `JSON.stringify` quotes it, or any other value as `String(value)` writes it.
pub(crate) enum CodeValue<'a> {
    Str(&'a str),
    Raw(&'a str),
}

/// The message of an error XState reports as a code (its production
/// message, `xstateError`): the code, the values that identify what failed,
/// and a link to the code's entry in XState's error reference.
pub(crate) fn xstate_error(code: u32, values: &[CodeValue<'_>]) -> String {
    let mut message = format!("XState error E{code}");
    if !values.is_empty() {
        let values: Vec<String> = values
            .iter()
            .map(|v| match v {
                CodeValue::Str(s) => serde_json::Value::String((*s).to_owned()).to_string(),
                CodeValue::Raw(s) => (*s).to_owned(),
            })
            .collect();
        message.push_str(&format!(" ({})", values.join(", ")));
    }
    message.push_str(&format!(". See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e{code}"));
    message
}