feat: dependency graph topological sort with cycle/missing-dep validation
This commit is contained in:
2 files changed
+64
No files matched your search
@@ -0,0 +1,39 @@
|
||||
export interface GraphNode {
|
||||
name: string;
|
||||
needs: string[];
|
||||
provides: string[];
|
||||
origin: string;
|
||||
}
|
||||
|
||||
export function topoSort(nodes: GraphNode[], seedKeys: string[]): GraphNode[] {
|
||||
const producedBy = new Map<string, GraphNode>();
|
||||
for (const n of nodes) for (const key of n.provides) producedBy.set(key, n);
|
||||
|
||||
// validate dependencies exist
|
||||
for (const n of nodes) {
|
||||
for (const key of n.needs) {
|
||||
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
||||
throw new Error(`missing dependency: ${key} needed by ${n.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ordered: GraphNode[] = [];
|
||||
const state = new Map<GraphNode, 'visiting' | 'done'>();
|
||||
|
||||
const visit = (n: GraphNode, trail: string[]): void => {
|
||||
const s = state.get(n);
|
||||
if (s === 'done') return;
|
||||
if (s === 'visiting') throw new Error(`cycle detected: ${[...trail, n.name].join(' -> ')}`);
|
||||
state.set(n, 'visiting');
|
||||
for (const key of n.needs) {
|
||||
const dep = producedBy.get(key);
|
||||
if (dep && dep !== n) visit(dep, [...trail, n.name]);
|
||||
}
|
||||
state.set(n, 'done');
|
||||
ordered.push(n);
|
||||
};
|
||||
|
||||
for (const n of nodes) visit(n, []);
|
||||
return ordered;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { topoSort, GraphNode } from '../src/graph';
|
||||
|
||||
const node = (name: string, needs: string[], provides: string[]): GraphNode =>
|
||||
({ name, needs, provides, origin: 'test' });
|
||||
|
||||
test('orders nodes so dependencies come first (regardless of input order)', () => {
|
||||
const nodes = [
|
||||
node('handler', ['user'], []),
|
||||
node('auth', ['db'], ['user']),
|
||||
node('db', ['config'], ['db']),
|
||||
];
|
||||
const ordered = topoSort(nodes, ['config']).map((n) => n.name);
|
||||
expect(ordered).toEqual(['db', 'auth', 'handler']);
|
||||
});
|
||||
|
||||
test('throws on missing dependency', () => {
|
||||
const nodes = [node('handler', ['user'], [])];
|
||||
expect(() => topoSort(nodes, [])).toThrow(/missing dependency: user needed by handler/);
|
||||
});
|
||||
|
||||
test('throws on cycle', () => {
|
||||
const nodes = [node('a', ['b'], ['a']), node('b', ['a'], ['b'])];
|
||||
expect(() => topoSort(nodes, [])).toThrow(/cycle detected/);
|
||||
});
|
||||
Reference in new issue
Block a user