@schema-engine/actions 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Andrea Zanenghi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @schema-engine/actions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Registered behaviour that runs from plain data. You define an action once in code. A workflow is a JSON array of action entries that name registered actions by `$type`: entries run in order, an entry that is a list runs in parallel, and a failure can stop the rest and cancel the group. `parseActions` checks a workflow against the registrations before anything runs. The package knows no domain and has no UI.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @schema-engine/actions zod
9
+ ```
10
+
11
+ Install the [Standard Schema](https://standardschema.dev/) validator you prefer. The example uses `zod/mini`.
12
+
13
+ ## Example
14
+
15
+ ```ts
16
+ import * as z from 'zod/mini';
17
+ import {
18
+ ActionDispatcher,
19
+ ActionRegistry,
20
+ defineAction,
21
+ parseActions,
22
+ type ActionConfigBase,
23
+ } from '@schema-engine/actions';
24
+
25
+ type Trigger = 'save';
26
+
27
+ interface Context {
28
+ readonly sent: string[];
29
+ }
30
+
31
+ interface NotifyConfig extends ActionConfigBase<'notify'> {
32
+ channel: string;
33
+ }
34
+
35
+ const defineNotify = defineAction<Context, Trigger>();
36
+
37
+ const notify = defineNotify<NotifyConfig>({
38
+ $type: 'notify',
39
+ schema: z.object({ channel: z.string() }),
40
+ metadata: { name: 'Notify', defaultTriggers: ['save'] },
41
+ execute: async ({ config, sent, signal }) => {
42
+ if (signal.aborted) return { success: false, error: 'Cancelled' };
43
+ sent.push(config.channel);
44
+ return { success: true };
45
+ },
46
+ });
47
+
48
+ const registry = new ActionRegistry<Context, Trigger>([notify]);
49
+
50
+ export async function run(input: unknown, sent: string[]) {
51
+ const parsed = parseActions(registry, input);
52
+ if (!parsed.success) return { issues: parsed.issues };
53
+ const dispatcher = new ActionDispatcher<Context, Trigger>(registry);
54
+ return { results: await dispatcher.dispatch({ actions: parsed.data, trigger: 'save', context: { sent } }) };
55
+ }
56
+ ```
57
+
58
+ `run([{ "id": "a", "$type": "notify", "channel": "ops" }], sent)` checks the entry, dispatches it for the `save` trigger and returns one result per action that ran. `parseActions` checks `id`, `$type`, `enabled` and `triggers` itself, so a schema lists only an action's own arguments.
59
+
60
+ ## Exports
61
+
62
+ The package has one entry, `@schema-engine/actions`: `ActionRegistry`, `ActionDispatcher`, `parseActions`, `defineAction` and the registration, entry and result types.
63
+
64
+ ## Documentation
65
+
66
+ - [Actions](https://schema-engine.com/docs/actions/overview): register actions, check a workflow and dispatch it.
67
+ - [Concepts](https://schema-engine.com/docs/actions/concepts): the registration, the context, trigger matching and results.
68
+ - [Sequences, parallel groups, cancellation](https://schema-engine.com/docs/actions/sequences-and-cancellation): ordering and stopping a workflow.
69
+ - [Writing actions](https://schema-engine.com/docs/actions/writing-actions): `defineAction`, a service call and testing.
70
+ - [Serialized workflows](https://schema-engine.com/docs/actions/serialized-workflows): a workflow as JSON.
71
+ - [API reference](https://schema-engine.com/docs/actions/api-reference): every export.
72
+ - [For AI agents](https://schema-engine.com/docs/schema-engine/agent-skill): the package ships its part of the agent skill.
73
+
74
+ ## License
75
+
76
+ MIT
@@ -0,0 +1,25 @@
1
+ import type { ActionConfigBase, ActionDispatchInput, ActionDispatchResult, ParsedActionSequence } from './types';
2
+ import type { ActionRegistryProvider } from './registry';
3
+ /** Dispatches actions in sequence, allowing groups to execute concurrently. */
4
+ export declare class ActionDispatcher<TBaseContext = unknown, TTrigger = string> {
5
+ private readonly registry;
6
+ constructor(registry: ActionRegistryProvider<TBaseContext, TTrigger>);
7
+ dispatch<TConfig extends ActionConfigBase>({ actions, trigger, context, metadata, triggeredBy, signal: outer, }: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): Promise<ActionDispatchResult[]>;
8
+ /**
9
+ * Whether `dispatch` would run, or report a missing handler for, at least one of the actions on this trigger.
10
+ *
11
+ * @remarks
12
+ * Lets a caller skip building a context for a trigger no action answers. It checks the same conditions
13
+ * `dispatch` does, so the two cannot disagree.
14
+ */
15
+ hasMatching<TConfig extends ActionConfigBase>(actions: ParsedActionSequence<TConfig>, trigger: TTrigger): boolean;
16
+ /**
17
+ * @remarks
18
+ * An action of an unregistered type always matches, so `dispatch` can report the missing handler. The
19
+ * registration it looked up comes back so `dispatch` does not look it up again.
20
+ */
21
+ private match;
22
+ /** @remarks Best-effort dispatch never rejects to its caller. */
23
+ dispatchSync<TConfig extends ActionConfigBase>(input: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): void;
24
+ private mergeMetadata;
25
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @schema-engine/actions
3
+ *
4
+ * Domain-agnostic action system for event-driven architectures: register handlers,
5
+ * execute them in sequence or parallel groups, and dispatch by trigger from any host (forms, workflows, UI).
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import * as z from 'zod/mini';
10
+ * import { Logger } from '@ecopages/logger';
11
+ * import { ActionDispatcher, ActionRegistry, parseActions } from '@schema-engine/actions';
12
+ *
13
+ * const logger = new Logger('[my-app]');
14
+ * const registry = new ActionRegistry<{ formId: string }, 'submit' | 'change'>([
15
+ * {
16
+ * $type: 'log',
17
+ * schema: z.object({ message: z.string() }),
18
+ * metadata: { name: 'Log', defaultTriggers: ['change'] },
19
+ * execute: async (ctx) => {
20
+ * logger.info(ctx.config.message, ctx);
21
+ * return { success: true };
22
+ * },
23
+ * },
24
+ * ]);
25
+ *
26
+ * const dispatcher = new ActionDispatcher(registry);
27
+ * const parsed = parseActions(registry, [{ id: '1', $type: 'log', message: 'hello' }]);
28
+ * if (parsed.success) {
29
+ * await dispatcher.dispatch({ actions: parsed.data, trigger: 'change', context: { formId: 'demo' } });
30
+ * }
31
+ * ```
32
+ */
33
+ export * from './types';
34
+ export * from './registry';
35
+ export * from './dispatcher';
36
+ export * from './parse-actions';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ function j(){return function(n){return n}}import{createRegistry as E}from"@schema-engine/registry";var P=class{#e;constructor(e){this.#e=E("Action",e)}get kind(){return this.#e.kind}get size(){return this.#e.size}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}all(){return this.#e.all()}keys(){return this.#e.keys()}getAction(e){return this.get(e)}getActionTypes(){return[...this.keys()]}};import{Logger as $}from"@ecopages/logger";var C=new $("[@schema-engine/actions]");function I(n){return typeof n=="object"&&n!==null}function w(n){return Array.isArray(n)}function q(n,e){return e.aborted&&n instanceof Error&&n.name==="AbortError"}var S=class{constructor(e){this.registry=e}registry;async dispatch({actions:e,trigger:i,context:t,metadata:o,triggeredBy:r,signal:s}){if(!e?.length)return[];let u=o?this.mergeMetadata(t,o):t,g=[];for(let[f,T]of e.entries()){if(s?.aborted)break;let a=new AbortController,p=()=>a.abort(s?.reason);s?.addEventListener("abort",p,{once:!0});let m=async(c,y)=>{let B=this.match(c,i);if(!B.runs)return;let{registration:k}=B;if(!k){let A=`No handler registered for action type: ${c.$type}`;return C.error(A,{actionId:c.id,availableActions:this.registry.getActionTypes()}),{actionId:c.id,sequenceIndex:f,...y===void 0?{}:{groupIndex:y},status:"failed",cancellationRequested:!1,success:!1,error:A,shouldContinue:!0}}C.debug(`Executing action: ${c.id} (${c.$type})`);let l,b=!1;try{l=await k.execute({...u,config:c,trigger:i,signal:a.signal,...r?{triggeredBy:r}:{}})}catch(A){b=q(A,a.signal),l={success:!1,error:A instanceof Error?A.message:String(A),cause:A,shouldContinue:!0}}let D=a.signal.aborted;return!l.success&&l.shouldContinue===!1&&a.abort(),l.success||C.warn(`Action ${c.id} failed`,l),{...l,actionId:c.id,sequenceIndex:f,...y===void 0?{}:{groupIndex:y},status:b?"cancelled":l.success?"succeeded":"failed",cancellationRequested:D}},x;try{x=w(T)?await Promise.all(T.map(m)):[await m(T)]}finally{s?.removeEventListener("abort",p)}let R=x.filter(c=>c!==void 0);if(g.push(...R),R.some(c=>!c.success&&c.shouldContinue===!1))break}return g}hasMatching(e,i){return e.some(t=>w(t)?t.some(o=>this.match(o,i).runs):this.match(t,i).runs)}match(e,i){if(e.enabled===!1)return{runs:!1};if(e.triggers!==void 0&&!e.triggers.some(r=>r===i))return{runs:!1};let t=this.registry.getAction(e.$type);return e.triggers===void 0&&t&&!(t.metadata.defaultTriggers??[]).includes(i)?{runs:!1}:{runs:!0,registration:t}}dispatchSync(e){this.dispatch(e).catch(i=>C.error("dispatchSync failed:",i))}mergeMetadata(e,i){if(!I(e))return e;let t=e.metadata;return{...e,metadata:{...typeof t=="object"&&t!==null?t:{},...i}}}};import{safeParseStandardSchema as v}from"@schema-engine/registry";function h(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n,e){return{message:e,path:n}}var M=["id","$type","enabled","triggers"];function O(n,e,i){let t=[];(typeof n.id!="string"||n.id==="")&&t.push(d([...e,"id"],"Action ID must be a non-empty string.")),n.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push(d([...e,"enabled"],"enabled must be a boolean."));let{triggers:o}=n;return o===void 0?t:Array.isArray(o)?(o.forEach((r,s)=>{typeof r!="string"?t.push(d([...e,"triggers",s],"A trigger must be a string.")):i?.triggers&&!i.triggers.includes(r)&&t.push(d([...e,"triggers",s],`Unknown trigger '${r}'. Use one of: ${i.triggers.join(", ")}.`))}),t):(t.push(d([...e,"triggers"],"triggers must be an array of trigger names.")),t)}function K(n,e,i,t){if(!h(e)||typeof e.$type!="string")return{ok:!1,issues:[d([...i,"$type"],"Invalid action configuration: missing $type.")]};let o=n.getAction(e.$type);if(!o)return{ok:!1,issues:[d([...i,"$type"],`Unknown action type '${e.$type}'. Register it in the action registry.`)]};let r=O(e,i,t),s={},u={};for(let[a,p]of Object.entries(e))M.includes(a)?s[a]=p:u[a]=p;let g=v(o.schema,u);if(!g.success)return r.push(...g.error.issues.map(a=>({...a,path:[...i,...a.path??[]]}))),{ok:!1,issues:r};let{data:f}=g;return h(f)||r.push(d(i,`Invalid action configuration for '${e.$type}': the schema must return an object.`)),r.length>0||!h(f)?{ok:!1,issues:r}:{ok:!0,action:{...f,...s,id:e.id,$type:e.$type}}}function G(n,e,i){if(!Array.isArray(e))return{success:!1,issues:[d([],"Actions must be an array.")]};let t=[],o=[],r=(s,u)=>{let g=K(n,s,u,i);if(g.ok)return g.action;t.push(...g.issues)};return e.forEach((s,u)=>{if(Array.isArray(s)){if(s.length===0){t.push(d([u],"A group of actions must hold at least one action."));return}let f=s.map((T,a)=>r(T,[u,a])).filter(T=>T!==void 0);o.push(f);return}let g=r(s,[u]);g&&o.push(g)}),t.length>0?{success:!1,issues:t}:{success:!0,data:o}}export{S as ActionDispatcher,P as ActionRegistry,j as defineAction,G as parseActions};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/types.ts", "../src/registry.ts", "../src/dispatcher.ts", "../src/parse-actions.ts"],
4
+ "sourcesContent": ["import type { BaseRegistration, RegistrationMetadata } from '@schema-engine/registry';\n\n/**\n * The keys every action entry carries, owned by the engine.\n *\n * @template TType - The action type identifier\n *\n * @remarks\n * {@link parseActions} checks these keys itself and hands only the rest to the registration's schema. A\n * registration's config type is this interface plus the output of its schema, which lists the action's own\n * arguments and none of these keys: `ActionConfigBase<'post'> & { endpoint: string }`.\n */\nexport interface ActionConfigBase<TType extends string = string> {\n\t/** Unique identifier for this action instance */\n\tid: string;\n\t/** Action type - references a registered action */\n\t$type: TType;\n\t/** Whether this action is enabled */\n\tenabled?: boolean;\n\t/** Custom triggers for this specific action instance */\n\ttriggers?: readonly string[];\n}\n\n/**\n * Action Runtime Context\n *\n * Context received by action handlers at execution time.\n * The dispatcher creates this runtime shape by enriching the caller-provided\n * base context with the current action config and trigger.\n *\n * @template TConfig - Action configuration type\n * @template TBaseContext - Caller-provided base context\n * @template TTrigger - Trigger/event type\n */\nexport type ActionRuntimeContext<TConfig = unknown, TBaseContext = unknown, TTrigger = string> = TBaseContext & {\n\t/** Current action configuration */\n\tconfig: TConfig;\n\t/** Trigger/event that caused this action to execute */\n\ttrigger: TTrigger;\n\t/** Action config that triggered nested execution, when applicable */\n\ttriggeredBy?: TConfig;\n\t/** Cooperative cancellation for the current action. */\n\tsignal: AbortSignal;\n};\n\n/**\n * Action Execution Result\n *\n * Standardized return type for all action handlers.\n * Provides success status, messages, data, and flow control information.\n *\n * @template TData - Type of data returned by the action\n *\n * @example Success Result\n * ```typescript\n * return {\n * success: true,\n * message: \"Action completed successfully\",\n * data: { submissionId: \"abc123\" },\n * shouldContinue: true\n * };\n * ```\n *\n * @example Error Result\n * ```typescript\n * return {\n * success: false,\n * error: \"Validation failed\",\n * shouldContinue: false,\n * };\n * ```\n */\nexport interface ActionExecutionResult<TData = unknown> {\n\t/** Whether the action executed successfully */\n\tsuccess: boolean;\n\t/** Success message to display or log */\n\tmessage?: string;\n\t/** Error message if action failed */\n\terror?: string;\n\t/** Original error thrown by the handler, when available. */\n\tcause?: unknown;\n\t/** Data returned by the action (e.g., API response) */\n\tdata?: TData;\n\t/**\n\t * Whether to continue after this action fails.\n\t *\n\t * @remarks\n\t * The dispatcher stops after a failed action only when this is `false`. Form submissions also\n\t * fail only for unsuccessful actions with `shouldContinue: false`; omitted or `true` continues.\n\t */\n\tshouldContinue?: boolean;\n}\n\n/** An action result annotated by the dispatcher for correlation with its configuration. */\nexport type ActionDispatchResult<TData = unknown> = ActionExecutionResult<TData> & {\n\tactionId: string;\n\tsequenceIndex: number;\n\tgroupIndex?: number;\n\tstatus: 'succeeded' | 'failed' | 'cancelled';\n\tcancellationRequested: boolean;\n};\n\n/** A sequence entry is either one action or a group that runs concurrently. */\nexport type ActionSequenceEntry<TConfig extends ActionConfigBase> = TConfig | readonly TConfig[];\n\ndeclare const PARSED_ACTION: unique symbol;\n\n/**\n * An action config that {@link parseActions} checked against its registration's schema.\n *\n * @remarks\n * The brand exists in the type only. {@link parseActions} is the one function that produces it, and\n * {@link ActionDispatcher.dispatch} accepts nothing else, so an action that arrived as raw JSON or an object\n * literal cannot reach a handler unchecked.\n */\nexport type ParsedAction<TConfig extends ActionConfigBase = ActionConfigBase> = TConfig & {\n\treadonly [PARSED_ACTION]: true;\n};\n\n/** The sequence {@link parseActions} returns and {@link ActionDispatcher.dispatch} runs. */\nexport type ParsedActionSequence<TConfig extends ActionConfigBase = ActionConfigBase> = readonly ActionSequenceEntry<\n\tParsedAction<TConfig>\n>[];\n\n/**\n * Action Handler Function Type\n *\n * Function signature for action handlers using the current runtime-enrichment model.\n * At execution time, the domain context is enriched with the current action config\n * and trigger before the handler is called.\n *\n * @template TConfig - The action configuration type\n * @template TContext - Domain-specific base context data\n * @template TTrigger - The trigger/event type\n * @template TData - The type of data returned by the action\n */\nexport type ActionHandler<TConfig = unknown, TContext = unknown, TTrigger = string, TData = unknown> = (\n\tcontext: ActionRuntimeContext<TConfig, TContext, TTrigger>,\n) => Promise<ActionExecutionResult<TData>> | ActionExecutionResult<TData>;\n\n/**\n * Action Metadata\n *\n * Descriptive information about an action type.\n *\n * @template TTrigger - The trigger/event type\n */\nexport interface ActionMetadata<TTrigger = string> extends RegistrationMetadata {\n\t/** Icon identifier (optional) */\n\ticon?: string;\n\t/** Default triggers that this action responds to */\n\tdefaultTriggers?: readonly TTrigger[];\n\t/** Category for grouping actions (optional) */\n\tcategory?: string;\n}\n\n/**\n * Action Registration\n *\n * Configuration object for registering actions in an action registry.\n * Used to define action behavior, validation, and metadata. The schema describes the action's own\n * arguments; {@link ActionConfigBase} keys are checked by {@link parseActions}.\n *\n * @template TConfig - Action configuration type\n * @template TBaseContext - Caller-provided base context data\n * @template TTrigger - The trigger/event type\n *\n * @example\n * ```typescript\n * import * as z from 'zod/mini';\n *\n * const logAction: ActionRegistration<LogActionConfig, AppContext, AppTrigger> = {\n * $type: 'log',\n * schema: z.object({\n * level: z.enum(['info', 'warn', 'error']),\n * message: z.string(),\n * }),\n * metadata: {\n * name: 'Log Message',\n * description: 'Logs a message to the console',\n * defaultTriggers: ['change', 'submit'],\n * },\n * execute: async (context) => {\n * console[context.config.level](context.config.message);\n * return { success: true };\n * },\n * };\n * ```\n */\nexport interface ActionRegistration<\n\tTConfig extends ActionConfigBase = ActionConfigBase,\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTData = unknown,\n> extends BaseRegistration<TConfig, ActionMetadata<TTrigger>> {\n\t/** Unique action type identifier */\n\t$type: TConfig['$type'];\n\t/**\n\t * Action execution function.\n\t * Receives the runtime context produced by the dispatcher.\n\t */\n\texecute: ActionHandler<TConfig, TBaseContext, TTrigger, TData>;\n}\n\n/** Input for trigger-based sequential dispatch. */\nexport interface ActionDispatchInput<\n\tTConfig extends ActionConfigBase = ActionConfigBase,\n\tTBaseContext = unknown,\n\tTTrigger = string,\n> {\n\ttrigger: TTrigger;\n\tactions: ParsedActionSequence<TConfig>;\n\tcontext: TBaseContext;\n\ttriggeredBy?: TConfig;\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Cancels the dispatch from outside.\n\t *\n\t * @remarks It is chained into the signal each action receives, and the sequence runs no further entry once it is aborted.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/**\n * Create a strongly typed action-definition helper for one domain.\n */\nexport function defineAction<TBaseContext, TTrigger = string>() {\n\treturn function <TConfig extends ActionConfigBase, TData = unknown>(\n\t\tregistration: ActionRegistration<TConfig, TBaseContext, TTrigger, TData>,\n\t): ActionRegistration<TConfig, TBaseContext, TTrigger, TData> {\n\t\treturn registration;\n\t};\n}\n", "import type { ActionRegistration } from './types';\nimport { createRegistry, type ReadOnlyRegistry } from '@schema-engine/registry';\n\n/**\n * Registry storage must be able to hold heterogeneous action config shapes.\n * `any` is used here as an existential placeholder for that internal storage boundary.\n */\ntype AnyActionRegistration<TBaseContext, TTrigger> = ActionRegistration<any, TBaseContext, TTrigger>;\n\n/**\n * Action Registry Provider\n *\n * Interface for objects that can provide action registrations.\n * This allows the ActionDispatcher to look up action handlers without\n * depending on a specific registry implementation.\n *\n * @template TContext - Domain-specific context data\n * @template TTrigger - The trigger/event type\n * @template TRegistration - The registration type (defaults to ActionRegistration)\n *\n * @example\n * ```typescript\n * class MyActionRegistry implements ActionRegistryProvider<MyContext, MyTrigger> {\n * private actions = new Map<string, ActionRegistration<any, MyContext, MyTrigger>>();\n *\n * register(action: ActionRegistration<any, MyContext, MyTrigger>): void {\n * this.actions.set(action.$type, action);\n * }\n *\n * getAction(type: string): ActionRegistration<any, MyContext, MyTrigger> | undefined {\n * return this.actions.get(type);\n * }\n *\n * getActionTypes(): string[] {\n * return Array.from(this.actions.keys());\n * }\n * }\n * ```\n */\nexport interface ActionRegistryProvider<\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>,\n> {\n\t/**\n\t * Get an action registration by type\n\t *\n\t * @param type - The action type identifier\n\t * @returns The action registration or undefined if not found\n\t */\n\tgetAction(type: string): TRegistration | undefined;\n\n\t/**\n\t * Get all registered action types\n\t *\n\t * @returns Array of action type identifiers\n\t */\n\tgetActionTypes(): string[];\n}\n\n/**\n * Action Registry\n *\n * Generic, domain-agnostic, read-only registry of action registrations, built\n * from a list on the shared {@link createRegistry} mechanism.\n *\n * @template TContext - Domain-specific context data\n * @template TTrigger - The trigger/event type\n *\n * @remarks\n * A later registration with the same `$type` replaces an earlier one without a\n * warning. Every winning schema must implement Standard Schema; the constructor\n * throws naming the offending `$type`. The registrations are held in a private\n * field, so the registry cannot be changed, and subclasses may add their own fields. To register actions at runtime, implement\n * {@link ActionRegistryProvider} on a `BaseRegistry` subclass instead.\n *\n * @example\n * ```typescript\n * import { ActionRegistry } from '@schema-engine/actions';\n *\n * type MyTrigger = 'submit' | 'change';\n * import { Logger } from '@ecopages/logger';\n * type MyContext = { formId: string; data: Record<string, unknown> };\n *\n * const logger = new Logger('[my-app]');\n * const registry = new ActionRegistry<MyContext, MyTrigger>([\n * {\n * $type: 'log',\n * schema: logSchema,\n * metadata: {\n * name: 'Log Action',\n * description: 'Logs data',\n * defaultTriggers: ['change'],\n * },\n * execute: async (context) => {\n * logger.info(context);\n * return { success: true };\n * },\n * },\n * ]);\n *\n * const action = registry.getAction('log');\n * ```\n */\nexport class ActionRegistry<\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>,\n>\n\timplements ReadOnlyRegistry<TRegistration>, ActionRegistryProvider<TBaseContext, TTrigger, TRegistration>\n{\n\treadonly #registry: ReadOnlyRegistry<TRegistration>;\n\n\tconstructor(registrations: readonly TRegistration[]) {\n\t\tthis.#registry = createRegistry('Action', registrations);\n\t}\n\n\tget kind(): string {\n\t\treturn this.#registry.kind;\n\t}\n\n\tget size(): number {\n\t\treturn this.#registry.size;\n\t}\n\n\tget(key: string): TRegistration | undefined {\n\t\treturn this.#registry.get(key);\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.#registry.has(key);\n\t}\n\n\tall(): readonly TRegistration[] {\n\t\treturn this.#registry.all();\n\t}\n\n\tkeys(): readonly string[] {\n\t\treturn this.#registry.keys();\n\t}\n\n\t/**\n\t * Get an action registration by type\n\t */\n\tgetAction(type: string): TRegistration | undefined {\n\t\treturn this.get(type);\n\t}\n\n\t/**\n\t * Get all registered action types\n\t */\n\tgetActionTypes(): string[] {\n\t\treturn [...this.keys()];\n\t}\n}\n", "import type {\n\tActionConfigBase,\n\tActionDispatchInput,\n\tActionDispatchResult,\n\tActionExecutionResult,\n\tActionSequenceEntry,\n\tParsedAction,\n\tParsedActionSequence,\n} from './types';\nimport type { ActionRegistryProvider } from './registry';\nimport { Logger } from '@ecopages/logger';\n\nconst logger = new Logger('[@schema-engine/actions]');\n\ntype MetadataContext = { metadata?: Record<string, unknown> };\n\nfunction isMetadataContext(value: unknown): value is MetadataContext {\n\treturn typeof value === 'object' && value !== null;\n}\n\nfunction isGroup<T extends ActionConfigBase>(entry: ActionSequenceEntry<T>): entry is readonly T[] {\n\treturn Array.isArray(entry);\n}\n\nfunction isCancellation(error: unknown, signal: AbortSignal): boolean {\n\treturn signal.aborted && error instanceof Error && error.name === 'AbortError';\n}\n\ntype ActionMatch<TBaseContext, TTrigger> =\n\t| { runs: false }\n\t| { runs: true; registration: ReturnType<ActionRegistryProvider<TBaseContext, TTrigger>['getAction']> };\n\n/** Dispatches actions in sequence, allowing groups to execute concurrently. */\nexport class ActionDispatcher<TBaseContext = unknown, TTrigger = string> {\n\tconstructor(private readonly registry: ActionRegistryProvider<TBaseContext, TTrigger>) {}\n\n\tasync dispatch<TConfig extends ActionConfigBase>({\n\t\tactions,\n\t\ttrigger,\n\t\tcontext,\n\t\tmetadata,\n\t\ttriggeredBy,\n\t\tsignal: outer,\n\t}: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): Promise<ActionDispatchResult[]> {\n\t\tif (!actions?.length) return [];\n\t\tconst enhancedContext = metadata ? this.mergeMetadata(context, metadata) : context;\n\t\tconst results: ActionDispatchResult[] = [];\n\t\tfor (const [sequenceIndex, entry] of actions.entries()) {\n\t\t\tif (outer?.aborted) break;\n\t\t\tconst controller = new AbortController();\n\t\t\tconst abortWithOuter = () => controller.abort(outer?.reason);\n\t\t\touter?.addEventListener('abort', abortWithOuter, { once: true });\n\t\t\tconst run = async (\n\t\t\t\taction: ParsedAction<TConfig>,\n\t\t\t\tgroupIndex?: number,\n\t\t\t): Promise<ActionDispatchResult | undefined> => {\n\t\t\t\tconst match = this.match(action, trigger);\n\t\t\t\tif (!match.runs) return undefined;\n\t\t\t\tconst { registration } = match;\n\t\t\t\tif (!registration) {\n\t\t\t\t\tconst error = `No handler registered for action type: ${action.$type}`;\n\t\t\t\t\tlogger.error(error, { actionId: action.id, availableActions: this.registry.getActionTypes() });\n\t\t\t\t\treturn {\n\t\t\t\t\t\tactionId: action.id,\n\t\t\t\t\t\tsequenceIndex,\n\t\t\t\t\t\t...(groupIndex === undefined ? {} : { groupIndex }),\n\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\tcancellationRequested: false,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tshouldContinue: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlogger.debug(`Executing action: ${action.id} (${action.$type})`);\n\t\t\t\tlet result: ActionExecutionResult;\n\t\t\t\tlet cancelled = false;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await registration.execute({\n\t\t\t\t\t\t...enhancedContext,\n\t\t\t\t\t\tconfig: action,\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\t\t...(triggeredBy ? { triggeredBy } : {}),\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancelled = isCancellation(error, controller.signal);\n\t\t\t\t\tresult = {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\tshouldContinue: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst cancellationRequested = controller.signal.aborted;\n\t\t\t\tif (!result.success && result.shouldContinue === false) controller.abort();\n\t\t\t\tif (!result.success) logger.warn(`Action ${action.id} failed`, result);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tactionId: action.id,\n\t\t\t\t\tsequenceIndex,\n\t\t\t\t\t...(groupIndex === undefined ? {} : { groupIndex }),\n\t\t\t\t\tstatus: cancelled ? 'cancelled' : result.success ? 'succeeded' : 'failed',\n\t\t\t\t\tcancellationRequested,\n\t\t\t\t};\n\t\t\t};\n\t\t\tlet groupResults: Array<ActionDispatchResult | undefined>;\n\t\t\ttry {\n\t\t\t\tgroupResults = isGroup(entry) ? await Promise.all(entry.map(run)) : [await run(entry)];\n\t\t\t} finally {\n\t\t\t\touter?.removeEventListener('abort', abortWithOuter);\n\t\t\t}\n\t\t\tconst executed = groupResults.filter((result): result is ActionDispatchResult => result !== undefined);\n\t\t\tresults.push(...executed);\n\t\t\tif (executed.some((result) => !result.success && result.shouldContinue === false)) break;\n\t\t}\n\t\treturn results;\n\t}\n\n\t/**\n\t * Whether `dispatch` would run, or report a missing handler for, at least one of the actions on this trigger.\n\t *\n\t * @remarks\n\t * Lets a caller skip building a context for a trigger no action answers. It checks the same conditions\n\t * `dispatch` does, so the two cannot disagree.\n\t */\n\thasMatching<TConfig extends ActionConfigBase>(actions: ParsedActionSequence<TConfig>, trigger: TTrigger): boolean {\n\t\treturn actions.some((entry) =>\n\t\t\tisGroup(entry) ? entry.some((action) => this.match(action, trigger).runs) : this.match(entry, trigger).runs,\n\t\t);\n\t}\n\n\t/**\n\t * @remarks\n\t * An action of an unregistered type always matches, so `dispatch` can report the missing handler. The\n\t * registration it looked up comes back so `dispatch` does not look it up again.\n\t */\n\tprivate match(action: ActionConfigBase, trigger: TTrigger): ActionMatch<TBaseContext, TTrigger> {\n\t\tif (action.enabled === false) return { runs: false };\n\t\tif (action.triggers !== undefined && !action.triggers.some((candidate) => candidate === trigger)) {\n\t\t\treturn { runs: false };\n\t\t}\n\t\tconst registration = this.registry.getAction(action.$type);\n\t\tconst implicit = action.triggers === undefined;\n\t\tif (implicit && registration && !(registration.metadata.defaultTriggers ?? []).includes(trigger)) {\n\t\t\treturn { runs: false };\n\t\t}\n\t\treturn { runs: true, registration };\n\t}\n\n\t/** @remarks Best-effort dispatch never rejects to its caller. */\n\tdispatchSync<TConfig extends ActionConfigBase>(input: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): void {\n\t\tvoid this.dispatch(input).catch((error) => logger.error('dispatchSync failed:', error));\n\t}\n\n\tprivate mergeMetadata(context: TBaseContext, metadata: Record<string, unknown>): TBaseContext {\n\t\tif (!isMetadataContext(context)) return context;\n\t\tconst existingMetadata = context.metadata;\n\t\treturn {\n\t\t\t...context,\n\t\t\tmetadata: {\n\t\t\t\t...(typeof existingMetadata === 'object' && existingMetadata !== null ? existingMetadata : {}),\n\t\t\t\t...metadata,\n\t\t\t},\n\t\t};\n\t}\n}\n", "import { safeParseStandardSchema, type BaseRegistration, type StandardSchemaIssue } from '@schema-engine/registry';\nimport type { ActionConfigBase, ParsedAction, ParsedActionSequence } from './types';\n\n/** What {@link parseActions} needs of a registry: the registration of a `$type`, for its schema. */\nexport interface ActionSchemaLookup {\n\tgetAction(type: string): Pick<BaseRegistration, 'schema'> | undefined;\n}\n\n/** What a domain tells {@link parseActions} about the entries it accepts. */\nexport interface ParseActionsOptions {\n\t/**\n\t * The trigger names an entry's `triggers` may hold.\n\t *\n\t * @remarks Without it, any string is accepted, since the engine cannot know a domain's triggers.\n\t */\n\ttriggers?: readonly string[];\n}\n\n/**\n * What {@link parseActions} returns: the parsed sequence, or every issue found.\n *\n * @remarks\n * An issue is a Standard Schema issue whose `path` starts with the index of the entry, then the index inside\n * a group, then the path the schema reported (`[1, 0, 'endpoint']`). An entry that is not an action object\n * with a `$type`, and a `$type` no registration answers, are issues at `$type`. An empty group is an issue at its index.\n */\nexport type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> =\n\t{ success: true; data: ParsedActionSequence<TConfig> } | { success: false; issues: StandardSchemaIssue[] };\n\ntype ParsedEntry<TConfig extends ActionConfigBase> =\n\t{ ok: true; action: ParsedAction<TConfig> } | { ok: false; issues: StandardSchemaIssue[] };\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction issueAt(path: ReadonlyArray<PropertyKey>, message: string): StandardSchemaIssue {\n\treturn { message, path };\n}\n\n/** The envelope keys the engine checks itself; a registration's schema never sees them. */\nconst BASE_KEYS = ['id', '$type', 'enabled', 'triggers'] as const;\n\nfunction checkBase(\n\tentry: Record<PropertyKey, unknown>,\n\tpath: ReadonlyArray<PropertyKey>,\n\toptions: ParseActionsOptions | undefined,\n): StandardSchemaIssue[] {\n\tconst issues: StandardSchemaIssue[] = [];\n\tif (typeof entry.id !== 'string' || entry.id === '') {\n\t\tissues.push(issueAt([...path, 'id'], 'Action ID must be a non-empty string.'));\n\t}\n\tif (entry.enabled !== undefined && typeof entry.enabled !== 'boolean') {\n\t\tissues.push(issueAt([...path, 'enabled'], 'enabled must be a boolean.'));\n\t}\n\tconst { triggers } = entry;\n\tif (triggers === undefined) return issues;\n\tif (!Array.isArray(triggers)) {\n\t\tissues.push(issueAt([...path, 'triggers'], 'triggers must be an array of trigger names.'));\n\t\treturn issues;\n\t}\n\ttriggers.forEach((trigger: unknown, index) => {\n\t\tif (typeof trigger !== 'string') {\n\t\t\tissues.push(issueAt([...path, 'triggers', index], 'A trigger must be a string.'));\n\t\t} else if (options?.triggers && !options.triggers.includes(trigger)) {\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, 'triggers', index],\n\t\t\t\t\t`Unknown trigger '${trigger}'. Use one of: ${options.triggers.join(', ')}.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t});\n\treturn issues;\n}\n\nfunction parseEntry<TConfig extends ActionConfigBase>(\n\tregistry: ActionSchemaLookup,\n\tentry: unknown,\n\tpath: ReadonlyArray<PropertyKey>,\n\toptions: ParseActionsOptions | undefined,\n): ParsedEntry<TConfig> {\n\tif (!isRecord(entry) || typeof entry.$type !== 'string') {\n\t\treturn { ok: false, issues: [issueAt([...path, '$type'], 'Invalid action configuration: missing $type.')] };\n\t}\n\tconst registration = registry.getAction(entry.$type);\n\tif (!registration) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissues: [\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, '$type'],\n\t\t\t\t\t`Unknown action type '${entry.$type}'. Register it in the action registry.`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\tconst issues = checkBase(entry, path, options);\n\tconst base: Record<string, unknown> = {};\n\tconst own: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(entry)) {\n\t\tif ((BASE_KEYS as readonly string[]).includes(key)) base[key] = value;\n\t\telse own[key] = value;\n\t}\n\tconst result = safeParseStandardSchema(registration.schema, own);\n\tif (!result.success) {\n\t\tissues.push(...result.error.issues.map((issue) => ({ ...issue, path: [...path, ...(issue.path ?? [])] })));\n\t\treturn { ok: false, issues };\n\t}\n\tconst { data } = result;\n\tif (!isRecord(data)) {\n\t\tissues.push(\n\t\t\tissueAt(path, `Invalid action configuration for '${entry.$type}': the schema must return an object.`),\n\t\t);\n\t}\n\tif (issues.length > 0 || !isRecord(data)) return { ok: false, issues };\n\tconst action: ActionConfigBase = { ...data, ...base, id: entry.id as string, $type: entry.$type };\n\treturn { ok: true, action: action as ParsedAction<TConfig> };\n}\n\n/**\n * Check serialized actions against their registrations, and return them as {@link ParsedAction}s.\n *\n * @param registry - Where each entry's `$type` finds its registration and schema\n * @param input - The sequence as it arrived, for example the result of `JSON.parse`: entries, where an array entry is a group\n * @param options - What the domain adds, such as the trigger names it accepts\n *\n * @remarks\n * This is the only way to produce a {@link ParsedAction}, and so the only way to a call of\n * {@link ActionDispatcher.dispatch}. Every entry is checked, so a sequence with two bad entries reports both.\n *\n * The engine owns the keys every entry carries: `id` (a non-empty string), `$type` (a registered one), `enabled` and\n * `triggers`. It checks them itself, then hands the remaining keys to the registration's schema, which describes\n * the action's own arguments only. The result is those keys merged with what the schema returned, so its defaults and\n * transforms apply. `TConfig` is the caller's claim about the result; the parse itself checks the schemas, not that claim.\n *\n * @throws {Error} When a registration's schema validates asynchronously, which is a misuse of the registry.\n */\nexport function parseActions<TConfig extends ActionConfigBase = ActionConfigBase>(\n\tregistry: ActionSchemaLookup,\n\tinput: unknown,\n\toptions?: ParseActionsOptions,\n): ParseActionsResult<TConfig> {\n\tif (!Array.isArray(input)) {\n\t\treturn { success: false, issues: [issueAt([], 'Actions must be an array.')] };\n\t}\n\n\tconst issues: StandardSchemaIssue[] = [];\n\tconst sequence: Array<ParsedAction<TConfig> | Array<ParsedAction<TConfig>>> = [];\n\tconst collect = (entry: unknown, path: ReadonlyArray<PropertyKey>): ParsedAction<TConfig> | undefined => {\n\t\tconst parsed = parseEntry<TConfig>(registry, entry, path, options);\n\t\tif (parsed.ok) return parsed.action;\n\t\tissues.push(...parsed.issues);\n\t\treturn undefined;\n\t};\n\n\tinput.forEach((entry: unknown, index) => {\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (entry.length === 0) {\n\t\t\t\tissues.push(issueAt([index], 'A group of actions must hold at least one action.'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst group = entry\n\t\t\t\t.map((member: unknown, memberIndex) => collect(member, [index, memberIndex]))\n\t\t\t\t.filter((action): action is ParsedAction<TConfig> => action !== undefined);\n\t\t\tsequence.push(group);\n\t\t\treturn;\n\t\t}\n\t\tconst action = collect(entry, [index]);\n\t\tif (action) sequence.push(action);\n\t});\n\n\tif (issues.length > 0) return { success: false, issues };\n\treturn { success: true, data: sequ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 "names": ["defineAction", "registration", "createRegistry", "ActionRegistry", "#registry", "registrations", "key", "type", "Logger", "logger", "isMetadataContext", "value", "isGroup", "entry", "isCancellation", "error", "signal", "ActionDispatcher", "registry", "actions", "trigger", "context", "metadata", "triggeredBy", "outer", "enhancedContext", "results", "sequenceIndex", "controller", "abortWithOuter", "run", "action", "groupIndex", "match", "registration", "result", "cancelled", "cancellationRequested", "groupResults", "executed", "candidate", "input", "existingMetadata", "safeParseStandardSchema", "isRecord", "value", "issueAt", "path", "message", "BASE_KEYS", "checkBase", "entry", "options", "issues", "triggers", "trigger", "index", "parseEntry", "registry", "registration", "base", "own", "key", "result", "issue", "data", "parseActions", "input", "sequence", "collect", "parsed", "group", "member", "memberIndex", "action"]
7
+ }
@@ -0,0 +1,49 @@
1
+ import { type BaseRegistration, type StandardSchemaIssue } from '@schema-engine/registry';
2
+ import type { ActionConfigBase, ParsedActionSequence } from './types';
3
+ /** What {@link parseActions} needs of a registry: the registration of a `$type`, for its schema. */
4
+ export interface ActionSchemaLookup {
5
+ getAction(type: string): Pick<BaseRegistration, 'schema'> | undefined;
6
+ }
7
+ /** What a domain tells {@link parseActions} about the entries it accepts. */
8
+ export interface ParseActionsOptions {
9
+ /**
10
+ * The trigger names an entry's `triggers` may hold.
11
+ *
12
+ * @remarks Without it, any string is accepted, since the engine cannot know a domain's triggers.
13
+ */
14
+ triggers?: readonly string[];
15
+ }
16
+ /**
17
+ * What {@link parseActions} returns: the parsed sequence, or every issue found.
18
+ *
19
+ * @remarks
20
+ * An issue is a Standard Schema issue whose `path` starts with the index of the entry, then the index inside
21
+ * a group, then the path the schema reported (`[1, 0, 'endpoint']`). An entry that is not an action object
22
+ * with a `$type`, and a `$type` no registration answers, are issues at `$type`. An empty group is an issue at its index.
23
+ */
24
+ export type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> = {
25
+ success: true;
26
+ data: ParsedActionSequence<TConfig>;
27
+ } | {
28
+ success: false;
29
+ issues: StandardSchemaIssue[];
30
+ };
31
+ /**
32
+ * Check serialized actions against their registrations, and return them as {@link ParsedAction}s.
33
+ *
34
+ * @param registry - Where each entry's `$type` finds its registration and schema
35
+ * @param input - The sequence as it arrived, for example the result of `JSON.parse`: entries, where an array entry is a group
36
+ * @param options - What the domain adds, such as the trigger names it accepts
37
+ *
38
+ * @remarks
39
+ * This is the only way to produce a {@link ParsedAction}, and so the only way to a call of
40
+ * {@link ActionDispatcher.dispatch}. Every entry is checked, so a sequence with two bad entries reports both.
41
+ *
42
+ * The engine owns the keys every entry carries: `id` (a non-empty string), `$type` (a registered one), `enabled` and
43
+ * `triggers`. It checks them itself, then hands the remaining keys to the registration's schema, which describes
44
+ * the action's own arguments only. The result is those keys merged with what the schema returned, so its defaults and
45
+ * transforms apply. `TConfig` is the caller's claim about the result; the parse itself checks the schemas, not that claim.
46
+ *
47
+ * @throws {Error} When a registration's schema validates asynchronously, which is a misuse of the registry.
48
+ */
49
+ export declare function parseActions<TConfig extends ActionConfigBase = ActionConfigBase>(registry: ActionSchemaLookup, input: unknown, options?: ParseActionsOptions): ParseActionsResult<TConfig>;
@@ -0,0 +1,115 @@
1
+ import type { ActionRegistration } from './types';
2
+ import { type ReadOnlyRegistry } from '@schema-engine/registry';
3
+ /**
4
+ * Registry storage must be able to hold heterogeneous action config shapes.
5
+ * `any` is used here as an existential placeholder for that internal storage boundary.
6
+ */
7
+ type AnyActionRegistration<TBaseContext, TTrigger> = ActionRegistration<any, TBaseContext, TTrigger>;
8
+ /**
9
+ * Action Registry Provider
10
+ *
11
+ * Interface for objects that can provide action registrations.
12
+ * This allows the ActionDispatcher to look up action handlers without
13
+ * depending on a specific registry implementation.
14
+ *
15
+ * @template TContext - Domain-specific context data
16
+ * @template TTrigger - The trigger/event type
17
+ * @template TRegistration - The registration type (defaults to ActionRegistration)
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * class MyActionRegistry implements ActionRegistryProvider<MyContext, MyTrigger> {
22
+ * private actions = new Map<string, ActionRegistration<any, MyContext, MyTrigger>>();
23
+ *
24
+ * register(action: ActionRegistration<any, MyContext, MyTrigger>): void {
25
+ * this.actions.set(action.$type, action);
26
+ * }
27
+ *
28
+ * getAction(type: string): ActionRegistration<any, MyContext, MyTrigger> | undefined {
29
+ * return this.actions.get(type);
30
+ * }
31
+ *
32
+ * getActionTypes(): string[] {
33
+ * return Array.from(this.actions.keys());
34
+ * }
35
+ * }
36
+ * ```
37
+ */
38
+ export interface ActionRegistryProvider<TBaseContext = unknown, TTrigger = string, TRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>> {
39
+ /**
40
+ * Get an action registration by type
41
+ *
42
+ * @param type - The action type identifier
43
+ * @returns The action registration or undefined if not found
44
+ */
45
+ getAction(type: string): TRegistration | undefined;
46
+ /**
47
+ * Get all registered action types
48
+ *
49
+ * @returns Array of action type identifiers
50
+ */
51
+ getActionTypes(): string[];
52
+ }
53
+ /**
54
+ * Action Registry
55
+ *
56
+ * Generic, domain-agnostic, read-only registry of action registrations, built
57
+ * from a list on the shared {@link createRegistry} mechanism.
58
+ *
59
+ * @template TContext - Domain-specific context data
60
+ * @template TTrigger - The trigger/event type
61
+ *
62
+ * @remarks
63
+ * A later registration with the same `$type` replaces an earlier one without a
64
+ * warning. Every winning schema must implement Standard Schema; the constructor
65
+ * throws naming the offending `$type`. The registrations are held in a private
66
+ * field, so the registry cannot be changed, and subclasses may add their own fields. To register actions at runtime, implement
67
+ * {@link ActionRegistryProvider} on a `BaseRegistry` subclass instead.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * import { ActionRegistry } from '@schema-engine/actions';
72
+ *
73
+ * type MyTrigger = 'submit' | 'change';
74
+ * import { Logger } from '@ecopages/logger';
75
+ * type MyContext = { formId: string; data: Record<string, unknown> };
76
+ *
77
+ * const logger = new Logger('[my-app]');
78
+ * const registry = new ActionRegistry<MyContext, MyTrigger>([
79
+ * {
80
+ * $type: 'log',
81
+ * schema: logSchema,
82
+ * metadata: {
83
+ * name: 'Log Action',
84
+ * description: 'Logs data',
85
+ * defaultTriggers: ['change'],
86
+ * },
87
+ * execute: async (context) => {
88
+ * logger.info(context);
89
+ * return { success: true };
90
+ * },
91
+ * },
92
+ * ]);
93
+ *
94
+ * const action = registry.getAction('log');
95
+ * ```
96
+ */
97
+ export declare class ActionRegistry<TBaseContext = unknown, TTrigger = string, TRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>> implements ReadOnlyRegistry<TRegistration>, ActionRegistryProvider<TBaseContext, TTrigger, TRegistration> {
98
+ #private;
99
+ constructor(registrations: readonly TRegistration[]);
100
+ get kind(): string;
101
+ get size(): number;
102
+ get(key: string): TRegistration | undefined;
103
+ has(key: string): boolean;
104
+ all(): readonly TRegistration[];
105
+ keys(): readonly string[];
106
+ /**
107
+ * Get an action registration by type
108
+ */
109
+ getAction(type: string): TRegistration | undefined;
110
+ /**
111
+ * Get all registered action types
112
+ */
113
+ getActionTypes(): string[];
114
+ }
115
+ export {};
@@ -0,0 +1,202 @@
1
+ import type { BaseRegistration, RegistrationMetadata } from '@schema-engine/registry';
2
+ /**
3
+ * The keys every action entry carries, owned by the engine.
4
+ *
5
+ * @template TType - The action type identifier
6
+ *
7
+ * @remarks
8
+ * {@link parseActions} checks these keys itself and hands only the rest to the registration's schema. A
9
+ * registration's config type is this interface plus the output of its schema, which lists the action's own
10
+ * arguments and none of these keys: `ActionConfigBase<'post'> & { endpoint: string }`.
11
+ */
12
+ export interface ActionConfigBase<TType extends string = string> {
13
+ /** Unique identifier for this action instance */
14
+ id: string;
15
+ /** Action type - references a registered action */
16
+ $type: TType;
17
+ /** Whether this action is enabled */
18
+ enabled?: boolean;
19
+ /** Custom triggers for this specific action instance */
20
+ triggers?: readonly string[];
21
+ }
22
+ /**
23
+ * Action Runtime Context
24
+ *
25
+ * Context received by action handlers at execution time.
26
+ * The dispatcher creates this runtime shape by enriching the caller-provided
27
+ * base context with the current action config and trigger.
28
+ *
29
+ * @template TConfig - Action configuration type
30
+ * @template TBaseContext - Caller-provided base context
31
+ * @template TTrigger - Trigger/event type
32
+ */
33
+ export type ActionRuntimeContext<TConfig = unknown, TBaseContext = unknown, TTrigger = string> = TBaseContext & {
34
+ /** Current action configuration */
35
+ config: TConfig;
36
+ /** Trigger/event that caused this action to execute */
37
+ trigger: TTrigger;
38
+ /** Action config that triggered nested execution, when applicable */
39
+ triggeredBy?: TConfig;
40
+ /** Cooperative cancellation for the current action. */
41
+ signal: AbortSignal;
42
+ };
43
+ /**
44
+ * Action Execution Result
45
+ *
46
+ * Standardized return type for all action handlers.
47
+ * Provides success status, messages, data, and flow control information.
48
+ *
49
+ * @template TData - Type of data returned by the action
50
+ *
51
+ * @example Success Result
52
+ * ```typescript
53
+ * return {
54
+ * success: true,
55
+ * message: "Action completed successfully",
56
+ * data: { submissionId: "abc123" },
57
+ * shouldContinue: true
58
+ * };
59
+ * ```
60
+ *
61
+ * @example Error Result
62
+ * ```typescript
63
+ * return {
64
+ * success: false,
65
+ * error: "Validation failed",
66
+ * shouldContinue: false,
67
+ * };
68
+ * ```
69
+ */
70
+ export interface ActionExecutionResult<TData = unknown> {
71
+ /** Whether the action executed successfully */
72
+ success: boolean;
73
+ /** Success message to display or log */
74
+ message?: string;
75
+ /** Error message if action failed */
76
+ error?: string;
77
+ /** Original error thrown by the handler, when available. */
78
+ cause?: unknown;
79
+ /** Data returned by the action (e.g., API response) */
80
+ data?: TData;
81
+ /**
82
+ * Whether to continue after this action fails.
83
+ *
84
+ * @remarks
85
+ * The dispatcher stops after a failed action only when this is `false`. Form submissions also
86
+ * fail only for unsuccessful actions with `shouldContinue: false`; omitted or `true` continues.
87
+ */
88
+ shouldContinue?: boolean;
89
+ }
90
+ /** An action result annotated by the dispatcher for correlation with its configuration. */
91
+ export type ActionDispatchResult<TData = unknown> = ActionExecutionResult<TData> & {
92
+ actionId: string;
93
+ sequenceIndex: number;
94
+ groupIndex?: number;
95
+ status: 'succeeded' | 'failed' | 'cancelled';
96
+ cancellationRequested: boolean;
97
+ };
98
+ /** A sequence entry is either one action or a group that runs concurrently. */
99
+ export type ActionSequenceEntry<TConfig extends ActionConfigBase> = TConfig | readonly TConfig[];
100
+ declare const PARSED_ACTION: unique symbol;
101
+ /**
102
+ * An action config that {@link parseActions} checked against its registration's schema.
103
+ *
104
+ * @remarks
105
+ * The brand exists in the type only. {@link parseActions} is the one function that produces it, and
106
+ * {@link ActionDispatcher.dispatch} accepts nothing else, so an action that arrived as raw JSON or an object
107
+ * literal cannot reach a handler unchecked.
108
+ */
109
+ export type ParsedAction<TConfig extends ActionConfigBase = ActionConfigBase> = TConfig & {
110
+ readonly [PARSED_ACTION]: true;
111
+ };
112
+ /** The sequence {@link parseActions} returns and {@link ActionDispatcher.dispatch} runs. */
113
+ export type ParsedActionSequence<TConfig extends ActionConfigBase = ActionConfigBase> = readonly ActionSequenceEntry<ParsedAction<TConfig>>[];
114
+ /**
115
+ * Action Handler Function Type
116
+ *
117
+ * Function signature for action handlers using the current runtime-enrichment model.
118
+ * At execution time, the domain context is enriched with the current action config
119
+ * and trigger before the handler is called.
120
+ *
121
+ * @template TConfig - The action configuration type
122
+ * @template TContext - Domain-specific base context data
123
+ * @template TTrigger - The trigger/event type
124
+ * @template TData - The type of data returned by the action
125
+ */
126
+ export type ActionHandler<TConfig = unknown, TContext = unknown, TTrigger = string, TData = unknown> = (context: ActionRuntimeContext<TConfig, TContext, TTrigger>) => Promise<ActionExecutionResult<TData>> | ActionExecutionResult<TData>;
127
+ /**
128
+ * Action Metadata
129
+ *
130
+ * Descriptive information about an action type.
131
+ *
132
+ * @template TTrigger - The trigger/event type
133
+ */
134
+ export interface ActionMetadata<TTrigger = string> extends RegistrationMetadata {
135
+ /** Icon identifier (optional) */
136
+ icon?: string;
137
+ /** Default triggers that this action responds to */
138
+ defaultTriggers?: readonly TTrigger[];
139
+ /** Category for grouping actions (optional) */
140
+ category?: string;
141
+ }
142
+ /**
143
+ * Action Registration
144
+ *
145
+ * Configuration object for registering actions in an action registry.
146
+ * Used to define action behavior, validation, and metadata. The schema describes the action's own
147
+ * arguments; {@link ActionConfigBase} keys are checked by {@link parseActions}.
148
+ *
149
+ * @template TConfig - Action configuration type
150
+ * @template TBaseContext - Caller-provided base context data
151
+ * @template TTrigger - The trigger/event type
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * import * as z from 'zod/mini';
156
+ *
157
+ * const logAction: ActionRegistration<LogActionConfig, AppContext, AppTrigger> = {
158
+ * $type: 'log',
159
+ * schema: z.object({
160
+ * level: z.enum(['info', 'warn', 'error']),
161
+ * message: z.string(),
162
+ * }),
163
+ * metadata: {
164
+ * name: 'Log Message',
165
+ * description: 'Logs a message to the console',
166
+ * defaultTriggers: ['change', 'submit'],
167
+ * },
168
+ * execute: async (context) => {
169
+ * console[context.config.level](context.config.message);
170
+ * return { success: true };
171
+ * },
172
+ * };
173
+ * ```
174
+ */
175
+ export interface ActionRegistration<TConfig extends ActionConfigBase = ActionConfigBase, TBaseContext = unknown, TTrigger = string, TData = unknown> extends BaseRegistration<TConfig, ActionMetadata<TTrigger>> {
176
+ /** Unique action type identifier */
177
+ $type: TConfig['$type'];
178
+ /**
179
+ * Action execution function.
180
+ * Receives the runtime context produced by the dispatcher.
181
+ */
182
+ execute: ActionHandler<TConfig, TBaseContext, TTrigger, TData>;
183
+ }
184
+ /** Input for trigger-based sequential dispatch. */
185
+ export interface ActionDispatchInput<TConfig extends ActionConfigBase = ActionConfigBase, TBaseContext = unknown, TTrigger = string> {
186
+ trigger: TTrigger;
187
+ actions: ParsedActionSequence<TConfig>;
188
+ context: TBaseContext;
189
+ triggeredBy?: TConfig;
190
+ metadata?: Record<string, unknown>;
191
+ /**
192
+ * Cancels the dispatch from outside.
193
+ *
194
+ * @remarks It is chained into the signal each action receives, and the sequence runs no further entry once it is aborted.
195
+ */
196
+ signal?: AbortSignal;
197
+ }
198
+ /**
199
+ * Create a strongly typed action-definition helper for one domain.
200
+ */
201
+ export declare function defineAction<TBaseContext, TTrigger = string>(): <TConfig extends ActionConfigBase, TData = unknown>(registration: ActionRegistration<TConfig, TBaseContext, TTrigger, TData>) => ActionRegistration<TConfig, TBaseContext, TTrigger, TData>;
202
+ export {};
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@schema-engine/actions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "0.5.1",
5
+ "description": "Registered actions that run from plain data: serializable workflows of sequential and parallel steps, checked before they run",
6
+ "keywords": [
7
+ "schema-engine",
8
+ "actions",
9
+ "workflow",
10
+ "json",
11
+ "serialization"
12
+ ],
13
+ "author": "Andrea Zanenghi",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/schema-engine/schema-engine.git",
18
+ "directory": "packages/actions"
19
+ },
20
+ "engines": {
21
+ "node": "^24.22.0 || >=26.0.0"
22
+ },
23
+ "homepage": "https://schema-engine.com/docs/actions/overview",
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "sideEffects": false,
28
+ "main": "dist/index.js",
29
+ "module": "dist/index.js",
30
+ "types": "dist/index.d.ts",
31
+ "files": [
32
+ "/dist/*",
33
+ "/skill"
34
+ ],
35
+ "lint-staged": {
36
+ "**/*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}": [
37
+ "oxlint",
38
+ "prettier --write"
39
+ ],
40
+ "**/*.{json,jsonc,md,yml,yaml}": [
41
+ "prettier --write"
42
+ ]
43
+ },
44
+ "dependencies": {
45
+ "@ecopages/logger": "^0.2.3",
46
+ "@schema-engine/registry": "^0.5.1"
47
+ },
48
+ "devDependencies": {
49
+ "esbuild": "^0.27.0",
50
+ "tsc-alias": "^1.8.16",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "^5.1.1",
53
+ "zod": "^4.0.17",
54
+ "@schema-engine/scripts": "^0.0.0"
55
+ },
56
+ "scripts": {
57
+ "build:lib": "pnpm clean && pnpm build:files && pnpm build:types",
58
+ "build:files": "node ./build.ts",
59
+ "build:types": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
60
+ "watch:lib": "node ./build.ts --watch",
61
+ "clean": "rm -rf ./dist",
62
+ "test:all": "vitest run",
63
+ "lint-staged": "lint-staged",
64
+ "check-types": "tsc --noEmit"
65
+ }
6
66
  }
package/skill/SKILL.md ADDED
@@ -0,0 +1,79 @@
1
+ ---
2
+ name: schema-engine
3
+ description: |
4
+ Schema Engine is a common language for declarative interfaces: registrations
5
+ keyed by `$type`, actions that run in sequences, documents that are plain
6
+ data, and rendering from that data. Forms is its first domain. Use this
7
+ skill when an agent is asked to build, configure, validate, submit or extend
8
+ anything with @schema-engine/registry, @schema-engine/actions,
9
+ @schema-engine/layout, @schema-engine/forms, @schema-engine/forms-react or
10
+ @schema-engine/forms-radiant, or to write a form widget for React or Radiant.
11
+ ---
12
+
13
+ # Schema Engine
14
+
15
+ Schema Engine is one grammar for interfaces that are described as data. A team registers the pieces (elements, actions, rules, appearance axes) under a `$type`, and a document, plain JSON or YAML, names them. The engine checks the document against the registrations and the renderer draws what passed. Forms is the first domain: a framework-free engine owns validation, state and submission, and a renderer (React or Radiant) only draws the fields and bridges the user's controls into that state.
16
+
17
+ This file is the router. It defines the concepts once; the references assume them and never repeat them. Read a reference only when the task needs it.
18
+
19
+ ## Core concepts
20
+
21
+ - **registration**: `{ $type, schema, metadata, ... }`, where `$type` is the stable key, `schema` is any Standard Schema that describes its config, and `metadata` names it. Elements, recipes, actions, validation rules and appearance axes are all registrations.
22
+ - **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list. The last registration of a `$type` wins without a warning, which is how you replace a built-in.
23
+ - **document**: serializable data whose every node names a registration by `$type`. It is checked against the registrations at the boundary, so what is rendered or run has passed its schema.
24
+ - **action**: a registration with `execute` that runs on a trigger. Actions run as a sequence, an inner array is a parallel group, and a failure that sets `shouldContinue: false` stops what follows and cancels the group's siblings through their `signal`.
25
+
26
+ ## Forms concepts
27
+
28
+ - **config**: a form is plain data, a `FormConfig` of steps holding elements, each with a `$type`, a `name`, `rules` and `constraints`. `engine.defineForm()` (typed, in TypeScript) or `engine.validateForm(unknown)` (portable JSON) checks it against the engine's registrations and returns a frozen `NormalizedFormConfig` that the engine owns.
29
+ - **container**: the form's state, a `FormStateContainer` from `@schema-engine/forms/state-container`. It owns the nested values, errors, warnings, touched and dirty marks, field-array row ids and the validation in flight. Paths are dotted (`contacts.1.email`) and `FORM_ROOT` is the form itself. Every change is a command (`setValue`, `blur`, `reportNative`, `validate`, `submit`, `reset`, `fieldArray`), and every read is a pure selector over an immutable snapshot.
30
+ - **runtime**: `createFormRuntime` is the lifecycle every renderer shares. It builds the container and owns the submission, the wizard steps and their navigation, `form_mount` and `form_change`, and every action dispatch. A renderer supplies only what an element can do, such as focus.
31
+ - **issues and the formatter**: the engine reports what is wrong as an issue (`type`, `source`, `ruleId`, `params`, `message`) and never makes up text. `formatIssue`, a function of the application, turns an issue into the words shown, and falls back to the issue's own `message`.
32
+
33
+ Outcomes use one vocabulary: a check or a submission ends `passed`, `invalid` or `overtaken`. `overtaken` means an edit or a reset outran the check, so there is no verdict and nothing to show.
34
+
35
+ ## Packages
36
+
37
+ | Package | Role |
38
+ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
39
+ | `@schema-engine/registry` | The registration contract and read-only registries every package builds on, and `/yaml` for documents authored as YAML. Ships this router |
40
+ | `@schema-engine/actions` | Actions: `parseActions`, and a dispatcher that runs a sequence with parallel groups, cancellation and results |
41
+ | `@schema-engine/layout` | Domain-neutral grid, appearance axes, layout themes and the recipe protocol |
42
+ | `@schema-engine/forms` | The forms engine: config, validation, constraints, the container, the runtime |
43
+ | `@schema-engine/forms-react` | React renderer: `FormRenderer` and the hooks. You write the widgets; ready-made ones come from the optional shadcn registry |
44
+ | `@schema-engine/forms-radiant` | Radiant renderer: `se-form-instance`, `FormController`, widgets and recipes in the package |
45
+
46
+ A symbol has one import path. `@schema-engine/forms` has these entries: `.` (the engine, the runtime and the types), `/state-container` (the container and its selectors), `/csrf`, `/server-errors`, `/recipes`, `/recipes/built-in`, `/browser` (browser-side actions such as auto-save), `/testing` (conformance suites; they need vitest) and `/agent-tool` (experimental).
47
+
48
+ ## To do X, read Y
49
+
50
+ Each package ships this router as its own `skill/SKILL.md` and its references in its `skill/reference/` folder, so a reference is `node_modules/@schema-engine/<package>/skill/reference/<file>`, and any installed package has the router. Read the rows of the packages the project depends on and skip the others: a package that is not installed has no file. The deployed site serves the latest version of the router and of every reference at `/skill/`, with the references flat at `/skill/reference/<file>`.
51
+
52
+ | To do | Package | Reference |
53
+ | ---------------------------------------------------------------------------- | ------------------------------ | ------------------------------------ |
54
+ | Register something, build a registry, or read a YAML document | `@schema-engine/registry` | `reference/registry.md` |
55
+ | Parse, dispatch or cancel actions outside a form | `@schema-engine/actions` | `reference/actions.md` |
56
+ | Build a grid, an appearance axis or a layout theme | `@schema-engine/layout` | `reference/layout.md` |
57
+ | Create an engine, author a config, use the container or the runtime directly | `@schema-engine/forms` | `reference/forms.md` |
58
+ | Add a rule, explain a validation result, or translate messages | `@schema-engine/forms` | `reference/forms-validation.md` |
59
+ | Handle submit, server errors, CSRF or wizard steps | `@schema-engine/forms` | `reference/forms-submission.md` |
60
+ | Run code on a form event, or define a form action | `@schema-engine/forms` | `reference/forms-actions.md` |
61
+ | Render a form in React, or use its hooks | `@schema-engine/forms-react` | `reference/forms-react.md` |
62
+ | Write or change a React field widget, and test it | `@schema-engine/forms-react` | `reference/forms-react-widgets.md` |
63
+ | Render a form in Radiant, or reach the container from an element | `@schema-engine/forms-radiant` | `reference/forms-radiant.md` |
64
+ | Write or change a Radiant field widget, and test it | `@schema-engine/forms-radiant` | `reference/forms-radiant-widgets.md` |
65
+
66
+ ## Documentation map
67
+
68
+ The full documentation is at `/docs` on the deployed site. The LLM-exported corpus is `/llms.txt` (index) and `/docs-llm/<section>/<slug>.md` (page bodies).
69
+
70
+ | Section | Path prefix |
71
+ | ------------------------------ | ---------------------------------- |
72
+ | Schema Engine | `/docs/schema-engine/introduction` |
73
+ | `@schema-engine/registry` | `/docs/registry/overview` |
74
+ | `@schema-engine/actions` | `/docs/actions/overview` |
75
+ | `@schema-engine/forms` | `/docs/forms/overview` |
76
+ | `@schema-engine/forms-react` | `/docs/forms-react/overview` |
77
+ | `@schema-engine/forms-radiant` | `/docs/forms-radiant/overview` |
78
+ | `@schema-engine/layout` | `/docs/layout/overview` |
79
+ | Examples | `/docs/examples/overview` |
@@ -0,0 +1,68 @@
1
+ # @schema-engine/actions
2
+
3
+ The domain-agnostic action package: a registration, a registry, `parseActions` and a dispatcher that runs a sequence for a trigger. A form uses it through its runtime (`forms-actions.md`). The terms are defined in the router (`SKILL.md`).
4
+
5
+ ## The flow
6
+
7
+ Serialized actions are checked, then dispatched: `parseActions(registry, input)`, then `dispatcher.dispatch({ actions: parsed.data, trigger, context })`. `dispatch` takes only what `parseActions` returned, as a type, so dispatching an unchecked action does not type-check. `defineAction<Context, Trigger>()` fixes the context and the trigger of a domain once, so each registration states only its config.
8
+
9
+ ```ts title="actions/dispatch.ts"
10
+ import * as z from 'zod/mini';
11
+ import {
12
+ ActionDispatcher,
13
+ ActionRegistry,
14
+ defineAction,
15
+ parseActions,
16
+ type ActionConfigBase,
17
+ } from '@schema-engine/actions';
18
+
19
+ type Trigger = 'save';
20
+
21
+ interface Context {
22
+ readonly sent: string[];
23
+ }
24
+
25
+ interface NotifyConfig extends ActionConfigBase<'notify'> {
26
+ channel: string;
27
+ }
28
+
29
+ const defineNotify = defineAction<Context, Trigger>();
30
+
31
+ const notify = defineNotify<NotifyConfig>({
32
+ $type: 'notify',
33
+ schema: z.object({ channel: z.string() }),
34
+ metadata: { name: 'Notify', defaultTriggers: ['save'] },
35
+ execute: async ({ config, sent, signal }) => {
36
+ if (signal.aborted) return { success: false, error: 'Cancelled' };
37
+ sent.push(config.channel);
38
+ return config.channel === 'broken'
39
+ ? { success: false, error: 'No such channel', shouldContinue: false }
40
+ : { success: true };
41
+ },
42
+ });
43
+
44
+ export const registry = new ActionRegistry<Context, Trigger>([notify]);
45
+
46
+ const dispatcher = new ActionDispatcher<Context, Trigger>(registry);
47
+
48
+ /** Parses a serialized sequence, then runs it for a trigger; the entry in brackets is a parallel group. */
49
+ export async function run(input: unknown, sent: string[]) {
50
+ const parsed = parseActions(registry, input);
51
+ if (!parsed.success) return { issues: parsed.issues };
52
+ return { results: await dispatcher.dispatch({ actions: parsed.data, trigger: 'save', context: { sent } }) };
53
+ }
54
+ ```
55
+
56
+ ## An action
57
+
58
+ A registration is `{ $type, schema, metadata, execute }`; an instance is `{ $type, id, ...config, enabled?, triggers? }`. `schema` describes the action's own arguments: `parseActions` checks `id`, `$type`, `enabled` and `triggers` itself, so a schema never lists them. `metadata.defaultTriggers` says when it runs unless the instance sets its own `triggers`. `execute` receives the base context you pass to `dispatch` plus `config` (the instance), `trigger` and an abort `signal`, and returns `{ success, message?, error?, data?, shouldContinue? }`. `ActionRegistry` is built once from a list, like any registry (`registry.md`). A domain that registers at runtime implements `ActionRegistryProvider` instead.
59
+
60
+ ## parseActions
61
+
62
+ `input` is the sequence as it arrived. Each entry is validated with the schema of the registration its `$type` names, and `data` holds what the schema returned, so defaults and transforms apply. Every entry is checked, so two bad entries report both. An issue's `path` is the index of the entry, the index inside a group when the entry is one, then the path the schema reported (`[1, 0, 'channel']`); an entry with no string `$type`, and a `$type` no registration answers, are issues at `$type`.
63
+
64
+ ## Sequences, groups and cancellation
65
+
66
+ Entries run in order. An inner array is a parallel group: its actions start together and the sequence waits for all of them before the next entry. An action that is disabled, or whose triggers do not include the current one, is skipped. A thrown handler is a failed result and the sequence continues. A result with `success: false` and `shouldContinue: false` stops the sequence; in a group it also aborts the `signal` of the siblings, waits for every started handler to settle, and stops what follows. A handler must observe `signal`: one that ignores it can keep the dispatcher waiting, and cancellation never undoes a remote side effect. `dispatch({ signal })` cancels the whole dispatch from outside.
67
+
68
+ `dispatch` resolves one result per action that ran, in configuration order: the handler's result plus `actionId`, `sequenceIndex`, `groupIndex` (inside a group), `status` (`succeeded`, `failed` or `cancelled`) and `cancellationRequested`. Indexes are positions in the input, skipped actions included. `hasMatching(actions, trigger)` says whether a trigger would run anything, so a caller can skip building a context. `dispatchSync` starts the same dispatch and logs a rejection.