sfn-diagram 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,11 +8,62 @@ Generate beautiful, interactive diagrams from AWS Step Functions ASL (Amazon Sta
8
8
 
9
9
  **▶ [Try it in the live playground](https://yusufaf.github.io/sfn-diagram/)** — paste any ASL definition and preview the diagram instantly, no install required.
10
10
 
11
+ ## What it looks like
12
+
13
+ Give it an ASL definition like this order-processing workflow ([`examples/order-processing.asl.json`](examples/order-processing.asl.json)):
14
+
15
+ ```jsonc
16
+ {
17
+ "StartAt": "ValidateOrder",
18
+ "States": {
19
+ "ValidateOrder": { "Type": "Pass", "Next": "CheckStock" },
20
+ "CheckStock": {
21
+ "Type": "Choice",
22
+ "Choices": [{ "Variable": "$.inStock", "BooleanEquals": true, "Next": "ChargePayment" }],
23
+ "Default": "CancelOrder"
24
+ },
25
+ "ChargePayment": { "Type": "Task", "Resource": "arn:aws:lambda:...:charge-payment", "Next": "ShipOrder" },
26
+ "ShipOrder": { "Type": "Task", "Resource": "arn:aws:lambda:...:ship-order", "Next": "OrderComplete" },
27
+ "CancelOrder": { "Type": "Fail", "Error": "OutOfStock" },
28
+ "OrderComplete": { "Type": "Succeed" }
29
+ }
30
+ }
31
+ ```
32
+
33
+ …and `generateMermaid` turns it into a diagram GitHub renders inline (the same code also drives SVG and PNG output):
34
+
35
+ ```mermaid
36
+ stateDiagram-v2
37
+
38
+ [*] --> ValidateOrder
39
+ ValidateOrder --> CheckStock
40
+ CheckStock --> ChargePayment: $.inStock == true
41
+ CheckStock --> CancelOrder: Default
42
+ ChargePayment --> ShipOrder
43
+ ShipOrder --> OrderComplete
44
+
45
+ CancelOrder --> [*]
46
+ OrderComplete --> [*]
47
+
48
+ classDef successState fill:#e8f5e8,stroke:#4caf50,stroke-width:3px
49
+ classDef failState fill:#ffebee,stroke:#f44336,stroke-width:3px
50
+ classDef choiceState fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
51
+ classDef taskState fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
52
+
53
+ class CheckStock choiceState
54
+ class ChargePayment taskState
55
+ class ShipOrder taskState
56
+ class CancelOrder failState
57
+ class OrderComplete successState
58
+ ```
59
+
11
60
  ## Features
12
61
 
13
62
  - **Multiple Output Formats**: SVG (D3.js), Mermaid syntax, and PNG
14
63
  - **Automatic Layout**: Smart graph positioning using Dagre layout engine
15
- - **Full ASL Support**: All state types (Pass, Task, Choice, Wait, Succeed, Fail, Parallel, Map)
64
+ - **Full ASL Support**: All state types (Pass, Task, Choice, Wait, Succeed, Fail, Parallel, Map), both JSONPath and JSONata query languages, plus `Catch`/`Retry` rendering
65
+ - **Visual Diffing**: Compare two definitions and highlight added / modified / removed states — drives the PR-preview GitHub Action
66
+ - **Execution Overlays**: Paint a real execution's history onto the diagram — succeeded/failed/caught/not-reached states, the taken path, and per-state duration & retry counts
16
67
  - **Customizable Themes**: AWS light/dark themes plus custom theme support
17
68
  - **Flexible Layouts**: Top-bottom, left-right, right-left, bottom-top
18
69
  - **Type-Safe**: Full TypeScript support with comprehensive type definitions
@@ -26,6 +77,12 @@ Generate beautiful, interactive diagrams from AWS Step Functions ASL (Amazon Sta
26
77
  npm install sfn-diagram
27
78
  ```
28
79
 
80
+ The core package pulls in **no browser engine** — SVG and Mermaid generation stay lightweight. PNG export relies on a headless browser, provided by the optional peer dependency `node-html-to-image`. Install it only if you use `sfn-diagram/png`:
81
+
82
+ ```bash
83
+ npm install sfn-diagram node-html-to-image
84
+ ```
85
+
29
86
  ## Runtime Support
30
87
 
31
88
  The core entry (`sfn-diagram`) builds SVG with a DOM-free string renderer, so
@@ -34,7 +91,9 @@ run in **Node, browsers, and edge runtimes** (Cloudflare Workers, Vercel Edge, D
34
91
  with no DOM polyfill.
35
92
 
36
93
  PNG export (`sfn-diagram/png`) and the CLI are **Node-only** — they rely on a headless
37
- browser (`node-html-to-image`) and Node's filesystem respectively.
94
+ browser (`node-html-to-image`) and Node's filesystem respectively. Because `node-html-to-image`
95
+ is an **optional peer dependency**, install it alongside `sfn-diagram` when you need PNG output;
96
+ `exportPng` throws an actionable error if it is missing.
38
97
 
39
98
  ```ts
40
99
  // Works in Node, browser, and edge:
@@ -214,6 +273,125 @@ const { svg } = generateFromAwsResponse({
214
273
  });
215
274
  ```
216
275
 
276
+ ### generateMermaidDiff(params) / generateDiff(params)
277
+
278
+ Compare two ASL definitions and highlight what changed. `generateMermaidDiff` returns Mermaid code (renders inline on GitHub); `generateDiff` returns the same comparison as an SVG. Added states are green, modified yellow, removed red — and both return a `metadata` change summary (`added`, `modified`, `removed`, `unchanged`). The comparison is order-insensitive, so reordering a state's properties is **not** flagged as a change.
279
+
280
+ ```typescript
281
+ import { generateMermaidDiff } from 'sfn-diagram';
282
+
283
+ const { code, metadata } = generateMermaidDiff({
284
+ before: baseAsl, // old (base) ASL definition, object or JSON string
285
+ after: headAsl, // new (head) ASL definition, object or JSON string
286
+ });
287
+
288
+ metadata; // { added: [...], modified: [...], removed: [...], unchanged: [...], stateCount, edgeCount }
289
+ ```
290
+
291
+ For the order-processing workflow above, adding a `FraudCheck` step, bumping `ChargePayment`'s resource, and dropping `CancelOrder` renders like this:
292
+
293
+ ```mermaid
294
+ stateDiagram-v2
295
+
296
+ [*] --> ValidateOrder
297
+ ValidateOrder --> CheckStock
298
+ CheckStock --> ChargePayment: $.inStock == true
299
+ CheckStock --> OrderComplete: Default
300
+ ChargePayment --> FraudCheck
301
+ FraudCheck --> ShipOrder
302
+ ShipOrder --> OrderComplete
303
+
304
+ OrderComplete --> [*]
305
+ CancelOrder --> [*]
306
+
307
+ classDef diffAdded fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
308
+ classDef diffModified fill:#fff9c4,stroke:#f57f17,stroke-width:2px
309
+ classDef diffRemoved fill:#ffcdd2,stroke:#c62828,stroke-width:2px
310
+
311
+ class FraudCheck diffAdded
312
+ class CheckStock diffModified
313
+ class ChargePayment diffModified
314
+ class CancelOrder diffRemoved
315
+ ```
316
+
317
+ > This is exactly what the [GitHub Action](#github-action) posts on pull requests that touch ASL files.
318
+
319
+ ### generateExecution(params) / generateMermaidExecution(params)
320
+
321
+ Overlay a **real execution** onto the diagram. Where the diff shows how a definition
322
+ _changed_, the execution overlay shows what one _run_ actually did: which path it took,
323
+ which states succeeded (green), failed (red), were caught and recovered (orange), or were
324
+ never reached (grey) — plus per-state duration and retry counts.
325
+
326
+ Pass the ASL definition plus the execution's history. `history` accepts the events array
327
+ from `GetExecutionHistory`, the raw command output, or a JSON string of either — so the
328
+ core stays credential-free and runs in the browser.
329
+
330
+ ```typescript
331
+ import { generateExecution, generateMermaidExecution } from 'sfn-diagram';
332
+
333
+ // history: events from `aws stepfunctions get-execution-history`, or the SDK response
334
+ const { svg, metadata } = generateExecution({ aslDefinition: asl, history });
335
+
336
+ metadata;
337
+ // { succeeded: [...], failed: [...], caught: [...], notReached: [...], running: [...],
338
+ // takenEdgeCount, executionStatus, nodeCount, edgeCount }
339
+
340
+ // Mermaid variant (states coloured + duration/retry annotations in labels):
341
+ const { code } = generateMermaidExecution({ aslDefinition: asl, history });
342
+ ```
343
+
344
+ > **Note:** Mermaid `stateDiagram-v2` cannot style individual transitions, so taken-path
345
+ > emphasis in Mermaid is expressed through node colours and label annotations. The SVG
346
+ > overlay additionally dims the transitions the run did not take.
347
+
348
+ Need just the data (no rendering)? `parseExecutionHistory({ events })` returns the pure
349
+ `ExecutionOverlay` model — per-state status, attempts, duration, and the taken edges — for
350
+ building your own UI.
351
+
352
+ ```typescript
353
+ import { parseExecutionHistory } from 'sfn-diagram';
354
+
355
+ const overlay = parseExecutionHistory({ events });
356
+ overlay.states['ProcessOrder']; // { status: 'succeeded', attempts: 1, durationMs: 1250 }
357
+ overlay.takenEdges; // [{ from: 'ValidateOrder', to: 'ProcessOrder' }, ...]
358
+ ```
359
+
360
+ Fetching history from AWS (Node) — use the `sfn-diagram/aws` helper, which paginates `GetExecutionHistory` for you:
361
+
362
+ ```typescript
363
+ import { SFNClient } from '@aws-sdk/client-sfn';
364
+ import { fetchExecutionHistory } from 'sfn-diagram/aws';
365
+
366
+ const client = new SFNClient({ region: 'us-east-1' });
367
+ const events = await fetchExecutionHistory({ client, executionArn });
368
+
369
+ const { svg } = generateExecution({ aslDefinition: asl, history: events });
370
+ ```
371
+
372
+ `sfn-diagram/aws` is a Node-only subpath. `@aws-sdk/client-sfn` is an **optional peer dependency** — install it yourself (`npm i @aws-sdk/client-sfn`); the core `sfn-diagram` package stays dependency-free and browser-safe.
373
+
374
+ <details>
375
+ <summary>Prefer to paginate yourself? The manual loop:</summary>
376
+
377
+ ```typescript
378
+ import { SFNClient, GetExecutionHistoryCommand } from '@aws-sdk/client-sfn';
379
+
380
+ const client = new SFNClient({ region: 'us-east-1' });
381
+ const events = [];
382
+ let nextToken;
383
+ do {
384
+ const page = await client.send(
385
+ new GetExecutionHistoryCommand({ executionArn, nextToken, maxResults: 1000 }),
386
+ );
387
+ events.push(...(page.events ?? []));
388
+ nextToken = page.nextToken;
389
+ } while (nextToken);
390
+
391
+ const { svg } = generateExecution({ aslDefinition: asl, history: events });
392
+ ```
393
+ </details>
394
+
217
395
  ### SfnDiagramGenerator Class
218
396
 
219
397
  Reusable generator that holds diagram options once and applies them to every call. Configure options via the constructor or the fluent `setOptions()` method; pass the `aslDefinition` per generation.
@@ -251,23 +429,34 @@ const mermaidResult = generator.generateMermaid({ aslDefinition: asl });
251
429
  - `'dark'` - AWS dark theme
252
430
 
253
431
  **Custom theme:**
432
+
433
+ A `CustomTheme` sets the background, per-state-type fill/stroke colours, edge colours, and typography. Pass it anywhere a theme is accepted.
434
+
254
435
  ```typescript
255
- const customTheme = {
256
- backgroundColor: '#ffffff',
257
- nodeStroke: '#232f3e',
258
- nodeStrokeWidth: 2,
259
- fontSize: 14,
436
+ import type { CustomTheme } from 'sfn-diagram';
437
+
438
+ const customTheme: CustomTheme = {
439
+ background: '#ffffff',
440
+ edgeColors: {
441
+ choice: '#7b1fa2',
442
+ default: '#607d8b',
443
+ error: '#f44336',
444
+ normal: '#232f3e',
445
+ retry: '#f9a825', // optional; falls back to `error` when omitted
446
+ },
260
447
  fontFamily: 'Arial, sans-serif',
261
- stateColors: {
262
- Pass: '#4CAF50',
263
- Task: '#2196F3',
264
- Choice: '#FF9800',
265
- Wait: '#9C27B0',
266
- Succeed: '#4CAF50',
267
- Fail: '#F44336',
268
- Parallel: '#00BCD4',
269
- Map: '#3F51B5'
270
- }
448
+ fontSize: 14,
449
+ nodeColors: {
450
+ Pass: { fill: '#e8f5e9', stroke: '#4caf50' },
451
+ Task: { fill: '#e3f2fd', stroke: '#2196f3' },
452
+ Choice: { fill: '#fff3e0', stroke: '#ff9800' },
453
+ Wait: { fill: '#f3e5f5', stroke: '#9c27b0' },
454
+ Succeed: { fill: '#e8f5e9', stroke: '#4caf50' },
455
+ Fail: { fill: '#ffebee', stroke: '#f44336' },
456
+ Parallel: { fill: '#e0f7fa', stroke: '#00bcd4' },
457
+ Map: { fill: '#e8eaf6', stroke: '#3f51b5' },
458
+ },
459
+ textColor: '#232f3e',
271
460
  };
272
461
 
273
462
  generateSvg({ aslDefinition: asl, theme: customTheme });
@@ -363,7 +552,16 @@ All AWS Step Functions state types are fully supported:
363
552
  | **Succeed** | Circle | Terminates successfully |
364
553
  | **Fail** | Circle | Terminates with failure |
365
554
  | **Parallel** | Rectangle | Executes branches in parallel |
366
- | **Map** | Rectangle | Iterates over array items |
555
+ | **Map** | Rectangle | Iterates over array items (legacy `Iterator` and modern `ItemProcessor`/Distributed Map) |
556
+
557
+ ### Error handling & retries
558
+
559
+ - **`Catch`** blocks render as dashed error edges to their handler states.
560
+ - **`Retry`** policies render as a labelled self-loop on the state (e.g. `↻ States.Timeout (4x); States.ALL (2x)`) — a self-transition in Mermaid output.
561
+
562
+ ### Query languages
563
+
564
+ Both JSONPath and JSONata (`QueryLanguage: "JSONata"`) definitions are supported. Choice branch labels are derived from JSONPath comparison operators (`$.score >= 90`, `And`/`Or`/`Not`, `Is*` checks) or from JSONata `Condition` expressions, whichever the state uses.
367
565
 
368
566
  ## Examples
369
567
 
@@ -514,7 +712,7 @@ pnpm install
514
712
  pnpm dev
515
713
  ```
516
714
 
517
- Paste any ASL JSON, switch themes, and see the SVG diagram update instantly — no install required beyond the dev server.
715
+ Paste any ASL JSON, switch themes, and see the SVG diagram update instantly — no install required beyond the dev server. Switch **Mode** to _Execution overlay_ to paste an execution history alongside the definition and watch the run's path light up.
518
716
 
519
717
  ### VS Code Extension
520
718
 
@@ -530,28 +728,53 @@ code --install-extension vscode-sfn-diagram-*.vsix
530
728
 
531
729
  **Usage:** Open any `.json` or `.asl` file and run **Step Functions: Preview Step Functions Diagram** from the command palette, or click the diagram icon in the editor title bar.
532
730
 
731
+ ### React Component
732
+
733
+ Render diagrams in a React app with the [`sfn-diagram-react`](packages/sfn-diagram-react/) package. It wraps `generateSvg`/`generateMermaid` in a component with the same platform-agnostic core, so it works in any React renderer.
734
+
735
+ ```tsx
736
+ import { SfnDiagram } from 'sfn-diagram-react';
737
+
738
+ <SfnDiagram
739
+ definition={asl} // ASL object or JSON string
740
+ format="svg" // 'svg' (default) | 'mermaid'
741
+ theme="dark" // 'light' | 'dark' | CustomTheme
742
+ layout="LR" // 'TB' | 'LR' | 'RL' | 'BT'
743
+ history={history} // optional: renders an execution overlay
744
+ onError={(err) => console.error(err)}
745
+ />
746
+ ```
747
+
533
748
  ### GitHub Action
534
749
 
535
- Post SVG diff previews and Mermaid diagrams as PR comments whenever ASL files change. Located in [`packages/github-action-sfn-diagram/`](packages/github-action-sfn-diagram/).
750
+ Comment a Step Functions diagram on every pull request that touches an ASL file. For **changed** files the comment highlights the diff added states green, modified yellow, removed red — plus a summary table of what changed; **new** and **deleted** files get a plain diagram. Everything is Mermaid, so it renders inline in the PR with no image hosting. The comment is upserted (updated in place) on each push.
751
+
752
+ Available on the [GitHub Marketplace](https://github.com/marketplace/actions/step-functions-diagram-preview) as [`yusufaf/sfn-diagram-action`](https://github.com/yusufaf/sfn-diagram-action) — pin the moving major tag `@v1`. (Source lives here in [`packages/github-action-sfn-diagram/`](packages/github-action-sfn-diagram/); the Marketplace repo is generated from it.)
536
753
 
537
754
  ```yaml
538
755
  # .github/workflows/sfn-preview.yml
539
756
  name: Step Functions Preview
540
757
  on:
541
758
  pull_request:
542
- paths: ['**/*.asl.json']
759
+ paths: ['**/*.asl.json', '**/*.asl']
760
+
761
+ permissions:
762
+ contents: read
763
+ pull-requests: write # required to post the comment
543
764
 
544
765
  jobs:
545
766
  preview:
546
767
  runs-on: ubuntu-latest
547
768
  steps:
548
- - uses: actions/checkout@v4
549
- with: { fetch-depth: 0 }
550
- - uses: ./packages/github-action-sfn-diagram
551
- with:
552
- github-token: ${{ secrets.GITHUB_TOKEN }}
769
+ - uses: actions/checkout@v5
770
+ with: { fetch-depth: 0 } # needed to diff base vs head
771
+ - uses: yusufaf/sfn-diagram-action@v1
553
772
  ```
554
773
 
774
+ Inputs: `github-token` (defaults to `${{ github.token }}`), `asl-glob` (comma-separated globs, default `**/*.asl.json,**/*.asl`), `comment-tag` (marker used to find/update the comment, default `sfn-diagram-preview`).
775
+
776
+ Optionally overlay a real run: set `execution-mode` (`latest` or `latest-failed`) and `state-machine-arn` to append the most recent (or most recent failed) execution as a Mermaid overlay beneath the diff. This is opt-in (`off` by default), needs AWS credentials (`states:ListExecutions` + `states:GetExecutionHistory`), and applies when exactly one ASL file changed — see the [action README](packages/github-action-sfn-diagram/README.marketplace.md) for a full workflow.
777
+
555
778
  ## Contributing
556
779
 
557
780
  Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
package/dist/aws.cjs ADDED
@@ -0,0 +1,50 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _aws_sdk_client_sfn = require("@aws-sdk/client-sfn");
3
+ //#region src/aws.ts
4
+ /**
5
+ * Node-only AWS convenience helpers for `sfn-diagram`.
6
+ *
7
+ * This subpath (`sfn-diagram/aws`) is isolated from the core entry so that
8
+ * importing `sfn-diagram` never pulls in `@aws-sdk/client-sfn`, keeping the core
9
+ * dependency-free and browser-safe. `@aws-sdk/client-sfn` is an optional peer
10
+ * dependency — install it yourself to use these helpers.
11
+ */
12
+ /**
13
+ * Fetches the complete history of a Step Functions execution, paginating through
14
+ * every `GetExecutionHistory` page so callers don't have to hand-roll the
15
+ * `nextToken` loop.
16
+ *
17
+ * The returned `HistoryEvent[]` can be passed straight to `parseExecutionHistory`,
18
+ * `generateExecution`, or `generateMermaidExecution` from `sfn-diagram`.
19
+ *
20
+ * @param params - The SFN client, execution ARN, and optional page size.
21
+ * @returns All history events for the execution, in chronological order.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { SFNClient } from '@aws-sdk/client-sfn';
26
+ * import { fetchExecutionHistory } from 'sfn-diagram/aws';
27
+ * import { generateExecution } from 'sfn-diagram';
28
+ *
29
+ * const client = new SFNClient({ region: 'us-east-1' });
30
+ * const events = await fetchExecutionHistory({ client, executionArn });
31
+ * const { svg } = generateExecution({ aslDefinition: asl, history: events });
32
+ * ```
33
+ */
34
+ async function fetchExecutionHistory(params) {
35
+ const { client, executionArn, maxResults = 1e3 } = params;
36
+ const events = [];
37
+ let nextToken;
38
+ do {
39
+ const page = await client.send(new _aws_sdk_client_sfn.GetExecutionHistoryCommand({
40
+ executionArn,
41
+ maxResults,
42
+ nextToken
43
+ }));
44
+ events.push(...page.events ?? []);
45
+ nextToken = page.nextToken;
46
+ } while (nextToken);
47
+ return events;
48
+ }
49
+ //#endregion
50
+ exports.fetchExecutionHistory = fetchExecutionHistory;
package/dist/aws.d.cts ADDED
@@ -0,0 +1,36 @@
1
+ import { HistoryEvent, SFNClient } from "@aws-sdk/client-sfn";
2
+
3
+ //#region src/aws.d.ts
4
+ interface FetchExecutionHistoryParams {
5
+ /** A caller-constructed SFN client (with the caller's credentials/region). */
6
+ client: SFNClient;
7
+ /** ARN of the execution whose history should be fetched. */
8
+ executionArn: string;
9
+ /** Page size passed to `GetExecutionHistory`. Defaults to 1000 (the AWS max). */
10
+ maxResults?: number;
11
+ }
12
+ /**
13
+ * Fetches the complete history of a Step Functions execution, paginating through
14
+ * every `GetExecutionHistory` page so callers don't have to hand-roll the
15
+ * `nextToken` loop.
16
+ *
17
+ * The returned `HistoryEvent[]` can be passed straight to `parseExecutionHistory`,
18
+ * `generateExecution`, or `generateMermaidExecution` from `sfn-diagram`.
19
+ *
20
+ * @param params - The SFN client, execution ARN, and optional page size.
21
+ * @returns All history events for the execution, in chronological order.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { SFNClient } from '@aws-sdk/client-sfn';
26
+ * import { fetchExecutionHistory } from 'sfn-diagram/aws';
27
+ * import { generateExecution } from 'sfn-diagram';
28
+ *
29
+ * const client = new SFNClient({ region: 'us-east-1' });
30
+ * const events = await fetchExecutionHistory({ client, executionArn });
31
+ * const { svg } = generateExecution({ aslDefinition: asl, history: events });
32
+ * ```
33
+ */
34
+ declare function fetchExecutionHistory(params: FetchExecutionHistoryParams): Promise<HistoryEvent[]>;
35
+ //#endregion
36
+ export { FetchExecutionHistoryParams, fetchExecutionHistory };
package/dist/aws.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { HistoryEvent, SFNClient } from "@aws-sdk/client-sfn";
2
+
3
+ //#region src/aws.d.ts
4
+ interface FetchExecutionHistoryParams {
5
+ /** A caller-constructed SFN client (with the caller's credentials/region). */
6
+ client: SFNClient;
7
+ /** ARN of the execution whose history should be fetched. */
8
+ executionArn: string;
9
+ /** Page size passed to `GetExecutionHistory`. Defaults to 1000 (the AWS max). */
10
+ maxResults?: number;
11
+ }
12
+ /**
13
+ * Fetches the complete history of a Step Functions execution, paginating through
14
+ * every `GetExecutionHistory` page so callers don't have to hand-roll the
15
+ * `nextToken` loop.
16
+ *
17
+ * The returned `HistoryEvent[]` can be passed straight to `parseExecutionHistory`,
18
+ * `generateExecution`, or `generateMermaidExecution` from `sfn-diagram`.
19
+ *
20
+ * @param params - The SFN client, execution ARN, and optional page size.
21
+ * @returns All history events for the execution, in chronological order.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { SFNClient } from '@aws-sdk/client-sfn';
26
+ * import { fetchExecutionHistory } from 'sfn-diagram/aws';
27
+ * import { generateExecution } from 'sfn-diagram';
28
+ *
29
+ * const client = new SFNClient({ region: 'us-east-1' });
30
+ * const events = await fetchExecutionHistory({ client, executionArn });
31
+ * const { svg } = generateExecution({ aslDefinition: asl, history: events });
32
+ * ```
33
+ */
34
+ declare function fetchExecutionHistory(params: FetchExecutionHistoryParams): Promise<HistoryEvent[]>;
35
+ //#endregion
36
+ export { FetchExecutionHistoryParams, fetchExecutionHistory };
package/dist/aws.js ADDED
@@ -0,0 +1,49 @@
1
+ import { GetExecutionHistoryCommand } from "@aws-sdk/client-sfn";
2
+ //#region src/aws.ts
3
+ /**
4
+ * Node-only AWS convenience helpers for `sfn-diagram`.
5
+ *
6
+ * This subpath (`sfn-diagram/aws`) is isolated from the core entry so that
7
+ * importing `sfn-diagram` never pulls in `@aws-sdk/client-sfn`, keeping the core
8
+ * dependency-free and browser-safe. `@aws-sdk/client-sfn` is an optional peer
9
+ * dependency — install it yourself to use these helpers.
10
+ */
11
+ /**
12
+ * Fetches the complete history of a Step Functions execution, paginating through
13
+ * every `GetExecutionHistory` page so callers don't have to hand-roll the
14
+ * `nextToken` loop.
15
+ *
16
+ * The returned `HistoryEvent[]` can be passed straight to `parseExecutionHistory`,
17
+ * `generateExecution`, or `generateMermaidExecution` from `sfn-diagram`.
18
+ *
19
+ * @param params - The SFN client, execution ARN, and optional page size.
20
+ * @returns All history events for the execution, in chronological order.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { SFNClient } from '@aws-sdk/client-sfn';
25
+ * import { fetchExecutionHistory } from 'sfn-diagram/aws';
26
+ * import { generateExecution } from 'sfn-diagram';
27
+ *
28
+ * const client = new SFNClient({ region: 'us-east-1' });
29
+ * const events = await fetchExecutionHistory({ client, executionArn });
30
+ * const { svg } = generateExecution({ aslDefinition: asl, history: events });
31
+ * ```
32
+ */
33
+ async function fetchExecutionHistory(params) {
34
+ const { client, executionArn, maxResults = 1e3 } = params;
35
+ const events = [];
36
+ let nextToken;
37
+ do {
38
+ const page = await client.send(new GetExecutionHistoryCommand({
39
+ executionArn,
40
+ maxResults,
41
+ nextToken
42
+ }));
43
+ events.push(...page.events ?? []);
44
+ nextToken = page.nextToken;
45
+ } while (nextToken);
46
+ return events;
47
+ }
48
+ //#endregion
49
+ export { fetchExecutionHistory };