JavaScript API
Do it with an agent
Write a Node.js script at
scripts/render-diagrams.tsthat usesdiagramkit’s programmatic API. Readnode_modules/diagramkit/llms-full.txtfirst. The script should callrenderAll({ dir: '.' }), logrendered/skipped/failedcounts, exit non-zero if any render failed, and always callawait dispose()in afinallyblock.
Do it manually
For programmatic control, diagramkit exports an async API. All rendering functions return promises. Mermaid, Excalidraw, and Draw.io use Playwright internally; Graphviz uses bundled Viz.js/WASM.
npm add diagramkitNote
The CLI is the recommended way to use diagramkit. Use the API when you need programmatic control in build scripts, custom tooling, or Node.js applications.
render(source, type, options?)
Render a diagram from a source string.
import { render } from 'diagramkit'const result = await render( `graph TD A[Client] --> B[Server] B --> C[(Database)]`, 'mermaid', { format: 'svg', theme: 'both' },)// result.light -- Buffer containing light theme SVG// result.dark -- Buffer containing dark theme SVG// result.format -- 'svg'// result.width -- SVG width in pixels (SVG only)// result.height -- SVG height in pixels (SVG only)| Parameter | Type | Description |
|---|---|---|
source |
string |
Diagram source content |
type |
DiagramType |
'mermaid', 'excalidraw', 'drawio', or 'graphviz' |
options |
RenderOptions |
Optional rendering config |
renderFile(filePath, options?)
Render a file from disk. Type is inferred from the extension.
import { renderFile } from 'diagramkit'import { writeFileSync } from 'fs'const result = await renderFile('/path/to/architecture.mermaid', { format: 'png', scale: 3,})if (result.light) writeFileSync('architecture-light.png', result.light)if (result.dark) writeFileSync('architecture-dark.png', result.dark)renderAll(options?)
Batch render all diagrams in a directory tree. Writes to .diagramkit/ folders. Uses the manifest for incremental builds.
import { renderAll, dispose } from 'diagramkit'const { rendered, skipped, failed } = await renderAll({ dir: '/path/to/project', formats: ['svg'], theme: 'both', force: false,})// Always dispose when doneawait dispose()The function discovers files, checks the manifest, renders stale files, updates the manifest, and cleans orphaned outputs.
renderDiagramFileToDisk(file, options?)
Render a single discovered file and write output to disk. Used internally by renderAll() and watch mode.
import { renderDiagramFileToDisk, dispose } from 'diagramkit'import { findDiagramFiles } from 'diagramkit/utils'const files = findDiagramFiles('/path/to/project')for (const file of files) { const written = await renderDiagramFileToDisk(file, { formats: ['svg'] }) // written -- ['flow-light.svg', 'flow-dark.svg']}await dispose()watchDiagrams(options)
Watch for changes and re-render automatically. Returns a cleanup function.
import { watchDiagrams, dispose } from 'diagramkit'const stop = watchDiagrams({ dir: '/path/to/project', renderOptions: { format: 'svg', theme: 'both' }, onChange: (file) => console.log(`Re-rendered: ${file}`),})await stop()await dispose()createRendererRuntime()
Create an isolated runtime with its own browser pool. Use this for workers, long-running services, and tests where shared singleton state is undesirable.
import { createRendererRuntime } from 'diagramkit'const runtime = createRendererRuntime()const result = await runtime.renderAll({ dir: '/path/to/project', formats: ['svg'], includeMetrics: true,})await runtime.dispose()Tip
When issuing overlapping renders (Promise.all) for browser-backed engines, prefer createRendererRuntime() per worker/service boundary so each runtime has an isolated pool.
Note
The top-level APIs (render, renderAll, watchDiagrams, warmup, dispose) share a singleton browser pool. Runtime methods use their own isolated pool, so clean them up with runtime.dispose() instead of the global dispose().
createRendererRuntime() returns runtime-scoped versions of:
renderrenderFilerenderDiagramFileToDiskrenderAllwatchDiagramswarmupdispose
Browser Lifecycle
warmup()
Pre-warm the browser pool. Optional — the browser launches automatically on first render.
import { warmup } from 'diagramkit'await warmup()dispose()
Close the browser pool and release resources.
import { dispose } from 'diagramkit'await dispose()Important
Always call dispose() when done rendering, especially in scripts and CI. The pool has an idle timeout, but explicit disposal prevents resource leaks.
convertSvg(svg, options)
Convert SVG to raster format using sharp.
import { convertSvg } from 'diagramkit/convert'const png = await convertSvg(svgBuffer, { format: 'png', scale: 2 })const jpeg = await convertSvg(svgString, { format: 'jpeg', quality: 85, scale: 3 })loadConfig(overrides?, dir?, configFile?, options?)
Load merged config from all sources. Pass configFile to load a specific file instead of auto-discovery.
import { loadConfig } from 'diagramkit'const config = loadConfig( { outputDir: 'images' }, '/path/to/project',)// Or with explicit config fileconst ciConfig = loadConfig({}, '.', './ci.config.json5')// Strict mode throws on invalid config instead of warning and falling backconst strictConfig = loadConfig({}, '.', undefined, { strict: true })defineConfig(config)
Identity helper for TypeScript config files. Lets diagramkit.config.ts opt into autocomplete and DiagramkitConfig typing without runtime cost.
import { defineConfig } from 'diagramkit'export default defineConfig({ outputDir: '.diagramkit', defaultFormats: ['svg', 'png'],})getDefaultConfig() and getFileOverrides(filePath, config?, rootDir?)
getDefaultConfig() returns the baseline config object before any layering (defaults → global → env → local → overrides). getFileOverrides(filePath, config?, rootDir?) resolves any per-file overrides rules in the loaded config for a single source file.
import { getDefaultConfig, getFileOverrides, loadConfig } from 'diagramkit'const defaults = getDefaultConfig()const config = loadConfig()const overrides = getFileOverrides('docs/diagrams/system.mermaid', config)Engine Metadata: ENGINE_PROFILES, getEngineProfile, defaultMermaidDarkTheme
Reflective metadata for the four engines (mermaid, excalidraw, drawio, graphviz). Useful when you build dashboards, pickers, or per-engine tooling without hard-coding the engine list.
import { ENGINE_PROFILES, getEngineProfile, defaultMermaidDarkTheme,} from 'diagramkit'ENGINE_PROFILES.forEach((profile) => { console.log(profile.type, profile.browserPool ? '(browser)' : '(wasm)')})const mermaid = getEngineProfile('mermaid')// Inject the built-in dark theme variables into a custom mermaid.initialize() callconst themeVars = defaultMermaidDarkThemeDiagramkitError and error codes
All thrown errors are instances of DiagramkitError. Inspect error.code (a DiagramkitErrorCode) for machine-readable handling — codes match the CLI failedDetails[].code strings (UNKNOWN_TYPE, RENDER_FAILED, MISSING_DEPENDENCY, CONFIG_INVALID, BROWSER_LAUNCH_FAILED, BUNDLE_FAILED).
import { renderFile, DiagramkitError } from 'diagramkit'try { await renderFile('diagrams/broken.mermaid')} catch (err) { if (err instanceof DiagramkitError) { console.error(`[${err.code}] ${err.message}`) if (err.code === 'MISSING_DEPENDENCY') { console.error('Run: npm add sharp') } } throw err}File Discovery
import { findDiagramFiles, filterByType } from 'diagramkit/utils'const all = findDiagramFiles('/path/to/project')const mermaidOnly = filterByType(all, 'mermaid')Color Utilities
import { postProcessDarkSvg } from 'diagramkit/color'const optimized = postProcessDarkSvg(rawDarkSvg)Finds inline fill colors with high luminance and darkens them while preserving hue, ensuring readability against dark backgrounds.
Subpath Exports
| Import | Content |
|---|---|
diagramkit |
Core rendering functions, config, lifecycle, and convertSvg |
diagramkit/utils |
Utility barrel (discovery, manifest, extensions, output, color, validation) |
diagramkit/color |
Color utilities only |
diagramkit/convert |
SVG-to-raster conversion |
diagramkit/validate |
SVG structural + WCAG 2.2 AA contrast validation |
Note
convertSvg is available from both diagramkit (main) and diagramkit/convert (subpath). Discovery, manifest, color, and validation utilities live in the subpath exports (diagramkit/utils, diagramkit/color, diagramkit/validate), not the main entry. The diagramkit/validate subpath re-exports the same validateSvg* functions available from diagramkit/utils.