xmachines-eval-quickjs 6.0.0

A JavaScript evaluator (embedded QuickJS) for code nodes in xmachines-rs machines
Documentation
# xmachines-eval-quickjs

A JavaScript evaluator for [`xmachines-runtime`](https://docs.rs/xmachines-runtime): it runs the code nodes of a language (`{ "@code": "({ context }) => context.n + 1", "@lang": "js" }`, or `ts` with its types stripped by the extract script) in an embedded QuickJS, as XState's own evaluators run them.

## When to use it

XState v6 serializes inline functions (guards, actions, transitions written as functions) to code nodes in the `ts` language. Register this evaluator when a machine authored that way should run in Rust unchanged, or when its computed values are written in JavaScript. It is opt-in, so the runtime itself keeps no JavaScript engine: code nodes in the `rust` language call Rust functions instead and cost what a Rust closure costs (an event that runs a guard and a context value took about 8.1 µs with JavaScript code nodes and 1.3 µs with Rust expressions; a JavaScript code node costs about 3.4 µs, mostly QuickJS's own call and JSON work).

## How code runs

- `@code` is a function, called as `fn(scope, scope.enq)` (`Function("return (" + source + ")")()(scope, scope.enq)`);
- `@expr` is an expression over the scope's names (`with (scope) { return (expr); }`).

The scope is XState's: `context`, `event`, `input`, `params`, `self` (with `_parent`), `children`, `actions` and `actors` (each name maps to itself: `enq(actions.notify, params)`, `enq.spawn(actors.worker)`), and `enq` in actions and transitions (`raise`, `emit`, `cancel`, `log`, `sendTo`, `spawn`, `stop`; `listen` and `subscribeTo` throw). The root `context` sees `input`, `self`, `actors` and `spawn`. Actor references are `{ "@actor", incarnation }` as XState persists them, with `id` as a non-enumerable property.

Values cross as JSON text, parsed in JavaScript only when the code reads them. Code runs deterministically by default: `Math.random()`, `Date.now()` and argument-less `Date` throw, as the runtime never reads a clock. Each thread keeps its own QuickJS runtime per evaluator (and per nesting depth, for a context `spawn` whose child runs code too), with a memory limit, a stack limit and an interrupt budget per call, so a runaway loop fails the step instead of the worker. An exception fails the step, as an exception from XState's evaluator does.

## Example

```rust
use std::sync::Arc;

use serde_json::{json, Value};
use xmachines_eval_quickjs::JsEvaluator;
use xmachines_runtime::{Actor, Machine, Registry};

let mut registry: Registry<Value, Value> = Registry::new();
registry.evaluator("js", JsEvaluator::new());
let definition = json!({
    "@exprLang": "js",
    "context": { "count": 0 },
    "initial": "on",
    "states": { "on": { "on": { "inc": {
        "guard": { "@expr": "context.count < 2" },
        "context": { "count": { "@code": "({ context, event }) => context.count + event.by" } }
    } } } }
});
let machine = Machine::from_json(&definition, &registry).unwrap();
let mut actor = Actor::start(Arc::new(machine), 0).unwrap();
actor.send(json!({ "type": "inc", "by": 5 }), 0).unwrap();
assert_eq!(actor.context().unwrap()["count"], 5);
```

Register the same evaluator for `ts` too when the machine was extracted from TypeScript (`registry.evaluator("ts", evaluator.clone())`; clones share their engines). `JsEvaluator::with_options` takes `JsOptions`:

| Option            | Default | What it bounds                                                           |
| ----------------- | ------- | ------------------------------------------------------------------------ |
| `memory_limit`    | 32 MiB  | the QuickJS heap of one runtime                                          |
| `max_stack_size`  | 512 KiB | the stack of one call                                                    |
| `interrupt_limit` | 1000    | interrupt checks per call, each after about 10 000 bytecode instructions |
| `deterministic`   | `true`  | whether `Math.random()`, `Date.now()` and `new Date()` throw             |

## Pins

QuickJS through `rquickjs` 0.14.

## Related crates

- [`xmachines-runtime`](https://docs.rs/xmachines-runtime): the `Evaluator` trait this implements, and `HostEvaluator` for an evaluator in another runtime.
- [`xmachines-kafka`](https://docs.rs/xmachines-kafka): its `js` feature registers this evaluator for `js` and `ts` in the generic binary.
- [`xmachines-docs`](https://docs.rs/xmachines-docs): the `evaluators` guide.

## License

MIT