feat: typed flow core with compile-time context guarantee

This commit is contained in:
chrnx committed 2026-06-26 00:35:44 -05:00
1 parent 96880d055b
commit 11fc746d28
3 files changed
+70

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
export type StepFn<In, Out> = (ctx: In) => Out | Promise<Out>;
export interface CompiledFlow<Seed, Acc> {
steps: { name: string; fn: StepFn<any, any> }[];
handler: (ctx: Acc) => unknown;
run(seed: Seed): Promise<unknown>;
}
export class Flow<Seed, Acc> {
constructor(private readonly steps: { name: string; fn: StepFn<any, any> }[] = []) {}
step<Out>(name: string, fn: StepFn<Acc, Out>): Flow<Seed, Acc & Out> {
return new Flow<Seed, Acc & Out>([...this.steps, { name, fn }]);
}
handle(handler: (ctx: Acc) => unknown): CompiledFlow<Seed, Acc> {
const steps = this.steps;
return {
steps,
handler,
async run(seed: Seed): Promise<unknown> {
let ctx: any = { ...seed };
for (const s of steps) {
const out = await s.fn(ctx);
ctx = { ...ctx, ...out };
}
return handler(ctx);
},
};
}
}
export function flow<Seed extends object>(): Flow<Seed, Seed> {
return new Flow<Seed, Seed>();
}
+19
View File
@@ -0,0 +1,19 @@
import { expect, test } from 'vitest';
import { flow } from '../src/flow';
test('flow accumulates context and runs steps in order', async () => {
const compiled = flow<{ req: { token: string } }>()
.step('auth', (ctx) => ({ user: { id: ctx.req.token } }))
.step('load', (ctx) => ({ greeting: `hi ${ctx.user.id}` }))
.handle((ctx) => ctx.greeting);
const result = await compiled.run({ req: { token: 'abc' } });
expect(result).toBe('hi abc');
});
test('async steps are awaited and accumulate', async () => {
const compiled = flow<{ n: number }>()
.step('double', async (ctx) => ({ doubled: ctx.n * 2 }))
.handle((ctx) => ctx.doubled);
expect(await compiled.run({ n: 21 })).toBe(42);
});
+16
View File
@@ -0,0 +1,16 @@
import { test, expect } from 'vitest';
import { flow } from '../../src/flow';
test('type guarantee holds (this file must typecheck)', () => {
// OK: handler reads `user`, produced by the auth step.
flow<{ req: { token: string } }>()
.step('auth', (ctx) => ({ user: ctx.req.token }))
.handle((ctx) => ctx.user);
// GUARANTEE: remove the auth step and reading `user` must NOT compile.
flow<{ req: { token: string } }>()
// @ts-expect-error — `user` is not in the accumulated context
.handle((ctx) => ctx.user);
expect(true).toBe(true);
});