Built-in graph viz (app.graph/toMermaid/toDOT + opt-in GET /__graph__),
app.explain(route), one-line createApp({ overrides }), and a 'did you
mean' boot hint + flow compile-time type-test. All leverage the graph
being inspectable data — differentiators vs NestJS.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
10 files changed
+321
-6
No files matched your search
@@ -228,6 +228,47 @@ const app = createApp({ modules: [ApiModule], plugins: [logger] });
|
||||
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
|
||||
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
|
||||
|
||||
## Inspect & test the graph
|
||||
|
||||
### Visualize with Mermaid
|
||||
|
||||
```typescript
|
||||
console.log(app.toMermaid()); // flowchart diagram of all nodes and routes
|
||||
```
|
||||
|
||||
Enable a live `GET /__graph__` endpoint (renders HTML with Mermaid, or plain-text with `Accept: text/plain`):
|
||||
|
||||
```typescript
|
||||
const app = createApp({ modules: [ApiModule], devGraph: true });
|
||||
// GET /__graph__ → HTML viewer
|
||||
// GET /__graph__ (text/plain) → raw Mermaid source
|
||||
```
|
||||
|
||||
### Explain a route
|
||||
|
||||
```typescript
|
||||
const e = app.explain('/api/users/:id');
|
||||
// { pattern, method, transport, chain: [{ name, kind, origin, needs, provides }, ...] }
|
||||
console.log(e.chain.map((n) => `${n.kind}:${n.name}`));
|
||||
// → ['provider:db', 'step:user', 'handler:getUser']
|
||||
```
|
||||
|
||||
### Override tokens in tests
|
||||
|
||||
Swap any provider or step token with a test double at construction time — no monkey-patching:
|
||||
|
||||
```typescript
|
||||
const app = createApp({
|
||||
modules: [ApiModule],
|
||||
overrides: {
|
||||
db: { find: () => ({ id: 'test-user' }) }, // plain object — wrapped as { db: value }
|
||||
user: () => ({ user: { id: 'stub' } }), // function runner
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Overrides replace only the named token's runner; the rest of the graph is untouched.
|
||||
|
||||
## The one rule to remember
|
||||
|
||||
```
|
||||
|
||||
@@ -67,6 +67,8 @@ export const streamApp = createApp({ modules: [StreamModule] });
|
||||
|
||||
if (require.main === module) {
|
||||
console.log('chain for /api/users/:id ->', app.inspect('/api/users/:id'));
|
||||
console.log('graph:\n' + app.toMermaid());
|
||||
console.log('explain /api/users/:id:', app.explain('/api/users/:id'));
|
||||
app.listen(3000).then(() => console.log('green-tea on http://localhost:3000'));
|
||||
streamApp.listen(3001).then(() => console.log('green-tea streams on http://localhost:3001'));
|
||||
}
|
||||
|
||||
+64
-4
@@ -1,7 +1,8 @@
|
||||
import http from 'http';
|
||||
import { Bus } from './bus';
|
||||
import { Container } from './container';
|
||||
import { topoSort, subgraphFor, GraphNode } from './graph';
|
||||
import { topoSort, subgraphFor, GraphNode, nearest } from './graph';
|
||||
import { toMermaid, toDOT, graphHtml, type GraphView } from './graph-viz';
|
||||
import { runPipeline, PipelineStep } from './pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
|
||||
import { isAsyncIterable } from './channel';
|
||||
@@ -18,10 +19,16 @@ import type { MeshControl } from './http';
|
||||
import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
|
||||
|
||||
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
||||
export interface ExplainNode { name: string; kind: 'provider' | 'step' | 'handler'; origin: string; needs: string[]; provides: string[] }
|
||||
export interface Explain { pattern: string; method: HttpMethod; transport: Transport; chain: ExplainNode[] }
|
||||
export interface App {
|
||||
listen(port: number): Promise<http.Server>;
|
||||
close(): Promise<void>;
|
||||
inspect(routePath: string): InspectLine[];
|
||||
graph(): GraphView;
|
||||
toMermaid(): string;
|
||||
toDOT(): string;
|
||||
explain(routePath: string): Explain;
|
||||
bus: Bus;
|
||||
}
|
||||
|
||||
@@ -44,7 +51,7 @@ export interface MeshConfig {
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App {
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown> }): App {
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
let server: http.Server | undefined;
|
||||
@@ -146,7 +153,8 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
for (const plan of routePlans) {
|
||||
for (const need of plan.needs) {
|
||||
if (!allowed.has(need)) {
|
||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it`);
|
||||
const hint = nearest(need, allowed);
|
||||
throw new Error(`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,6 +173,35 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
];
|
||||
};
|
||||
|
||||
const graph = (): GraphView => {
|
||||
if (!booted) throw new Error('graph() unavailable before listen() for mesh apps');
|
||||
return {
|
||||
nodes: [
|
||||
...providerNodes.map((n) => ({ name: n.name, kind: 'provider' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
|
||||
...stepNodes.map((n) => ({ name: n.name, kind: 'step' as const, origin: n.origin, needs: n.needs, provides: n.provides })),
|
||||
],
|
||||
routes: routePlans.map((p) => ({
|
||||
pattern: p.pattern, method: p.method, transport: p.transport,
|
||||
chain: [...p.providers.map((n) => n.name), ...p.steps.map((n) => n.name), p.handlerName],
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
const explain = (routePath: string): Explain => {
|
||||
if (!booted) throw new Error('explain() unavailable before listen() for mesh apps');
|
||||
const plan = routePlans.find((p) => p.pattern === routePath);
|
||||
if (!plan) throw new Error(`no route: ${routePath}`);
|
||||
const nv = (n: GraphNode, kind: 'provider' | 'step'): ExplainNode => ({ name: n.name, kind, origin: n.origin, needs: n.needs, provides: n.provides });
|
||||
return {
|
||||
pattern: plan.pattern, method: plan.method, transport: plan.transport,
|
||||
chain: [
|
||||
...plan.providers.map((n) => nv(n, 'provider')),
|
||||
...plan.steps.map((n) => nv(n, 'step')),
|
||||
{ name: plan.handlerName, kind: 'handler', origin: plan.origin, needs: plan.needs, provides: [] },
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const providedSeed = async (plan: RoutePlan): Promise<Record<string, unknown>> => {
|
||||
const provided: Record<string, unknown> = {};
|
||||
for (const p of plan.providers) {
|
||||
@@ -212,6 +249,16 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
}
|
||||
}
|
||||
|
||||
// apply overrides: swap any provider/step runner by token in one line
|
||||
if (opts.overrides) {
|
||||
const produced = new Set([...providerNodes, ...stepNodes].flatMap((n) => n.provides));
|
||||
for (const [token, val] of Object.entries(opts.overrides)) {
|
||||
if (!produced.has(token)) throw new Error(`override for unknown token '${token}'`);
|
||||
const fn = typeof val === 'function' ? (val as (ctx: any) => any) : () => ({ [token]: val });
|
||||
runners.set(token, fn); // direct set (setRunner throws on dup); replaces the real runner
|
||||
}
|
||||
}
|
||||
|
||||
// run app-scoped providers in order (fail-fast for required)
|
||||
for (const node of orderedProviders) {
|
||||
bus.emit('boot:provider:start', { name: node.name, scope: node.origin });
|
||||
@@ -274,6 +321,19 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
...remoteRoutes,
|
||||
];
|
||||
|
||||
if (opts.devGraph) {
|
||||
httpRoutes.push({
|
||||
method: 'GET', pattern: '/__graph__', transport: 'buffer',
|
||||
handler: async (req) => {
|
||||
const mermaid = toMermaid(graph());
|
||||
const accept = String(req.headers['accept'] ?? '');
|
||||
return accept.includes('text/plain')
|
||||
? { status: 200, headers: { 'content-type': 'text/plain' }, body: mermaid }
|
||||
: { status: 200, headers: { 'content-type': 'text/html' }, body: graphHtml(mermaid) };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const wsRoutes: WsRouteDef[] = routePlans
|
||||
.filter((plan) => plan.transport === 'ws' || plan.transport === 'negotiate')
|
||||
.map((plan) => ({
|
||||
@@ -302,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
|
||||
});
|
||||
|
||||
return { listen, close, inspect, bus };
|
||||
return { listen, close, inspect, graph, toMermaid: () => toMermaid(graph()), toDOT: () => toDOT(graph()), explain, bus };
|
||||
}
|
||||
|
||||
async function snapshot(c: Container, needs: string[]): Promise<Record<string, unknown>> {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export interface GraphNodeView { name: string; kind: 'provider' | 'step'; origin: string; needs: string[]; provides: string[] }
|
||||
export interface GraphRouteView { pattern: string; method: string; transport: string; chain: string[] }
|
||||
export interface GraphView { nodes: GraphNodeView[]; routes: GraphRouteView[] }
|
||||
|
||||
const nid = (s: string) => 'n_' + s.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
const rid = (s: string) => 'r_' + s.replace(/[^a-zA-Z0-9]/g, '_');
|
||||
|
||||
export function toMermaid(view: GraphView): string {
|
||||
const known = new Set(view.nodes.map((n) => n.name));
|
||||
const out: string[] = ['flowchart LR'];
|
||||
for (const n of view.nodes) {
|
||||
out.push(n.kind === 'provider' ? ` ${nid(n.name)}(["${n.name}"])` : ` ${nid(n.name)}["${n.name}"]`);
|
||||
}
|
||||
for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` ${nid(need)} --> ${nid(n.name)}`);
|
||||
for (const r of view.routes) {
|
||||
out.push(` ${rid(r.pattern)}{{"${r.method} ${r.pattern}"}}`);
|
||||
for (const c of r.chain) if (known.has(c)) out.push(` ${nid(c)} --> ${rid(r.pattern)}`);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
export function toDOT(view: GraphView): string {
|
||||
const known = new Set(view.nodes.map((n) => n.name));
|
||||
const out: string[] = ['digraph green_tea {', ' rankdir=LR;'];
|
||||
for (const n of view.nodes) {
|
||||
out.push(` "${n.name}" [shape=${n.kind === 'provider' ? 'ellipse' : 'box'}];`);
|
||||
}
|
||||
for (const n of view.nodes) for (const need of n.needs) if (known.has(need)) out.push(` "${need}" -> "${n.name}";`);
|
||||
for (const r of view.routes) {
|
||||
const label = `${r.method} ${r.pattern}`;
|
||||
out.push(` "${label}" [shape=hexagon];`);
|
||||
for (const c of r.chain) if (known.has(c)) out.push(` "${c}" -> "${label}";`);
|
||||
}
|
||||
out.push('}');
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
export function graphHtml(mermaid: string): string {
|
||||
return [
|
||||
'<!doctype html><html><head><meta charset="utf-8"><title>green-tea graph</title>',
|
||||
'<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script></head>',
|
||||
'<body><pre class="mermaid">', mermaid, '</pre>',
|
||||
'<script>mermaid.initialize({ startOnLoad: true });</script></body></html>',
|
||||
].join('\n');
|
||||
}
|
||||
@@ -1,3 +1,21 @@
|
||||
function levenshtein(a: string, b: string): number {
|
||||
const m = a.length, n = b.length;
|
||||
const d: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
||||
for (let i = 0; i <= m; i++) d[i][0] = i;
|
||||
for (let j = 0; j <= n; j++) d[0][j] = j;
|
||||
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
|
||||
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
||||
}
|
||||
return d[m][n];
|
||||
}
|
||||
|
||||
export function nearest(token: string, candidates: Iterable<string>): string | undefined {
|
||||
let best: string | undefined;
|
||||
let bestD = 3; // only suggest edit distance <= 2
|
||||
for (const c of candidates) { const dist = levenshtein(token, c); if (dist < bestD) { bestD = dist; best = c; } }
|
||||
return best;
|
||||
}
|
||||
|
||||
export interface GraphNode {
|
||||
name: string;
|
||||
needs: string[];
|
||||
|
||||
+3
-1
@@ -2,7 +2,9 @@ import 'reflect-metadata';
|
||||
|
||||
export const VERSION = '0.0.0';
|
||||
export { createApp } from './app';
|
||||
export type { App, InspectLine } from './app';
|
||||
export type { App, InspectLine, Explain } from './app';
|
||||
export { toMermaid, toDOT } from './graph-viz';
|
||||
export type { GraphView } from './graph-viz';
|
||||
export { Provider, Step, Route, Get, Module, Transformer } from './metadata';
|
||||
export type { Plugin } from './plugin';
|
||||
export { JsonTransformer } from './transformers';
|
||||
|
||||
@@ -108,6 +108,13 @@ test('boot fails when a handler needs something nothing provides', () => {
|
||||
.toThrow(/handler 'list' needs 'missing'/);
|
||||
});
|
||||
|
||||
it('boot error for a misspelled @needs suggests the closest token', () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
|
||||
});
|
||||
|
||||
import { Sse, Ws } from '../src/metadata';
|
||||
import { inbound } from '../src/params';
|
||||
import { channel } from '../src/channel';
|
||||
@@ -209,6 +216,61 @@ describe('per-route subgraph slicing', () => {
|
||||
});
|
||||
});
|
||||
|
||||
import { toMermaid as renderMermaid } from '../src/graph-viz';
|
||||
|
||||
describe('app.graph / explain', () => {
|
||||
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
|
||||
@Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const g = app.graph();
|
||||
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
|
||||
expect(g.nodes.find((n) => n.name === 'user')).toMatchObject({ kind: 'step', needs: ['db'] });
|
||||
const route = g.routes.find((r) => r.pattern === '/api/u/:id')!;
|
||||
expect(route.chain).toEqual(['db', 'user', 'get']);
|
||||
expect(app.toMermaid()).toContain('flowchart');
|
||||
});
|
||||
|
||||
it('explain() returns the rich chain with origin and a handler entry', async () => {
|
||||
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
|
||||
@Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
|
||||
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const e = app.explain('/api/u/me');
|
||||
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
|
||||
expect(e.chain.map((c) => `${c.kind}:${c.name}`)).toEqual(['step:user', 'handler:me']);
|
||||
expect(e.chain[0]).toMatchObject({ origin: 'module:M', provides: ['user'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('devGraph endpoint', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('serves /__graph__ as HTML when devGraph:true', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M], devGraph: true });
|
||||
const s = await app.listen(0);
|
||||
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
|
||||
expect(html).toContain('class="mermaid"');
|
||||
expect(html).toContain('flowchart');
|
||||
const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } });
|
||||
expect(mmd.headers.get('content-type')).toContain('text/plain');
|
||||
expect(await mmd.text()).toContain('flowchart');
|
||||
s.close();
|
||||
});
|
||||
it('does NOT mount /__graph__ without devGraph', async () => {
|
||||
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
const s = await app.listen(0);
|
||||
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
|
||||
expect(res.status).toBe(404);
|
||||
s.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('graceful shutdown', () => {
|
||||
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
|
||||
@Route('/')
|
||||
@@ -227,3 +289,31 @@ describe('graceful shutdown', () => {
|
||||
reader.cancel().catch(() => {});
|
||||
});
|
||||
});
|
||||
|
||||
describe('overrides', () => {
|
||||
const portOf = (s: any) => (s.address() as any).port;
|
||||
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
|
||||
s.close();
|
||||
});
|
||||
it('overrides with a function runner', async () => {
|
||||
@Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
|
||||
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
|
||||
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
|
||||
const s = await app.listen(0);
|
||||
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
|
||||
s.close();
|
||||
});
|
||||
it('rejects an override for an unknown token', async () => {
|
||||
@Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
|
||||
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
|
||||
const app = createApp({ modules: [M], overrides: { nope: 1 } });
|
||||
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { toMermaid, toDOT, graphHtml, type GraphView } from '../src/graph-viz';
|
||||
|
||||
const view: GraphView = {
|
||||
nodes: [
|
||||
{ name: 'db', kind: 'provider', origin: 'module:M', needs: ['config'], provides: ['db'] },
|
||||
{ name: 'config', kind: 'provider', origin: 'module:M', needs: [], provides: ['config'] },
|
||||
{ name: 'user', kind: 'step', origin: 'module:M', needs: ['db', 'req'], provides: ['user'] },
|
||||
],
|
||||
routes: [{ pattern: '/users/:id', method: 'GET', transport: 'buffer', chain: ['config', 'db', 'user', 'getUser'] }],
|
||||
};
|
||||
|
||||
describe('toMermaid', () => {
|
||||
it('declares nodes and draws needs edges between known nodes', () => {
|
||||
const m = toMermaid(view);
|
||||
expect(m).toContain('flowchart');
|
||||
expect(m).toContain('"db"');
|
||||
expect(m).toContain('"user"');
|
||||
expect(m).toContain('n_config --> n_db'); // db needs config
|
||||
expect(m).toContain('n_db --> n_user'); // user needs db
|
||||
expect(m).not.toContain('n_req'); // 'req' is a seed (no node) -> no edge
|
||||
expect(m).toContain('GET /users/:id'); // route node label
|
||||
});
|
||||
});
|
||||
|
||||
describe('toDOT', () => {
|
||||
it('emits a digraph with nodes and edges', () => {
|
||||
const d = toDOT(view);
|
||||
expect(d).toContain('digraph');
|
||||
expect(d).toContain('"config" -> "db"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('graphHtml', () => {
|
||||
it('wraps mermaid source in an HTML page that loads mermaid', () => {
|
||||
const html = graphHtml('flowchart LR\n a-->b');
|
||||
expect(html).toContain('<pre class="mermaid">');
|
||||
expect(html).toContain('flowchart LR');
|
||||
expect(html).toContain('mermaid');
|
||||
});
|
||||
});
|
||||
+11
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, test } from 'vitest';
|
||||
import { topoSort, GraphNode, subgraphFor } from '../src/graph';
|
||||
import { topoSort, GraphNode, subgraphFor, nearest } from '../src/graph';
|
||||
|
||||
const node = (name: string, needs: string[], provides: string[]): GraphNode =>
|
||||
({ name, needs, provides, origin: 'test' });
|
||||
@@ -41,3 +41,13 @@ describe('subgraphFor', () => {
|
||||
expect(subgraphFor(['user'], ordered).map((n) => n.name)).not.toContain('audit');
|
||||
});
|
||||
});
|
||||
|
||||
describe('nearest', () => {
|
||||
it('suggests a close candidate (edit distance <= 2)', () => {
|
||||
expect(nearest('usr', ['user', 'config', 'db'])).toBe('user');
|
||||
expect(nearest('confgi', ['user', 'config'])).toBe('config');
|
||||
});
|
||||
it('returns undefined when nothing is close', () => {
|
||||
expect(nearest('zzzzzz', ['user', 'db'])).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -12,5 +12,11 @@ test('type guarantee holds (this file must typecheck)', () => {
|
||||
// @ts-expect-error — `user` is not in the accumulated context
|
||||
.handle((ctx) => ctx.user);
|
||||
|
||||
// GUARANTEE: a step can only read tokens produced by PRIOR steps.
|
||||
flow<{ req: { token: string } }>()
|
||||
.step('user', (ctx) => ({ user: ctx.req.token })) // produces `user`
|
||||
// @ts-expect-error — `db` was never produced by a prior step (only `user` was)
|
||||
.step('next', (ctx) => ({ next: ctx.db }));
|
||||
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
Reference in new issue
Block a user