@schema-engine/actions 0.5.2 → 0.7.0

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/README.md CHANGED
@@ -5,7 +5,7 @@ Registered behaviour that runs from plain data. You define an action once in cod
5
5
  ## Install
6
6
 
7
7
  ```bash
8
- pnpm add @schema-engine/actions zod
8
+ pnpm add @schema-engine/actions @schema-engine/registry zod
9
9
  ```
10
10
 
11
11
  Install the [Standard Schema](https://standardschema.dev/) validator you prefer. The example uses `zod/mini`.
@@ -14,13 +14,8 @@ Install the [Standard Schema](https://standardschema.dev/) validator you prefer.
14
14
 
15
15
  ```ts
16
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';
17
+ import { createRegistry } from '@schema-engine/registry';
18
+ import { ActionDispatcher, defineAction, parseActions, type ActionConfigBase } from '@schema-engine/actions';
24
19
 
25
20
  type Trigger = 'save';
26
21
 
@@ -45,12 +40,12 @@ const notify = defineNotify<NotifyConfig>({
45
40
  },
46
41
  });
47
42
 
48
- const registry = new ActionRegistry<Context, Trigger>([notify]);
43
+ const registry = createRegistry('Action', [notify]);
49
44
 
50
45
  export async function run(input: unknown, sent: string[]) {
51
46
  const parsed = parseActions(registry, input);
52
47
  if (!parsed.success) return { issues: parsed.issues };
53
- const dispatcher = new ActionDispatcher<Context, Trigger>(registry);
48
+ const dispatcher = new ActionDispatcher(registry);
54
49
  return { results: await dispatcher.dispatch({ actions: parsed.data, trigger: 'save', context: { sent } }) };
55
50
  }
56
51
  ```
@@ -59,7 +54,7 @@ export async function run(input: unknown, sent: string[]) {
59
54
 
60
55
  ## Exports
61
56
 
62
- The package has one entry, `@schema-engine/actions`: `ActionRegistry`, `ActionDispatcher`, `parseActions`, `defineAction` and the registration, entry and result types.
57
+ The package has one entry, `@schema-engine/actions`: `ActionDispatcher`, `parseActions`, `defineAction` and the registration, entry and result types. The registry is the one from `@schema-engine/registry`, and `parseActions` and `ActionDispatcher` take any lookup with `get($type)`.
63
58
 
64
59
  ## Documentation
65
60
 
@@ -1,9 +1,17 @@
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. */
1
+ import type { ActionConfigBase, ActionDispatchInput, ActionDispatchResult, AnyActionRegistration, ParsedActionSequence } from './types.js';
2
+ import type { NodeLookup } from '@schema-engine/registry';
3
+ /**
4
+ * Dispatches actions in sequence, allowing groups to execute concurrently.
5
+ *
6
+ * @remarks
7
+ * The registry is any {@link NodeLookup}: a `createRegistry` or `createMutableRegistry` result from
8
+ * `@schema-engine/registry`, or `{ get }` over a store of your own. The context and trigger types are inferred from the
9
+ * registrations, which fix them through `defineAction<Context, Trigger>()`. The dispatcher calls only `get`, at
10
+ * dispatch time, so a mutable registry may gain registrations after the dispatcher is built.
11
+ */
4
12
  export declare class ActionDispatcher<TBaseContext = unknown, TTrigger = string> {
5
13
  private readonly registry;
6
- constructor(registry: ActionRegistryProvider<TBaseContext, TTrigger>);
14
+ constructor(registry: NodeLookup<AnyActionRegistration<TBaseContext, TTrigger>>);
7
15
  dispatch<TConfig extends ActionConfigBase>({ actions, trigger, context, metadata, triggeredBy, signal: outer, }: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): Promise<ActionDispatchResult[]>;
8
16
  /**
9
17
  * Whether `dispatch` would run, or report a missing handler for, at least one of the actions on this trigger.
package/dist/index.d.ts CHANGED
@@ -7,21 +7,20 @@
7
7
  * @example
8
8
  * ```typescript
9
9
  * import * as z from 'zod/mini';
10
- * import { Logger } from '@ecopages/logger';
11
- * import { ActionDispatcher, ActionRegistry, parseActions } from '@schema-engine/actions';
10
+ * import { createRegistry } from '@schema-engine/registry';
11
+ * import { ActionDispatcher, defineAction, parseActions } from '@schema-engine/actions';
12
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
- * },
13
+ * const defineLogAction = defineAction<{ formId: string }, 'submit' | 'change'>();
14
+ * const log = defineLogAction({
15
+ * $type: 'log',
16
+ * schema: z.object({ message: z.string() }),
17
+ * metadata: { name: 'Log', defaultTriggers: ['change'] },
18
+ * execute: async (ctx) => {
19
+ * console.info(ctx.config.message, ctx);
20
+ * return { success: true };
23
21
  * },
24
- * ]);
22
+ * });
23
+ * const registry = createRegistry('Action', [log]);
25
24
  *
26
25
  * const dispatcher = new ActionDispatcher(registry);
27
26
  * const parsed = parseActions(registry, [{ id: '1', $type: 'log', message: 'hello' }]);
@@ -30,7 +29,6 @@
30
29
  * }
31
30
  * ```
32
31
  */
33
- export * from './types';
34
- export * from './registry';
35
- export * from './dispatcher';
36
- export * from './parse-actions';
32
+ export * from './types.js';
33
+ export * from './dispatcher.js';
34
+ export * from './parse-actions.js';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- function _(){return function(t){return t}}import{createRegistry as D}from"@schema-engine/registry";var k=class{#e;constructor(e){this.#e=D("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 E}from"@ecopages/logger";var C=new E("[@schema-engine/actions]");function I(t){return typeof t=="object"&&t!==null}function P(t){return Array.isArray(t)}function q(t,e){return e.aborted&&t instanceof Error&&t.name==="AbortError"}var w=class{constructor(e){this.registry=e}registry;async dispatch({actions:e,trigger:n,context:i,metadata:r,triggeredBy:s,signal:f}){if(!e?.length)return[];let a=r?this.mergeMetadata(i,r):i,o=[];for(let[g,d]of e.entries()){if(f?.aborted)break;let u=new AbortController,p=()=>u.abort(f?.reason);f?.addEventListener("abort",p,{once:!0});let h=async(c,y)=>{let R=this.match(c,n);if(!R.runs)return;let{registration:B}=R;if(!B){let l=`No handler registered for action type: ${c.$type}`;return C.error(l,{actionId:c.id,availableActions:this.registry.getActionTypes()}),{actionId:c.id,sequenceIndex:g,...y===void 0?{}:{groupIndex:y},status:"failed",cancellationRequested:!1,success:!1,error:l,shouldContinue:!0}}C.debug(`Executing action: ${c.id} (${c.$type})`);let T,b=!1;try{T=await B.execute({...a,config:c,trigger:n,signal:u.signal,...s?{triggeredBy:s}:{}})}catch(l){b=q(l,u.signal),T={success:!1,error:l instanceof Error?l.message:String(l),cause:l,shouldContinue:!0}}let S=u.signal.aborted;return!T.success&&T.shouldContinue===!1&&u.abort(),T.success||C.warn(`Action ${c.id} failed`,T),{...T,actionId:c.id,sequenceIndex:g,...y===void 0?{}:{groupIndex:y},status:b?"cancelled":T.success?"succeeded":"failed",cancellationRequested:S}},m;try{m=P(d)?await Promise.all(d.map(h)):[await h(d)]}finally{f?.removeEventListener("abort",p)}let x=m.filter(c=>c!==void 0);if(o.push(...x),x.some(c=>!c.success&&c.shouldContinue===!1))break}return o}hasMatching(e,n){return e.some(i=>P(i)?i.some(r=>this.match(r,n).runs):this.match(i,n).runs)}match(e,n){if(e.enabled===!1)return{runs:!1};if(e.triggers!==void 0&&!e.triggers.some(s=>s===n))return{runs:!1};let i=this.registry.getAction(e.$type);return e.triggers===void 0&&i&&!(i.metadata.defaultTriggers??[]).includes(n)?{runs:!1}:{runs:!0,registration:i}}dispatchSync(e){this.dispatch(e).catch(n=>C.error("dispatchSync failed:",n))}mergeMetadata(e,n){if(!I(e))return e;let i=e.metadata;return{...e,metadata:{...typeof i=="object"&&i!==null?i:{},...n}}}};import{safeParseNode as v,safeParseStandardSchema as $,standardSchema as M}from"@schema-engine/registry";function O(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function A(t,e){return{message:e,path:t}}var L="Register it in the action registry.",N=["id","$type","enabled","triggers"];function j(t,e){let n=[];(typeof t.id!="string"||t.id==="")&&n.push(A(["id"],"Action ID must be a non-empty string.")),t.enabled!==void 0&&typeof t.enabled!="boolean"&&n.push(A(["enabled"],"enabled must be a boolean."));let{triggers:i}=t;return i===void 0?n:Array.isArray(i)?(i.forEach((r,s)=>{typeof r!="string"?n.push(A(["triggers",s],"A trigger must be a string.")):e?.triggers&&!e.triggers.includes(r)&&n.push(A(["triggers",s],`Unknown trigger '${r}'. Use one of: ${e.triggers.join(", ")}.`))}),n):(n.push(A(["triggers"],"triggers must be an array of trigger names.")),n)}function K(t,e,n){return M(i=>{let r=i,s=j(r,n),f={},a={};for(let[d,u]of Object.entries(r))N.includes(d)?f[d]=u:a[d]=u;let o=$(e,a);if(!o.success)return{issues:[...s,...o.error.issues]};let{data:g}=o;if(!O(g)){let d=`Invalid action configuration for '${t}': the schema must return an object.`;return{issues:[...s,A([],d)]}}return s.length>0?{issues:s}:{value:{...g,...f,id:r.id,$type:t}}})}function Y(t,e,n){if(!Array.isArray(e))return{success:!1,issues:[A([],"Actions must be an array.")]};let i={get(a){let o=t.getAction(a);return o&&{schema:K(a,o.schema,n)}},hint:n?.hint??L},r=[],s=[],f=(a,o)=>{let g=v(i,a,o);if(g.success)return g.data;r.push(...g.issues)};return e.forEach((a,o)=>{if(Array.isArray(a)){if(a.length===0){r.push(A([o],"A group of actions must hold at least one action."));return}let d=a.map((u,p)=>f(u,[o,p])).filter(u=>u!==void 0);s.push(d);return}let g=f(a,[o]);g&&s.push(g)}),r.length>0?{success:!1,issues:r}:{success:!0,data:s}}export{w as ActionDispatcher,k as ActionRegistry,_ as defineAction,Y as parseActions};
1
+ function _(){return function(e){return e}}var h="[schema-engine/actions]",C={info:(e,...n)=>console.info(h,e,...n),warn:(e,...n)=>console.warn(h,e,...n),error:(e,...n)=>console.error(h,e,...n)};function P(e){return e instanceof Error?e:"A non-Error value was thrown"}function I(e){return typeof e=="object"&&e!==null}function S(e){return Array.isArray(e)}function q(e,n){return n.aborted&&e instanceof Error&&e.name==="AbortError"}var E=class{constructor(n){this.registry=n}registry;async dispatch({actions:n,trigger:t,context:r,metadata:o,triggeredBy:s,signal:f}){if(!n?.length)return[];let a=o?this.mergeMetadata(r,o):r,i=[];for(let[u,d]of n.entries()){if(f?.aborted)break;let g=new AbortController,p=()=>g.abort(f?.reason);f?.addEventListener("abort",p,{once:!0});let m=async(c,y)=>{let B=this.match(c,t);if(!B.runs)return;let{registration:k}=B;if(!k){let T=`No handler registered for action type: ${c.$type}`;return C.error(T,{actionId:c.id,...this.registry.kind===void 0?{}:{registry:this.registry.kind}}),{actionId:c.id,sequenceIndex:u,...y===void 0?{}:{groupIndex:y},status:"failed",cancellationRequested:!1,success:!1,error:T,shouldContinue:!0}}let l,b=!1,w=!1;try{l=await k.execute({...a,config:c,trigger:t,signal:g.signal,...s?{triggeredBy:s}:{}})}catch(T){b=q(T,g.signal),w=!(T instanceof Error),l={success:!1,error:T instanceof Error?T.message:String(T),cause:T,shouldContinue:!0}}let D=g.signal.aborted;return!l.success&&l.shouldContinue===!1&&g.abort(),l.success||C.warn(`Action ${c.id} failed`,{actionId:c.id,$type:c.$type,error:w?"The action threw a non-Error value":l.error,...l.cause instanceof Error?{cause:l.cause}:{}}),{...l,actionId:c.id,sequenceIndex:u,...y===void 0?{}:{groupIndex:y},status:b?"cancelled":l.success?"succeeded":"failed",cancellationRequested:D}},x;try{x=S(d)?await Promise.all(d.map(m)):[await m(d)]}finally{f?.removeEventListener("abort",p)}let R=x.filter(c=>c!==void 0);if(i.push(...R),R.some(c=>!c.success&&c.shouldContinue===!1))break}return i}hasMatching(n,t){return n.some(r=>S(r)?r.some(o=>this.match(o,t).runs):this.match(r,t).runs)}match(n,t){if(n.enabled===!1)return{runs:!1};if(n.triggers!==void 0&&!n.triggers.some(s=>s===t))return{runs:!1};let r=this.registry.get(n.$type);return n.triggers===void 0&&r&&!(r.metadata.defaultTriggers??[]).includes(t)?{runs:!1}:{runs:!0,registration:r}}dispatchSync(n){this.dispatch(n).catch(t=>C.error("dispatchSync failed:",P(t)))}mergeMetadata(n,t){if(!I(n))return n;let r=n.metadata;return{...n,metadata:{...typeof r=="object"&&r!==null?r:{},...t}}}};import{safeParseNode as $,safeParseStandardSchema as v,standardSchema as M}from"@schema-engine/registry";function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A(e,n){return{message:n,path:e}}var O="Register it in the action registry.",j=["id","$type","enabled","triggers"];function L(e,n){let t=[];(typeof e.id!="string"||e.id==="")&&t.push(A(["id"],"Action ID must be a non-empty string.")),e.enabled!==void 0&&typeof e.enabled!="boolean"&&t.push(A(["enabled"],"enabled must be a boolean."));let{triggers:r}=e;return r===void 0?t:Array.isArray(r)?(r.forEach((o,s)=>{typeof o!="string"?t.push(A(["triggers",s],"A trigger must be a string.")):n?.triggers&&!n.triggers.includes(o)&&t.push(A(["triggers",s],`Unknown trigger '${o}'. Use one of: ${n.triggers.join(", ")}.`))}),t):(t.push(A(["triggers"],"triggers must be an array of trigger names.")),t)}function K(e,n,t){return M(r=>{let o=r,s=L(o,t),f={},a={};for(let[d,g]of Object.entries(o))j.includes(d)?f[d]=g:a[d]=g;let i=v(n,a);if(!i.success)return{issues:[...s,...i.error.issues]};let{data:u}=i;if(!N(u)){let d=`Invalid action configuration for '${e}': the schema must return an object.`;return{issues:[...s,A([],d)]}}return s.length>0?{issues:s}:{value:{...u,...f,id:o.id,$type:e}}})}function Y(e,n,t){if(!Array.isArray(n))return{success:!1,issues:[A([],"Actions must be an array.")]};let r={get(a){let i=e.get(a);return i&&{schema:K(a,i.schema,t)}},hint:e.hint??O},o=[],s=[],f=(a,i)=>{let u=$(r,a,{path:i});if(u.success)return u.data;o.push(...u.issues)};return n.forEach((a,i)=>{if(Array.isArray(a)){if(a.length===0){o.push(A([i],"A group of actions must hold at least one action."));return}let d=a.map((g,p)=>f(g,[i,p])).filter(g=>g!==void 0);s.push(d);return}let u=f(a,[i]);u&&s.push(u)}),o.length>0?{success:!1,issues:o}:{success:!0,data:s}}export{E as ActionDispatcher,_ as defineAction,Y as parseActions};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
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 {\n\tsafeParseNode,\n\tsafeParseStandardSchema,\n\tstandardSchema,\n\ttype BaseRegistration,\n\ttype NodeLookup,\n\ttype StandardSchemaIssue,\n} 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\t/**\n\t * The sentence that follows the message of an action `$type` nothing registers, naming where to register it.\n\t *\n\t * @remarks Without it, the sentence is `Register it in the action registry.`. A domain that registers actions through its own entry point says that one.\n\t */\n\thint?: NodeLookup['hint'];\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']`). Each entry is checked by `safeParseNode`, so its\n * issues sit where that function puts them: an entry that is not an object at the entry, and a missing or unregistered\n * `$type` at `$type`. An unregistered `$type` says where to register it ({@link ParseActionsOptions.hint}). 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\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\nconst DEFAULT_HINT = 'Register it in the action registry.';\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\toptions: ParseActionsOptions | undefined,\n): StandardSchemaIssue[] {\n\tconst issues: StandardSchemaIssue[] = [];\n\tif (typeof entry.id !== 'string' || entry.id === '') {\n\t\tissues.push(issueAt(['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(['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(['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(['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['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\n/**\n * The schema of a whole entry: the envelope keys the engine checks, then the remaining keys checked by the\n * registration's schema, merged into the parsed action.\n *\n * @remarks\n * `safeParseNode` runs it only once it has found the registration, so the entry is an object with a registered\n * `$type`. Its issues are relative to the entry; `safeParseNode` puts the entry's path in front.\n */\nfunction entrySchema(\n\ttype: string,\n\town: BaseRegistration['schema'],\n\toptions: ParseActionsOptions | undefined,\n): BaseRegistration['schema'] {\n\treturn standardSchema((value) => {\n\t\tconst entry = value as Record<PropertyKey, unknown>;\n\t\tconst issues = checkBase(entry, options);\n\t\tconst base: Record<string, unknown> = {};\n\t\tconst rest: Record<string, unknown> = {};\n\t\tfor (const [key, field] of Object.entries(entry)) {\n\t\t\tif ((BASE_KEYS as readonly string[]).includes(key)) base[key] = field;\n\t\t\telse rest[key] = field;\n\t\t}\n\t\tconst result = safeParseStandardSchema(own, rest);\n\t\tif (!result.success) return { issues: [...issues, ...result.error.issues] };\n\t\tconst { data } = result;\n\t\tif (!isRecord(data)) {\n\t\t\tconst message = `Invalid action configuration for '${type}': the schema must return an object.`;\n\t\t\treturn { issues: [...issues, issueAt([], message)] };\n\t\t}\n\t\tif (issues.length > 0) return { issues };\n\t\treturn { value: { ...data, ...base, id: entry.id, $type: type } };\n\t});\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 * Each entry is a node, checked with `safeParseNode` from `@schema-engine/registry` like any other node. The engine\n * 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 entries: NodeLookup<Pick<BaseRegistration, 'schema'>> = {\n\t\tget(type) {\n\t\t\tconst registration = registry.getAction(type);\n\t\t\treturn registration && { schema: entrySchema(type, registration.schema, options) };\n\t\t},\n\t\thint: options?.hint ?? DEFAULT_HINT,\n\t};\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 = safeParseNode(entries, entry, path);\n\t\tif (parsed.success) return parsed.data as ParsedAction<TConfig>;\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: sequence };\n}\n"],
5
- "mappings": "AAkOO,SAASA,GAAgD,CAC/D,OAAO,SACNC,EAC6D,CAC7D,OAAOA,CACR,CACD,CCvOA,OAAS,kBAAAC,MAA6C,0BAuG/C,IAAMC,EAAN,KAMP,CACUC,GAET,YAAYC,EAAyC,CACpD,KAAKD,GAAYF,EAAe,SAAUG,CAAa,CACxD,CAEA,IAAI,MAAe,CAClB,OAAO,KAAKD,GAAU,IACvB,CAEA,IAAI,MAAe,CAClB,OAAO,KAAKA,GAAU,IACvB,CAEA,IAAIE,EAAwC,CAC3C,OAAO,KAAKF,GAAU,IAAIE,CAAG,CAC9B,CAEA,IAAIA,EAAsB,CACzB,OAAO,KAAKF,GAAU,IAAIE,CAAG,CAC9B,CAEA,KAAgC,CAC/B,OAAO,KAAKF,GAAU,IAAI,CAC3B,CAEA,MAA0B,CACzB,OAAO,KAAKA,GAAU,KAAK,CAC5B,CAKA,UAAUG,EAAyC,CAClD,OAAO,KAAK,IAAIA,CAAI,CACrB,CAKA,gBAA2B,CAC1B,MAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CACvB,CACD,EChJA,OAAS,UAAAC,MAAc,mBAEvB,IAAMC,EAAS,IAAID,EAAO,0BAA0B,EAIpD,SAASE,EAAkBC,EAA0C,CACpE,OAAO,OAAOA,GAAU,UAAYA,IAAU,IAC/C,CAEA,SAASC,EAAoCC,EAAsD,CAClG,OAAO,MAAM,QAAQA,CAAK,CAC3B,CAEA,SA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AAA,CAAO,EAChD,CAAE,QAAS,GAAM,KAAMkB,CAAS,CACxC",
6
- "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", "safeParseNode", "safeParseStandardSchema", "standardSchema", "isRecord", "value", "issueAt", "path", "message", "DEFAULT_HINT", "BASE_KEYS", "checkBase", "entry", "options", "issues", "triggers", "trigger", "index", "entrySchema", "type", "own", "base", "rest", "key", "field", "result", "data", "parseActions", "registry", "input", "entries", "registration", "sequence", "collect", "parsed", "group", "member", "memberIndex", "action"]
3
+ "sources": ["../src/types.ts", "../src/logger.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/**\n * An action registration of any config shape, for a registry that holds actions of several configs.\n *\n * @remarks\n * A registry holds actions of many config shapes, so the config type is an existential placeholder: `any` is the one\n * type every `ActionRegistration<TConfig, ...>` is assignable to, whatever its `TConfig`. Use it as the type of a\n * `createMutableRegistry<AnyActionRegistration<Context, Trigger>>('Action')`, which a single `ActionRegistration<TConfig>`\n * could not type. The `$type` stays a `string`: with `any` as the config, `TConfig['$type']` would be `any`.\n */\nexport type AnyActionRegistration<TBaseContext = unknown, TTrigger = string> = Omit<\n\tActionRegistration<any, TBaseContext, TTrigger>,\n\t'$type'\n> & { readonly $type: string };\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", "const TAG = '[schema-engine/actions]';\n\n/**\n * The package's diagnostics, each prefixed with the package tag.\n *\n * @remarks\n * Plain `console` calls with no level switch. A diagnostic never carries data the package passes through: a field\n * value, a submission, a saved draft, analytics event data or an action's returned data. Pass a caught value through\n * `loggableError`, never as it is.\n */\nexport const logger = {\n\tinfo: (message: string, ...details: unknown[]): void => console.info(TAG, message, ...details),\n\twarn: (message: string, ...details: unknown[]): void => console.warn(TAG, message, ...details),\n\terror: (message: string, ...details: unknown[]): void => console.error(TAG, message, ...details),\n};\n\n/**\n * The value to log for a caught value: the `Error` itself, or a fixed message for anything else.\n *\n * @remarks\n * A thrown value that is not an `Error` may hold anything the app put in it, so it is never logged.\n */\nexport function loggableError(value: unknown): Error | string {\n\treturn value instanceof Error ? value : 'A non-Error value was thrown';\n}\n", "import type {\n\tActionConfigBase,\n\tActionDispatchInput,\n\tActionDispatchResult,\n\tActionExecutionResult,\n\tActionSequenceEntry,\n\tAnyActionRegistration,\n\tParsedAction,\n\tParsedActionSequence,\n} from './types.js';\nimport type { NodeLookup } from '@schema-engine/registry';\nimport { loggableError, logger } from './logger.js';\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 } | { runs: true; registration: AnyActionRegistration<TBaseContext, TTrigger> | undefined };\n\n/**\n * Dispatches actions in sequence, allowing groups to execute concurrently.\n *\n * @remarks\n * The registry is any {@link NodeLookup}: a `createRegistry` or `createMutableRegistry` result from\n * `@schema-engine/registry`, or `{ get }` over a store of your own. The context and trigger types are inferred from the\n * registrations, which fix them through `defineAction<Context, Trigger>()`. The dispatcher calls only `get`, at\n * dispatch time, so a mutable registry may gain registrations after the dispatcher is built.\n */\nexport class ActionDispatcher<TBaseContext = unknown, TTrigger = string> {\n\tconstructor(private readonly registry: NodeLookup<AnyActionRegistration<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, {\n\t\t\t\t\t\tactionId: action.id,\n\t\t\t\t\t\t...(this.registry.kind === undefined ? {} : { registry: this.registry.kind }),\n\t\t\t\t\t});\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\tlet result: ActionExecutionResult;\n\t\t\t\tlet cancelled = false;\n\t\t\t\tlet threwNonError = 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\tthrewNonError = !(error instanceof Error);\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) {\n\t\t\t\t\tlogger.warn(`Action ${action.id} failed`, {\n\t\t\t\t\t\tactionId: action.id,\n\t\t\t\t\t\t$type: action.$type,\n\t\t\t\t\t\terror: threwNonError ? 'The action threw a non-Error value' : result.error,\n\t\t\t\t\t\t...(result.cause instanceof Error ? { cause: result.cause } : {}),\n\t\t\t\t\t});\n\t\t\t\t}\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.get(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: unknown) => logger.error('dispatchSync failed:', loggableError(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 {\n\tsafeParseNode,\n\tsafeParseStandardSchema,\n\tstandardSchema,\n\ttype BaseRegistration,\n\ttype NodeLookup,\n\ttype RegistryIssue,\n\ttype StandardSchemaIssue,\n} from '@schema-engine/registry';\nimport type { ActionConfigBase, ParsedAction, ParsedActionSequence } from './types.js';\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']`). Each entry is checked by `safeParseNode`, so its\n * issues sit where that function puts them: an entry that is not an object at the entry, and a missing or unregistered\n * `$type` at `$type`. An unregistered `$type` says where to register it ({@link NodeLookup.hint}). An empty group is an issue at its index.\n * An issue the registry creates has its namespaced `code` (`registry/unregistered-type` with `received`, say); the ones\n * of the engine's own checks have none.\n */\nexport type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> =\n\t{ success: true; data: ParsedActionSequence<TConfig> } | { success: false; issues: RegistryIssue[] };\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\nconst DEFAULT_HINT = 'Register it in the action registry.';\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\toptions: ParseActionsOptions | undefined,\n): StandardSchemaIssue[] {\n\tconst issues: StandardSchemaIssue[] = [];\n\tif (typeof entry.id !== 'string' || entry.id === '') {\n\t\tissues.push(issueAt(['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(['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(['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(['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['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\n/**\n * The schema of a whole entry: the envelope keys the engine checks, then the remaining keys checked by the\n * registration's schema, merged into the parsed action.\n *\n * @remarks\n * `safeParseNode` runs it only once it has found the registration, so the entry is an object with a registered\n * `$type`. Its issues are relative to the entry; `safeParseNode` puts the entry's path in front.\n */\nfunction entrySchema(\n\ttype: string,\n\town: BaseRegistration['schema'],\n\toptions: ParseActionsOptions | undefined,\n): BaseRegistration['schema'] {\n\treturn standardSchema((value) => {\n\t\tconst entry = value as Record<PropertyKey, unknown>;\n\t\tconst issues = checkBase(entry, options);\n\t\tconst base: Record<string, unknown> = {};\n\t\tconst rest: Record<string, unknown> = {};\n\t\tfor (const [key, field] of Object.entries(entry)) {\n\t\t\tif ((BASE_KEYS as readonly string[]).includes(key)) base[key] = field;\n\t\t\telse rest[key] = field;\n\t\t}\n\t\tconst result = safeParseStandardSchema(own, rest);\n\t\tif (!result.success) return { issues: [...issues, ...result.error.issues] };\n\t\tconst { data } = result;\n\t\tif (!isRecord(data)) {\n\t\t\tconst message = `Invalid action configuration for '${type}': the schema must return an object.`;\n\t\t\treturn { issues: [...issues, issueAt([], message)] };\n\t\t}\n\t\tif (issues.length > 0) return { issues };\n\t\treturn { value: { ...data, ...base, id: entry.id, $type: type } };\n\t});\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: a registry of either kind, or any\n * {@link NodeLookup}. Its `hint` ends the message of an unregistered `$type`; without one the sentence is\n * `Register it in the action registry.`\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 * Each entry is a node, checked with `safeParseNode` from `@schema-engine/registry` like any other node. The engine\n * 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: NodeLookup<Pick<BaseRegistration, 'schema'>>,\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 entries: NodeLookup<Pick<BaseRegistration, 'schema'>> = {\n\t\tget(type) {\n\t\t\tconst registration = registry.get(type);\n\t\t\treturn registration && { schema: entrySchema(type, registration.schema, options) };\n\t\t},\n\t\thint: registry.hint ?? DEFAULT_HINT,\n\t};\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 = safeParseNode(entries, entry, { path });\n\t\tif (parsed.success) return parsed.data as ParsedAction<TConfig>;\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: sequence };\n}\n"],
5
+ "mappings": "AAgPO,SAASA,GAAgD,CAC/D,OAAO,SACNC,EAC6D,CAC7D,OAAOA,CACR,CACD,CCtPA,IAAMC,EAAM,0BAUCC,EAAS,CACrB,KAAM,CAACC,KAAoBC,IAA6B,QAAQ,KAAKH,EAAKE,EAAS,GAAGC,CAAO,EAC7F,KAAM,CAACD,KAAoBC,IAA6B,QAAQ,KAAKH,EAAKE,EAAS,GAAGC,CAAO,EAC7F,MAAO,CAACD,KAAoBC,IAA6B,QAAQ,MAAMH,EAAKE,EAAS,GAAGC,CAAO,CAChG,EAQO,SAASC,EAAcC,EAAgC,CAC7D,OAAOA,aAAiB,M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,CAACW,CAAK,EAAG,mDAAmD,CAAC,EACjF,MACD,CACA,IAAMkB,EAAQvB,EACZ,IAAI,CAACwB,EAAiBC,IAAgBJ,EAAQG,EAAQ,CAACnB,EAAOoB,CAAW,CAAC,CAAC,EAC3E,OAAQC,GAA4CA,IAAW,MAAS,EAC1EN,EAAS,KAAKG,CAAK,EACnB,MACD,CACA,IAAMG,EAASL,EAAQrB,EAAO,CAACK,CAAK,CAAC,EACjCqB,GAAQN,EAAS,KAAKM,CAAM,CACjC,CAAC,EAEGxB,EAAO,OAAS,EAAU,CAAE,QAAS,GAAO,OAAAA,CAAO,EAChD,CAAE,QAAS,GAAM,KAAMkB,CAAS,CACxC",
6
+ "names": ["defineAction", "registration", "TAG", "logger", "message", "details", "loggableError", "value", "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", "logger", "result", "cancelled", "threwNonError", "cancellationRequested", "groupResults", "executed", "candidate", "input", "loggableError", "existingMetadata", "safeParseNode", "safeParseStandardSchema", "standardSchema", "isRecord", "value", "issueAt", "path", "message", "DEFAULT_HINT", "BASE_KEYS", "checkBase", "entry", "options", "issues", "triggers", "trigger", "index", "entrySchema", "type", "own", "base", "rest", "key", "field", "result", "data", "parseActions", "registry", "input", "entries", "registration", "sequence", "collect", "parsed", "group", "member", "memberIndex", "action"]
7
7
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The package's diagnostics, each prefixed with the package tag.
3
+ *
4
+ * @remarks
5
+ * Plain `console` calls with no level switch. A diagnostic never carries data the package passes through: a field
6
+ * value, a submission, a saved draft, analytics event data or an action's returned data. Pass a caught value through
7
+ * `loggableError`, never as it is.
8
+ */
9
+ export declare const logger: {
10
+ info: (message: string, ...details: unknown[]) => void;
11
+ warn: (message: string, ...details: unknown[]) => void;
12
+ error: (message: string, ...details: unknown[]) => void;
13
+ };
14
+ /**
15
+ * The value to log for a caught value: the `Error` itself, or a fixed message for anything else.
16
+ *
17
+ * @remarks
18
+ * A thrown value that is not an `Error` may hold anything the app put in it, so it is never logged.
19
+ */
20
+ export declare function loggableError(value: unknown): Error | string;
@@ -1,9 +1,5 @@
1
- import { type BaseRegistration, type NodeLookup, 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
- }
1
+ import { type BaseRegistration, type NodeLookup, type RegistryIssue } from '@schema-engine/registry';
2
+ import type { ActionConfigBase, ParsedActionSequence } from './types.js';
7
3
  /** What a domain tells {@link parseActions} about the entries it accepts. */
8
4
  export interface ParseActionsOptions {
9
5
  /**
@@ -12,12 +8,6 @@ export interface ParseActionsOptions {
12
8
  * @remarks Without it, any string is accepted, since the engine cannot know a domain's triggers.
13
9
  */
14
10
  triggers?: readonly string[];
15
- /**
16
- * The sentence that follows the message of an action `$type` nothing registers, naming where to register it.
17
- *
18
- * @remarks Without it, the sentence is `Register it in the action registry.`. A domain that registers actions through its own entry point says that one.
19
- */
20
- hint?: NodeLookup['hint'];
21
11
  }
22
12
  /**
23
13
  * What {@link parseActions} returns: the parsed sequence, or every issue found.
@@ -26,19 +16,23 @@ export interface ParseActionsOptions {
26
16
  * An issue is a Standard Schema issue whose `path` starts with the index of the entry, then the index inside
27
17
  * a group, then the path the schema reported (`[1, 0, 'endpoint']`). Each entry is checked by `safeParseNode`, so its
28
18
  * issues sit where that function puts them: an entry that is not an object at the entry, and a missing or unregistered
29
- * `$type` at `$type`. An unregistered `$type` says where to register it ({@link ParseActionsOptions.hint}). An empty group is an issue at its index.
19
+ * `$type` at `$type`. An unregistered `$type` says where to register it ({@link NodeLookup.hint}). An empty group is an issue at its index.
20
+ * An issue the registry creates has its namespaced `code` (`registry/unregistered-type` with `received`, say); the ones
21
+ * of the engine's own checks have none.
30
22
  */
31
23
  export type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> = {
32
24
  success: true;
33
25
  data: ParsedActionSequence<TConfig>;
34
26
  } | {
35
27
  success: false;
36
- issues: StandardSchemaIssue[];
28
+ issues: RegistryIssue[];
37
29
  };
38
30
  /**
39
31
  * Check serialized actions against their registrations, and return them as {@link ParsedAction}s.
40
32
  *
41
- * @param registry - Where each entry's `$type` finds its registration and schema
33
+ * @param registry - Where each entry's `$type` finds its registration and schema: a registry of either kind, or any
34
+ * {@link NodeLookup}. Its `hint` ends the message of an unregistered `$type`; without one the sentence is
35
+ * `Register it in the action registry.`
42
36
  * @param input - The sequence as it arrived, for example the result of `JSON.parse`: entries, where an array entry is a group
43
37
  * @param options - What the domain adds, such as the trigger names it accepts
44
38
  *
@@ -54,4 +48,4 @@ export type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBa
54
48
  *
55
49
  * @throws {Error} When a registration's schema validates asynchronously, which is a misuse of the registry.
56
50
  */
57
- export declare function parseActions<TConfig extends ActionConfigBase = ActionConfigBase>(registry: ActionSchemaLookup, input: unknown, options?: ParseActionsOptions): ParseActionsResult<TConfig>;
51
+ export declare function parseActions<TConfig extends ActionConfigBase = ActionConfigBase>(registry: NodeLookup<Pick<BaseRegistration, 'schema'>>, input: unknown, options?: ParseActionsOptions): ParseActionsResult<TConfig>;
package/dist/types.d.ts CHANGED
@@ -181,6 +181,18 @@ export interface ActionRegistration<TConfig extends ActionConfigBase = ActionCon
181
181
  */
182
182
  execute: ActionHandler<TConfig, TBaseContext, TTrigger, TData>;
183
183
  }
184
+ /**
185
+ * An action registration of any config shape, for a registry that holds actions of several configs.
186
+ *
187
+ * @remarks
188
+ * A registry holds actions of many config shapes, so the config type is an existential placeholder: `any` is the one
189
+ * type every `ActionRegistration<TConfig, ...>` is assignable to, whatever its `TConfig`. Use it as the type of a
190
+ * `createMutableRegistry<AnyActionRegistration<Context, Trigger>>('Action')`, which a single `ActionRegistration<TConfig>`
191
+ * could not type. The `$type` stays a `string`: with `any` as the config, `TConfig['$type']` would be `any`.
192
+ */
193
+ export type AnyActionRegistration<TBaseContext = unknown, TTrigger = string> = Omit<ActionRegistration<any, TBaseContext, TTrigger>, '$type'> & {
194
+ readonly $type: string;
195
+ };
184
196
  /** Input for trigger-based sequential dispatch. */
185
197
  export interface ActionDispatchInput<TConfig extends ActionConfigBase = ActionConfigBase, TBaseContext = unknown, TTrigger = string> {
186
198
  trigger: TTrigger;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@schema-engine/actions",
3
3
  "type": "module",
4
- "version": "0.5.2",
4
+ "version": "0.7.0",
5
5
  "description": "Registered actions that run from plain data: serializable workflows of sequential and parallel steps, checked before they run",
6
6
  "keywords": [
7
7
  "schema-engine",
@@ -17,9 +17,6 @@
17
17
  "url": "git+https://github.com/schema-engine/schema-engine.git",
18
18
  "directory": "packages/actions"
19
19
  },
20
- "engines": {
21
- "node": "^24.22.0 || >=26.0.0"
22
- },
23
20
  "homepage": "https://schema-engine.com/docs/actions/overview",
24
21
  "publishConfig": {
25
22
  "access": "public"
@@ -28,6 +25,15 @@
28
25
  "main": "dist/index.js",
29
26
  "module": "dist/index.js",
30
27
  "types": "dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ },
33
+ "./package.json": {
34
+ "import": "./package.json"
35
+ }
36
+ },
31
37
  "files": [
32
38
  "/dist/*",
33
39
  "/skill"
@@ -41,22 +47,21 @@
41
47
  "prettier --write"
42
48
  ]
43
49
  },
44
- "dependencies": {
45
- "@ecopages/logger": "^0.2.3",
46
- "@schema-engine/registry": "^0.5.2"
47
- },
48
50
  "devDependencies": {
49
51
  "esbuild": "^0.27.0",
50
- "tsc-alias": "^1.8.16",
51
52
  "typescript": "^5.9.3",
52
53
  "vitest": "^5.1.1",
53
- "zod": "^4.0.17",
54
+ "zod": "^4.5.0",
55
+ "@schema-engine/registry": "^0.7.0",
54
56
  "@schema-engine/scripts": "^0.0.0"
55
57
  },
58
+ "peerDependencies": {
59
+ "@schema-engine/registry": "^0.7.0"
60
+ },
56
61
  "scripts": {
57
62
  "build:lib": "pnpm clean && pnpm build:files && pnpm build:types",
58
63
  "build:files": "node ./build.ts",
59
- "build:types": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
64
+ "build:types": "tsc -p tsconfig.build.json",
60
65
  "watch:lib": "node ./build.ts --watch",
61
66
  "clean": "rm -rf ./dist",
62
67
  "test:all": "vitest run",
package/skill/SKILL.md CHANGED
@@ -19,7 +19,7 @@ This file is the router. It defines the concepts once; the references assume the
19
19
  ## Core concepts
20
20
 
21
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; pass `{ duplicates: 'error' }` to make a repeat a build error instead.
22
+ - **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list, or `createMutableRegistry(kind)` for registrations that arrive at runtime; both are read the same way. The last registration of a `$type` wins without a warning, which is how you replace a built-in; pass `{ duplicates: 'error' }` to make a repeat a build error instead.
23
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
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
25
 
@@ -34,14 +34,14 @@ Outcomes use one vocabulary: a check or a submission ends `passed`, `invalid` or
34
34
 
35
35
  ## Packages
36
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 |
37
+ | Package | Role |
38
+ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
39
+ | `@schema-engine/registry` | The registration contract and the registries every package builds on, `safeParseTree` and `exportTreeSchema` for a whole document, 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
45
 
46
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
47
 
@@ -1,6 +1,6 @@
1
1
  # @schema-engine/actions
2
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`).
3
+ The domain-agnostic action package: a registration, `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
4
 
5
5
  ## The flow
6
6
 
@@ -8,13 +8,8 @@ Serialized actions are checked, then dispatched: `parseActions(registry, input)`
8
8
 
9
9
  ```ts title="actions/dispatch.ts"
10
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';
11
+ import { createRegistry } from '@schema-engine/registry';
12
+ import { ActionDispatcher, defineAction, parseActions, type ActionConfigBase } from '@schema-engine/actions';
18
13
 
19
14
  type Trigger = 'save';
20
15
 
@@ -41,9 +36,9 @@ const notify = defineNotify<NotifyConfig>({
41
36
  },
42
37
  });
43
38
 
44
- export const registry = new ActionRegistry<Context, Trigger>([notify]);
39
+ export const registry = createRegistry('Action', [notify]);
45
40
 
46
- const dispatcher = new ActionDispatcher<Context, Trigger>(registry);
41
+ const dispatcher = new ActionDispatcher(registry);
47
42
 
48
43
  /** Parses a serialized sequence, then runs it for a trigger; the entry in brackets is a parallel group. */
49
44
  export async function run(input: unknown, sent: string[]) {
@@ -55,14 +50,16 @@ export async function run(input: unknown, sent: string[]) {
55
50
 
56
51
  ## An action
57
52
 
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.
53
+ 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? }`. The registry is the one of `@schema-engine/registry` (`registry.md`): `createRegistry('Action', [...])` from a list, or `createMutableRegistry<AnyActionRegistration<Context, Trigger>>('Action')` for actions that register at runtime (`AnyActionRegistration` is a registration of any config, so one registry holds actions of several configs). `parseActions` and `ActionDispatcher` take any lookup with `get($type)`, so `{ get, hint }` over a store of your own works too; its `hint` ends the message of an unregistered `$type`. The dispatcher infers its context and trigger types from the registrations. The package exports no registry of its own.
54
+
55
+ `ActionRegistration`, `ActionHandler` (the `execute` function), `ActionRuntimeContext` (what it receives) and `ActionExecutionResult` (what it returns) type those parts. When a handler throws, the dispatcher turns it into a failed result whose `cause` is the thrown error.
59
56
 
60
57
  ## parseActions
61
58
 
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']`); each entry is checked with `safeParseNode` of the registry, so an entry that is not an object is an issue at its own path, and one with no string `$type` or a `$type` no registration answers is an issue at `$type`.
59
+ `parseActions(registry, input, options?)` takes `input`, the sequence as it arrived, and `registry`, a registry of either kind or any lookup `{ get($type), hint? }`. `options.triggers` lists the trigger names an entry's `triggers` may hold (any string without it). The lookup's `hint` replaces `Register it in the action registry.`, the sentence that ends the message of an unregistered `$type`. It returns `{ success: true, data }` or `{ success: false, issues }`. 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']`); each entry is checked with `safeParseNode` of the registry, so an entry that is not an object is an issue at its own path, and one with no string `$type` or a `$type` no registration answers is an issue at `$type`. An issue the registry creates has a namespaced `code` (`registry/not-an-object`, `registry/missing-type`, `registry/unregistered-type` with `received`), so a caller can branch on it; the issues of the checks `parseActions` makes itself (`id`, `enabled`, `triggers`, an empty group) have none, and an issue from a schema is its library's own.
63
60
 
64
61
  ## Sequences, groups and cancellation
65
62
 
66
63
  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
64
 
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.
65
+ `dispatch({ actions, trigger, context, triggeredBy?, metadata?, signal? })` passes `triggeredBy` on to each handler and merges `metadata` over the context's own `metadata`. It 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.
@@ -1,115 +0,0 @@
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 {};