# xmachines-machine-node
Typed Node.js native addons (napi-rs) for one machine each: the machine's guards, actions, delays and invoked actors are Rust compiled into the addon (no call into JavaScript per guard), and its events are checked against the machine's generated types at the boundary. It is the Node counterpart of [`xmachines-machine-wasi`](https://docs.rs/xmachines-machine-wasi), and like every Node-API addon, Bun and Deno load it too.
## When to use it
Use it when a machine and its implementations are known at build time and JavaScript should only drive actors: the addon runs on the JavaScript thread and never calls into JavaScript. For machines loaded at run time, with implementations in JavaScript, use the generic addon of [`xmachines-runtime-node`](https://docs.rs/xmachines-runtime-node).
## The API
The addon's API is the typed world `xmachines:machine` (`wit/machine.wit` of `xmachines-machine-wasi`) in camelCase:
```ts
function machineInterface(): string // "xmachines:machine@0.3.0"
namespace info {
function id(): string
function version(): string | null
function definition(): string
function schemas(): string
}
class Machine {
static load(options: string): Machine
start(options: string, now: number): Actor
restore(snapshot: string): Actor
}
class Actor {
apply(batch: string): string // the step; throws when refused: `code` "WORKFLOW_REJECTED" and `rejected`, or the contract's `code`
persist(): string
takeLogs(): string[]
can(event: string): boolean
takeSystemEmitted(): string[]
stop(): void
}
```
The addon compiles its machine once; `Machine.load` adds the load options its actors share (`{ "maxSteps", "maxTimers", "observeSystemEmitted" }`; the children and actions are compiled in, so there are no `children` or `hostActions`), `start` takes `{ "input"?, "id"? }`, and `restore` only the snapshot. `load`, `start`, `restore` and `apply` throw as the generic addon's do. A load whose options do not parse throws an `Error` whose `code` is `WORKFLOW_INVALID_INPUT`, and one whose machine does not compile `WORKFLOW_INVALID_MACHINE`; a root that fails as it starts throws `WORKFLOW_MACHINE_FAILED`, and start options that do not parse `WORKFLOW_INVALID_INPUT`; a snapshot that does not restore throws `WORKFLOW_INVALID_SNAPSHOT`. `apply` takes a chunk of the contract's inputs and gives the step, and an event input that is not an event of the machine is a `WORKFLOW_INVALID_INPUT`. A refused chunk leaves the actor as it was. A rejection, of an event the root fails on or one to a run that is `done`, in `error` or stopped, throws an `Error` whose `code` is `WORKFLOW_REJECTED`, whose `message` is the rejection's, and whose `rejected` is the rejection itself, `{ message, data? }`; the run goes on. A fault throws an `Error` whose `code` is the contract's. A time or work input that fails ends the run in `error`. `can` says whether the root would select a transition for the event, an empty one among them, as XState's `snapshot.can`. `now` is a whole number of milliseconds, at most `2^53 - 1`.
The machine's custom actions all run inside the addon: a typed machine cannot declare host actions (there is no `hostActions`, and `xmachines-build` generates nothing for them), so no step has work of kind `action`. A machine whose host does some of its actions runs on the generic addon.
An implementation that panics fails the call that ran it with the panic's message, and the actor is unusable afterwards, since the step it interrupted is half done.
## Example
A machine crate implements `xmachines_machine::TypedMachine` (the same implementation a WASI component of the machine uses) and calls `export_machine!` in a `cdylib` crate with `napi_build::setup()` in its build script:
```rust,no_run
use serde_json::Value;
use xmachines_machine::TypedMachine;
use xmachines_runtime::{Machine, Registry};
pub struct Toggle;
impl TypedMachine for Toggle {
type Context = Value;
type Event = Value;
const DEFINITION: &'static str = r#"{
"id": "toggle", "initial": "off",
"states": { "off": { "on": { "toggle": { "target": "on" } } }, "on": {} }
}"#;
const SCHEMAS: &'static str = "{}";
fn machine() -> Result<Machine<Value, Value>, String> {
Machine::from_json_str(Self::DEFINITION, &Registry::new()).map_err(|e| e.to_string())
}
}
xmachines_machine_node::export_machine!(Toggle);
// A cdylib has no `main`; this one lets the example build as a test.
fn main() {}
```
With codegen, the implementations are the generated trait's, as in [`examples/checkout-node`](https://gitlab.com/xmachin-es/xmachines-rs/-/tree/main/examples/checkout-node), which exports the `TypedMachine` of `examples/checkout-wasi`. From JavaScript:
```js
const addon = { exports: {} };
process.dlopen(addon, './target/release/libcheckout_node.so');
const { Machine, info, machineInterface } = addon.exports;
console.log(machineInterface(), info.id()); // xmachines:machine@0.3.0 checkout
const actor = Machine.load('{}').start('{}', 0);
const step = actor.apply(JSON.stringify([{ kind: 'time', now: 10 }, { type: 'checkout', total: 120 }]));
console.log(JSON.parse(step).root.value); // paying
```
## Notes
- The machine crate needs no `napi` or `napi-derive` of its own: the macro brings them from this crate. It needs `napi-build` in its build script, as every napi-rs addon does, for the link arguments of its platform (`-undefined dynamic_lookup` on macOS, `-z nodelete` with glibc).
- The macro puts the addon's items in a module of its own, so they do not clash with the crate's. An addon exports one machine (its `Machine`, `Actor` and `info` are the addon's), and `xmachines-runtime-node`'s generic API has the same `Machine` and `Actor` names, so the two do not share an addon.
## Contract
The addon is the Node binding of the WIT package `xmachines:machine@0.3.0`, which `machineInterface()` reports (`MACHINE_INTERFACE`), with the time in milliseconds as a number and values as the JSON text the package's JSON Schemas describe.
## Pins
napi-rs 3 (`napi` with Node-API version 8, `napi-derive` 3).
## Related crates
- [`xmachines-machine`](https://docs.rs/xmachines-machine): the contract of a typed machine.
- [`xmachines-machine-wasi`](https://docs.rs/xmachines-machine-wasi): the same machine as a WASI component.
- [`xmachines-build`](https://docs.rs/xmachines-build): the generated module a machine crate implements.
## License
MIT