export type StepFn = (ctx: In) => Out | Promise; export interface CompiledFlow { steps: { name: string; fn: StepFn }[]; handler: (ctx: Acc) => unknown; run(seed: Seed): Promise; } export class Flow { constructor(private readonly steps: { name: string; fn: StepFn }[] = []) {} step(name: string, fn: StepFn): Flow { return new Flow([...this.steps, { name, fn }]); } handle(handler: (ctx: Acc) => unknown): CompiledFlow { const steps = this.steps; return { steps, handler, async run(seed: Seed): Promise { let ctx: any = { ...seed }; for (const s of steps) { const out = await s.fn(ctx); ctx = { ...ctx, ...out }; } return handler(ctx); }, }; } } export function flow(): Flow { return new Flow(); }