@lsde/dialog-engine
v2.1.0
Published
Callback-driven dialogue graph engine — load LSDE blueprints and dispatch dialog, choice, condition and action blocks to handler callbacks
Maintainers
Readme

LSDE Dialog Engine — TypeScript
Reference implementation of the LSDE callback-driven dialogue graph dispatcher.
This is the source of truth. All other runtimes (C#, C++, GDScript) are ports validated against the same cross-language test suite. If there is any ambiguity in the specification, the TypeScript behavior is authoritative.
Quick Start
npm install
npm run buildimport { DialogueEngine, LsdeUtils } from '@lsde/dialog-engine';
const engine = new DialogueEngine();
// init() reports what is wrong with the payload instead of half-loading it.
const report = engine.init({ data: blueprintJson });
if (report.errors.length) throw new Error(report.errors[0].message);
engine.setLocale('en');
// Which actor of a block is the one speaking. Optional — the default takes the first.
// LSDE deliberately refuses to say what the order of `actors` means; that call is yours.
engine.onResolveCharacter((actors) => actors[0]);
// The single game-state evaluator: it tags option visibility AND pre-evaluates condition cases.
// A test on the reserved `choice` dictionary never reaches it — the engine answers those from
// the choice history it kept during the scene.
engine.onResolveCondition(({ dict, entry, op, value }) => {
return gameState.evaluate(dict, entry, op, value);
});
// ─── 3 Required Handlers (onCondition is optional with onResolveCondition) ──
engine.onDialog(({ block, context, next }) => {
const text = LsdeUtils.getLocalizedText(block.text);
console.log(`${context.character?.name}: ${text ?? '—'}`);
next();
return () => { /* cleanup when leaving this block */ };
});
engine.onChoice(({ context, next }) => {
// EVERY option is handed over, tagged - never a shortened list. Filter on `visible !== false`:
// with no resolver installed `visible` is undefined, meaning UNKNOWN, not hidden.
const offered = context.options.filter((o) => o.visible !== false);
// The option id IS its exit port (C1, C2...), so hand it straight back.
context.selectChoice(offered[0].id);
next();
});
// onCondition is OPTIONAL: with onResolveCondition installed the engine already knows which port
// the cases picked. Keep it to log what matched, or to override with a PORT NAME.
engine.onCondition(({ block, context, next }) => {
const matched = context.cases.find((c) => c.result);
console.log(`${block.id} -> ${matched?.port ?? 'default'}`);
next();
});
engine.onAction(({ block, context, next }) => {
for (const call of block.calls ?? []) {
console.log(`Call: ${call.fn}`, call.args);
}
context.resolve(); // or context.reject() to leave by `catch`
next();
});
// ─── Run ─────────────────────────────────────────────────────────
// A path (`reactor_breach`) or the stable id (`sc_u0vqg2g8`). Store the ID anywhere outside the
// payload - a save file, a Unity asset - because a path stops resolving the day someone renames it.
const handle = engine.scene('reactor_breach');
handle.start();Scripts
| Command | Description |
|---------|-------------|
| npm run build | Compile TypeScript |
| npm run test | Run the full suite (vitest) |
| npm run lint | Type-check |
| npm run playground | Run interactive playground against a real blueprint |
| npm run docs | Generate API docs (TypeDoc + VitePress) |
Architecture
src/
├── index.ts # Public barrel export — what a game imports
├── engine.ts # Public facade — init, handlers, scene()
├── track.ts # THE traversal, written once. The main flow is a track, id 0
├── scene-handle.ts # The scene: public API, and what its tracks share
├── handler-registry.ts # Two-tier handler resolution
├── port-resolver.ts # Output port routing (critical algorithm)
├── block-context.ts # Context factories per block type
├── condition-evaluator.ts # AND/OR chain evaluation
├── graph.ts # Scene + Blueprint indexing
├── validator.ts # Blueprint validation + diagnostics
├── types.ts # The engine's own types
├── blueprint-types.ts # The payload contract, generated by LSDE - never edited by hand
├── lsde-utils.ts # Localization, condition helpers, type guards
└── utils.ts # Internal utilitiesAPI Overview
Engine Lifecycle
| Method | Description |
|--------|-------------|
| engine.init({ data }) | Validate blueprint, build graph. Returns DiagnosticReport — errors refuse the payload. Warnings also cover what the blocks use that the export does not declare: a function, argument, dictionary, entry or choice test (UNDECLARED_*, UNKNOWN_CHOICE_*, EMPTY_FUNCTION), no check needed. |
| engine.setLocale(locale) | Set active locale for text resolution. |
| engine.scene(sceneRef) | Create a scene handle (does not start). |
| engine.stop() | Cancel every running scene, even if a cleanup throws. |
| engine.isRunning() | True if at least one scene is active. |
| engine.getActiveScenes() | Get all running scene handles. |
| engine.getCurrentBlocks() | Get current block of every active scene. |
| engine.getSceneConnections(sceneRef) | Every wire INSIDE a scene, flattened. Graph inspection; wires never cross a scene. |
Handler Registration (Tier 1 — Global)
All 4 type handlers are required — the engine will throw if a scene starts without them.
| Method | Description |
|--------|-------------|
| engine.onDialog(handler) | Handle DIALOG blocks. |
| engine.onChoice(handler) | Handle CHOICE blocks (choices tagged with visible when onResolveCondition is set). |
| engine.onCondition(handler) | Handle CONDITION blocks. Optional when onResolveCondition is installed. |
| engine.onAction(handler) | Handle ACTION blocks. Developer must call context.resolve() or context.reject(). |
A ROUTER block has no handler and needs none: the engine evaluates every case, launches the port of each true one and continues by then (all held) or catch (one did not) on its own. To observe one, use handle.onBlock(id) — its RouterContext carries the pre-evaluated cases and no resolve.
Optional Handlers
| Method | Description |
|--------|-------------|
| engine.onResolveCharacter(fn) | Character resolver. Default: first character in the list. |
| engine.onResolveCondition(fn) | Unified condition resolver (choice visibility + condition pre-evaluation). |
| engine.onBeforeBlock(handler) | Pre-execution gate. Must call resolve() to continue. |
| engine.onValidateNextBlock(handler) | Validate before entering a block. |
| engine.onInvalidateBlock(handler) | Called when a block fails validation. |
| engine.onSceneEnter(handler) | Called when any scene starts. |
| engine.onSceneExit(handler) | Called when any scene ends. context.reason says why: completed, cancelled, invalidated, faulted (with context.error, what was thrown) or deadlocked (with context.waitingFor). |
Scene Handle (Tier 2 — Per-Scene)
| Method | Description |
|--------|-------------|
| handle.start() | Begin traversal from the entry block. |
| handle.cancel() | Stop the scene and all async tracks. |
| handle.onDialog(handler) | Override global DIALOG handler for this scene. |
| handle.onChoice(handler) | Override global CHOICE handler for this scene. |
| handle.onCondition(handler) | Override global CONDITION handler for this scene. |
| handle.onAction(handler) | Override global ACTION handler for this scene. |
| handle.onBlock(id, handler) | Override the handler for one block, by its id (DIALOG-007). |
| handle.onDialogId(id, handler) | Override one DIALOG block by id (type-safe). |
| handle.onChoiceId(id, handler) | Override one CHOICE block by id (type-safe). |
| handle.onConditionId(id, handler) | Override one CONDITION block by id (type-safe). |
| handle.onActionId(id, handler) | Override one ACTION block by id (type-safe). |
| handle.onEnter(handler) | Override global onSceneEnter for this scene. |
| handle.onExit(handler) | Override global onSceneExit for this scene. |
| handle.onResolveCharacter(fn) | Override character resolver for this scene. |
| handle.getSceneId() | The stable id of the scene (sc_…). Store this one: it survives a rename. |
| handle.getScenePath() | The scene path (reactor_breach) — what a writer reads, and what a rename changes. |
| handle.getCurrentBlock() | Get the block currently being executed, or null. |
| handle.getVisitedBlocks() | Set of visited block ids, for this scene. |
| handle.getChoiceHistory() | Map of CHOICE block id → the option ids the player picked. |
| handle.getChoice(blockId) | The option ids picked at one CHOICE block. |
| handle.evaluateCondition(cond) | Evaluate a choice: condition against history. |
| handle.isRunning() | Whether the scene is still active. |
| handle.getActiveTracks() | Number of active async tracks. |
| handle.getTrackInfos() | Snapshot of all track states. |
Handler Pattern
Every handler receives { scene, block, context, next } and may return a cleanup function:
engine.onDialog(({ block, context, next }) => {
// Display dialogue...
next(); // Advance to next block
return () => {
// Called when leaving this block (cleanup)
};
});Utilities (LsdeUtils)
| Method | Description |
|--------|-------------|
| LsdeUtils.locale | Current locale, synced by engine.setLocale(). |
| LsdeUtils.isDialogBlock(block) | Type guard: true if block is a DialogBlock. |
| LsdeUtils.isChoiceBlock(block) | Type guard: true if block is a ChoiceBlock. |
| LsdeUtils.isConditionBlock(block) | Type guard: true if block is a ConditionBlock. |
| LsdeUtils.isRouterBlock(block) | Type guard: true if block is a RouterBlock. |
| LsdeUtils.isActionBlock(block) | Type guard: true if block is an ActionBlock. |
| LsdeUtils.isNoteBlock(block) | Type guard: true if block is a NoteBlock. |
| LsdeUtils.getBlockLabel(block) | How to name a block on screen: label, else the designer note, else the id. |
| LsdeUtils.getLocalizedText(text, locale?) | Pick a locale out of an inline text map. Uses the engine locale by default. |
| LsdeUtils.getTextFromTable(table, scene, blockId, optionId?) | Read a line out of a loaded localization/<locale>/__blueprints__.json (separate-text mode). |
| LsdeUtils.getTextKey(block, optionId?) | The i18n key of a block, or of one option of a choice. |
| LsdeUtils.getNativeProperties(block) | The properties the ENGINE acts on, out of props. delay/timeout are MILLISECONDS. |
| LsdeUtils.getCustomProperties(block) | The properties the DESIGNER declared, with the natives taken out. |
| LsdeUtils.isChoiceCondition(test) | True if the test reads a past answer - { dict: "choice" }. |
| LsdeUtils.getChoiceConditionBlockId(test) | The CHOICE block a choice: test reads. |
| LsdeUtils.evaluateConditionChain(tests, evaluator) | Evaluate an AND/OR chain, left to right, no precedence. Absent or empty = true. |
| LsdeUtils.evaluateConditionCases(cases, portPerCase, evaluator) | The exit port of a condition block: out/default, or K1... with portPerCase. |
| LsdeUtils.evaluateEachCase(cases, evaluator) | Each case on its own, in order - to show what matched without changing the routing. |
| LsdeUtils.pickRouterPorts(cases, results) | The exits of a ROUTER from results already computed: every true case's port, then then or catch LAST. |
| LsdeUtils.tagOptionVisibility(options, evaluator) | Tag every option with whether its when holds, returning them ALL. |
Cross-Language Tests
This runtime shares its JSON-based test specifications with all other ports:
tests/test-cases.json— Flow tests (linear, choice, condition, router, action, async, waits, wire queue, per-character entry)tests/test-port-routing.json— Port resolution for all block typestests/test-init-validation.json— Blueprint validation error/warning codes, single file and per-scene files
81 shared cases, in 72 suites, run by all four runtimes: 81/81 passing. Generated by tests/generate-specs.py — never edited by hand.
License
Proprietary — distributed under the LSDE license.
