Expand description
§xmachines-build
Generates a typed Rust module for an XState v6 machine bundle, at build time, for xmachines-runtime.
A bundle (<name>.machine.json, written by the extract script tools/extract/extract.mjs of the repository from a TypeScript module with Zod schemas) holds a MachineJSON definition and the JSON Schemas of its context, events, emitted events, rejections, input, output and guard and action params: { "machine": ..., "schemas": ... }.
§When to use it
Use it from build.rs when a machine is authored in TypeScript and its guards, actions, delays, actors and expressions are implemented in Rust: the generated trait has one method per name the definition references, so a missing or misspelled implementation is a compile error, and contexts, events and params are Rust types instead of JSON values. Untyped machines (Machine<Value, Value>) need no codegen.
§What it generates
For each bundle:
Context,Event(a serde enum tagged bytype, with anEventTypeimpl that matches instead of serializing),Emitted,Rejection(the reasons of rejecting transitions, ofschemas.rejections),Input,Outputand one*Paramstype per guard or action with params;- for each child in
schemas.children(keyed by invokeid, with the child’s acceptedeventsand itsoutput):<Id>ChildEvent,<Id>ChildOutput, a handle<Id>Child(fromchild_<id>(&mut actor)) that sends typed events to the running child, andchild_<id>_output(event), which reads the child’s typed output from itsxstate.done.actorevent; - a trait,
<MachineId>Impl, with one method per guard, action, delay, actor and expression ({"@code": name, "@lang": "rust"}) the definition needs from Rust, and oneevaluator_<lang>per other language of its code nodes; registry(impl)andmachine(impl), which wire an implementation of the trait into the runtime, the constantsID,DEFINITIONandSCHEMAS, andtype Actor;- of a bundle with
hostActions(besidemachineandschemas: the custom actions the host does) orschemas.actors(bysrc: theinput,outputanderrorof invoked logic the host runs):Invoke, tagged bysrc, with<Src>Input,<Src>Outputand<Src>Error;HostAction, tagged bytype, with each one’s params; both with aWorkIdimpl; and the record protocol’s types of the machine, ofxmachines-workflow, which the crate then depends on:Work,WorkflowInput(Inputis the machine’s input),SnapshotandRecord. A host action has no method in the trait: the registry names it (HostActions::Named), so it is work of kindactionthe host settlesdone. It still needs its entry inschemas.actions, as every custom action does, with its params if it takes any.Invokehas a variant for everysrcthe definition invokes, of JSON whereschemas.actorshas no entry of it.
Before generating, the bundle is checked: the definition must load (Machine::references, the runtime’s own resolution), every referenced guard and action needs an entry in schemas.guards / schemas.actions, and every static value the definition contains (params, the initial context, @xstate.assign and transition context patches, raised and emitted events, the reasons of rejecting branches, output) must fit its schema; where a value holds expressions, its static properties are checked one by one. Handled, raised and emitted event types must be declared, and so must a rejection’s type when there are rejection schemas, as XState checks it. Unused schema entries are warnings.
JSON Schema maps to Rust as follows: number is xmachines_runtime::Number, serde_json’s Number (1 writes back as 1, 1.5 as 1.5; compare by as_f64()), integer is i64, string enums and consts are unit enums, optional properties are Option<T>, arrays are Vec, records are IndexMap<String, T>, objects are structs, nullable types are Option<T> (a nullable schema of a name, as XParams, is Option<XParamsValue> of its struct), discriminated unions are internally tagged enums, and {} is serde_json::Value. Intersections (allOf), untagged unions and non-string enums are rejected with their schema path.
§Example
In build.rs, with the crate as a build dependency:
xmachines_build::Builder::new().machine("machines/checkout.machine.json").build().unwrap();Then include the module with xmachines_runtime::include_machine!("checkout") and implement its trait:
pub mod checkout {
xmachines_runtime::include_machine!("checkout");
}
impl checkout::CheckoutImpl for Shop {
fn guard_within_limit(&self, args: &GuardArgs<'_, checkout::Context, checkout::Event>, p: &checkout::WithinLimitParams) -> bool {
matches!(args.event, Ev::User(checkout::Event::Checkout { total }) if total.as_f64() <= p.max.as_f64())
}
// ... one method per action, delay, actor and expression the machine references
}
let mut actor = checkout::Actor::start(Arc::new(checkout::machine(Arc::new(Shop))?), 0)?;
actor.send(checkout::Event::Checkout { total: 120.into() }, 10)?;include_machine! includes the file the build script wrote to $OUT_DIR, so this block is not compiled with the docs: examples/checkout is the whole crate, and the typed_machines guide of xmachines-docs runs it.
generate is what the builder runs for each bundle, without the files:
use serde_json::json;
let bundle = json!({
"machine": {
"id": "toggle",
"initial": "off",
"states": {
"off": { "on": { "flip": { "target": "on", "guard": { "type": "allowed" } } } },
"on": { "on": { "flip": { "target": "off" } } }
}
},
"schemas": {
"events": { "flip": { "type": "object", "properties": {} } },
"guards": { "allowed": {} }
}
});
let generated = xmachines_build::generate(&bundle, "toggle").unwrap();
assert!(generated.code.contains("pub trait ToggleImpl"));
assert!(generated.code.contains("fn guard_allowed"));§Related crates
xmachines-runtime: the runtime the generated module runs on; user crates depend only on it at run time.xmachines-machine: the contract that turns a generated machine into a WASI component or a Node.js addon.xmachines-codec-protobufandxmachines-codec-avro: event schemas from the same bundles.
§License
MIT
Structs§
- Builder
- Generates modules for bundles from
build.rs. - Error
- A problem with a bundle, at a JSON path (
$...for the definition,schemas...for the schemas). - Generated
- The generated module and any warnings (unused schema entries).
Functions§
- generate
- Generates the module for a bundle.
modulenames it in comments and is the trait’s name when the machine has noid.