API reference
The public surface is intentionally small. Most callers only need renderSvg. See the Overview for which entry point to use, Types for the shapes each function consumes and returns, and the generated Reference for exhaustive signatures, every field, and every overload.
Type declarations (
.d.ts) are emitted bynpm run build(thebuild:typesstep runstsc -p tsconfig.build.json). Thepackage.jsonexportsmap wirestypesconditions for each entry, so@knowvah/dot-engine,@knowvah/dot-engine/api, and@knowvah/dot-engine/renderall resolve types in editors and downstream builds.The build also emits declaration maps (
.d.ts.map) and JS source maps, and the package ships itssrc/sources — so "go to definition" jumps straight to the real TypeScript, making it easy to read the code and open a PR.
This page is organized by the three entry points (Overview covers when to reach for each): the root @knowvah/dot-engine package (parse + render in one call, plus process-global configuration), @knowvah/dot-engine/api (build a graph in code, read back computed geometry), and @knowvah/dot-engine/render (multi-format output and raw draw-ops). Every function below re-exports from the root package too (export * from './api/index.js' / export * from './render/index.js' in src/index.ts) — importing everything from @knowvah/dot-engine works, but the sub-path imports are more explicit about which layer you're touching.
@knowvah/dot-engine (root)
renderSvg
function renderSvg(dotSource: string, engine: EngineName): string;Parses the DOT source, runs the named layout engine, renders to SVG, and returns the SVG string. This is the one-call convenience wrapper: it constructs a GvcContext, registers the eight built-in engines and the SVG renderer, lays out, renders, and frees the layout — see GvcContext / renderWithContext below if you need those steps separated.
dotSource— DOT-language graph source.engine—EngineName: one of the built-ins (dot,neato,fdp,sfdp,circo,twopi,osage,patchwork) or any custom-registered name.- Throws
ParseErrorifdotSourceis invalid;RenderErrorif layout or rendering fails. Every throw implements the sharedGvErrorshape.
Full signature, JSDoc, and the GvError field list: Reference.
tryRenderSvg / RenderResult
function tryRenderSvg(dotSource: string, engine: EngineName): RenderResult;Result-style sibling of renderSvg — never throws. Returns { svg } on success or { errors: [one] } on the first failure; svg and errors are mutually exclusive. Each entry in errors is a plain, JSON-serializable GvError object (no stack trace), so it's safe to send across a worker/postMessage boundary or serialize into a log. Prefer this over renderSvg + try/catch when the caller wants to branch on code / type rather than catch an exception. Reference.
parse / ParseError
function parse(dotSource: string): Graph;Parses DOT into the in-memory graph model without laying it out. Useful for inspecting or transforming the graph — or handing it to @knowvah/dot-engine/api's getLayout / @knowvah/dot-engine/render's render — before rendering.
- Throws
ParseErrorfor syntax errors or edge-direction violations (e.g.->in an undirected graph).ParseErrorimplementsGvErrorwithtype: 'syntax'and carries alocation: { line, column, offset? }when the parser can pinpoint one. Reference.
RenderError
class RenderError extends Error implements GvError {
readonly type: 'render';
readonly code: GvErrorCode;
readonly friendlyMessage: string;
}Thrown for known layout/render-stage failures (code is 'RENDER_ERROR' or 'GENERIC_ERROR'). Every @knowvah/dot-engine throw — ParseError, RenderError, or an HtmlParseError from an HTML-like label — implements the shared GvError contract, so callers can branch on err.type / err.code without an instanceof chain per error class. See Types for the full GvError shape and Reference for GvErrorCode's member list.
setTextMeasurer / getTextMeasurer
function setTextMeasurer(measurer: TextMeasurer | null): void;
function getTextMeasurer(): TextMeasurer;Registers (or clears, with null) the process-global text measurer consulted during layout to size labels. Clearing falls back to the library default (browser: CanvasTextMeasurer; headless/Node: EstimateTextMeasurer, unless a LUT measurer is wired — see Text measurement for the full resolution order and the CanvasTextMeasurer / EstimateTextMeasurer / LutTextMeasurer implementations exported alongside these functions). Reference.
setImageSizer / setImageResolver
Two related, but distinct, image-configuration seams — both process-global registries mirroring the same pattern (register a callback, pass null to clear), both no-ops until a caller registers one:
setImageSizer— reports an external image's intrinsic dimensions so the layout engine can reserve space for an HTML<IMG>cell or a nodeimage=attribute before rendering. Returningnull(or leaving no sizer registered) reproduces native Graphviz's missing-image behavior: a warning and zero size.setImageResolver(new — seeinlineImagesbelow) — supplies the actual image bytes so the SVG renderer can inline them as adata:URI instead of emittingxlink:href="src"as a raw passthrough.
type ImageSizer = (src: string) => { w: number; h: number } | null;
function setImageSizer(sizer: ImageSizer | null): void;
type ImageResolver = (
src: string,
) => { bytes: Uint8Array; mime?: string } | Uint8Array | null;
function setImageResolver(fn: ImageResolver | null): void;ImageResolver may return a bare Uint8Array (MIME inferred from src's file extension — .png, .jpg/.jpeg, .gif, .svg, .webp; anything else falls back to application/octet-stream) or { bytes, mime } to set the MIME type explicitly. Return null when src can't be resolved — the renderer falls back to the raw src passthrough, same as no resolver being registered. Registering a resolver has no effect by itself; it's consulted only when render's inlineImages option is true (below). See Working with images for a worked example and Reference for both callback types.
GvcContext / renderWithContext
class GvcContext {
constructor(measurer: TextMeasurer, options?: { debug?: DebugOptions });
register(plugin: LayoutEngine | RendererPlugin): void;
layout(g: Graph, engineName: EngineName): void;
freeLayout(g: Graph, engineName: EngineName): void;
}
function renderWithContext(ctx: GvcContext, g: Graph, format: string): string;Lower-level orchestration for callers that need to drive layout and rendering as separate steps. renderSvg is a convenience wrapper over exactly this: construct a context, register engines/renderers, layout, renderWithContext, freeLayout. Reach for these directly only when you need that control — for example, to register a subset of engines, add a custom LayoutEngine or RendererPlugin, or render the same laid-out graph to multiple formats without re-running layout (call layout once, then renderWithContext for each format, then freeLayout). Reference.
@knowvah/dot-engine/api
Programmatic construction, safe edge insertion, and computed-geometry readout — the layer for building a graph without hand-writing DOT text and reading its layout back as plain data. See Types for LayoutSnapshot and its nested shapes.
createGraph
function createGraph(opts?: {
directed?: boolean;
strict?: boolean;
name?: string;
}): GvGraphBuilder;Creates a fresh graph ready for handoff to render / getLayout / getDrawOps. Defaults: directed: true, strict: false, name: ''. Returns a GvGraphBuilder — addNode, addEdge, addSubgraph, setAttr/getAttr, setHtmlAttr (for HTML-table labels), and a .graph property exposing the opaque Graph handle. See Build a graph in code and Reference for the full GvGraphBuilder/GvNode/GvEdge interfaces.
addEdge
function addEdge(g: Graph, tail: Node, head: Node, name?: string): Edge;Lower-level edge-insertion helper underlying GvGraphBuilder.addEdge — exported directly for callers working with the internal Node/Edge references (e.g. edges added onto a graph returned by parse()) rather than the builder's opaque GvNode/GvEdge handles. Most callers should use createGraph(...).addEdge(tail, head, attrs?) instead.
name— edge key; defaults to''(anonymous). Ignored for strict-graph dedup, which matches on(tail, head)alone (symmetric for undirected graphs).- Returns the new edge, or the existing one if
gis strict and a(tail, head)edge already exists (mirrorsagedgewithcflag=1).
See Build a graph in code and Reference.
getLayout
function getLayout(g: Graph, opts?: { yAxis?: 'up' | 'down' }): LayoutSnapshot;Returns a plain, JSON-serializable snapshot of the graph's computed geometry — node positions, edge spline control points, edge labels, cluster bounding boxes, and the overall graph bounds — all in points.
g— must already be laid out (viarender(g, ...),getDrawOps(g), orctx.layout(g, engine)); callinggetLayouton a not-yet-laid-out graph throws rather than silently returning all-zero geometry.opts.yAxis— default'down': screen coordinates, origin top-left, y increases downward, andboundsis normalized to(0, 0).'up'returns native Graphviz coordinates (origin bottom-left, y increases upward) withbounds.x/bounds.yat the raw lower-left corner.- Throws
RenderErrorifghas not been laid out.
Node width/height are converted to points (the internal model stores inches); every other coordinate is already in points. See Read computed geometry for the coordinate-system writeup and Types / Reference for the full LayoutSnapshot, NodeGeometry, EdgeGeometry, ClusterGeometry, and BoundsGeometry field lists.
Graph
Opaque handle type re-exported from the internal model. Only the type is exposed (not the mutable class) — annotate a variable holding a builder's .graph or a parse() result with it, but don't construct or inspect its fields directly; use the builder, getLayout, or getDrawOps to read state back out. Reference.
@knowvah/dot-engine/render
Multi-format output and raw draw-op access — the layer for rendering an already-parsed or builder-constructed graph.
render
function render(
g: Graph,
format: OutputFormat,
opts?: RenderOptions,
): string;Lays out and renders a graph to the requested format string.
format—OutputFormat:'svg' | 'dot' | 'xdot' | 'json' | 'plain' | 'plain-ext' | 'imap' | 'cmapx'.opts.engine— layout engine (default'dot').opts.inlineImages— see below.- Throws
RenderErroron layout or render failure.
opts.engine mirrors renderSvg's engine parameter; format is the axis renderSvg doesn't expose (renderSvg is hardcoded to 'svg'). See Render to other formats and Reference for the full OutputFormat union and RenderOptions shape.
inlineImages
RenderOptions.inlineImages (default false) inlines external images as data: URIs instead of the raw xlink:href="src" passthrough. It has no effect unless a resolver is registered via setImageResolver (above) — and no effect on non-SVG formats. Unset, output is byte-identical to before this option existed.
import { setImageResolver } from '@knowvah/dot-engine';
import { render } from '@knowvah/dot-engine/render';
import { parse } from '@knowvah/dot-engine';
setImageResolver((src) => {
// Return the bytes for any src your DOT source references via
// `image="..."` or an HTML <IMG SRC="...">; null for anything else.
if (src === 'logo.png') return fetchLogoBytesSync(); // Uint8Array
return null;
});
const g = parse('digraph { a [image="logo.png" shape=none label=""]; }');
const svg = render(g, 'svg', { inlineImages: true });
// svg now embeds `xlink:href="data:image/png;base64,..."` for the `a` node
// instead of `xlink:href="logo.png"`.See Working with images for the full guide, including resolving from fetch in the browser and from the filesystem in Node.
getDrawOps / DEFAULT_DRAW_ENGINE
const DEFAULT_DRAW_ENGINE: EngineName; // 'dot'
function getDrawOps(g: Graph, opts?: { engine?: EngineName }): XdotOp[];Lays out g, renders to xdot, and returns a flat, typed draw-op array — node shapes, text spans, colors, and fonts as discriminated-union values (narrow on op.kind in a switch) — for feeding a custom canvas/WebGL/PDF renderer without touching SVG or xdot's string encoding. opts.engine defaults to DEFAULT_DRAW_ENGINE ('dot').
- Throws
ParseErrorif the intermediate xdot output can't be re-parsed (defensive; not expected in practice);RenderErroron layout/render failure.
See Custom rendering with xdot draw-ops for the op-kind list and a worked canvas example, and Types / Reference for the full XdotOp union and Xdot/XdotColor shapes.