Skip to main content

xmachines_runtime/
load.rs

1//! Parsing, validation and compilation of `MachineJSON` (the output of
2//! XState v6 `machineToJSON` / `machineConfigToJSON`) into a [`Machine`].
3
4use std::sync::Arc;
5
6use serde::de::DeserializeOwned;
7use serde_json::{json, Map, Value};
8
9use crate::core::{DomainHint, Kind as NodeKind, Nid, Tid, Tree, TreeNode, TreeTransition};
10use crate::delay::{ms_to_u64, parse_duration_ms};
11use crate::error::{xstate_error, CodeValue::Raw, CodeValue::Str, LoadError, LoadErrorKind as K};
12use crate::event::{Ev, EventType, AFTER, DONE_STATE};
13use crate::machine::*;
14use crate::registry::{Code, CodeKind, ContextArgs, ExprArgs, Registry, Scope, Slot};
15use crate::FixedMap;
16
17/// Ids of compiled code nodes ([`Code::id`]).
18static NEXT_CODE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
19
20type TransitionId = Tid;
21
22/// A node while loading; split into the shared [`Tree`] and [`NodeData`] at the end.
23struct Node {
24    key: String,
25    id: String,
26    parent: Option<NodeId>,
27    end: NodeId,
28    kind: NodeKind,
29    children: Vec<NodeId>,
30    history_children: Vec<NodeId>,
31    initial: Option<NodeId>,
32    history_target: Vec<NodeId>,
33    initial_input: Option<Value>,
34    /// Whether the state declares `onError` (XState's `config.onError`).
35    on_error: bool,
36    entry: Vec<Action>,
37    exit: Vec<Action>,
38    on: Vec<(String, Vec<Tid>)>,
39    always: Vec<Tid>,
40    delayed: Vec<DelayedDef>,
41    invokes: Vec<InvokeDef>,
42    output: Option<Template>,
43    tags: Vec<String>,
44}
45
46type Result<T> = std::result::Result<T, LoadError>;
47
48/// Keys `machineFromJSON` accepts on a state node, plus `onDone`, which
49/// `machineToJSON` emits and `createMachine` accepts.
50const STATE_KEYS: &[&str] = &[
51    "id",
52    "key",
53    "type",
54    "initial",
55    "states",
56    "on",
57    "onDone",
58    "onError",
59    "after",
60    "always",
61    "choice",
62    "route",
63    "invoke",
64    "entry",
65    "exit",
66    "meta",
67    "description",
68    "tags",
69    "input",
70    "timeout",
71    "onTimeout",
72    "history",
73    "target",
74    "output",
75    "context",
76];
77/// Keys `machineFromJSON` accepts on the root, plus `options`, which
78/// `machineToJSON` emits and `createMachine` accepts.
79const MACHINE_KEYS: &[&str] =
80    &["@exprLang", "version", "options", "actions", "guards", "actors", "delays", "schemas", "internalEvents"];
81const TRANSITION_KEYS: &[&str] =
82    &["reject", "target", "matches", "context", "actions", "guard", "description", "reenter", "meta", "input"];
83
84/// State-node keys that name v6 features this runtime does not run yet.
85const UNSUPPORTED_STATE_KEYS: &[(&str, &str)] = &[];
86
87fn err(kind: K, path: &str, message: impl Into<String>) -> LoadError {
88    LoadError::new(kind, path, message)
89}
90
91fn invalid(path: &str, message: impl Into<String>) -> LoadError {
92    err(K::Invalid, path, message)
93}
94
95fn child_path(path: &str, key: &str) -> String {
96    format!("{path}.{key}")
97}
98
99/// The language of the code nodes this runtime evaluates: the source is the
100/// name of a Rust implementation ([`Registry::expr`]).
101pub const RUST_LANG: &str = "rust";
102
103/// The source of a code node (`{"@code": ...}` or `{"@expr": ...}`).
104fn code_source(value: &Value) -> Option<&str> {
105    let map = value.as_object()?;
106    map.get("@code").or_else(|| map.get("@expr")).and_then(Value::as_str)
107}
108
109/// The language of a code node (its `@lang`, else the root `@exprLang`).
110fn code_lang<'v>(value: &'v Value, default_lang: Option<&'v str>) -> Option<&'v str> {
111    value.get("@lang").and_then(Value::as_str).or(default_lang)
112}
113
114/// Checks every code node's language: `rust`, or one `accept`s (a language
115/// with an evaluator).
116fn check_code(value: &Value, path: &str, default_lang: Option<&str>, accept: &dyn Fn(&str) -> bool) -> Result<()> {
117    match value {
118        Value::Object(map) => {
119            if let Some(key) = ["@code", "@expr"].into_iter().find(|k| map.contains_key(*k)) {
120                if !map[key].is_string() {
121                    return Err(err(K::Code, path, format!("{key} must be a string")));
122                }
123                let lang = match map.get("@lang") {
124                    Some(Value::String(l)) => Some(l.as_str()),
125                    Some(_) => return Err(err(K::Code, path, "@lang must be a string")),
126                    None => default_lang,
127                };
128                return match lang {
129                    Some(RUST_LANG) => Ok(()),
130                    Some(other) if accept(other) => Ok(()),
131                    Some(other) => Err(err(
132                        K::Code,
133                        path,
134                        format!(
135                            "{key} in language '{other}' has no evaluator: register one with Registry::evaluator, \
136                             or use \"@lang\": \"rust\" with the name of a Rust expression"
137                        ),
138                    )),
139                    None => Err(err(K::Code, path, format!("{key} without @lang (and no root @exprLang)"))),
140                };
141            }
142            for (k, v) in map {
143                check_code(v, &child_path(path, k), default_lang, accept)?;
144            }
145        }
146        Value::Array(items) => {
147            for (i, v) in items.iter().enumerate() {
148                check_code(v, &format!("{path}[{i}]"), default_lang, accept)?;
149            }
150        }
151        _ => {}
152    }
153    Ok(())
154}
155
156fn contains_code(value: &Value) -> bool {
157    match value {
158        Value::Object(map) => code_source(value).is_some() || map.values().any(contains_code),
159        Value::Array(items) => items.iter().any(contains_code),
160        _ => false,
161    }
162}
163
164fn has_unescaped_dot(key: &str) -> bool {
165    let mut chars = key.chars();
166    while let Some(c) = chars.next() {
167        match c {
168            '\\' => {
169                chars.next();
170            }
171            '.' => return true,
172            _ => {}
173        }
174    }
175    false
176}
177
178/// `key` with each unescaped dot escaped as a JavaScript string literal
179/// writes it (`\\.`), as XState's error for such a key suggests.
180fn escape_dots(key: &str) -> String {
181    let mut out = String::with_capacity(key.len() + 2);
182    let mut escaped = false;
183    for c in key.chars() {
184        if c == '.' && !escaped {
185            out.push_str("\\\\.");
186        } else {
187            out.push(c);
188        }
189        escaped = c == '\\';
190    }
191    out
192}
193
194/// Splits a state path on unescaped dots. `\.` stays in the segment (state
195/// keys keep their escapes); other escapes drop the backslash.
196pub(crate) fn to_state_path(path: &str) -> Vec<String> {
197    let mut out = Vec::new();
198    let mut segment = String::new();
199    let mut chars = path.chars();
200    while let Some(c) = chars.next() {
201        match c {
202            '\\' => match chars.next() {
203                Some('.') => segment.push_str("\\."),
204                Some(other) => segment.push(other),
205                None => {}
206            },
207            '.' => out.push(std::mem::take(&mut segment)),
208            other => segment.push(other),
209        }
210    }
211    out.push(segment);
212    out
213}
214
215struct RawNode<'j> {
216    json: &'j Map<String, Value>,
217    path: String,
218}
219
220struct Loader<'j, 'r, C, E> {
221    root_json: &'j Map<String, Value>,
222    default_lang: Option<&'j str>,
223    registry: &'r Registry<C, E>,
224    machine_id: Option<String>,
225    nodes: Vec<Node>,
226    raw: Vec<RawNode<'j>>,
227    id_map: FixedMap<String, NodeId>,
228    transitions: Vec<TransitionData>,
229    transition_sources: Vec<Nid>,
230    guards: Vec<crate::registry::GuardFn<C, E>>,
231    actions: Vec<CustomAction>,
232    delays: Vec<crate::registry::DelayFn<C, E>>,
233    named_delays: FixedMap<String, DelaySpec>,
234    raise_events: Vec<Ev<E>>,
235    exprs: Vec<crate::registry::ExprFn<C, E>>,
236    expr_index: FixedMap<String, u32>,
237    context_exprs: Vec<crate::registry::ContextFn>,
238    context_index: FixedMap<String, u32>,
239    /// Code nodes compiled so far (to tell whether a named action or guard
240    /// has expressions that read its params).
241    expr_refs: usize,
242    dynamic_actions: Vec<Dynamic<crate::registry::ActionFn>>,
243    dynamic_guards: Vec<Dynamic<crate::registry::GuardFn<C, E>>>,
244    /// When set, missing implementations are recorded here and replaced by
245    /// stubs instead of failing the load (see [`references`]).
246    refs: Option<References>,
247}
248
249/// A name the definition references without defining it, with the JSON path
250/// of the reference and its `params`.
251#[derive(Debug, Clone, PartialEq)]
252pub struct Reference {
253    pub name: String,
254    pub path: String,
255    pub params: Option<Value>,
256}
257
258/// Every guard, action, delay and actor source a definition needs from the
259/// host, in document order. Names defined in the JSON itself and built-ins
260/// are not included.
261#[derive(Debug, Clone, Default, PartialEq)]
262pub struct References {
263    pub guards: Vec<Reference>,
264    pub actions: Vec<Reference>,
265    pub delays: Vec<Reference>,
266    pub actors: Vec<Reference>,
267    /// Expressions (`{"@code": name, "@lang": "rust"}`), each name once.
268    pub exprs: Vec<Reference>,
269    /// Expressions in the root `context`, computed from the input.
270    pub contexts: Vec<Reference>,
271    /// Languages other than `rust` whose code nodes need an evaluator
272    /// ([`Registry::evaluator`]), each once, at its first node.
273    pub languages: Vec<Reference>,
274}
275
276/// Validates a definition as [`load`] does and lists the implementations it
277/// needs, with the runtime's own name resolution.
278pub(crate) fn references(json: &Value) -> Result<References> {
279    let registry: Registry<Value, Value> = Registry::new();
280    let (_, refs) = load_inner(json, &registry, Some(References::default()))?;
281    Ok(refs.unwrap_or_default())
282}
283
284/// Compiles a machine definition against a registry of implementations.
285pub(crate) fn load<C, E>(json: &Value, registry: &Registry<C, E>) -> Result<Machine<C, E>>
286where
287    C: DeserializeOwned + 'static,
288    E: EventType + 'static,
289{
290    load_inner(json, registry, None).map(|(m, _)| m)
291}
292
293/// The machine's `options`, as `createMachine` takes them: `maxIterations`
294/// bounds the microsteps of one macrostep, and a macrostep is unbounded
295/// without it.
296fn machine_options(root: &Map<String, Value>) -> Result<MachineOptions> {
297    let Some(options) = opt_object(root, "options", "$")? else {
298        return Ok(MachineOptions::default());
299    };
300    let mut max_iterations = None;
301    for (key, value) in options {
302        let path = format!("$.options.{key}");
303        match key.as_str() {
304            "maxIterations" => {
305                let max = value
306                    .as_u64()
307                    .and_then(|n| usize::try_from(n).ok())
308                    .ok_or_else(|| invalid(&path, "expected a non-negative integer"))?;
309                max_iterations = Some(max);
310            }
311            _ => return Err(err(K::UnknownKey, &path, format!("unknown key \"{key}\""))),
312        }
313    }
314    Ok(MachineOptions { max_iterations })
315}
316
317fn load_inner<C, E>(
318    json: &Value,
319    registry: &Registry<C, E>,
320    refs: Option<References>,
321) -> Result<(Machine<C, E>, Option<References>)>
322where
323    C: DeserializeOwned + 'static,
324    E: EventType + 'static,
325{
326    let root_json = json.as_object().ok_or_else(|| invalid("$", "a machine definition must be a JSON object"))?;
327    let default_lang = opt_str(root_json, "@exprLang", "$")?;
328    let listing = refs.is_some();
329    check_code(json, "$", default_lang, &|lang| listing || registry.evaluators.contains_key(lang))?;
330    let machine_id = opt_str(root_json, "id", "$")?.map(str::to_owned);
331    let version = opt_str(root_json, "version", "$")?.map(str::to_owned);
332    let options = machine_options(root_json)?;
333
334    let mut loader = Loader {
335        root_json,
336        default_lang,
337        registry,
338        machine_id,
339        nodes: Vec::new(),
340        raw: Vec::new(),
341        id_map: FixedMap::default(),
342        transitions: Vec::new(),
343        transition_sources: Vec::new(),
344        guards: Vec::new(),
345        actions: Vec::new(),
346        delays: Vec::new(),
347        named_delays: FixedMap::default(),
348        raise_events: Vec::new(),
349        exprs: Vec::new(),
350        expr_index: FixedMap::default(),
351        context_exprs: Vec::new(),
352        context_index: FixedMap::default(),
353        expr_refs: 0,
354        dynamic_actions: Vec::new(),
355        dynamic_guards: Vec::new(),
356        refs,
357    };
358    loader.check_machine_keys()?;
359    loader.load_named_delays()?;
360    loader.build_node(root_json, String::new(), None, "$".to_string(), &mut Vec::new())?;
361    for i in 0..loader.nodes.len() {
362        loader.resolve_node(i as NodeId)?;
363    }
364
365    let initial_context = match root_json.get("context") {
366        Some(ctx) if contains_code(ctx) => {
367            InitialContext::Template(loader.compile_template(ctx, "$.context", Slot::Context)?)
368        }
369        Some(ctx) => InitialContext::Value(
370            C::deserialize(ctx)
371                .map_err(|e| invalid("$.context", format!("context does not fit the context type: {e}")))?,
372        ),
373        None => InitialContext::Value(
374            C::deserialize(&Value::Object(Map::new())).or_else(|_| C::deserialize(&Value::Null)).map_err(|e| {
375                invalid(
376                    "$",
377                    format!("the definition has no context and the context type cannot be built from {{}}: {e}"),
378                )
379            })?,
380        ),
381    };
382    let output = match root_json.get("output") {
383        Some(o) => Some(loader.compile_template(o, "$.output", Slot::Output)?),
384        None => None,
385    };
386    let internal_events = match root_json.get("internalEvents") {
387        None => Vec::new(),
388        Some(Value::Array(items)) => items
389            .iter()
390            .enumerate()
391            .map(|(i, v)| {
392                v.as_str()
393                    .map(str::to_owned)
394                    .ok_or_else(|| invalid(&format!("$.internalEvents[{i}]"), "expected a string"))
395            })
396            .collect::<Result<_>>()?,
397        Some(_) => return Err(invalid("$.internalEvents", "expected an array of event descriptors")),
398    };
399
400    let mut tree_nodes = Vec::with_capacity(loader.nodes.len());
401    let mut nodes = Vec::with_capacity(loader.nodes.len());
402    for n in loader.nodes {
403        let mut t = TreeNode::new(n.parent, n.kind);
404        t.children = n.children;
405        t.history_children = n.history_children;
406        t.on = n.on;
407        t.always = n.always;
408        tree_nodes.push(t);
409        nodes.push(NodeData {
410            key: n.key,
411            id: n.id,
412            entry: n.entry,
413            exit: n.exit,
414            delayed: n.delayed,
415            invokes: n.invokes,
416            output: n.output,
417            tags: n.tags,
418            initial: n.initial.into_iter().collect::<Vec<_>>().into(),
419            initial_input: n.initial_input,
420            history_target: n.history_target.into(),
421            on_error: n.on_error,
422        });
423    }
424    for t in &mut loader.transitions {
425        t.selects = t.evaluates();
426    }
427    let tree_transitions =
428        loader.transition_sources.iter().map(|&source| TreeTransition { source, domain: DomainHint::None }).collect();
429
430    let refs = loader.refs;
431    let machine = Machine {
432        id: loader.machine_id,
433        version,
434        tree: Tree::new(tree_nodes, tree_transitions),
435        nodes,
436        transitions: loader.transitions,
437        guards: loader.guards,
438        actions: loader.actions,
439        actors: registry.actors.clone(),
440        delays: loader.delays,
441        raise_events: loader.raise_events,
442        exprs: loader.exprs,
443        context_exprs: loader.context_exprs,
444        dynamic_actions: loader.dynamic_actions,
445        dynamic_guards: loader.dynamic_guards,
446        action_factories: registry.actions.clone(),
447        host_actions: registry.host_actions.clone(),
448        id_map: loader.id_map,
449        internal_events,
450        initial_context,
451        output,
452        options,
453        start_error: (root_json.contains_key("initial") && obj_is_empty(root_json.get("states"))).then(|| {
454            // XState's code names the initial target and the root's id (the
455            // machine's).
456            let id = root_json.get("id").and_then(Value::as_str).unwrap_or_default();
457            let initial = root_json.get("initial").map(|v| v.get("target").unwrap_or(v));
458            let target = match initial {
459                Some(Value::Array(targets)) => targets.first(),
460                other => other,
461            };
462            match target {
463                Some(Value::String(target)) => xstate_error(64, &[Str(target), Str(id)]),
464                _ => xstate_error(64, &[Raw("undefined"), Str(id)]),
465            }
466        }),
467        empty: Default::default(),
468    };
469    Ok((machine, refs))
470}
471
472/// Rejects a v5 lifecycle event type with the id in it (`xstate.done.actor.job`,
473/// `xstate.after.1000.loading`) as an `on` key, as `createMachine` does: v6
474/// never sends these types, the id is in the event's payload, so the
475/// transition would never fire. A wildcard over a category
476/// (`xstate.done.actor.*`) and `xstate.snapshot.actor` are v6's own.
477fn check_lifecycle_descriptor(descriptor: &str, path: &str) -> Result<()> {
478    let Some(rest) = descriptor.strip_prefix("xstate.") else {
479        return Ok(());
480    };
481    let Some((category, suffix)) = ["done.actor", "error.actor", "snapshot", "done.state", "after"]
482        .iter()
483        .find_map(|c| Some((*c, rest.strip_prefix(c)?.strip_prefix('.')?)))
484    else {
485        return Ok(());
486    };
487    if suffix.is_empty() || suffix == "*" || (category == "snapshot" && (suffix == "actor" || suffix == "actor.*")) {
488        return Ok(());
489    }
490    let replacement = match category {
491        "after" => {
492            "use `after` on the state, or key on 'xstate.after' and select `matches: { stateId, delay }`".to_owned()
493        }
494        "done.state" => format!(
495            "use `onDone` on the state, or key on 'xstate.done.state' with `matches: {{ stateId: '{suffix}' }}`"
496        ),
497        "snapshot" => format!("key on 'xstate.snapshot.actor' with `matches: {{ actorId: '{suffix}' }}`"),
498        _ => format!("key on 'xstate.{category}' with `matches: {{ actorId: '{suffix}' }}`"),
499    };
500    Err(invalid(
501        path,
502        format!(
503            "transition \"{descriptor}\" never fires: v6 lifecycle event types carry the id in a payload field instead of the type; {replacement}"
504        ),
505    ))
506}
507
508fn obj_is_empty(v: Option<&Value>) -> bool {
509    v.and_then(Value::as_object).is_none_or(Map::is_empty)
510}
511
512fn opt_str<'a>(obj: &'a Map<String, Value>, key: &str, path: &str) -> Result<Option<&'a str>> {
513    match obj.get(key) {
514        None => Ok(None),
515        Some(Value::String(s)) => Ok(Some(s)),
516        Some(_) => Err(invalid(&child_path(path, key), "expected a string")),
517    }
518}
519
520fn opt_object<'a>(obj: &'a Map<String, Value>, key: &str, path: &str) -> Result<Option<&'a Map<String, Value>>> {
521    match obj.get(key) {
522        None => Ok(None),
523        Some(Value::Object(m)) => Ok(Some(m)),
524        Some(_) => Err(invalid(&child_path(path, key), "expected an object")),
525    }
526}
527
528fn check_reserved(kind: &str, name: &str, path: &str) -> Result<()> {
529    if name.starts_with("xstate.") || name.starts_with("@xstate.") {
530        return Err(invalid(
531            path,
532            format!(
533                "invalid {kind} name '{name}': the 'xstate.' and '@xstate.' prefixes are reserved for built-in names"
534            ),
535        ));
536    }
537    Ok(())
538}
539
540impl<'j, C: 'static, E: EventType + 'static> Loader<'j, '_, C, E> {
541    /// A JSON value with code nodes compiled to expressions.
542    fn compile_template(&mut self, value: &Value, path: &str, slot: Slot) -> Result<Template> {
543        if code_source(value).is_some() {
544            return self.code(value, path, slot).map(Template::Expr);
545        }
546        if !contains_code(value) {
547            return Ok(Template::Static(value.clone()));
548        }
549        match value {
550            Value::Object(map) => map
551                .iter()
552                .map(|(k, v)| Ok((k.clone(), self.compile_template(v, &child_path(path, k), slot)?)))
553                .collect::<Result<_>>()
554                .map(Template::Object),
555            Value::Array(items) => items
556                .iter()
557                .enumerate()
558                .map(|(i, v)| self.compile_template(v, &format!("{path}[{i}]"), slot))
559                .collect::<Result<_>>()
560                .map(Template::Array),
561            _ => unreachable!("only objects and arrays contain code"),
562        }
563    }
564
565    /// The index of a named expression.
566    fn expr(&mut self, name: &str, path: &str, slot: Slot) -> Result<u32> {
567        let (index, found) = match slot {
568            Slot::Context => (&self.context_index, self.registry.contexts.contains_key(name)),
569            _ => (&self.expr_index, self.registry.exprs.contains_key(name)),
570        };
571        if let Some(&i) = index.get(name) {
572            return Ok(i);
573        }
574        if !found {
575            let recorded = match slot {
576                Slot::Context => self.record(|r| &mut r.contexts, name, path, None),
577                _ => self.record(|r| &mut r.exprs, name, path, None),
578            };
579            if !recorded {
580                let hint = match slot {
581                    Slot::Context if self.registry.exprs.contains_key(name) => {
582                        " (the root `context` is computed from the input: register it with `Registry::context`)"
583                    }
584                    _ if slot != Slot::Context && self.registry.contexts.contains_key(name) => {
585                        " (it is registered with `Registry::context`, which only the root `context` uses)"
586                    }
587                    _ => "",
588                };
589                return Err(err(K::MissingImplementation, path, format!("missing expression \"{name}\"{hint}")));
590            }
591        }
592        let i = match slot {
593            Slot::Context => {
594                let f = self.registry.contexts.get(name).cloned().unwrap_or_else(|| Arc::new(|_| Value::Null));
595                self.context_exprs.push(f);
596                self.context_index.insert(name.to_owned(), self.context_exprs.len() as u32 - 1);
597                self.context_exprs.len() as u32 - 1
598            }
599            _ => {
600                let f = self.registry.exprs.get(name).cloned().unwrap_or_else(|| Arc::new(|_| Value::Null));
601                self.exprs.push(f);
602                self.expr_index.insert(name.to_owned(), self.exprs.len() as u32 - 1);
603                self.exprs.len() as u32 - 1
604            }
605        };
606        Ok(i)
607    }
608
609    /// The index of a code node's expression (in `exprs`, or for the root
610    /// `context` in `context_exprs`): a [`Registry::expr`] by name for the
611    /// `rust` language, otherwise the language's evaluator bound to the node.
612    fn code(&mut self, value: &Value, path: &str, slot: Slot) -> Result<u32> {
613        self.expr_refs += 1;
614        let source = code_source(value).expect("a code node");
615        let lang = code_lang(value, self.default_lang).expect("checked by check_code");
616        if lang == RUST_LANG {
617            return self.expr(source, path, slot);
618        }
619        let evaluator = self.registry.evaluators.get(lang).cloned();
620        let listed = self.refs.as_ref().is_some_and(|r| r.languages.iter().any(|l| l.name == lang));
621        if evaluator.is_none() && !listed {
622            self.record(|r| &mut r.languages, lang, path, None);
623        }
624        let code = Code {
625            id: NEXT_CODE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
626            lang: lang.to_owned(),
627            source: source.to_owned(),
628            kind: if value.get("@code").is_some() { CodeKind::Code } else { CodeKind::Expr },
629            slot,
630            path: path.to_owned(),
631        };
632        Ok(match slot {
633            Slot::Context => {
634                let f: crate::registry::ContextFn = match evaluator {
635                    Some(ev) => Arc::new(move |args: &ContextArgs<'_>| {
636                        ev.eval(&code, Scope::Context(args)).unwrap_or_else(|m| {
637                            args.fail(m);
638                            Value::Null
639                        })
640                    }),
641                    None => Arc::new(|_| Value::Null),
642                };
643                self.context_exprs.push(f);
644                self.context_exprs.len() as u32 - 1
645            }
646            _ => {
647                let f: crate::registry::ExprFn<C, E> = match evaluator {
648                    Some(ev) => Arc::new(move |args: &ExprArgs<'_, C, E>| {
649                        ev.eval(&code, Scope::Expr(args)).unwrap_or_else(|m| {
650                            args.fail(m);
651                            Value::Null
652                        })
653                    }),
654                    None => Arc::new(|_| Value::Null),
655                };
656                self.exprs.push(f);
657                self.exprs.len() as u32 - 1
658            }
659        })
660    }
661
662    /// A delay given as a code node.
663    fn delay_expr(&mut self, value: &Value, path: &str) -> Result<Option<DelaySpec>> {
664        match code_source(value) {
665            Some(_) => Ok(Some(DelaySpec::Expr(self.code(value, path, Slot::Delay)?))),
666            None => Ok(None),
667        }
668    }
669
670    fn check_machine_keys(&self) -> Result<()> {
671        for kind in ["actions", "guards", "delays"] {
672            if let Some(map) = opt_object(self.root_json, kind, "$")? {
673                for name in map.keys() {
674                    check_reserved(kind, name, &format!("$.{kind}.{name}"))?;
675                }
676            }
677        }
678        if let Some(guards) = opt_object(self.root_json, "guards", "$")? {
679            for (name, def) in guards {
680                if def.get("when").is_none() {
681                    return Err(invalid(&format!("$.guards.{name}"), "a named guard must be { \"when\": <guard> }"));
682                }
683            }
684        }
685        Ok(())
686    }
687
688    fn load_named_delays(&mut self) -> Result<()> {
689        let Some(delays) = opt_object(self.root_json, "delays", "$")? else { return Ok(()) };
690        for (name, def) in delays {
691            let path = format!("$.delays.{name}");
692            if code_source(def).is_some() {
693                return Err(invalid(&path, "a computed delay is { \"duration\": <expression> }"));
694            }
695            if let Some(spec) =
696                def.get("duration").map(|d| self.delay_expr(d, &child_path(&path, "duration"))).transpose()?.flatten()
697            {
698                self.named_delays.insert(name.clone(), spec);
699                continue;
700            }
701            let value = match def {
702                Value::Object(o) => o
703                    .get("duration")
704                    .ok_or_else(|| invalid(&path, "expected a number, a duration string or { \"duration\": ... }"))?,
705                other => other,
706            };
707            let ms = match value {
708                Value::Number(n) => n.as_f64(),
709                Value::String(s) => parse_duration_ms(s),
710                _ => None,
711            }
712            .and_then(ms_to_u64)
713            .ok_or_else(|| {
714                invalid(
715                    &path,
716                    "invalid delay: expected milliseconds or a duration string such as \"500ms\", \"1.5s\" or \"PT1M\"",
717                )
718            })?;
719            self.named_delays.insert(name.clone(), DelaySpec::Fixed(ms));
720        }
721        Ok(())
722    }
723
724    /// Builds the arena in pre-order, so a node's index is its document order.
725    fn build_node(
726        &mut self,
727        json: &'j Map<String, Value>,
728        key: String,
729        parent: Option<NodeId>,
730        path: String,
731        key_path: &mut Vec<String>,
732    ) -> Result<NodeId> {
733        let is_root = parent.is_none();
734        for k in json.keys() {
735            let known = STATE_KEYS.contains(&k.as_str()) || (is_root && MACHINE_KEYS.contains(&k.as_str()));
736            if !known {
737                return Err(err(K::UnknownKey, &path, format!("unknown key \"{k}\"")));
738            }
739            if let Some((_, feature)) = UNSUPPORTED_STATE_KEYS.iter().find(|(name, _)| name == k) {
740                return Err(err(K::Unsupported, &child_path(&path, k), format!("{feature} is not supported yet")));
741            }
742        }
743        if !is_root && json.contains_key("context") {
744            return Err(err(
745                K::Unsupported,
746                &child_path(&path, "context"),
747                "context is only supported on the root node",
748            ));
749        }
750        if !is_root && has_unescaped_dot(&key) {
751            return Err(invalid(
752                &path,
753                format!(
754                    "State key \"{key}\" contains \".\". Nest the states or escape it as \"{}\".",
755                    escape_dots(&key)
756                ),
757            ));
758        }
759
760        let states = opt_object(json, "states", &path)?;
761        let has_children = states.is_some_and(|s| !s.is_empty());
762        let kind = match opt_str(json, "type", &path)? {
763            Some("atomic") => NodeKind::Atomic,
764            Some("compound") => NodeKind::Compound,
765            Some("parallel") => NodeKind::Parallel,
766            Some("final") => NodeKind::Final,
767            Some("history") => NodeKind::History { deep: false },
768            Some("choice") => NodeKind::Choice,
769            Some(other) => return Err(invalid(&child_path(&path, "type"), format!("unknown state type \"{other}\""))),
770            None if has_children => NodeKind::Compound,
771            None if json.contains_key("history") => NodeKind::History { deep: false },
772            None => NodeKind::Atomic,
773        };
774        let kind = match kind {
775            NodeKind::History { .. } => match json.get("history") {
776                None | Some(Value::Bool(true)) => NodeKind::History { deep: false },
777                Some(Value::String(s)) if s == "shallow" => NodeKind::History { deep: false },
778                Some(Value::String(s)) if s == "deep" => NodeKind::History { deep: true },
779                Some(_) => return Err(invalid(&child_path(&path, "history"), "expected \"shallow\" or \"deep\"")),
780            },
781            other => other,
782        };
783        if has_children
784            && matches!(kind, NodeKind::Atomic | NodeKind::Final | NodeKind::History { .. } | NodeKind::Choice)
785        {
786            return Err(invalid(
787                &child_path(&path, "states"),
788                "only compound and parallel states can have child states",
789            ));
790        }
791        if is_root && matches!(kind, NodeKind::Final | NodeKind::History { .. }) {
792            return Err(invalid(&path, "the root state must be atomic, compound or parallel"));
793        }
794        if kind == NodeKind::Compound && !json.contains_key("initial") {
795            return Err(invalid(&path, "no initial state specified for compound state"));
796        }
797
798        let id = match opt_str(json, "id", &path)? {
799            Some(explicit) if !is_root => explicit.to_owned(),
800            _ => {
801                let mut parts: Vec<&str> = Vec::with_capacity(key_path.len() + 1);
802                if let Some(mid) = &self.machine_id {
803                    parts.push(mid);
804                }
805                parts.extend(key_path.iter().map(String::as_str));
806                parts.join(".")
807            }
808        };
809        let index = self.nodes.len() as NodeId;
810        if self.id_map.insert(id.clone(), index).is_some() {
811            return Err(err(K::DuplicateId, &path, format!("duplicate state id '{id}'; state ids must be unique")));
812        }
813        self.nodes.push(Node {
814            key,
815            id,
816            parent,
817            end: index + 1,
818            kind,
819            children: Vec::new(),
820            history_children: Vec::new(),
821            initial: None,
822            history_target: Vec::new(),
823            initial_input: None,
824            on_error: false,
825            entry: Vec::new(),
826            exit: Vec::new(),
827            on: Vec::new(),
828            always: Vec::new(),
829            delayed: Vec::new(),
830            invokes: Vec::new(),
831            output: None,
832            tags: Vec::new(),
833        });
834        self.raw.push(RawNode { json, path: path.clone() });
835
836        if let Some(states) = states {
837            for (child_key, child_json) in states {
838                let child_path = format!("{path}.states.{child_key}");
839                let child_json =
840                    child_json.as_object().ok_or_else(|| invalid(&child_path, "a state node must be an object"))?;
841                key_path.push(child_key.clone());
842                let child = self.build_node(child_json, child_key.clone(), Some(index), child_path, key_path)?;
843                key_path.pop();
844                if matches!(self.nodes[child as usize].kind, NodeKind::History { .. }) {
845                    self.nodes[index as usize].history_children.push(child);
846                } else {
847                    self.nodes[index as usize].children.push(child);
848                }
849            }
850        }
851        self.nodes[index as usize].end = self.nodes.len() as NodeId;
852        Ok(index)
853    }
854
855    fn child_by_key(&self, node: NodeId, key: &str) -> Option<NodeId> {
856        let n = &self.nodes[node as usize];
857        n.children.iter().chain(&n.history_children).copied().find(|&c| self.nodes[c as usize].key == key)
858    }
859
860    /// `getStateNodeByPath`: `#id`, or a `.`-separated path below `base`.
861    fn node_by_path(&self, base: NodeId, path: &str) -> std::result::Result<NodeId, String> {
862        if let Some(id) = path.strip_prefix('#') {
863            return self.id_map.get(id).copied().ok_or_else(|| format!("no state has id \"{id}\""));
864        }
865        let mut current = base;
866        for segment in to_state_path(path) {
867            if segment.is_empty() {
868                break;
869            }
870            current = self.child_by_key(current, &segment).ok_or_else(|| {
871                format!("child state '{segment}' does not exist on '{}'", self.nodes[current as usize].id)
872            })?;
873        }
874        Ok(current)
875    }
876
877    /// Resolves a transition target relative to its source state.
878    fn resolve_target(&self, source: NodeId, target: &str, path: &str) -> Result<NodeId> {
879        let resolved = if target.starts_with('#') {
880            self.node_by_path(source, target)
881        } else if let Some(rest) = target.strip_prefix('.') {
882            self.node_by_path(source, rest)
883        } else {
884            match self.nodes[source as usize].parent {
885                Some(parent) => self.node_by_path(parent, target),
886                None => Err(format!("invalid target \"{target}\" on the root; use \".child\" or \"#id\"")),
887            }
888        };
889        resolved.map_err(|m| err(K::InvalidTarget, path, m))
890    }
891
892    fn resolve_targets(
893        &self,
894        source: NodeId,
895        value: Option<&Value>,
896        path: &str,
897        base_parent: bool,
898    ) -> Result<Vec<NodeId>> {
899        let list: Vec<&str> = match value {
900            None => return Ok(Vec::new()),
901            Some(Value::String(s)) => vec![s.as_str()],
902            Some(Value::Array(items)) => items
903                .iter()
904                .map(|v| v.as_str().ok_or_else(|| invalid(path, "a target must be a string")))
905                .collect::<Result<_>>()?,
906            Some(_) => return Err(invalid(path, "a target must be a string or an array of strings")),
907        };
908        let mut targets = Vec::with_capacity(list.len());
909        for t in list {
910            let node = if base_parent {
911                // History defaults resolve against the history state's parent.
912                let parent = self.nodes[source as usize].parent.expect("history states have a parent");
913                self.node_by_path(parent, t).map_err(|m| err(K::InvalidTarget, path, m))?
914            } else {
915                self.resolve_target(source, t, path)?
916            };
917            targets.push(node);
918        }
919        self.assert_legal_target_set(&targets, path)?;
920        Ok(targets)
921    }
922
923    fn assert_legal_target_set(&self, targets: &[NodeId], path: &str) -> Result<()> {
924        for (i, &a) in targets.iter().enumerate() {
925            for &b in &targets[i + 1..] {
926                let lca = self.lca(a, b);
927                let related = a == b || self.is_desc(a, b) || self.is_desc(b, a);
928                if related || lca.map(|l| self.nodes[l as usize].kind) != Some(NodeKind::Parallel) {
929                    return Err(err(
930                        K::InvalidTarget,
931                        path,
932                        "invalid target set: multiple targets must be in different regions of a parallel state",
933                    ));
934                }
935            }
936        }
937        Ok(())
938    }
939
940    fn is_desc(&self, node: NodeId, ancestor: NodeId) -> bool {
941        node > ancestor && node < self.nodes[ancestor as usize].end
942    }
943
944    fn lca(&self, a: NodeId, b: NodeId) -> Option<NodeId> {
945        let mut m = Some(a);
946        while let Some(x) = m {
947            if x == b || self.is_desc(b, x) {
948                return Some(x);
949            }
950            m = self.nodes[x as usize].parent;
951        }
952        None
953    }
954
955    fn resolve_node(&mut self, node: NodeId) -> Result<()> {
956        let json: &'j Map<String, Value> = self.raw[node as usize].json;
957        let path = self.raw[node as usize].path.clone();
958        let kind = self.nodes[node as usize].kind;
959
960        match kind {
961            NodeKind::Compound => {
962                let mut initial_path = child_path(&path, "initial");
963                // The object form, `{ target, input?, description?, meta? }`.
964                let initial = match json.get("initial") {
965                    Some(Value::Object(o)) => {
966                        for k in o.keys() {
967                            if !["target", "input", "description", "meta"].contains(&k.as_str()) {
968                                return Err(err(K::UnknownKey, &initial_path, format!("unknown key \"{k}\"")));
969                            }
970                        }
971                        self.nodes[node as usize].initial_input = o.get("input").cloned();
972                        initial_path = child_path(&initial_path, "target");
973                        o.get("target").and_then(Value::as_str)
974                    }
975                    other => other.and_then(Value::as_str),
976                }
977                .ok_or_else(|| invalid(&initial_path, "expected the key of a child state"))?;
978                let target = self.node_by_path(node, initial).map_err(|m| err(K::InvalidTarget, &initial_path, m))?;
979                if !self.is_desc(target, node) {
980                    return Err(err(K::InvalidTarget, &initial_path, "the initial state must be a descendant"));
981                }
982                self.nodes[node as usize].initial = Some(target);
983            }
984            NodeKind::History { .. } => {
985                let target_path = child_path(&path, "target");
986                let has_target = match json.get("target") {
987                    Some(Value::String(s)) => !s.trim().is_empty(),
988                    Some(Value::Array(items)) => {
989                        !items.is_empty() && items.iter().all(|t| t.as_str().is_some_and(|s| !s.trim().is_empty()))
990                    }
991                    _ => false,
992                };
993                if !has_target {
994                    return Err(invalid(&path, "a history state must declare a non-empty target"));
995                }
996                let targets = self.resolve_targets(node, json.get("target"), &target_path, true)?;
997                self.nodes[node as usize].history_target = targets;
998            }
999            _ => {}
1000        }
1001
1002        // Entry and exit actions.
1003        let entry = self.compile_action_list(json.get("entry"), &child_path(&path, "entry"), true)?;
1004        let exit = self.compile_action_list(json.get("exit"), &child_path(&path, "exit"), true)?;
1005
1006        // Event transitions, in the order XState's `formatTransitions` builds
1007        // its transition map: `on` keys; `onDone` (appended to
1008        // `xstate.done.state`); `onError` (replacing `xstate.error.*`); each
1009        // invoke's completion transitions; then the delayed transitions.
1010        let mut by_descriptor: Vec<(String, Vec<TransitionId>)> = Vec::new();
1011        let add = |list: &mut Vec<(String, Vec<TransitionId>)>, d: &str, ts: Vec<TransitionId>| match list
1012            .iter_mut()
1013            .find(|(k, _)| k == d)
1014        {
1015            Some((_, existing)) => existing.extend(ts),
1016            None => list.push((d.to_owned(), ts)),
1017        };
1018        if let Some(on) = opt_object(json, "on", &path)? {
1019            for (descriptor, value) in on {
1020                let tpath = format!("{path}.on.{descriptor}");
1021                if descriptor.is_empty() {
1022                    return Err(invalid(&tpath, "empty event descriptor; use `always` for eventless transitions"));
1023                }
1024                check_lifecycle_descriptor(descriptor, &tpath)?;
1025                let ts = self.compile_transitions(node, value, &tpath, &[])?;
1026                add(&mut by_descriptor, descriptor, ts);
1027            }
1028        }
1029        if let Some(value) = json.get("onDone") {
1030            let id = Value::String(self.nodes[node as usize].id.clone());
1031            let ts = self.compile_transitions(node, value, &child_path(&path, "onDone"), &[("stateId".into(), id)])?;
1032            add(&mut by_descriptor, DONE_STATE, ts);
1033        }
1034        if let Some(value) = json.get("onError") {
1035            // JavaScript truthiness: an empty list declares it too.
1036            self.nodes[node as usize].on_error = !matches!(value, Value::Null | Value::Bool(false));
1037            let ts = self.compile_transitions(node, value, &child_path(&path, "onError"), &[])?;
1038            match by_descriptor.iter_mut().find(|(k, _)| k == "xstate.error.*") {
1039                Some((_, existing)) => *existing = ts,
1040                None => by_descriptor.push(("xstate.error.*".into(), ts)),
1041            }
1042        }
1043        let state_id = Value::String(self.nodes[node as usize].id.clone());
1044        let mut invokes = Vec::new();
1045        let mut invoke_timeouts = Vec::new();
1046        if let Some(value) = json.get("invoke") {
1047            let (items, many) = match value {
1048                Value::Array(items) => (items.iter().collect::<Vec<_>>(), true),
1049                single => (vec![single], false),
1050            };
1051            for (index, item) in items.into_iter().enumerate() {
1052                let ipath = if many { format!("{path}.invoke[{index}]") } else { child_path(&path, "invoke") };
1053                let (def, timeout) = self.compile_invoke(node, item, index, &ipath, &mut by_descriptor)?;
1054                if let Some(timeout) = timeout {
1055                    invoke_timeouts.push((def.id.clone(), timeout));
1056                }
1057                invokes.push(def);
1058            }
1059        }
1060        let mut delayed = Vec::new();
1061        let mut delayed_transitions: Vec<(&str, Vec<TransitionId>)> = Vec::new();
1062        if let Some(after) = opt_object(json, "after", &path)? {
1063            for (key, value) in after {
1064                let apath = format!("{path}.after.{key}");
1065                let (event_delay, delay) = self.after_delay(key, &apath)?;
1066                let extra = [("delay".to_owned(), event_delay.clone()), ("stateId".to_owned(), state_id.clone())];
1067                let ts = self.compile_transitions(node, value, &apath, &extra)?;
1068                delayed_transitions.push((AFTER, ts));
1069                delayed.push(DelayedDef { kind: DelayedKind::After { event_delay }, delay });
1070            }
1071        }
1072        match (json.get("timeout"), json.get("onTimeout")) {
1073            (None, None) => {}
1074            (Some(timeout), Some(on_timeout)) => {
1075                let tpath = child_path(&path, "timeout");
1076                let computed = self.delay_expr(timeout, &tpath)?;
1077                let delay = match timeout {
1078                    _ if computed.is_some() => computed,
1079                    Value::Number(n) => n.as_f64().and_then(ms_to_u64).map(DelaySpec::Fixed),
1080                    Value::String(s) => self
1081                        .named_delay(s)
1082                        .or_else(|| parse_duration_ms(s).and_then(ms_to_u64).map(DelaySpec::Fixed))
1083                        .or_else(|| self.stub_delay(s, &tpath)),
1084                    _ => None,
1085                }
1086                .ok_or_else(|| {
1087                    invalid(&tpath, "invalid timeout: expected milliseconds, a named delay or a duration string")
1088                })?;
1089                let extra = [("stateId".to_owned(), state_id.clone())];
1090                let ts = self.compile_transitions(node, on_timeout, &child_path(&path, "onTimeout"), &extra)?;
1091                delayed_transitions.push(("xstate.timeout.state", ts));
1092                delayed.push(DelayedDef { kind: DelayedKind::StateTimeout, delay });
1093            }
1094            (Some(_), None) => return Err(invalid(&path, "a state with `timeout` must declare `onTimeout`")),
1095            (None, Some(_)) => return Err(invalid(&path, "a state with `onTimeout` must declare `timeout`")),
1096        }
1097        for (invoke_id, (delay, ts)) in invoke_timeouts {
1098            delayed_transitions.push(("xstate.timeout.actor", ts));
1099            delayed.push(DelayedDef { kind: DelayedKind::InvokeTimeout { invoke_id }, delay });
1100        }
1101        for (descriptor, ts) in delayed_transitions {
1102            add(&mut by_descriptor, descriptor, ts);
1103        }
1104        if node == 0 {
1105            // `formatRouteTransitions`: the root's `xstate.route` transitions,
1106            // set after its other transitions (replacing any of its own).
1107            let routes = self.compile_routes()?;
1108            if !routes.is_empty() {
1109                match by_descriptor.iter_mut().find(|(k, _)| k == "xstate.route") {
1110                    Some((_, existing)) => *existing = routes,
1111                    None => by_descriptor.push(("xstate.route".into(), routes)),
1112                }
1113            }
1114        }
1115        // A choice state's one eventless transition is its choice, which
1116        // replaces `always` (XState's `formatChoiceTransitions`).
1117        let always = match (kind, json.get("always")) {
1118            (NodeKind::Choice, _) => vec![self.compile_choice(node, json, &path)?],
1119            (_, Some(value)) => self.compile_transitions(node, value, &child_path(&path, "always"), &[])?,
1120            (_, None) => Vec::new(),
1121        };
1122
1123        let tags = match json.get("tags") {
1124            None => Vec::new(),
1125            Some(Value::Array(items)) => items
1126                .iter()
1127                .map(|t| {
1128                    t.as_str()
1129                        .map(str::to_owned)
1130                        .ok_or_else(|| invalid(&child_path(&path, "tags"), "tags must be strings"))
1131                })
1132                .collect::<Result<_>>()?,
1133            Some(_) => return Err(invalid(&child_path(&path, "tags"), "expected an array of strings")),
1134        };
1135        let output = match json.get("output") {
1136            Some(o) if kind == NodeKind::Final => {
1137                Some(self.compile_template(o, &child_path(&path, "output"), Slot::Output)?)
1138            }
1139            _ => None,
1140        };
1141
1142        let n = &mut self.nodes[node as usize];
1143        n.entry = entry;
1144        n.exit = exit;
1145        n.on = by_descriptor;
1146        n.always = always;
1147        n.delayed = delayed;
1148        n.invokes = invokes;
1149        n.tags = tags;
1150        n.output = output;
1151        Ok(())
1152    }
1153
1154    /// Resolves an `after` key: a number of milliseconds, a named delay, or a
1155    /// duration string.
1156    fn after_delay(&mut self, key: &str, path: &str) -> Result<(Value, DelaySpec)> {
1157        if let Ok(ms) = key.trim().parse::<f64>() {
1158            let spec =
1159                ms_to_u64(ms).ok_or_else(|| invalid(path, "a delay must be a non-negative number of milliseconds"))?;
1160            let event_delay = if ms.fract() == 0.0 { Value::from(ms as u64) } else { Value::from(ms) };
1161            return Ok((event_delay, DelaySpec::Fixed(spec)));
1162        }
1163        let spec = self
1164            .named_delay(key)
1165            .or_else(|| parse_duration_ms(key).and_then(ms_to_u64).map(DelaySpec::Fixed))
1166            .or_else(|| self.stub_delay(key, path));
1167        match spec {
1168            Some(spec) => Ok((Value::String(key.to_owned()), spec)),
1169            None => Err(err(K::MissingImplementation, path, format!("missing delay source \"{key}\""))),
1170        }
1171    }
1172
1173    /// Records a missing reference when collecting [`References`]; returns
1174    /// whether the caller should continue with a stub.
1175    fn record(
1176        &mut self,
1177        kind: fn(&mut References) -> &mut Vec<Reference>,
1178        name: &str,
1179        path: &str,
1180        params: Option<&Value>,
1181    ) -> bool {
1182        match &mut self.refs {
1183            Some(refs) => {
1184                kind(refs).push(Reference { name: name.to_owned(), path: path.to_owned(), params: params.cloned() });
1185                true
1186            }
1187            None => false,
1188        }
1189    }
1190
1191    fn stub_delay(&mut self, name: &str, path: &str) -> Option<DelaySpec> {
1192        self.record(|r| &mut r.delays, name, path, None).then_some(DelaySpec::Fixed(0))
1193    }
1194
1195    fn named_delay(&mut self, name: &str) -> Option<DelaySpec> {
1196        if let Some(spec) = self.named_delays.get(name) {
1197            return Some(*spec);
1198        }
1199        let factory = self.registry.delays.get(name)?;
1200        let f = factory(&Value::Null).ok()?;
1201        let spec = DelaySpec::Named(self.delays.len() as u32);
1202        self.delays.push(f);
1203        self.named_delays.insert(name.to_owned(), spec);
1204        Some(spec)
1205    }
1206
1207    /// One `invoke`: its definition, and its timeout (delay and `onTimeout`
1208    /// transitions) if it has one. Completion transitions are added to
1209    /// `by_descriptor` as XState's `formatTransitions` adds them.
1210    #[allow(clippy::type_complexity)]
1211    fn compile_invoke(
1212        &mut self,
1213        node: NodeId,
1214        value: &Value,
1215        index: usize,
1216        path: &str,
1217        by_descriptor: &mut Vec<(String, Vec<TransitionId>)>,
1218    ) -> Result<(InvokeDef, Option<(DelaySpec, Vec<TransitionId>)>)> {
1219        const INVOKE_KEYS: &[&str] =
1220            &["id", "registryKey", "src", "input", "onDone", "onError", "onSnapshot", "timeout", "onTimeout"];
1221        let obj = value.as_object().ok_or_else(|| invalid(path, "an invoke must be an object"))?;
1222        for k in obj.keys() {
1223            if !INVOKE_KEYS.contains(&k.as_str()) {
1224                return Err(err(K::UnknownKey, path, format!("unknown key \"{k}\"")));
1225            }
1226        }
1227        let src = opt_str(obj, "src", path)?
1228            .ok_or_else(|| invalid(&child_path(path, "src"), "an invoke needs a string `src`"))?;
1229        let logic = match self.registry.actors.iter().find(|(name, _)| name == src) {
1230            Some((_, l)) => l.clone(),
1231            None if self.record(|r| &mut r.actors, src, &child_path(path, "src"), obj.get("input")) => {
1232                Arc::new(crate::step::async_logic(None, None).expect("no timeout")) as Arc<dyn crate::system::Logic>
1233            }
1234            None => {
1235                return Err(err(
1236                    K::MissingImplementation,
1237                    &child_path(path, "src"),
1238                    format!("missing actor source \"{src}\""),
1239                ))
1240            }
1241        };
1242        let id = match opt_str(obj, "id", path)? {
1243            Some(id) => id.to_owned(),
1244            None => format!("{}:{index}", self.nodes[node as usize].id),
1245        };
1246        let registry_key = opt_str(obj, "registryKey", path)?.map(str::to_owned);
1247        let timeout_key =
1248            crate::system::TimerKey::Event(Box::new(json!({ "type": "xstate.timeout.actor", "actorId": id })));
1249        let timeout = match (obj.get("timeout"), obj.get("onTimeout")) {
1250            (None, None) => None,
1251            (Some(timeout), Some(_)) => {
1252                let computed = self.delay_expr(timeout, &child_path(path, "timeout"))?;
1253                let delay = match timeout {
1254                    _ if computed.is_some() => computed,
1255                    Value::Number(n) => n.as_f64().and_then(ms_to_u64).map(DelaySpec::Fixed),
1256                    Value::String(s) => parse_duration_ms(s).and_then(ms_to_u64).map(DelaySpec::Fixed),
1257                    _ => None,
1258                }
1259                .ok_or_else(|| {
1260                    invalid(&child_path(path, "timeout"), "invalid timeout: expected milliseconds or a duration string")
1261                })?;
1262                Some(delay)
1263            }
1264            (Some(_), None) => return Err(invalid(path, "an invoke with `timeout` must declare `onTimeout`")),
1265            (None, Some(_)) => return Err(invalid(path, "an invoke with `onTimeout` must declare `timeout`")),
1266        };
1267        let actor_match = [("actorId".to_owned(), Value::String(id.clone()))];
1268        let add = |list: &mut Vec<(String, Vec<TransitionId>)>, d: &str, ts: Vec<TransitionId>| match list
1269            .iter_mut()
1270            .find(|(k, _)| k == d)
1271        {
1272            Some((_, existing)) => existing.extend(ts),
1273            None => list.push((d.to_owned(), ts)),
1274        };
1275        let completion = |this: &mut Self, value: &Value, p: String| -> Result<Vec<TransitionId>> {
1276            let ts = this.compile_transitions(node, value, &p, &actor_match)?;
1277            for &t in &ts {
1278                let tr = &mut this.transitions[t as usize];
1279                tr.session = Some(id.clone());
1280                if timeout.is_some() {
1281                    tr.cancel_timeout = Some(timeout_key.clone());
1282                }
1283            }
1284            Ok(ts)
1285        };
1286        let cancel_only = |this: &mut Self| -> TransitionId {
1287            this.transitions.push(TransitionData {
1288                targets: None,
1289                matches: vec![("actorId".to_owned(), Value::String(id.clone()))],
1290                guard: None,
1291                context: None,
1292                context_expr: None,
1293                actions: Vec::new(),
1294                reenter: false,
1295                session: Some(id.clone()),
1296                cancel_timeout: Some(timeout_key.clone()),
1297                function: None,
1298                input: None,
1299                selects: false,
1300            });
1301            this.transition_sources.push(node);
1302            this.transitions.len() as TransitionId - 1
1303        };
1304        if let Some(value) = obj.get("onDone") {
1305            let mut ts = completion(self, value, child_path(path, "onDone"))?;
1306            if timeout.is_some() {
1307                ts.push(cancel_only(self));
1308            }
1309            add(by_descriptor, "xstate.done.actor", ts);
1310        } else if timeout.is_some() {
1311            let t = cancel_only(self);
1312            add(by_descriptor, "xstate.done.actor", vec![t]);
1313        }
1314        if let Some(value) = obj.get("onError") {
1315            let ts = completion(self, value, child_path(path, "onError"))?;
1316            add(by_descriptor, "xstate.error.actor", ts);
1317        }
1318        if let Some(value) = obj.get("onSnapshot") {
1319            let ts = self.compile_transitions(node, value, &child_path(path, "onSnapshot"), &actor_match)?;
1320            for &t in &ts {
1321                self.transitions[t as usize].session = Some(id.clone());
1322            }
1323            add(by_descriptor, "xstate.snapshot.actor", ts);
1324        }
1325        let timeout = match (timeout, obj.get("onTimeout")) {
1326            (Some(delay), Some(on_timeout)) => {
1327                let ts = self.compile_transitions(node, on_timeout, &child_path(path, "onTimeout"), &actor_match)?;
1328                for &t in &ts {
1329                    self.transitions[t as usize].session = Some(id.clone());
1330                }
1331                Some((delay, ts))
1332            }
1333            _ => None,
1334        };
1335        let input = match obj.get("input") {
1336            Some(i) => Some(self.compile_template(i, &child_path(path, "input"), Slot::Input)?),
1337            None => None,
1338        };
1339        let def = InvokeDef { id, logic, input, registry_key, sync_snapshot: obj.contains_key("onSnapshot") };
1340        Ok((def, timeout))
1341    }
1342
1343    /// One transition on the root per routable state (explicit `id` and a
1344    /// `route`), in document order: `{ ...route, target: '#id' }`, enabled
1345    /// when the event's `to` is `#id` (and the route's named `guard`, if any,
1346    /// passes).
1347    fn compile_routes(&mut self) -> Result<Vec<TransitionId>> {
1348        let mut out = Vec::new();
1349        for n in 1..self.nodes.len() {
1350            let json = self.raw[n].json;
1351            let Some(route) = json.get("route") else { continue };
1352            let Some(Value::String(id)) = json.get("id") else { continue };
1353            let path = child_path(&self.raw[n].path, "route");
1354            if code_source(route).is_some() {
1355                // A route function: the route's guard and resolver.
1356                let expr = self.code(route, &path, Slot::Transition)?;
1357                let target: Arc<[NodeId]> = Arc::from([n as NodeId]);
1358                let t = self.push_function(0, TransitionFn::Route { expr, target }, &[]);
1359                self.transitions[t as usize].guard = Some(Guard::RouteTo(format!("#{id}")));
1360                out.push(t);
1361                continue;
1362            }
1363            let mut config = match route {
1364                Value::Null | Value::Bool(false) => continue,
1365                Value::Bool(true) => Map::new(),
1366                Value::Object(o) => o.clone(),
1367                _ => return Err(invalid(&path, "a route must be an object (or a code expression)")),
1368            };
1369            for k in config.keys() {
1370                if !["context", "reenter", "meta", "description", "input", "guard"].contains(&k.as_str()) {
1371                    return Err(err(K::UnknownKey, &path, format!("unknown key \"{k}\"")));
1372                }
1373            }
1374            let named = match config.remove("guard") {
1375                None | Some(Value::Null) => None,
1376                Some(Value::String(g)) => Some(g),
1377                Some(_) => return Err(invalid(&child_path(&path, "guard"), "a route guard is the name of a guard")),
1378            };
1379            let to = format!("#{id}");
1380            config.insert("target".into(), Value::String(to.clone()));
1381            let t = self.compile_transition(0, &Value::Object(config), &path, &[])?;
1382            let mut guard = Guard::RouteTo(to);
1383            if let Some(name) = named {
1384                let named = self.compile_guard(
1385                    &json!({ "type": name }),
1386                    &child_path(&path, "guard"),
1387                    Slot::Guard,
1388                    &mut Vec::new(),
1389                )?;
1390                guard = Guard::And(Box::new(guard), Box::new(named));
1391            }
1392            self.transitions[t as usize].guard = Some(guard);
1393            out.push(t);
1394        }
1395        Ok(out)
1396    }
1397
1398    fn compile_transitions(
1399        &mut self,
1400        source: NodeId,
1401        value: &Value,
1402        path: &str,
1403        extra_matches: &[(String, Value)],
1404    ) -> Result<Vec<TransitionId>> {
1405        match value {
1406            Value::Array(items) => items
1407                .iter()
1408                .enumerate()
1409                .map(|(i, t)| self.compile_transition(source, t, &format!("{path}[{i}]"), extra_matches))
1410                .collect(),
1411            single => Ok(vec![self.compile_transition(source, single, path, extra_matches)?]),
1412        }
1413    }
1414
1415    fn compile_transition(
1416        &mut self,
1417        source: NodeId,
1418        value: &Value,
1419        path: &str,
1420        extra_matches: &[(String, Value)],
1421    ) -> Result<TransitionId> {
1422        if code_source(value).is_some() {
1423            // A transition function: its result is the transition.
1424            let expr = self.code(value, path, Slot::Transition)?;
1425            return Ok(self.push_function(source, TransitionFn::Expr(expr), extra_matches));
1426        }
1427        let obj = match value {
1428            Value::Object(o) => o,
1429            Value::String(s) => {
1430                return Err(invalid(
1431                    path,
1432                    format!(
1433                        "invalid transition: use {{ \"target\": {} }} instead of a string",
1434                        Value::String(s.clone())
1435                    ),
1436                ))
1437            }
1438            _ => return Err(invalid(path, "invalid transition: expected an object")),
1439        };
1440        for k in obj.keys() {
1441            if !TRANSITION_KEYS.contains(&k.as_str()) {
1442                return Err(err(K::UnknownKey, path, format!("unknown key \"{k}\"")));
1443            }
1444        }
1445        if let Some(reasons) = obj.get("reject") {
1446            return self.compile_reject(source, obj, reasons, path, extra_matches);
1447        }
1448        let targets = match obj.get("target") {
1449            Some(t) => Some(self.resolve_targets(source, Some(t), &child_path(path, "target"), false)?.into()),
1450            None => None,
1451        };
1452        let mut matches: Vec<(String, Value)> = match opt_object(obj, "matches", path)? {
1453            Some(m) => m.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
1454            None => Vec::new(),
1455        };
1456        for (k, v) in extra_matches {
1457            match matches.iter_mut().find(|(mk, _)| mk == k) {
1458                Some(entry) => entry.1 = v.clone(),
1459                None => matches.push((k.clone(), v.clone())),
1460            }
1461        }
1462        let guard = match obj.get("guard") {
1463            Some(g) => Some(self.compile_guard(g, &child_path(path, "guard"), Slot::Guard, &mut Vec::new())?),
1464            None => None,
1465        };
1466        let (context, context_expr) = match obj.get("context") {
1467            Some(c) if contains_code(c) => {
1468                (None, Some(self.compile_template(c, &child_path(path, "context"), Slot::TransitionContext)?))
1469            }
1470            _ => (opt_object(obj, "context", path)?.cloned(), None),
1471        };
1472        let actions = self.compile_action_list(obj.get("actions"), &child_path(path, "actions"), false)?;
1473        let input = match obj.get("input") {
1474            Some(i) => Some(self.compile_template(i, &child_path(path, "input"), Slot::Input)?),
1475            None => None,
1476        };
1477        let reenter = match obj.get("reenter") {
1478            None => false,
1479            Some(Value::Bool(b)) => *b,
1480            Some(_) => return Err(invalid(&child_path(path, "reenter"), "expected a boolean")),
1481        };
1482        let id = self.transitions.len() as TransitionId;
1483        self.transitions.push(TransitionData {
1484            targets,
1485            matches,
1486            guard,
1487            context,
1488            context_expr,
1489            actions,
1490            reenter,
1491            session: None,
1492            cancel_timeout: None,
1493            function: None,
1494            input,
1495            selects: false,
1496        });
1497        self.transition_sources.push(source);
1498        Ok(id)
1499    }
1500
1501    /// A choice state's transition: its `choice` expression, or its branches
1502    /// (`{ when?, target, context?, reenter?, description?, meta? }`, the
1503    /// fallback without `when` last).
1504    fn compile_choice(&mut self, node: NodeId, json: &Map<String, Value>, path: &str) -> Result<TransitionId> {
1505        let cpath = child_path(path, "choice");
1506        let id = self.nodes[node as usize].id.clone();
1507        let function = match json.get("choice") {
1508            None => return Err(invalid(path, format!("Choice state at {path} must declare choice."))),
1509            Some(value) if code_source(value).is_some() => {
1510                let expr = self.code(value, &cpath, Slot::Choice)?;
1511                TransitionFn::ChoiceExpr { expr, id }
1512            }
1513            Some(Value::Array(items)) => {
1514                let mut branches = Vec::with_capacity(items.len());
1515                for (i, item) in items.iter().enumerate() {
1516                    let bpath = format!("{cpath}[{i}]");
1517                    let b = item.as_object().ok_or_else(|| invalid(&bpath, "a choice branch must be an object"))?;
1518                    for k in b.keys() {
1519                        if !["when", "target", "context", "input", "reenter", "description", "meta"]
1520                            .contains(&k.as_str())
1521                        {
1522                            return Err(err(K::UnknownKey, &bpath, format!("unknown key \"{k}\"")));
1523                        }
1524                    }
1525                    if !b.contains_key("when") && i + 1 != items.len() {
1526                        return Err(invalid(&bpath, format!("Choice fallback branch at {bpath} must be last.")));
1527                    }
1528                    let when = match b.get("when") {
1529                        Some(g) => {
1530                            Some(self.compile_guard(g, &child_path(&bpath, "when"), Slot::Choice, &mut Vec::new())?)
1531                        }
1532                        None => None,
1533                    };
1534                    let targets = match b.get("target") {
1535                        Some(t) => {
1536                            Some(self.resolve_targets(node, Some(t), &child_path(&bpath, "target"), false)?.into())
1537                        }
1538                        None => None,
1539                    };
1540                    let context = match b.get("context") {
1541                        Some(c) => {
1542                            Some(self.compile_template(c, &child_path(&bpath, "context"), Slot::TransitionContext)?)
1543                        }
1544                        None => None,
1545                    };
1546                    let input = match b.get("input") {
1547                        Some(i) => Some(self.compile_template(i, &child_path(&bpath, "input"), Slot::Input)?),
1548                        None => None,
1549                    };
1550                    let reenter = match b.get("reenter") {
1551                        None => false,
1552                        Some(Value::Bool(r)) => *r,
1553                        Some(_) => return Err(invalid(&child_path(&bpath, "reenter"), "expected a boolean")),
1554                    };
1555                    branches.push(ChoiceBranch { when, targets, context, input, reenter });
1556                }
1557                TransitionFn::Choice { branches, path: cpath, id }
1558            }
1559            Some(_) => return Err(invalid(&cpath, "a choice is an array of branches or an expression")),
1560        };
1561        Ok(self.push_function(node, function, &[]))
1562    }
1563
1564    /// A transition whose result an expression computes.
1565    /// A rejecting transition (`{ reject: [...], matches?, guard?,
1566    /// description?, meta? }`), as `machineFromJSON` checks and compiles it:
1567    /// a transition function returning `reject(reasons)`, its reasons
1568    /// computed when it is selected.
1569    fn compile_reject(
1570        &mut self,
1571        source: NodeId,
1572        obj: &Map<String, Value>,
1573        reasons: &Value,
1574        path: &str,
1575        extra_matches: &[(String, Value)],
1576    ) -> Result<TransitionId> {
1577        let reasons_path = child_path(path, "reject");
1578        let valid = reasons.as_array().is_some_and(|items| {
1579            !items.is_empty() && items.iter().all(|r| r.get("type").is_some_and(Value::is_string))
1580        });
1581        if !valid {
1582            return Err(invalid(&reasons_path, crate::machine::REJECT_REASONS));
1583        }
1584        if ["target", "context", "actions", "input", "reenter"].iter().any(|k| obj.contains_key(*k)) {
1585            return Err(invalid(
1586                path,
1587                format!("Rejecting transition at {path} cannot have target, context, actions, input, or reenter."),
1588            ));
1589        }
1590        let mut matches: Vec<(String, Value)> = match opt_object(obj, "matches", path)? {
1591            Some(m) => m.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
1592            None => Vec::new(),
1593        };
1594        for (k, v) in extra_matches {
1595            match matches.iter_mut().find(|(mk, _)| mk == k) {
1596                Some(entry) => entry.1 = v.clone(),
1597                None => matches.push((k.clone(), v.clone())),
1598            }
1599        }
1600        let guard = match obj.get("guard") {
1601            Some(g) => Some(self.compile_guard(g, &child_path(path, "guard"), Slot::Guard, &mut Vec::new())?),
1602            None => None,
1603        };
1604        let reasons = self.compile_template(reasons, &reasons_path, Slot::Transition)?;
1605        let id = self.push_function(source, TransitionFn::Reject(reasons), &matches);
1606        self.transitions[id as usize].guard = guard;
1607        Ok(id)
1608    }
1609
1610    fn push_function(&mut self, source: NodeId, function: TransitionFn, matches: &[(String, Value)]) -> TransitionId {
1611        self.transitions.push(TransitionData {
1612            targets: None,
1613            matches: matches.to_vec(),
1614            guard: None,
1615            context: None,
1616            context_expr: None,
1617            actions: Vec::new(),
1618            reenter: false,
1619            session: None,
1620            cancel_timeout: None,
1621            function: Some(function),
1622            input: None,
1623            selects: false,
1624        });
1625        self.transition_sources.push(source);
1626        self.transitions.len() as TransitionId - 1
1627    }
1628
1629    fn compile_guard(&mut self, value: &Value, path: &str, slot: Slot, stack: &mut Vec<String>) -> Result<Guard> {
1630        if code_source(value).is_some() {
1631            return Ok(Guard::Expr(self.code(value, path, slot)?));
1632        }
1633        let obj =
1634            value.as_object().ok_or_else(|| invalid(path, "a guard must be { \"type\": ..., \"params\"?: ... }"))?;
1635        let ty = opt_str(obj, "type", path)?.ok_or_else(|| invalid(path, "a guard must have a string \"type\""))?;
1636        let params = obj.get("params").unwrap_or(&Value::Null);
1637        let params_path = format!("{path}.params");
1638        match ty {
1639            "@xstate.not" => {
1640                let inner =
1641                    params.get("guard").ok_or_else(|| invalid(&format!("{path}.params.guard"), "missing guard"))?;
1642                Ok(Guard::Not(Box::new(self.compile_guard(inner, &format!("{path}.params.guard"), slot, stack)?)))
1643            }
1644            "@xstate.stateIn" => {
1645                let spath = format!("{path}.params.stateId");
1646                if contains_code(params) {
1647                    // Resolved when the guard runs, as XState does.
1648                    let params = self.compile_template(params, &params_path, slot)?;
1649                    return Ok(Guard::StateInExpr(Box::new(params)));
1650                }
1651                let id =
1652                    params.get("stateId").and_then(Value::as_str).ok_or_else(|| invalid(&spath, "missing state id"))?;
1653                let id = id.strip_prefix('#').unwrap_or(id);
1654                let node = self
1655                    .id_map
1656                    .get(id)
1657                    .copied()
1658                    .ok_or_else(|| err(K::InvalidTarget, &spath, format!("unknown state id \"{id}\"")))?;
1659                Ok(Guard::StateIn(node))
1660            }
1661            _ => {
1662                if let Some(def) = self.root_json.get("guards").and_then(|g| g.get(ty)) {
1663                    if stack.iter().any(|s| s == ty) {
1664                        return Err(invalid(path, format!("circular guard reference: {} -> {ty}", stack.join(" -> "))));
1665                    }
1666                    // The guard's params are its expressions' scope; they
1667                    // are resolved only when an expression reads them.
1668                    let scope = match obj.get("params") {
1669                        Some(p) => Some(self.compile_template(p, &params_path, slot)?),
1670                        None => None,
1671                    };
1672                    let before = self.expr_refs;
1673                    stack.push(ty.to_owned());
1674                    let when = def.get("when").expect("checked in check_machine_keys");
1675                    let guard = self.compile_guard(when, &format!("$.guards.{ty}.when"), Slot::Guard, stack);
1676                    stack.pop();
1677                    let guard = guard?;
1678                    return Ok(match scope {
1679                        Some(scope) if self.expr_refs > before => Guard::Scoped(Box::new(scope), Box::new(guard)),
1680                        _ => guard,
1681                    });
1682                }
1683                if let Some(factory) = self.registry.guards.get(ty) {
1684                    if contains_code(params) {
1685                        let template = self.compile_template(params, &params_path, slot)?;
1686                        self.dynamic_guards.push(Dynamic {
1687                            name: ty.to_owned(),
1688                            factory: factory.clone(),
1689                            params: template,
1690                        });
1691                        return Ok(Guard::Dynamic(self.dynamic_guards.len() as u32 - 1));
1692                    }
1693                    let f = factory(params).map_err(|m| {
1694                        err(K::InvalidParams, &params_path, format!("invalid params for guard '{ty}': {m}"))
1695                    })?;
1696                    self.guards.push(f);
1697                    return Ok(Guard::Custom(self.guards.len() as u32 - 1));
1698                }
1699                if ty.starts_with("@xstate.") {
1700                    return Err(err(K::Unsupported, path, format!("unknown built-in guard \"{ty}\"")));
1701                }
1702                if self.record(|r| &mut r.guards, ty, path, obj.get("params")) {
1703                    if contains_code(params) {
1704                        self.compile_template(params, &params_path, slot)?;
1705                    }
1706                    self.guards.push(Box::new(|_| Ok(false)));
1707                    return Ok(Guard::Custom(self.guards.len() as u32 - 1));
1708                }
1709                Err(err(K::MissingImplementation, path, format!("missing guard source \"{ty}\"")))
1710            }
1711        }
1712    }
1713
1714    fn compile_action_list(&mut self, value: Option<&Value>, path: &str, allow_single: bool) -> Result<Vec<Action>> {
1715        let mut out = Vec::new();
1716        match value {
1717            None => {}
1718            Some(Value::Array(items)) => {
1719                for (i, a) in items.iter().enumerate() {
1720                    self.compile_action(a, &format!("{path}[{i}]"), &mut Vec::new(), &mut out)?;
1721                }
1722            }
1723            Some(single @ Value::Object(_)) if allow_single => {
1724                self.compile_action(single, &format!("{path}[0]"), &mut Vec::new(), &mut out)?;
1725            }
1726            Some(_) => return Err(invalid(path, "expected an array of actions")),
1727        }
1728        Ok(out)
1729    }
1730
1731    fn compile_action(
1732        &mut self,
1733        value: &Value,
1734        path: &str,
1735        stack: &mut Vec<String>,
1736        out: &mut Vec<Action>,
1737    ) -> Result<()> {
1738        if code_source(value).is_some() {
1739            out.push(Action::Expr(self.code(value, path, Slot::Action)?));
1740            return Ok(());
1741        }
1742        let obj = value.as_object().ok_or_else(|| invalid(path, "invalid action: expected { \"type\": ... }"))?;
1743        let ty = opt_str(obj, "type", path)?.ok_or_else(|| invalid(path, "invalid action: missing string \"type\""))?;
1744        let event_object = |key: &str| -> Result<Value> {
1745            match obj.get(key) {
1746                Some(e @ Value::Object(o)) if o.get("type").is_some_and(Value::is_string) => Ok(e.clone()),
1747                _ => Err(invalid(&child_path(path, key), "expected an event object with a string \"type\"")),
1748            }
1749        };
1750        // A computed event: a code node, or an object with code in it.
1751        let computed_event = |this: &mut Self, key: &str| -> Result<Option<Template>> {
1752            match obj.get(key) {
1753                Some(e) if contains_code(e) => {
1754                    if let Some(t) = e.get("type").filter(|t| !t.is_string() && code_source(t).is_none()) {
1755                        return Err(invalid(
1756                            &child_path(path, key),
1757                            format!("an event's \"type\" must be a string, not {t}"),
1758                        ));
1759                    }
1760                    this.compile_template(e, &child_path(path, key), Slot::ActionParams).map(Some)
1761                }
1762                _ => Ok(None),
1763            }
1764        };
1765        match ty {
1766            "@xstate.raise" => {
1767                let computed = computed_event(self, "event")?;
1768                let event = match &computed {
1769                    Some(_) => Value::Null,
1770                    None => event_object("event")?,
1771                };
1772                let id = opt_str(obj, "id", path)?.map(str::to_owned);
1773                let delay =
1774                    match obj.get("delay") {
1775                        None => None,
1776                        Some(Value::Number(n)) => Some(n.as_f64().and_then(ms_to_u64).ok_or_else(|| {
1777                            invalid(&child_path(path, "delay"), "a delay must be a non-negative number")
1778                        })?),
1779                        Some(_) => {
1780                            return Err(invalid(&child_path(path, "delay"), "a delay must be a number of milliseconds"))
1781                        }
1782                    };
1783                if let Some(event) = computed {
1784                    out.push(Action::RaiseExpr { event, id, delay });
1785                    return Ok(());
1786                }
1787                let ev = Ev::<E>::from_json(event).expect("checked to have a string type");
1788                self.raise_events.push(ev);
1789                out.push(Action::Raise { event: self.raise_events.len() as u32 - 1, id, delay });
1790            }
1791            "@xstate.cancel" => {
1792                let id = opt_str(obj, "id", path)?.ok_or_else(|| invalid(&child_path(path, "id"), "missing id"))?;
1793                out.push(Action::Cancel(id.to_owned()));
1794            }
1795            "@xstate.log" => {
1796                let args = match obj.get("args") {
1797                    None => Vec::new(),
1798                    Some(Value::Array(a)) => a.clone(),
1799                    Some(_) => return Err(invalid(&child_path(path, "args"), "expected an array")),
1800                };
1801                out.push(Action::Log(args));
1802            }
1803            "@xstate.emit" => match computed_event(self, "event")? {
1804                Some(event) => out.push(Action::EmitExpr(event)),
1805                None => out.push(Action::Emit(event_object("event")?)),
1806            },
1807            "@xstate.assign" => {
1808                if let Some(c) = obj.get("context").filter(|c| contains_code(c)) {
1809                    let t = self.compile_template(c, &child_path(path, "context"), Slot::TransitionContext)?;
1810                    out.push(Action::AssignExpr(t));
1811                    return Ok(());
1812                }
1813                let patch = opt_object(obj, "context", path)?
1814                    .ok_or_else(|| invalid(&child_path(path, "context"), "missing context patch"))?;
1815                out.push(Action::Assign(patch.clone()));
1816            }
1817            _ if ty.starts_with("@xstate.") => {
1818                return Err(err(K::Unsupported, path, format!("unsupported built-in action \"{ty}\"")));
1819            }
1820            _ => {
1821                if let Some(def) = self.root_json.get("actions").and_then(|a| a.get(ty)) {
1822                    if stack.iter().any(|s| s == ty) {
1823                        return Err(invalid(
1824                            path,
1825                            format!("circular action reference: {} -> {ty}", stack.join(" -> ")),
1826                        ));
1827                    }
1828                    // The reference's params (resolved where it runs) are the
1829                    // scope of the expressions in the definition; they are
1830                    // resolved only when one of those reads them.
1831                    let scope = match obj.get("params") {
1832                        Some(p) => Some(self.compile_template(p, &child_path(path, "params"), Slot::ActionParams)?),
1833                        None => None,
1834                    };
1835                    let (start, before) = (out.len(), self.expr_refs);
1836                    stack.push(ty.to_owned());
1837                    let items: Vec<&Value> = match def {
1838                        Value::Array(items) => items.iter().collect(),
1839                        single => vec![single],
1840                    };
1841                    for (i, item) in items.into_iter().enumerate() {
1842                        // XState's path for the definition's actions.
1843                        let ipath = format!("{path}.actions.{ty}[{i}]");
1844                        self.compile_action(item, &ipath, stack, out)?;
1845                    }
1846                    stack.pop();
1847                    if let Some(scope) = scope.filter(|_| self.expr_refs > before) {
1848                        out.insert(start, Action::Params(scope));
1849                        out.push(Action::EndParams);
1850                    }
1851                    return Ok(());
1852                }
1853                let params = obj.get("params").unwrap_or(&Value::Null);
1854                if contains_code(params) {
1855                    let template = self.compile_template(params, &child_path(path, "params"), Slot::ActionParams)?;
1856                    let factory = match self.registry.actions.get(ty) {
1857                        // The host's action runs nothing here: the step keeps it pending.
1858                        _ if self.registry.is_host_action(ty) => {
1859                            Arc::new(|_: &Value| Ok(Arc::new(|| Ok(())) as crate::registry::ActionFn))
1860                        }
1861                        Some(factory) => factory.clone(),
1862                        None if self.record(|r| &mut r.actions, ty, path, obj.get("params")) => {
1863                            Arc::new(|_: &Value| Ok(Arc::new(|| Ok(())) as crate::registry::ActionFn))
1864                        }
1865                        None => {
1866                            return Err(err(K::MissingImplementation, path, format!("missing action source \"{ty}\"")))
1867                        }
1868                    };
1869                    self.dynamic_actions.push(Dynamic { name: ty.to_owned(), factory, params: template });
1870                    out.push(Action::CustomExpr(self.dynamic_actions.len() as u32 - 1));
1871                    return Ok(());
1872                }
1873                let f = match self.registry.actions.get(ty) {
1874                    _ if self.registry.is_host_action(ty) => Arc::new(|| Ok(())),
1875                    Some(factory) => factory(params).map_err(|m| {
1876                        err(
1877                            K::InvalidParams,
1878                            &child_path(path, "params"),
1879                            format!("invalid params for action '{ty}': {m}"),
1880                        )
1881                    })?,
1882                    None if self.record(|r| &mut r.actions, ty, path, obj.get("params")) => Arc::new(|| Ok(())),
1883                    None => return Err(err(K::MissingImplementation, path, format!("missing action source \"{ty}\""))),
1884                };
1885                self.actions.push(CustomAction { name: ty.to_owned(), params: obj.get("params").cloned(), exec: f });
1886                out.push(Action::Custom(self.actions.len() as u32 - 1));
1887            }
1888        }
1889        Ok(())
1890    }
1891}
1892
1893#[cfg(test)]
1894mod tests {
1895    use super::*;
1896
1897    #[test]
1898    fn state_paths() {
1899        assert_eq!(to_state_path("a.b"), vec!["a", "b"]);
1900        assert_eq!(to_state_path("a\\.b.c"), vec!["a\\.b", "c"]);
1901        assert!(has_unescaped_dot("a.b"));
1902        assert!(!has_unescaped_dot("a\\.b"));
1903    }
1904
1905    #[test]
1906    fn unescaped_dot_error() {
1907        let def = serde_json::json!({ "id": "m", "initial": "foo.bar", "states": { "foo.bar": {} } });
1908        let Err(error) = crate::Machine::<Value, Value>::from_json(&def, &crate::Registry::new()) else {
1909            panic!("loaded")
1910        };
1911        assert_eq!(error.message, r#"State key "foo.bar" contains ".". Nest the states or escape it as "foo\\.bar"."#);
1912        assert_eq!(escape_dots("a.b\\.c.d"), r"a\\.b\.c\\.d");
1913    }
1914}