Files
feuerwerk/tests/core/graph.test.ts
T
rootandClaude Opus 5 d54a620ebd Add ESLint and Prettier, and close the node test gaps
Tooling:
- Prettier as the single formatting authority (110 columns, single quotes,
  measured against the existing style); Markdown excluded because table-cell
  padding turns the README glossary into 1000-character lines.
- Type-aware ESLint ending in eslint-config-prettier, so a rule always means
  "this is a bug", never "this looks different".
- .editorconfig and an `npm run check` that runs typecheck, lint, format and
  tests in one go.

Findings fixed on the first run: three more duplicate imports, four
String(unknown) calls (parameter types narrowed instead of casts), two dead
initialisers, two redundant casts, a console.log for a real error. Two
warnings were false here and are disabled with a reason in place.

Tests 132 -> 269:
- node-catalog.test.ts covers every node with a run(), with a guard that fails
  when a new node has no row.
- behavior-events.test.ts covers the ten event nodes through a running World,
  checking timing rather than existence.
- Input's state machine (press/release/releaseAll) is reachable without DOM
  events now; the DOM handlers are thin adapters.

Compare fell back to == without a configured operator although the schema
default is <; aligned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 10:02:22 +02:00

355 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, it } from 'vitest';
import { CommandError } from '../../src/core/commands/Command';
import {
AddNodeCommand,
DisconnectCommand,
RemoveNodeCommand,
SetNodeParamCommand,
} from '../../src/core/commands/graphCommands';
import {
AddVariableCommand,
RemoveVariableCommand,
RenameVariableCommand,
} from '../../src/core/commands/variableCommands';
import { GraphInterpreter, allNodeDefs, findNode, portsCompatible } from '../../src/core/graph';
import type { BehaviorAsset } from '../../src/core/model/Asset';
import { findAsset } from '../../src/core/model/Project';
import { deserializeProject, serializeProject } from '../../src/core/store/serialize';
import {
type ProjectFixture,
fakeContext,
graphEditor,
makeBehavior,
makeProject,
makeSpriteScene,
place,
roundTrip,
} from '../helpers';
/** Adds "On key held(ArrowRight) → Move(owner, dx = speed × dt)" to a project, built through commands like the editor would. */
function withMover<F extends ProjectFixture>(fixture: F) {
const behavior = makeBehavior(fixture, 'Mover', ['speed']);
const edit = graphEditor(fixture, behavior);
const held = edit.addNode('OnKeyHeld', { key: 'ArrowRight' });
const owner = edit.addNode('Owner');
const speed = edit.addNode('GetVariable', { variable: 'speed' });
const mul = edit.addNode('Multiply');
const move = edit.addNode('Move');
edit.wire([
[held, 'exec', move, 'exec'],
[owner, 'object', move, 'object'],
[speed, 'value', mul, 'a'],
[held, 'dt', mul, 'b'],
[mul, 'result', move, 'dx'],
]);
return { ...fixture, behavior, edit, nodes: { held, owner, speed, mul, move } };
}
/** A behavior "B" with the given number variables and an empty graph to edit. */
function emptyBehavior(variables: string[] = []) {
const fixture = makeProject();
const behavior = makeBehavior(fixture, 'B', variables);
return { ...fixture, behavior, edit: graphEditor(fixture, behavior) };
}
describe('node registry', () => {
it('registers the built-in node set with well-formed ports', () => {
const defs = allNodeDefs();
expect(defs.length).toBeGreaterThan(20);
for (const def of defs) {
const keys = [...def.inputs, ...def.outputs].map((p) => p.key);
expect(new Set(def.inputs.map((p) => p.key)).size).toBe(def.inputs.length);
expect(new Set(def.outputs.map((p) => p.key)).size).toBe(def.outputs.length);
if (def.category === 'event') expect(def.inputs).toHaveLength(0);
else expect(def.run).toBeTypeOf('function');
expect(keys.every((k) => k.length > 0)).toBe(true);
}
});
it('type-checks port connections', () => {
expect(portsCompatible('exec', 'exec')).toBe(true);
expect(portsCompatible('exec', 'number')).toBe(false);
expect(portsCompatible('number', 'any')).toBe(true);
expect(portsCompatible('any', 'boolean')).toBe(true);
expect(portsCompatible('number', 'boolean')).toBe(false);
expect(portsCompatible('object', 'object')).toBe(true);
});
});
describe('GraphInterpreter', () => {
it('runs an event pulse and pulls data lazily (speed × dt moves the owner)', () => {
const { behavior } = withMover(makeProject());
const interpreter = new GraphInterpreter(behavior.graph);
const ctx = fakeContext({ variables: { speed: 100 } });
const fired = interpreter.fire('OnKeyHeld', ctx, { dt: 0.5 }, (n) => n.params.key === 'ArrowRight');
expect(fired).toBe(1);
expect(ctx.owner!.x).toBe(50);
expect(interpreter.fire('OnKeyHeld', ctx, { dt: 0.5 }, (n) => n.params.key === 'ArrowLeft')).toBe(0);
expect(ctx.owner!.x).toBe(50);
});
it('uses inline values for unconnected inputs', () => {
const { behavior, edit } = emptyBehavior();
const start = edit.addNode('OnStart');
const self = edit.addNode('Self');
const move = edit.addNode('Move', { dx: 7, dy: -3 });
edit.wire([
[start, 'exec', move, 'exec'],
[self, 'object', move, 'object'],
]);
const ctx = fakeContext();
new GraphInterpreter(behavior.graph).fire('OnStart', ctx);
expect(ctx.self.x).toBe(7);
expect(ctx.self.y).toBe(-3);
});
it('uses port defaults for unconnected inputs (Move scale = 1, Clamp 0…1)', () => {
const { behavior, edit } = emptyBehavior();
const start = edit.addNode('OnStart');
const self = edit.addNode('Self');
const clamp = edit.addNode('Clamp', { value: 5 });
const move = edit.addNode('Move', { dx: 4 });
edit.wire([
[start, 'exec', move, 'exec'],
[self, 'object', move, 'object'],
[clamp, 'result', move, 'dy'],
]);
const ctx = fakeContext();
new GraphInterpreter(behavior.graph).fire('OnStart', ctx);
expect(ctx.self.x).toBe(4); // scale defaulted to 1, not 0
expect(ctx.self.y).toBe(1); // clamp(5, 0, 1)
});
it('five-node mover: Axis input → Move(dt from On update) moves speed × dt, diagonals normalized', () => {
const { behavior, edit } = emptyBehavior(['speed']);
const update = edit.addNode('OnUpdate');
const owner = edit.addNode('Owner');
const axis = edit.addNode('AxisInput');
const speed = edit.addNode('GetVariable', { variable: 'speed' });
const move = edit.addNode('Move');
edit.wire([
[update, 'exec', move, 'exec'],
[update, 'dt', move, 'dt'],
[owner, 'object', move, 'object'],
[axis, 'x', move, 'dx'],
[axis, 'y', move, 'dy'],
[speed, 'value', move, 'scale'],
]);
expect(behavior.graph.nodes).toHaveLength(5);
const interpreter = new GraphInterpreter(behavior.graph);
const run = (keys: string[]) => {
const ctx = fakeContext({ variables: { speed: 100 }, dt: 0.5, isKeyDown: (k) => keys.includes(k) });
interpreter.fire('OnUpdate', ctx, { dt: 0.5 });
return { x: ctx.owner!.x, y: ctx.owner!.y };
};
expect(run([])).toEqual({ x: 0, y: 0 });
expect(run(['ArrowRight'])).toEqual({ x: 50, y: 0 });
expect(run(['ArrowLeft'])).toEqual({ x: -50, y: 0 });
expect(run(['ArrowUp'])).toEqual({ x: 0, y: -50 });
const diagonal = run(['ArrowLeft', 'ArrowUp']);
expect(Math.hypot(diagonal.x, diagonal.y)).toBeCloseTo(50, 6); // same distance as a straight move
expect(diagonal.x).toBeCloseTo(-50 / Math.SQRT2, 6);
expect(diagonal.y).toBeCloseTo(-50 / Math.SQRT2, 6);
expect(run(['ArrowLeft', 'ArrowRight'])).toEqual({ x: 0, y: 0 }); // opposite keys cancel
});
it('vector and math helpers', () => {
const { behavior, edit } = emptyBehavior();
const start = edit.addNode('OnStart');
const sources = [
edit.addNode('Normalize', { x: 3, y: 4 }),
edit.addNode('Length', { x: 3, y: 4 }),
edit.addNode('Sqrt', { value: 16 }),
edit.addNode('Abs', { value: -2 }),
edit.addNode('Min', { a: 3, b: -1 }),
edit.addNode('Max', { a: 3, b: -1 }),
];
const ports = ['x', 'result', 'result', 'result', 'result', 'result'];
// One Log per source, chained after On start.
let previous = start;
sources.forEach((source, i) => {
const log = edit.addNode('Log');
edit.wire([
[previous, 'exec', log, 'exec'],
[source, ports[i]!, log, 'message'],
]);
previous = log;
});
const ctx = fakeContext();
new GraphInterpreter(behavior.graph).fire('OnStart', ctx);
expect(ctx.logs).toEqual(['0.6', '5', '4', '2', '-1', '3']);
});
it('follows Branch, writes variables and logs', () => {
const { behavior, edit } = emptyBehavior(['count']);
const start = edit.addNode('OnStart');
const get = edit.addNode('GetVariable', { variable: 'count' });
const cmp = edit.addNode('Compare', { op: '<', b: 3 });
const branch = edit.addNode('Branch');
const add = edit.addNode('Add', { b: 1 });
const set = edit.addNode('SetVariable', { variable: 'count' });
const logThen = edit.addNode('Log', { message: 'then' });
const logElse = edit.addNode('Log', { message: 'else' });
edit.wire([
[start, 'exec', branch, 'exec'],
[get, 'value', cmp, 'a'],
[cmp, 'result', branch, 'condition'],
[branch, 'then', set, 'exec'],
[get, 'value', add, 'a'],
[add, 'result', set, 'value'],
[set, 'exec', logThen, 'exec'],
[branch, 'else', logElse, 'exec'],
]);
const interpreter = new GraphInterpreter(behavior.graph);
const ctx = fakeContext({ variables: { count: 0 } });
for (let i = 0; i < 5; i++) interpreter.fire('OnStart', ctx);
expect(ctx.variables.count).toBe(3);
expect(ctx.logs).toEqual(['then', 'then', 'then', 'else', 'else']);
});
it('reports traversed edges and nodes to the trace listener', () => {
const { behavior, nodes } = withMover(makeProject());
const interpreter = new GraphInterpreter(behavior.graph);
const edges: string[] = [];
const visited: string[] = [];
interpreter.trace = { onEdge: (id) => edges.push(id), onNode: (id) => visited.push(id) };
interpreter.fire('OnKeyHeld', fakeContext(), { dt: 1 });
expect(edges).toHaveLength(1);
expect(visited).toContain(nodes.mul.id);
expect(visited).toContain(nodes.move.id);
});
it('stops a runaway flow instead of hanging', () => {
const { behavior, edit } = emptyBehavior();
const start = edit.addNode('OnStart');
const a = edit.addNode('Sequence');
const b = edit.addNode('Sequence');
edit.wire([
[start, 'exec', a, 'exec'],
[a, 'a', b, 'exec'],
[b, 'a', a, 'exec'],
]);
expect(() => new GraphInterpreter(behavior.graph).fire('OnStart', fakeContext())).toThrow(/step limit/);
});
});
describe('graph commands', () => {
it('rejects incompatible, self and duplicate connections', () => {
const {
edit,
nodes: { held, mul, move },
} = withMover(makeProject());
expect(() => edit.connect(held, 'exec', mul, 'a')).toThrow(/Cannot connect/);
expect(() => edit.connect(mul, 'result', mul, 'a')).toThrow(/itself/);
expect(() => edit.connect(held, 'exec', move, 'exec')).toThrow(/Already/);
expect(() => edit.connect(held, 'nope', move, 'exec')).toThrow(/Port/);
});
it('replaces the edge of a data input and restores it on undo', () => {
const { behavior, stack, edit, nodes } = withMover(makeProject());
const literal = edit.addNode('Number', { value: 9 });
const before = behavior.graph.edges.length;
edit.connect(literal, 'value', nodes.move, 'dx');
expect(behavior.graph.edges.length).toBe(before); // one replaced, one added
const sourceOfDx = () =>
behavior.graph.edges.find((e) => e.to.node === nodes.move.id && e.to.port === 'dx')!.from.node;
expect(sourceOfDx()).toBe(literal.id);
stack.undo();
expect(sourceOfDx()).toBe(nodes.mul.id);
});
it('removing a node drops its edges; undo restores both', () => {
const { behavior, stack, nodes } = withMover(makeProject());
const edgesBefore = behavior.graph.edges.length;
stack.execute(new RemoveNodeCommand(behavior.id, nodes.mul.id));
expect(findNode(behavior.graph, nodes.mul.id)).toBeUndefined();
expect(behavior.graph.edges.length).toBe(edgesBefore - 3);
stack.undo();
expect(findNode(behavior.graph, nodes.mul.id)).toBeDefined();
expect(behavior.graph.edges.length).toBe(edgesBefore);
stack.execute(new DisconnectCommand(behavior.id, behavior.graph.edges[0]!.id));
expect(behavior.graph.edges.length).toBe(edgesBefore - 1);
stack.undo();
expect(behavior.graph.edges.length).toBe(edgesBefore);
});
it('coerces declared params and keeps inline input values', () => {
const { behavior, stack, nodes } = withMover(makeProject());
stack.execute(new SetNodeParamCommand(behavior.id, nodes.held.id, 'key', 'ArrowLeft'));
stack.execute(new SetNodeParamCommand(behavior.id, nodes.move.id, 'dy', 4));
const held = findNode(behavior.graph, nodes.held.id)!;
const move = findNode(behavior.graph, nodes.move.id)!;
expect(held.params.key).toBe('ArrowLeft');
expect(move.params.dy).toBe(4);
stack.undo();
expect(move.params.dy).toBeUndefined();
});
});
describe('variable commands', () => {
it('adds, renames (including graph references and overrides) and removes variables', () => {
const f = withMover(makeSpriteScene());
const { behavior, stack, nodes, object } = f;
const logic = place(f, behavior.id, { x: 0, y: 0 });
object(logic).overrides.speed = 5;
stack.execute(new RenameVariableCommand(behavior.id, 'speed', 'velocity'));
expect(behavior.variables[0]!.key).toBe('velocity');
expect(behavior.props).toEqual({ enabled: true, velocity: 0 });
expect(object(logic).overrides).toEqual({ velocity: 5 });
expect(findNode(behavior.graph, nodes.speed.id)!.params.variable).toBe('velocity');
stack.undo();
expect(behavior.variables[0]!.key).toBe('speed');
expect(object(logic).overrides).toEqual({ speed: 5 });
expect(() => stack.execute(new AddVariableCommand(behavior.id, 'speed', 'number'))).toThrow(/already/);
expect(() => stack.execute(new AddVariableCommand(behavior.id, '1bad', 'number'))).toThrow(/names/);
stack.execute(new RemoveVariableCommand(behavior.id, 'speed'));
expect(behavior.variables).toHaveLength(0);
expect(object(logic).overrides).toEqual({});
stack.undo();
expect(behavior.variables).toHaveLength(1);
expect(object(logic).overrides).toEqual({ speed: 5 });
});
});
describe('behavior serialization', () => {
it('round-trips variables and graph, dropping unknown node types and dangling edges', () => {
const { project, behavior } = withMover(makeProject());
const loaded = findAsset(roundTrip(project), behavior.id) as BehaviorAsset;
expect(loaded.variables).toEqual(behavior.variables);
expect(loaded.graph).toEqual(behavior.graph);
expect(loaded.props).toEqual({ enabled: true, speed: 0 });
const raw = serializeProject(project) as {
assets: { id: string; graph?: { nodes: unknown[]; edges: unknown[] } }[];
};
const rawGraph = raw.assets.find((a) => a.id === behavior.id)!.graph!;
rawGraph.nodes.push({ id: 'zzz', type: 'DoesNotExist', x: 0, y: 0, params: {} });
rawGraph.edges.push({
id: 'e-bad',
from: { node: 'zzz', port: 'exec' },
to: { node: behavior.graph.nodes[0]!.id, port: 'exec' },
});
const cleaned = findAsset(deserializeProject(raw), behavior.id) as BehaviorAsset;
expect(cleaned.graph.nodes.length).toBe(behavior.graph.nodes.length);
expect(cleaned.graph.edges.length).toBe(behavior.graph.edges.length);
});
});
describe('unknown node types', () => {
it('are rejected as a CommandError by execute, not thrown from the constructor', () => {
const fixture = makeProject();
const behavior = makeBehavior(fixture, 'B');
// Building the command must not throw: callers construct it outside the editor's
// error handling (`state.execute(new AddNodeCommand(…))`), so a throw here would crash.
const command = new AddNodeCommand(behavior.id, 'DoesNotExist', 0, 0);
expect(command.label).toBe('Add DoesNotExist');
expect(() => command.execute(fixture.project)).toThrow(CommandError);
expect(behavior.graph.nodes).toHaveLength(0);
});
});