API: core (@fragiola/flow)
The command bus
How the model runs commands with run, can, check and dispatch, the result and its error codes, middleware that vetoes or rewrites, and listeners.
Every change to a flow is a command run through one bus: a name, a JSON payload checked against
the command's JSON Schema, a middleware chain, then one commit that every listener sees. The
engine runs the same commands for the user's gestures (a drag is node.move steps, a dropped
connection edge.add, the Delete key selection.remove), so a middleware you write applies to
the mouse, the keyboard, your code and an assistant alike. The commands themselves are on
Commands.
Running
const result = model.run("node.move", { nodeId: "review", position: { x: 240, y: 80 } });
if (!result.ok) console.warn(result.error.code, result.error.message);
model.can("edge.add", { source: "review", target: "publish" }); // boolean, nothing committed
model.check("node.remove", { nodeId: "review" }); // the result, nothing committed
model.dispatch({ command: "selection.clear", payload: {} }, { meta: { source: "assistant" } });| member | signature | description |
|---|---|---|
run | (command, payload?, options?: RunOptions) => CommandResult<R> | runs a command, typed by your registry and your features |
can | (command, payload?, options?) => boolean | whether run would succeed now, middleware included |
check | (command, payload?, options?) => CommandResult<R> | what run would return, without committing or emitting |
dispatch | (input: unknown, options?: DispatchOptions) => CommandResult<unknown> | run for untrusted JSON { command, payload, transient? }, validated first |
use | (middleware: Middleware<T, F>) => () => void | adds a middleware (the first added runs outermost) |
subscribe | (listener: CommandListener<T>) => () => void | listens to every committed command |
get | (key, payload?) | reads; see Model |
is | (key, payload) | asks; see Model |
RunOptions:
| option | type | description |
|---|---|---|
transient | boolean | a step of a continuous gesture: listeners see it marked, so undo and persistence wait for the final step |
meta | Readonly<Record<string, unknown>> | free-form information for middleware and listeners |
DispatchOptions has meta only: it comes from your code, never from the untrusted input.
A dry run (can, check, and the engine asking model.can("edge.add", …) while a connection is
drawn) never calls your createId, and a command a middleware issues during one is refused: a
dry run causes nothing.
The result
Nothing on the bus throws on bad input. A CommandResult<R> is { ok: true, value } or
{ ok: false, error }, and a CommandError says why:
| field | type | description |
|---|---|---|
code | CommandErrorCode | one of the codes below |
message | string | a sentence for a log or an assistant |
path | string | a JSON pointer into the payload (or the dispatched input), when the error has a place |
issues | readonly ValidationIssue[] | every schema problem, for invalid_payload |
CommandErrorCode:
| code | when |
|---|---|
unknown_command | no command has this name |
invalid_payload | the payload does not match the command's schema, or names a field of a feature that is not installed |
not_found | a node or edge the payload names does not exist, or the command's feature is not installed (the message names it) |
refused | a rule of the flow forbids it: a permission flag, a duplicate edge, a parent cycle, a command issued during a dry run |
vetoed | a middleware returned veto(), or returned nothing without calling next() (another failure a middleware returns keeps its own code) |
queued | it was issued from a middleware while another command ran: it runs after that one |
middleware_error | a middleware threw |
Middleware
A Middleware<T, F> is a function (ctx, next) => CommandResult | undefined that runs around
every command, engine-issued or not. It can veto (return a failure without calling next:
veto(message?) builds one with the code vetoed), rewrite (assign a new ctx.payload, which
is validated again, then call next) or observe (call next and look at its result).
Returning undefined passes on next's result when it was called. A middleware may veto a
success but never turn a failed command into one.
import { type Middleware, veto } from "@fragiola/flow-react";
/** Connection rules: no self loop, and a "trigger" node takes no incoming edge. */
const rules: Middleware<Types, typeof features> = (ctx, next) => {
if (ctx.command !== "edge.add") return next();
const { source, target } = ctx.payload;
if (source === target) return veto("an edge joins two different nodes");
if (ctx.get("node-by", { id: target })?.type === "trigger") {
return veto("a trigger starts a workflow: nothing connects into it");
}
return next();
};
const stop = model.use(rules);The payload is a frozen copy: rewrite it by assigning a new object, never by writing into it.
Because the engine asks model.can("edge.add", …) while a connection is drawn, a vetoed target is
marked data-invalid before the drop (see Connection rules).
ctx is a CommandContext<T, F>: a union discriminated by command, so checking the command
narrows the payload. What every command's context has, CommandContextBase<T>:
| field | type | description |
|---|---|---|
command | CommandName | the command (narrows payload) |
payload | its payload type | the validated payload; assign a new object to rewrite it |
dryRun | boolean | can, check or a connection's hover: nothing will be committed, cause no side effects |
transient | boolean | a step of a gesture |
inBatch | boolean | the command runs inside a batch (the batch itself also passes the chain) |
meta | Readonly<Record<string, unknown>> | undefined | the run's meta |
state | FlowDocument<T> | the committed document the command applies to |
get(key, payload) | "node-by" or "edge-by" | reads a node or an edge as the command sees it: inside a batch, after its earlier commands |
CommandContextGetMap<T> types what ctx.get reads, CommandContextGetKey its keys.
Batches
batch runs several commands as one: all or nothing, one commit, one event. It is transient only
when every step may be. A middleware sees the batch, then each of its steps (inBatch: true).
model.run("batch", {
commands: [
{ command: "node.add", payload: { id: "notify", type: "task", position: { x: 0, y: 200 }, data: { title: "Notify" } } },
{ command: "edge.add", payload: { source: "review", target: "notify" } },
],
});BatchEntry<T> is one { command, payload }; the event reports the steps it ran as BatchSteps.
Listeners
subscribe gets one CommandEvent<T> per commit:
| field | type | description |
|---|---|---|
command | CommandName | the command, or batch |
payload | unknown | the payload it ran with (after the middleware rewrote it) |
result | unknown | the command's value |
before | FlowDocument<T> | the document before |
after | FlowDocument<T> | the document after: unchanged entities are the same objects |
transient | boolean | a step of a gesture; the gesture ends with a final, non-transient step |
meta | Readonly<Record<string, unknown>> | undefined | the run's meta |
commands | readonly BatchStep[] | for a batch: the commands it ran, flattened |
BatchStep:
| field | type | description |
|---|---|---|
command | CommandName | the step's command |
payload | unknown | its payload |
result | unknown | its value |
const stop = model.subscribe((event) => {
if (event.transient) return; // a drag in progress: wait for its drop
if (event.meta?.source === "controlled") return; // the root syncing controlled props
save(model.get("flow-json"));
});CommandListener<T> is the listener's type. What the React root runs to bring the model to
controlled nodes / edges carries meta: { source: "controlled" }.
Describing the commands
model.get("commands") lists every installed command as a CommandInfo, ready to become an AI
tool definition (see AI and automation):
| field | type | description |
|---|---|---|
name | CommandName | its name |
description | string | what it does, for an assistant |
payloadSchema | JsonSchema | its payload's JSON Schema |
resultSchema | JsonSchema | its result's JSON Schema |
transient | boolean | whether it may run as a step of a gesture |
feature | FeatureName | the feature it comes with; none for the core's |
The types
CommandName (every command, the core's and the features'), CommandMap<T> (each one's payload
and result), PayloadOf<T, C> and ResultOf<T, C>, CommandNameOf<F> (the commands of a model
with the features F). Payload and result types named by the commands: NodeFlagsPayload,
EdgeFlagsPayload, ConnectionPayload (source, target and their handles),
NodeDataPatchOf<T> and EdgeDataPatchOf<T> (a shallow patch of one type's data),
SelectionMode ("replace", "add", "toggle"), RemovedResult, SelectionResult.
A command is declared with a CommandDefinition (its name, description, schemas, transient and
a reducer that returns a result or a Failure, receiving a ReduceContext): the shape a feature's
commands have (see Features).