Actions

An action is registered behaviour: you define what it does once, in code, and a workflow refers to it by $type. A workflow is a list of action entries, plain data that can be stored, sent from a server to a client and replayed. @schema-engine/actions registers actions, checks a workflow against them with parseActions, and dispatches it: entries run in order, and an entry that is itself a list runs in parallel. See Core concepts for the shared vocabulary.

The package does not depend on any domain. A checkout flow, a support workflow and a background job all use the same registry, dispatcher and result type.

Action flow

These playgrounds dispatch through ActionDispatcher. Run an action, or run the whole sequence. Interrupt or reset from the same control.

Sequential dispatch

Matching actions run in order, each receiving config, trigger and signal

const parsed = parseActions(registry, [serialize, persist, index]);
await dispatcher.dispatch({ actions: parsed.data, trigger: 'submit', context });

Parallel group

An inner array runs concurrently and joins before the next entry

const parsed = parseActions(registry, [[analytics, webhook, cache]]);
await dispatcher.dispatch({ actions: parsed.data, trigger: 'submit', context });

Stop on failure

Later actions run after a failure unless shouldContinue is false

return { success: false, error: 'conflict', shouldContinue: false };

Install

pnpm add @schema-engine/actions zod

@schema-engine/actions has no schema-library dependency. Zod is the validator these examples use, and any Standard Schema validator works in its place.

Quick start

1. Define a context and two actions

The context is what the caller hands to every dispatch: here an API for support tickets, so no action reaches for a global. The first action is async. Each schema lists the action's own arguments only: parseActions checks id, $type, enabled and triggers itself.

import * as z from 'zod/mini';
import { ActionRegistry, type ActionConfigBase, type ActionRegistration } from '@schema-engine/actions';

z.config(z.locales.en());

export interface TicketApi {
	assign(ticketId: string, assignee: string): Promise<void>;
	notify(channel: string, text: string): void;
}

export interface TicketContext {
	tickets: TicketApi;
}

export type TicketTrigger = 'created' | 'escalated';

interface AssignConfig extends ActionConfigBase<'assign'> {
	ticketId: string;
	assignee: string;
}

interface NotifyConfig extends ActionConfigBase<'notify'> {
	channel: string;
	text: string;
}

const assign: ActionRegistration<AssignConfig, TicketContext, TicketTrigger> = {
	$type: 'assign',
	schema: z.object({
		ticketId: z.string(),
		assignee: z.string(),
	}),
	metadata: { name: 'Assign ticket', defaultTriggers: ['created', 'escalated'] },
	execute: async ({ config, tickets }) => {
		await tickets.assign(config.ticketId, config.assignee);
		return { success: true, message: `Assigned ${config.ticketId} to ${config.assignee}` };
	},
};

const notify: ActionRegistration<NotifyConfig, TicketContext, TicketTrigger> = {
	$type: 'notify',
	schema: z.object({
		channel: z.string(),
		text: z.string(),
	}),
	metadata: { name: 'Notify a channel', defaultTriggers: ['created', 'escalated'] },
	execute: ({ config, tickets }) => {
		tickets.notify(config.channel, config.text);
		return { success: true };
	},
};

export const registry = new ActionRegistry<TicketContext, TicketTrigger>([assign, notify]);

execute receives TicketContext enriched by the dispatcher with config, trigger and a cancellation signal, so a handler reads config.ticketId and tickets from one object.

2. Parse a workflow and dispatch it

The workflow arrives as JSON text. parseActions checks every entry against its registration's schema, and dispatch accepts only what it returned. The inner list is a group: both notifications run at the same time, after the assignment has finished.

import { ActionDispatcher, parseActions } from '@schema-engine/actions';
import { registry, type TicketApi } from './actions';

const workflowJson = `[
	{ "id": "assign", "$type": "assign", "ticketId": "T-1042", "assignee": "grace" },
	[
		{ "id": "notify-team", "$type": "notify", "channel": "#support", "text": "T-1042 was assigned to grace" },
		{ "id": "notify-requester", "$type": "notify", "channel": "[email protected]", "text": "We are on it" }
	]
]`;

const tickets: TicketApi = {
	async assign(ticketId, assignee) {
		console.log(`assign ${ticketId} to ${assignee}`);
	},
	notify(channel, text) {
		console.log(`notify ${channel}: ${text}`);
	},
};

async function main() {
	const parsed = parseActions(registry, JSON.parse(workflowJson));
	if (!parsed.success) throw new Error(parsed.issues.map((issue) => issue.message).join('; '));

	const results = await new ActionDispatcher(registry).dispatch({
		actions: parsed.data,
		trigger: 'created',
		context: { tickets },
	});
	for (const { actionId, sequenceIndex, groupIndex, status } of results) {
		const member = groupIndex === undefined ? '' : `, member ${groupIndex}`;
		console.log(`${actionId} (entry ${sequenceIndex}${member}): ${status}`);
	}
}

main();

3. Run it and read the results

assign T-1042 to grace
notify #support: T-1042 was assigned to grace
notify [email protected]: We are on it
assign (entry 0): succeeded
notify-team (entry 1, member 0): succeeded
notify-requester (entry 1, member 1): succeeded

The first three lines come from the handlers. The rest print the results.

dispatch returns one ActionDispatchResult per action that ran, in workflow order. Each carries the handler's own result (success, message, error, data) plus the actionId, the position in the workflow (sequenceIndex, and groupIndex for a group member), a status of succeeded, failed or cancelled, and whether cancellation had been requested. An action that does not match the trigger, or that has enabled: false, produces no result.

Where to go next