Skip to content

Command line

The package ships a CLI for use without writing any JavaScript.

Install: nothing to install when you run it through npx as below, or brew install yusufaf/tap/sfn-diagram for a build that needs no Node.js but cannot use --format png or the flags that reach AWS (see Standalone binary). A Docker image is also available.

Terminal window
npx sfn-diagram state.asl.json --format svg -o diagram.svg
Terminal window
npx sfn-diagram state.asl.json --format mermaid > diagram.mmd
Terminal window
cat state.asl.json | npx sfn-diagram - --format svg

Piped through any runner works the same way — swap npx for pnpm dlx, yarn dlx, or bunx.

Flag Description
--format <svg|mermaid|png|html> Output format (default: svg)
-o, --output <path> Output file (required for png; stdout otherwise)
--out-dir <dir> Write one output file per input into this directory — see Rendering several files
--preserve-tree With --out-dir, mirror each input’s directory instead of writing flat — see Mirroring the input layout
--from-aws <arn> Fetch the definition live from AWS instead of reading a file — see Rendering a live state machine
--watch Re-render whenever a watched file changes — see Watching files
--follow With --execution <arn>, keep polling and re-rendering until the run finishes — see Following a running execution
--poll-interval <seconds> How often --follow polls (default: 2)
--follow-timeout <seconds> Give up after this long and exit 1
--config <path> Read defaults from this config file instead of searching for one
--theme <light|dark|auto|path> Color theme for SVG/PNG/HTML: a built-in name, or a path to a custom theme JSON file (default: light). auto follows the reader’s colour scheme; PNG renders it as light
--layout <TB|LR|RL|BT> Graph direction (default: TB)
--hide-catch Drop error-handler (Catch) branches
--show-catch Draw them — overrides a config file’s catchHandling
--hide-variables Drop the $var annotations for ASL Assign blocks
--show-variables Draw them — overrides a config file’s showVariables
--hide-comments Don’t use a state’s Comment as its node label
--show-comments Use it — overrides a config file’s includeComments
--collapse[=names] Collapse Parallel/Map containers into placeholders. Bare flag collapses every container; --collapse=Name1,Name2 collapses only those. Write \, for a comma inside a state name
--no-collapse Don’t collapse containers — overrides a config file’s collapse
--show-icons Draw AWS service icons on Task states
--hide-icons Don’t draw them — overrides a config file’s showIcons
--icon-position <left|top|right> Icon placement relative to the label (default: left)
--icon-size <pixels> Icon size in pixels (default: 24)
--show-state-types Draw each state’s type as a label on the node
--hide-state-types Don’t draw them — overrides a config file’s showStateTypes
--edge-style <straight|curved|orthogonal> Edge path style (default: curved).
--style-preset <aws-standard|enhanced> Node shapes: AWS parity, or a distinct shape per state type (default: aws-standard)
--catch-label-style <error-type|catch-number> Label on Catch edges: the error name, or Catch #N (default: error-type)
--node-width <pixels> Width of each state node (default: 120)
--node-height <pixels> Height of each state node (default: 60)
--node-separation <pixels> Separation between nodes within a rank (default: 50)
--rank-separation <pixels> Separation between ranks (default: 50)
--padding <pixels> Padding around the diagram (default: 20)
--diagram-title <text> Accessible name, rendered as the SVG’s <title> and aria-label
--diagram-description <text> Accessible description, rendered as the SVG’s <desc>
--background-color <color> PNG background (default: transparent) — see the note below
--scale <n> PNG resolution multiplier (default 1, at most 10) — see PNG resolution and fonts
--load-system-fonts PNG: also parse every installed font — see PNG resolution and fonts
--no-load-system-fonts PNG: load only the one resolved font file — see PNG resolution and fonts
--redact-fields <names> HTML: inline [redacted] for these ASL fields wherever they appear (comma-separated, repeatable) — see Redacting the HTML document
--no-raw-state HTML: inline no state’s raw ASL — see Redacting the HTML document
--diff <baseline> Compare the input (head) against a baseline definition
--execution <history.json> Overlay a GetExecutionHistory result on the diagram
--resolve-cfn Treat the input as a CloudFormation/SAM/CDK template (JSON and YAML templates with a state machine resource, and Terraform .tf/.tf.json files, are detected automatically)
--resource <id> State machine to extract when a template or Terraform config has several (CloudFormation logical id, CDK construct path, or Terraform resource name)
--check Lint the definition instead of drawing it — see Linting
--check-format <text|json> With --check, json writes one JSON document to stdout — see Machine-readable output
-h, --help / -v, --version Show help / version and exit

Settings a project uses on every run can live in a config file instead of on every command line. Any explicit flag overrides it.

sfn-diagram.config.json
{
"layout": "LR",
"showIcons": true,
"padding": 40,
"theme": { "base": "dark", "background": "#101014" }
}
Terminal window
sfn-diagram state.asl.json -o diagram.svg # uses the file
sfn-diagram state.asl.json -o diagram.svg --layout TB # the flag wins
sfn-diagram state.asl.json -o diagram.svg --config ci/sfn.yaml

Starting in the working directory and walking up, stopping at the repository root (the first directory containing a .git entry) or, outside a repository, at your home directory. Within one directory these names are tried in order:

sfn-diagram.config.json
sfn-diagram.config.yaml
sfn-diagram.config.yml
.sfn-diagramrc
.sfn-diagramrc.json
.sfn-diagramrc.yaml
.sfn-diagramrc.yml

.sfn-diagramrc has no extension and is read as YAML, which accepts JSON too.

--config <path> skips the search. A file it names that cannot be read is an error, not a silent fallback to searching.

The search starts from the working directory, not from the input file’s directory — so sfn-diagram sub/dir/machine.asl.json does not pick up sub/dir/sfn-diagram.config.json. One invocation’s configuration does not depend on which input it happens to name.

Field names match the library options rather than the flags, so the file and the API read the same way: catchHandling: "hide", not hideCatch: true.

Field Type
backgroundColor string
catchHandling "show" | "hide"
catchLabelStyle "error-type" | "catch-number"
collapse boolean, or an array of state names
customColors object keyed by state type (Task, Choice, …), each naming fill and/or stroke
diagramDescription string
diagramTitle string
edgeOverrides object keyed by edge id or From->To, each naming stroke, strokeOpacity (0–1) and/or strokeWidth (SVG, HTML and PNG)
edgeStyle "straight" | "curved" | "orthogonal"
format "svg" | "mermaid" | "png" | "html"
iconPosition "left" | "top" | "right"
iconSize number
includeComments boolean
includeRawState boolean (HTML only; false redacts every state’s ASL)
layout "TB" | "LR" | "RL" | "BT"
loadSystemFonts boolean (PNG only)
nodeHeight, nodeWidth number
nodeOverrides object keyed by state id, each naming fill, stroke, strokeWidth and/or shape ("rect" | "diamond" | "circle") (SVG, HTML and PNG)
nodeSeparation, rankSeparation, padding number
redactFields array of ASL field names (HTML only)
scale number above 0, at most 10 (PNG only)
showIcons, showStateTypes, showVariables boolean
stylePreset "aws-standard" | "enhanced"
theme "light" | "dark" | "auto", or a custom theme object

Top-level keys it doesn’t recognise are ignored with a warning: on stderr that names the file and, when a known key is a close match, suggests it (layuot: did you mean layout?). The exit code is unchanged, so a field added by a later release won’t break an older CLI reading the same file. $schema (for editor completion) and commentGitlab (read by comment gitlab) never warn. iconResolver and redact take a function, and nodeAnnotations is meant for computed text, so those three stay API-only. redactFields and includeRawState cover the common cases of redact (see Redacting the HTML document). redactFields and includeRawState need sfn-diagram 1.9.0 or later, as do customColors, nodeOverrides and edgeOverrides; an older CLI ignores them like any unknown key.

customColors, nodeOverrides and edgeOverrides are the library’s override maps, set once for every render. They have no flags.

sfn-diagram.config.yaml
customColors:
Task: { fill: "#ff9900", stroke: "#232f3e" }
nodeOverrides:
Process Payment: { shape: circle, strokeWidth: 3 }
edgeOverrides:
"Check Stock->Ship": { stroke: "#1d8102" }

Quote colours in YAML: an unquoted # starts a comment. On its own line, fill: #ff9900 reads as an empty value and the run fails naming customColors.Task.fill; inside { … }, as in the example above, the comment swallows the closing brace and the file fails to parse at all.

  • customColors applies over whichever theme is chosen, including --theme dark on the command line. A custom theme’s nodeColors belongs to that theme and is replaced along with it.
  • With theme: auto, these colours stay fixed when the diagram switches to its dark palette, while text and background change. Pick colours that read against both.
  • Mermaid output, --diff and --execution overlays included, draws customColors but not the two override maps. An execution overlay colours every state by its run status, so customColors shows on none of them, in Mermaid and SVG alike. Mermaid separates style properties with commas, so Mermaid output rewrites rgb(), rgba(), hsl() and hsla() written with commas to the comma-free form (rgb(255, 153, 0) becomes rgb(255 153 0)). A colour that still needs a comma, such as color-mix(…), is left out of Mermaid output, which keeps the theme’s colour and says so in a %% comment.
  • A colour in these three maps must be on one line and can’t contain ;, {, } or control characters, none of which any colour syntax uses; in Mermaid output they would end the style line early. Colours inside a custom theme object aren’t rejected, but Mermaid output applies the same rules to them, leaving out any it can’t draw. SVG, HTML and PNG output take them as given.
  • Under --diff and --execution, an override for a state or edge wins over its status colour, as it does in the library.
  • Unlike the top level, mistakes inside these maps are errors: an unknown state type in customColors, an unknown style field, an empty entry, or an edgeOverrides key with no ->. A key naming a state or edge the input doesn’t have is not checked; it simply matches nothing.

The config file has a published JSON Schema, so an editor can complete field names and flag mistakes as you type. In JSON, add a $schema key:

sfn-diagram.config.json
{
"$schema": "https://sfn.yusufaf.dev/config.schema.json",
"layout": "LR"
}

In YAML, with an editor using the YAML language server (VS Code’s YAML extension, for one), add a comment on the first line:

sfn-diagram.config.yaml
# yaml-language-server: $schema=https://sfn.yusufaf.dev/config.schema.json
layout: LR

The hosted schema follows this site, which deploys from main, so it can list a field before a release ships it. To match the version you have installed exactly, or to work offline, point at the copy in the package instead: ./node_modules/sfn-diagram/config.schema.json. Tools that locate the schema from code can resolve the installed copy through the package exports, with require.resolve('sfn-diagram/config.schema.json'), or import it with import schema from 'sfn-diagram/config.schema.json' with { type: 'json' }.

The schema is stricter than the CLI in one way: it flags a key it doesn’t know, where the CLI ignores it. That catches a typo such as widht in the editor; the CLI stays lenient so an older version can read a file written for a newer one.

JavaScript and TypeScript config files are deliberately not supported: executing one would run arbitrary code, and it could not work in the standalone binary, which would make the feature silently absent there.

A boolean flag can only switch a setting on, so each one has an opposite for overriding a config file:

Config field Turn on Turn off
catchHandling --show-catch --hide-catch
includeComments --show-comments --hide-comments
showVariables --show-variables --hide-variables
showIcons --show-icons --hide-icons
showStateTypes --show-state-types --hide-state-types
collapse --collapse[=names] --no-collapse
loadSystemFonts --load-system-fonts --no-load-system-fonts

Passing both halves of a pair is a usage error (exit 2) rather than last-one-wins, which would be easy to miss in a long CI command.

redactFields and includeRawState have no “turn off” flag, and are the one exception to “the flag wins”: redaction only adds up. --redact-fields adds names to the file’s list, and --no-raw-state applies when either side asks for it, so nothing typed on a command line can re-expose what the project’s config withholds.

A config file’s contents being wrong is a runtime failure (exit 1), not a usage error — exit 2 is reserved for what is wrong on the command line. See Exit codes.

$ sfn-diagram state.asl.json --config ci/sfn.json
Error: Invalid theme in /repo/ci/sfn.json: expected 'light', 'dark', 'auto', or a custom theme object
$ echo $?
1

The comment gitlab subcommand reads only a commentGitlab block in the same file, never the top-level fields. A config written for local renders therefore cannot change what a pipeline posts to a merge request; the block is an explicit opt-in.

sfn-diagram.config.yaml
layout: LR # main command only
commentGitlab: # comment gitlab only
theme: dark
catchHandling: hide

The block takes the four render settings the subcommand forwards: theme (light, dark, auto, or a custom theme object), layout, catchHandling and collapse, with the same values as the top-level fields. Any other key in it is an error (exit 1), rather than silently ignored, and so is a block name that differs only in case, spacing or punctuation, such as commentGitLab or comment_gitlab. The CI-shaped options (--asl-glob, --comment-tag, --out-dir, --execution-mode) stay flags in the job.

Precedence is flag, then block, then the default. --show-catch and --no-collapse undo a catchHandling: hide or a collapse from the block. comment gitlab --config <path> reads that file instead of searching, and it is an error if the file has no commentGitlab block. When a block is read, the job log says so: Read commentGitlab settings from <path>.

Needs sfn-diagram 1.9.0 or later; an older CLI ignores the block.

Pass more than one input, or a glob, with --out-dir:

Terminal window
sfn-diagram machines/order.asl.json machines/refund.asl.json --out-dir diagrams
sfn-diagram 'machines/**/*.asl.json' --out-dir diagrams

Quote the glob. Unquoted, your shell expands it first — which works, but only where the shell supports the pattern; quoted, sfn-diagram expands it the same way everywhere, including Windows cmd and PowerShell.

A CDK cdk.out directory works as an input too: sfn-diagram cdk.out --out-dir diagrams renders every state machine in its stacks, Stages and nested stacks, named by construct path. See Every state machine in cdk.out.

By default output is flat: <out-dir>/<input basename with its suffix stripped>.<ext>, so machines/order.asl.json becomes diagrams/order.svg (see Mirroring the input layout for --preserve-tree). The extension follows --format (.svg, .mmd, .png, .html). The directory is created if it does not exist.

Two inputs that would produce the same filename are refused before anything is written, so a rejected batch never leaves a half-populated directory:

$ sfn-diagram a/order.asl.json b/order.asl.json --out-dir out
Error: Two or more inputs would be written to the same file:
out/order.svg <- a/order.asl.json, b/order.asl.json
Rename one, pass --preserve-tree to keep their directories apart, or render them in separate runs.
$ echo $?
2

Names that differ only in case, such as Order.svg and order.svg, are refused too, on every platform, because Windows and macOS treat them as one file.

A name whose first part, before the first ., is a device name Windows reserves (CON, NUL, COM1, …) gets a leading _, so nul.asl.json writes _nul.svg. Windows 10 and earlier read NUL.svg as the device itself. Directories kept by --preserve-tree are not renamed.

--preserve-tree keeps each input’s directory under --out-dir, so inputs that share a basename in different directories no longer collide:

Terminal window
sfn-diagram 'machines/**/*.asl.json' --out-dir diagrams --preserve-tree
# machines/a/order.asl.json -> diagrams/a/order.svg
# machines/b/order.asl.json -> diagrams/b/order.svg

The directory kept is relative to a root taken from the command line, not from the files that matched: a glob contributes its non-glob prefix (machines above), a plain path its own directory, and the root is the deepest directory all of them share. Adding a file therefore never moves the other outputs; they move only when the command line changes. '**/*.asl.json' has no plain prefix, so it mirrors from the working directory.

  • Two inputs in one directory that derive the same name (order.asl.json and order.json) are still refused.
  • Inputs that share no directory at all — on different drives, or a network share and a drive — are a usage error (exit 2).
  • It needs --out-dir, and cannot be combined with --from-aws: an ARN has no directory to mirror.

A pattern is matched against paths relative to the working directory, and node_modules and .git are never descended into. Other hidden directories are walked, so .github/workflows/machine.asl.json is reachable. Symlinked definitions are matched; symlinked directories are not descended, which is what keeps the walk from looping.

*.asl.json means “in this directory”; use **/*.asl.json for any depth. (This differs from comment gitlab --asl-glob, which matches by basename at any depth because it filters a list git gives it rather than searching the filesystem.)

A ./ prefix and an absolute pattern both work, so a CI job can pass "$CI_PROJECT_DIR/machines/*.asl.json". Only the pattern’s non-glob prefix is walked, so machines/**/*.asl.json never reads a sibling directory.

A filename containing glob characters is still renderable. order[1].asl.json is both a valid pattern and a real name: it is matched as a pattern first, and falls back to the literal path when the pattern matches nothing and the file exists.

These take a single input, and more than one is a usage error:

  • -o / --output — it names one file. Use --out-dir instead.
  • --diff — one definition against one baseline.
  • --execution — one run overlaid on one definition.
  • - (stdin) — there is only one of it.

--out-dir needs named inputs, so it cannot be combined with stdin: there is no filename to derive an output name from. It also cannot be combined with --check, which lints and writes nothing, or with -o, which names one file itself.

With --format png, either -o or --out-dir satisfies the output requirement — PNG batches the same way every other format does.

The batch continues, the failure is reported on stderr naming the file, and the run exits 1. Stopping at the first failure would hide the rest:

$ sfn-diagram order.asl.json broken.asl.json refund.asl.json --out-dir out
Error in broken.asl.json: ASL definition is not valid JSON: Unexpected token 'o', "not json" is not valid JSON
$ echo $?
1
$ ls out
order.svg refund.svg

A failure names its file whenever there is more than one input, and whenever the inputs came from a glob — with a pattern you did not choose the filename, so it is exactly what you need told. A single input you typed yourself is reported without the name.

A glob that matches nothing exits 1 — the invocation was fine, the filesystem had nothing. See Exit codes.

--check works over several inputs too, printing each file’s diagnostics under its name and exiting 1 if any input has an error.

--from-aws fetches a definition from AWS with DescribeStateMachine instead of reading it from disk:

Terminal window
sfn-diagram --from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Orders -o live.svg

It needs the optional peer dependency:

Terminal window
pnpm add @aws-sdk/client-sfn

The region comes from the ARN — there is no separate region flag, because the ARN already says which region the state machine is in. Credentials come from the AWS SDK’s default provider chain, so AWS_PROFILE, AWS_REGION, SSO, an EC2/ECS instance role and ~/.aws/credentials all work the way they do for the AWS CLI:

Terminal window
AWS_PROFILE=prod sfn-diagram --from-aws arn:aws:states:eu-west-1:111122223333:stateMachine:Orders -o prod.svg

With no usable credentials the run exits 1 and says where to look:

$ sfn-diagram --from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Orders
Failed to fetch state machine arn:aws:states:us-east-1:111122223333:stateMachine:Orders from AWS: Could not load credentials from any providers
Set AWS_PROFILE / AWS_REGION, or configure the AWS CLI (aws configure).

--from-aws takes a state machine ARN, a version ARN (…:stateMachine:Orders:3) or an alias ARN (…:stateMachine:Orders:PROD) — the three DescribeStateMachine itself accepts. A bare name is refused, because resolving one would take a second API call and a region flag that the ARN form makes unnecessary:

$ sfn-diagram --from-aws Orders
--from-aws expects a state machine ARN (arn:aws:states:<region>:<account>:stateMachine:<name>); got "Orders"

That is exit 2, like any other bad flag value — nothing is fetched.

--from-aws is repeatable. With --out-dir, each output is named after the state machine, not the ARN:

Terminal window
sfn-diagram \
--from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Orders \
--from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Refunds \
--out-dir diagrams
# diagrams/Orders.svg, diagrams/Refunds.svg

A version or alias qualifier is part of that name, so Orders and Orders:PROD write Orders.svg and Orders-PROD.svg rather than fighting over one file. A state machine named after a Windows device, such as CON, writes _CON.svg.

Two ARNs whose state machines share a name — the same machine in two accounts or two regions — collide on that filename and are refused before anything is written, the same way two colliding file inputs are.

A failing ARN does not stop the batch: the others still render and the run exits 1.

  • --diff compares a live definition against a baseline, and the baseline may itself be an ARN — so live-against-live drift needs no extra flag:
    Terminal window
    # deployed vs. the repo
    sfn-diagram --from-aws arn:...:stateMachine:Orders --diff machines/order.asl.json --format mermaid
    # staging vs. production
    sfn-diagram --from-aws arn:aws:states:us-east-1:1:stateMachine:Orders \
    --diff arn:aws:states:eu-west-1:2:stateMachine:Orders --format mermaid
  • --execution <history.json> overlays a run on a live definition.
  • --check lints what is deployed without drawing it.
  • --out-dir, as above.

--resolve-cfn and --resource are refused alongside --from-aws (exit 2): DescribeStateMachine returns ASL, never a CloudFormation template, so there is nothing to unwrap. They do still work on the head of a diff whose baseline is an ARN, which is the drift check most people want:

Terminal window
sfn-diagram template.yaml --diff arn:...:stateMachine:Orders --format mermaid

There, the template is unwrapped and the live baseline is left alone.

--from-aws is not available in the standalone binary — a single-file executable has no node_modules to load an optional peer from. Use the npm package instead:

Terminal window
npx --package sfn-diagram --package @aws-sdk/client-sfn sfn-diagram --from-aws arn:...

--watch renders once and then keeps going, re-rendering whenever something it is watching changes:

Terminal window
sfn-diagram order.asl.json --watch -o diagram.svg
sfn-diagram 'machines/**/*.asl.json' --watch --out-dir diagrams
watching 2 path(s); Ctrl-C to stop
machines/order.asl.json changed
machines/payments.asl.json changed
stopped watching
A literal input the file itself
A glob the pattern’s root directory, recursively — so a file added later is picked up, not just the ones that matched at startup
The config file the one that was actually loaded
--theme <path>, --diff <path>, --execution <path> each file, when it names a path rather than an ARN
A template’s DefinitionUri file, or a CDK template’s manifest.json, .assets.json and DefinitionBody.fromFile asset each file a render read, including one the template is later edited to point at

A change to an input re-renders just that input — a save in a batch of forty redraws one diagram, not forty. A change to a file a template read re-renders that template; one read by a --diff baseline’s template re-renders everything.

A change to the config file, a --theme file, a --diff baseline or an --execution history re-resolves everything and re-renders every input, because those feed every output. This is the reason the config file is watched at all: options are merged once at startup, so without it, editing a config mid-watch would silently do nothing.

Bursts collapse. One save often produces several filesystem events — a write, a truncate, sometimes a temporary file and a rename — and a 100ms quiet period turns those into one render. Renders never overlap: a change arriving mid-render is queued and runs straight after, so two renders cannot race on one output file.

A file is invalid for a moment every time you save it, so a failed render prints and the watch continues. A deleted file is not an error either — the next pass re-expands the globs and carries on with whatever is still there. A path that cannot be watched at all is reported and skipped rather than ending the run.

--watch is a development loop, not a gate. Interrupting it exits 0 whatever the last render did, including with --check:

$ sfn-diagram order.asl.json --check --watch
watching 1 path(s); Ctrl-C to stop
order.asl.json changed
error /States/Next Unreachable state [unreachable-state]
^C
stopped watching # exit 0

For a gate, drop --watch and let --check’s exit code mean something.

The one exception is a usage error: --watch cannot make a bad command line work, so an invocation that would have exited 2 still does, before any watching starts.

--watch needs files, so it is refused (exit 2) with stdin, with --from-aws, and with an ARN --execution — which would otherwise re-fetch from AWS on every save. It is also refused with --follow: both own the process and each wants to decide when to re-render. --follow tracks a running execution; --watch tracks files on disk.

--execution takes a saved GetExecutionHistory result or an execution ARN, which is fetched live:

Terminal window
sfn-diagram order.asl.json \
--execution arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 -o run.svg

Add --follow and it keeps going until the run does not:

Terminal window
sfn-diagram order.asl.json \
--execution arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 \
--follow -o run.html
following arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 every 2s (Ctrl-C to stop)
...
arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 succeeded after 14 update(s)

Each poll re-fetches the whole history and rewrites the one output file. The full re-fetch is deliberate rather than lazy: the overlay is built by a single forward pass that walks previousEventId back through earlier events and pairs each state’s entry with its exit, so a partial history silently loses edges and durations. Histories are small; correctness is not.

The definition is fixed for the whole follow: a template’s DefinitionUri file or CDK asset is read on the first update and reused, so saving it mid-run cannot end the follow. Restart the follow to pick up an edit.

The rewrite goes through a temporary file and a rename, so a reader never sees a half-written document, and Ctrl-C leaves the last complete render in place rather than a truncated one.

A browser with the HTML file open needs a manual reload — the CLI writes files and has no channel to a running page.

The run reaches a terminal status One final render, exit 0. The status comes from the history itself, so no extra API call is made to ask.
Ctrl-C Stops between polls, leaving the latest complete file. Exit 0 — you asked it to stop.
--follow-timeout <seconds> Exit 1, with the latest render still on disk, so a CI job cannot wait forever.
The execution is already finished Rendered once, exit 0, never polled. --follow on a finished run is just --execution.

--follow needs -o or --out-dir: there is no coherent way to re-render to stdout, since a pipe consumer would get one diagram per tick with no way to tell where one ended. It also needs an ARN — a history file on disk does not progress, and re-rendering when a file changes is what --watch is for. --poll-interval and --follow-timeout are refused without --follow, rather than silently doing nothing.

Express workflow ARNs are refused up front: GetExecutionHistory serves Standard workflows only, so accepting one would only move the failure to the API call.

It pairs with --from-aws, which fetches the definition the run belongs to:

Terminal window
sfn-diagram --from-aws arn:...:stateMachine:Orders \
--execution arn:...:execution:Orders:run-1 --follow -o run.html

One caveat worth knowing: --from-aws returns the machine’s current definition. If it was updated after the run started, the overlay paints a past run onto a newer shape. Point --execution at a local copy of the definition that actually ran when that matters.

--theme takes a built-in name (light, dark or auto) or a path to a JSON file holding a CustomTheme. Any value that isn’t a built-in name is read as a path:

Terminal window
sfn-diagram state.asl.json --theme ./brand.theme.json -o diagram.svg
brand.theme.json
{
"base": "light",
"background": "#fbfbfd",
"fontFamily": "Inter, system-ui, sans-serif",
"nodeColors": {
"Task": { "fill": "#eef2ff", "stroke": "#4338ca" },
"Choice": { "fill": "#fefce8", "stroke": "#a16207" }
}
}

Every field is optional. base picks which built-in theme supplies the ones you leave out, so a file naming only nodeColors.Task is a one-colour tweak to the light theme rather than a theme built from nothing.

A missing file, malformed JSON, or a top-level value that isn’t an object is a runtime failure: the CLI writes Error: Cannot read theme file <path>: <reason> to stderr and exits 1, the same as any other path it cannot read. See Exit codes.

--background-color is applied by the PNG rasterizer, beneath the rendered SVG. The built-in light and dark themes paint their own background across the full canvas, so that rectangle covers whatever the rasterizer put behind it and the flag has no visible effect. To use it, give the theme a transparent background:

Terminal window
sfn-diagram state.asl.json --format png --theme ./transparent.theme.json \
--background-color '#ffffff' -o diagram.png
transparent.theme.json
{ "base": "light", "background": "transparent" }

--scale multiplies the PNG’s pixel width and height without changing the layout, so --scale 2 gives a retina-sharp copy of the same diagram. Fractions work too (0.5 halves it). It is capped at 10, which catches a DPI value typed as a scale (--scale 300, which would ask for hundreds of gigabytes) and still covers retina (2-3x) and 300 dpi print (about 3.1x). Memory use grows with the diagram’s area times the square of the scale, so a very large diagram can still be too big at a scale under 10. An image that would need more memory than the machine, or the container, has is an error (exit 1) naming the scale and the image size. So is a scale so small that the image would round to 0 pixels wide or tall.

Terminal window
sfn-diagram state.asl.json --format png --scale 2 -o diagram@2x.png

By default the renderer loads the one font file it resolved and parses every installed font only when the text needs glyphs that file is unlikely to have (see Docker for the details). --load-system-fonts always parses them, around 250ms per export; --no-load-system-fonts never does. Turning it off with no font file to load from is an error (exit 1) rather than a PNG of blank text. The first of these that is set wins:

  1. --load-system-fonts or --no-load-system-fonts
  2. loadSystemFonts in the config file
  3. the SFN_DIAGRAM_PNG_LOAD_SYSTEM_FONTS environment variable
  4. the automatic choice above

All three flags need --format png; given with another format they exit 2, except under --check, which renders nothing and ignores them. Set in the config file, scale and loadSystemFonts apply to PNG runs and are ignored for the others, so one project file can serve every format.

Every invocation exits with one of three codes, so a script can tell a mistake in the command from a failure while running it without parsing stderr.

Code Meaning
0 Success. Also a deliberate no-op: comment gitlab on a pipeline with nothing to do, and --check finding nothing worse than a warning.
1 Runtime failure. The invocation was valid, but something went wrong: an input that could not be read or parsed, a template with no extractable state machine, an unreadable --theme file, a missing optional peer dependency, a failed write. Also --check finding at least one error-severity diagnostic.
2 Usage error. The invocation itself cannot work: an unknown flag, an invalid value, a blank value, a combination that is contradictory, or a required flag left out. Nothing about the input file would change the outcome.

Nothing else is ever returned.

--check lints instead of drawing, and exits 1 when it finds an error-severity diagnostic — a finding, not a malfunction, and the same code a linter uses for the same reason. That is why usage errors live on 2: it leaves 1 free to mean “I ran and the answer was no” without colliding with “you invoked me wrong”.

Terminal window
sfn-diagram state.asl.json --check
case $? in
0) echo "clean (or warnings only)" ;;
1) echo "lint errors found" ;;
2) echo "bad invocation" ;;
esac

A path that cannot be read is a runtime failure, not a usage error — the command was well formed and the filesystem was not cooperative:

Terminal window
sfn-diagram missing.asl.json # 1
sfn-diagram state.asl.json --diff gone.json # 1
sfn-diagram state.asl.json --theme gone.json # 1

A misspelled --theme lands in the same place, because --theme accepts either a built-in name or a path and the two are indistinguishable once the read fails. The error message names all the accepted forms for that reason:

$ sfn-diagram state.asl.json --theme ligth
Error: Cannot read theme file ligth: ENOENT: no such file or directory, open '…/ligth'
--theme takes light, dark, auto, or a path to a theme JSON file.

Capture the status into a variable before branching on it. Inside if ! command; then, $? is the status of the negated test rather than the command’s, so it is always 0 there and a case on it would never match:

- name: Render the diagram
run: |
set +e
sfn-diagram state.asl.json -o diagram.svg
status=$?
set -e
case "$status" in
0) ;;
2) echo "::error::sfn-diagram was invoked incorrectly - check the flags"; exit 1 ;;
*) echo "::error::sfn-diagram failed to render - check the definition"; exit 1 ;;
esac
Terminal window
# Highlight what changed between two revisions of a definition
npx sfn-diagram head.asl.json --diff base.asl.json -o diff.svg
npx sfn-diagram head.asl.json --diff base.asl.json --format mermaid > diff.mmd
# Colour a diagram by what actually happened in a run
aws stepfunctions get-execution-history --execution-arn "$ARN" > history.json
npx sfn-diagram state.asl.json --execution history.json -o run.svg
# Both at once: a run painted onto what changed (HTML only)
npx sfn-diagram head.asl.json --diff base.asl.json --execution history.json --format html -o run.html

Both flags support --format svg, --format mermaid, and --format html only. Together they need --format html: the viewer paints the run onto the diff. A state that ran takes its execution colour, and a changed one carries its diff status in its label; a changed state the run never reached keeps its diff colour, so a removed state stays visible. Any other format exits 2. The change/status summaries are written to stderr, so the diagram on stdout still pipes cleanly:

Diff summary:
Added: NewStep
Modified: StepB
Removed: StepC
Unchanged: 1

Both overlays honour --collapse and --hide-catch in every format. A collapsed container’s placeholder takes the status rolled up from the states it hides on an execution overlay, and counts the changes inside it on a diff (see Large diagrams). In Mermaid output the placeholder carries the same status class and annotation. A Mermaid overlay also honours --hide-comments, --catch-label-style and the variables flags, like plain --format mermaid.

--execution accepts either a full GetExecutionHistory response ({"events": [...]}) or a bare events array. See generateDiff and generateExecution for the programmatic equivalents.

CloudFormation/SAM/CDK templates work as input too. A JSON or YAML template is detected by a state machine resource under Resources, so --resolve-cfn is only needed to force it. See Generate diagrams from CDK and SAM templates for the workflow, and Extracting ASL from a CDK/CloudFormation template for the API.

.tf and .tf.json files are read as Terraform and detected automatically, by extension or, for stdin and extensionless files, by an aws_sfn_state_machine resource in the contents. Pick one machine from a file that declares several with --resource orders (or --resource aws_sfn_state_machine.orders).

Terminal window
sfn-diagram main.tf --resource orders -o orders.svg

The definition can be a heredoc (<<EOF, <<-EOF), a quoted string of JSON, or jsonencode({...}) of object, list, string, number, bool and null literals. Anything only Terraform can compute (aws_lambda_function.charge.arn, var.wait, format(...)) is kept as a ${...} placeholder in the diagram; function calls and operators also print a warning: on stderr. These are not evaluated, and fail with a message saying what to do instead: templatefile(), file(), a bare reference such as local.definition, %{ } template directives, and state machines defined through a module block. For those, render the ASL file directly. See Extracting ASL from Terraform.

--format png needs the optional @resvg/resvg-js peer. It is not installed by default. With npx, run npx --package sfn-diagram --package @resvg/resvg-js sfn-diagram …; in a project, npm install @resvg/resvg-js. Without it the CLI exits with an actionable error. Or skip the install entirely with the Docker image, which ships it preinstalled.

A --format html document inlines the raw ASL of every state, so the detail panel can print it when a state is clicked. That ASL can carry things you don’t want to share: Parameters holding an account id, Arguments naming a secret, Credentials. Two flags keep it out, both reading the same redaction hook the library offers as redact:

Terminal window
# Inline "[redacted]" in place of these fields, wherever they appear
npx sfn-diagram state.asl.json --format html --redact-fields Parameters,Arguments,Credentials -o share.html
# Inline no state's ASL at all; the panel shows "[redacted]" for every state
npx sfn-diagram state.asl.json --format html --no-raw-state -o share.html

How --redact-fields matches:

  • A name matches a key exactly and case-sensitively: parameters does not match Parameters. A name that matches nothing is not an error, so check the spelling.
  • It matches at any depth, so Token also reaches Parameters.Token, and a nested state’s copy inside its Parallel or Map container is caught as well as its own entry.
  • Payload also matches Payload.$, the same field with a dynamic value.
  • A dotted name names a nested key: Parameters.Token redacts only that key and keeps the rest of Parameters. Array items are named by index, so Catch.Next does not reach into Catch’s list: Catch[0].Next names the first catcher’s target only, and there is no wildcard. To reach every item, use the bare name (Next), which also matches every other Next.
  • A state’s own entry is never matched by its name, so a state called Parameters keeps its entry. Inside its Parallel or Map container’s copy, though, a nested state’s name is a key like any other: --redact-fields Parameters redacts the whole copy of a nested state named Parameters, and --redact-fields Catch.Next the Next of one named Catch.
  • Matching runs on the joined path, so a key that itself contains a . or [ can be matched too ("a.Next" by Next). That only ever redacts more, never less.
  • It is repeatable, and a comma inside a name is written \,.

The two flags combine, and the config file can set them too (redactFields, includeRawState); the file and the flags add up rather than one overriding the other. Both apply to --format html only: given with another format they exit 2 (--check ignores them), and set in the config file they are ignored for other formats. Other formats never inline raw ASL.

What they do not cover: they redact the detail panel’s copy of the ASL, nothing else. Anything the diagram derives from the ASL is not redacted, and it travels in the document even where it is not drawn: in the drawn SVG, the embedded Mermaid source, the collapse model, and the edge data the edge panel prints. Treat every field that shapes a node, edge or container label as shipped as-is. Field values the diagram draws are generally strings, paths and expressions, and for an object such as JSONata Arguments, Output or a Map’s ItemSelector, its key names; a string, array or other non-object value is drawn as itself, shortened with … when it is long. A label cut short on screen usually still ships in full, in the node’s or edge’s <title>, the Mermaid source or the edge data. Examples:

  • state names, and the machine-level and per-state Comment (a state’s Comment is its node label unless --hide-comments; --redact-fields Comment blanks the panel copy, not the label)
  • a Fail state’s Error, Cause and their *Path forms, Choice conditions, Retry and Catch ErrorEquals, and Retry MaxAttempts, IntervalSeconds, BackoffRate, MaxDelaySeconds and JitterStrategy (the retry loop’s <title> and edge data)
  • Wait Seconds/Timestamp, literal or expression, and their *Path forms, and Task TimeoutSeconds/HeartbeatSeconds and their *Path forms
  • Map ItemsPath, JSONata Items, Label, ItemSelector, MaxConcurrency and MaxConcurrencyPath, ToleratedFailure* and their *Path forms, ItemBatcher limits, and whether a Distributed Map’s ExecutionType is EXPRESS
  • Task Resource, and a Distributed Map’s ItemReader/ResultWriter Resource
  • Assign variable names, and JSONata Arguments and Output (--redact-fields Arguments blanks the panel copy, not the args … label)

Not drawn does not mean not shipped, so checking a rendered SVG is not enough: a value can sit in the Mermaid source or the edge data without being drawn. Keep anything that must not be shared out of those fields. An execution overlay’s error names are not touched either; the CLI inlines no other execution payload. For anything beyond field names, use the library’s redact hook directly.

--check runs lintAsl on the input and prints every finding to stderr instead of a diagram. The exit code is 1 when any finding is an error, 0 otherwise, so it drops straight into a pre-commit hook or CI step:

Terminal window
npx sfn-diagram state.asl.json --check
error /States/Ship/Next State "Ship" sets both "End: true" and "Next" [end-with-next]
warning /States/Audit State "Audit" is unreachable from StartAt "Validate" [unreachable-state]
1 error, 1 warning

Each line is severity, a JSON Pointer to the offending value, the message, and the rule code. --resolve-cfn / --resource work the same way they do for rendering; --check cannot be combined with --diff, --execution or --output.

--check-format json writes the findings as one JSON document on stdout instead of lines on stderr, for CI annotations, editors and other tools. --check-format text is the default. The flag only applies with --check; without it the run exits 2.

Terminal window
npx sfn-diagram 'machines/*.asl.json' --check --check-format json

The document is a single line; here it is pretty-printed:

{
"files": [
{
"file": "machines/order.asl.json",
"diagnostics": [
{
"code": "end-with-next",
"message": "State \"Ship\" sets both \"End: true\" and \"Next\"",
"path": "/States/Ship/Next",
"severity": "error"
}
],
"kind": "lint",
"warnings": []
},
{
"file": "machines/missing.asl.json",
"kind": "error",
"message": "Failed to read input: ENOENT: no such file or directory, open '/work/machines/missing.asl.json'",
"warnings": []
}
]
}

There is one entry per input, in the order the inputs were read:

  • file is the path as given (or as a glob expanded it), the ARN for --from-aws, and null for stdin.
  • resource appears only for a state machine from a CDK cloud assembly directory. It is the machine’s logical ID, and file is its template, so sfn-diagram <file> --resource <resource> lints the same machine again.
  • kind is "lint" when the input was linted, or "error" when it could not be read or a state machine could not be extracted from it; message then says why.
  • diagnostics holds the linter’s findings, each with the rule code, the message, a JSON Pointer path to the offending value ("" for the whole definition) and a severity of "error" or "warning".
  • warnings holds template and Terraform extraction warnings, the ones a render prints as warning: …. They are not lint findings and never affect the exit code.

The exit codes are the same as in text mode: 1 when any input has an error-severity diagnostic or a kind: "error" entry, 0 otherwise. Nothing about individual inputs goes to stderr. A failure before any input is read, such as an invalid config file or a glob that matches nothing, prints its message to stderr and writes no document.

Under --watch, each pass writes its own document on its own line (JSON Lines), and each one covers only the inputs that pass re-linted.

To print one line per finding, pipe the document to jq. Set pipefail first: without it the pipeline’s exit code is jq’s, and the 1 from a failed check is lost.

Terminal window
set -o pipefail
npx sfn-diagram 'machines/*.asl.json' --check --check-format json |
jq -r '.files[] | .file as $f | .diagnostics[]? | "\($f): \(.severity) \(.path) \(.code)"'
Code Severity What it catches
invalid-json error The definition string is not valid JSON
invalid-structure error The definition or a nested scope is not an object, or lacks StartAt / States
invalid-state-type error A state’s Type is missing or not one of the eight ASL state types
invalid-field error A field has the wrong type (Next not a string, Choices not an array, …)
missing-transition error A non-terminal state has neither Next nor End: true, or a Choices[] rule or Catch[] entry has no Next
dangling-transition error StartAt, Next, Default, Choices[].Next or Catch[].Next names a state that does not exist in its scope
unreachable-state warning No path from the scope’s StartAt leads to the state
choice-without-choices error A Choice has no Choices, or an empty array
choice-without-default warning A Choice has no Default, so an unmatched input fails the execution
duplicate-state-name warning The same state name is used in more than one States block
end-with-next error A state sets both End: true and Next
unsupported-transition error Next or End on a Choice, Succeed or Fail state
unsupported-retry-catch error Retry or Catch on a state type other than Task, Parallel or Map
wait-without-duration error A Wait sets none of Seconds, SecondsPath, Timestamp, TimestampPath
wait-multiple-durations error A Wait sets more than one of those four fields
fail-conflicting-fields error A Fail sets both Error and ErrorPath, or both Cause and CausePath
state-name-too-long error A state name is longer than 80 characters (counted in Unicode code points)
query-language-mismatch error A JSONPath-only field in a JSONata state, or a JSONata-only field in a JSONPath state

Details and the API are on the lintAsl reference.

sfn-diagram comment gitlab posts (or updates) a diagram/diff on a GitLab merge request from CI — see GitLab CI for the full workflow, the options, and the Mermaid size limit it works around.

Terminal window
sfn-diagram comment gitlab --help

sfn-diagram serve renders and lints over HTTP: POST a definition to /render with these flags (minus the --) as query parameters, and get the diagram back. See Render diagrams over HTTP for the endpoints, the status codes, and examples in curl, Python and Go.

Terminal window
sfn-diagram serve --port 8080
curl --data-binary @state.asl.json 'http://127.0.0.1:8080/render?format=svg&layout=LR'

A prebuilt image is published to GitHub Container Registry with the PNG rasterizer preinstalled, so --format png works out of the box — no browser, no extra install:

Terminal window
docker run --rm -v "$PWD":/work ghcr.io/yusufaf/sfn-diagram:latest \
/work/state.asl.json --format svg -o /work/diagram.svg
docker run --rm -v "$PWD":/work ghcr.io/yusufaf/sfn-diagram:latest \
/work/state.asl.json --format png -o /work/diagram.png

Tags: latest, <major>, <major>.<minor>, <major>.<minor>.<patch>.

The newest release’s tags are rebuilt every week to pick up base-image security fixes, so a tag’s digest changes over time. To freeze an image, pin it by digest (ghcr.io/yusufaf/sfn-diagram@sha256:…). Older versions’ tags are not rebuilt.

From 1.10.0 the image ships no npm, npx, corepack or yarn: it runs the CLI and nothing else. From 2.0 the image is based on Alpine Linux (node:24-alpine): add OS packages in a derived image with apk add, or start FROM node:24-alpine (or node:24-slim) to build your own image with npm packages. See Migrating to 2.0.

The same image is mirrored to Docker Hub as azulaf/sfn-diagram from 1.9.0 on — same tags, same image digest. Prefer ghcr.io in CI: Docker Hub rate-limits anonymous pulls, which shared runners can hit.

PNG text is rendered with Liberation Sans, which the image ships. To use your own fonts, mount them and point the renderer at them with SFN_DIAGRAM_PNG_FONT_DIRS (a :-separated list of directories) or SFN_DIAGRAM_PNG_FONT_FAMILY.

When an exact font file is known — the built-in per-platform default, which is the Liberation Sans the image ships — the renderer loads only that file and skips parsing every installed system font, saving around 250ms per export. Pointing SFN_DIAGRAM_PNG_FONT_DIRS at a directory keeps the scan on, because a directory that exists may hold no font the renderer can parse.

Text that needs glyphs the one resolved font is unlikely to have — CJK, emoji, or the ↻ in a retry-count label — turns the scan back on by itself, so those render rather than coming out as tofu. Pass --load-system-fonts (or set SFN_DIAGRAM_PNG_LOAD_SYSTEM_FONTS=true) to force it on regardless; the flag wins when both are set. Accepted values for the variable are 1/true/yes/on and 0/false/no/off; anything else is an error rather than being ignored. See PNG fonts for the full resolution order and what the single-file path gives up.

Each core release from v1.6.0 on attaches single-file executables for Linux (x64, arm64), macOS (Apple silicon, Intel), and Windows (x64) that need no Node.js. See CLI without Node for where to download them.

A few flags are unavailable there, all because a single-file executable has no node_modules to load an optional peer dependency from. Each exits 2 with a pointer rather than failing obscurely:

Flag Needs Instead
--format png @resvg/resvg-js (a native rasterizer) npx --package sfn-diagram --package @resvg/resvg-js sfn-diagram …
--from-aws, --diff <arn>, --execution <arn> @aws-sdk/client-sfn npx --package sfn-diagram --package @aws-sdk/client-sfn sfn-diagram …
comment gitlab --execution-mode latest / latest-failed @aws-sdk/client-sfn npx --package sfn-diagram --package @aws-sdk/client-sfn sfn-diagram comment gitlab …

Everything else works, including SVG, Mermaid and HTML output, --diff against a local file, --execution against a saved history file, --check, templates, --out-dir, and comment gitlab without an execution overlay.

Terminal window
brew install yusufaf/tap/sfn-diagram
# or download sfn-diagram-<os>-<arch> from a core release and chmod +x it

They support every format except png: the native rasterizer it needs cannot be bundled into a single-file executable. Use the Docker image above or the npm package with @resvg/resvg-js installed. See Use from Python, Go, Java, and other languages.