@grethel-labs/excaliplant 1.2.2 → 1.4.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
@@ -7,6 +7,11 @@
7
7
  Render PlantUML as editable <a href="https://excalidraw.com">Excalidraw</a> scenes, SVG and PNG — 29 diagram types, zero Java, zero network.
8
8
  </p>
9
9
 
10
+ <p align="center">
11
+ <b><a href="https://grethel-labs.github.io/excaliplant/#play">▶ Try it live — write PlantUML in your browser</a></b><br />
12
+ <sub>Live preview, every render option, all 41 examples open and editable, share by link, export SVG, PNG or Excalidraw.</sub>
13
+ </p>
14
+
10
15
  <p align="center">
11
16
  <a href="https://www.npmjs.com/package/@grethel-labs/excaliplant"><img src="https://img.shields.io/npm/v/@grethel-labs/excaliplant.svg?label=npm" alt="npm version" /></a>
12
17
  <a href="https://www.npmjs.com/package/@grethel-labs/excaliplant"><img src="https://img.shields.io/npm/dm/@grethel-labs/excaliplant.svg" alt="downloads" /></a>
@@ -16,44 +21,43 @@
16
21
  </p>
17
22
 
18
23
  <p align="center">
19
- <a href="https://grethel-labs.github.io/excaliplant/"><img src="docs/assets/carousel.svg" alt="Animated showcase of excaliplant diagram types" width="100%" /></a>
24
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery"><img src="docs/assets/carousel.svg" alt="Animated showcase of excaliplant diagram types" width="100%" /></a>
20
25
  </p>
21
26
 
22
27
  <p align="center">
23
- <a href="https://grethel-labs.github.io/excaliplant/#sequence"><kbd>Sequence</kbd></a>
24
- <a href="https://grethel-labs.github.io/excaliplant/#class"><kbd>Class & IE</kbd></a>
25
- <a href="https://grethel-labs.github.io/excaliplant/#activity"><kbd>Activity</kbd></a>
26
- <a href="https://grethel-labs.github.io/excaliplant/#state"><kbd>State</kbd></a>
27
- <a href="https://grethel-labs.github.io/excaliplant/#component"><kbd>Component & C4</kbd></a>
28
- <a href="https://grethel-labs.github.io/excaliplant/#usecase"><kbd>Use case</kbd></a>
29
- <a href="https://grethel-labs.github.io/excaliplant/#deployment"><kbd>Deployment</kbd></a>
30
- <a href="https://grethel-labs.github.io/excaliplant/#object"><kbd>Object</kbd></a>
31
- <a href="https://grethel-labs.github.io/excaliplant/#timing"><kbd>Timing</kbd></a>
32
- <a href="https://grethel-labs.github.io/excaliplant/#gantt"><kbd>Gantt</kbd></a>
33
- <a href="https://grethel-labs.github.io/excaliplant/#mindmap"><kbd>Mind map</kbd></a>
34
- <a href="https://grethel-labs.github.io/excaliplant/#wbs"><kbd>WBS</kbd></a>
35
- <a href="https://grethel-labs.github.io/excaliplant/#json"><kbd>JSON</kbd></a>
36
- <a href="https://grethel-labs.github.io/excaliplant/#yaml"><kbd>YAML</kbd></a>
37
- <a href="https://grethel-labs.github.io/excaliplant/#archimate"><kbd>ArchiMate</kbd></a>
38
- <a href="https://grethel-labs.github.io/excaliplant/#chen"><kbd>Chen ER</kbd></a>
39
- <a href="https://grethel-labs.github.io/excaliplant/#nwdiag"><kbd>Network</kbd></a>
40
- <a href="https://grethel-labs.github.io/excaliplant/#salt"><kbd>Salt wireframe</kbd></a>
41
- <a href="https://grethel-labs.github.io/excaliplant/#ebnf"><kbd>EBNF</kbd></a>
42
- <a href="https://grethel-labs.github.io/excaliplant/#regex"><kbd>Regex</kbd></a>
43
- <a href="https://grethel-labs.github.io/excaliplant/#dot"><kbd>Graphviz DOT</kbd></a>
44
- <a href="https://grethel-labs.github.io/excaliplant/#chronology"><kbd>Chronology</kbd></a>
45
- <a href="https://grethel-labs.github.io/excaliplant/#files"><kbd>Files</kbd></a>
46
- <a href="https://grethel-labs.github.io/excaliplant/#chart"><kbd>Chart</kbd></a>
47
- <a href="https://grethel-labs.github.io/excaliplant/#math"><kbd>AsciiMath</kbd></a>
48
- <a href="https://grethel-labs.github.io/excaliplant/#latex"><kbd>LaTeX</kbd></a>
49
- <a href="https://grethel-labs.github.io/excaliplant/#ditaa"><kbd>Ditaa</kbd></a>
50
- <a href="https://grethel-labs.github.io/excaliplant/#legacy-activity"><kbd>Legacy activity</kbd></a>
51
- <a href="https://grethel-labs.github.io/excaliplant/#creole"><kbd>Creole</kbd></a>
28
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/sequence"><kbd>Sequence</kbd></a>
29
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/class"><kbd>Class & IE</kbd></a>
30
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/activity"><kbd>Activity</kbd></a>
31
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/state"><kbd>State</kbd></a>
32
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/component"><kbd>Component & C4</kbd></a>
33
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/usecase"><kbd>Use case</kbd></a>
34
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/deployment"><kbd>Deployment</kbd></a>
35
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/object"><kbd>Object</kbd></a>
36
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/timing"><kbd>Timing</kbd></a>
37
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/gantt"><kbd>Gantt</kbd></a>
38
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/mindmap"><kbd>Mind map</kbd></a>
39
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/wbs"><kbd>WBS</kbd></a>
40
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/json"><kbd>JSON</kbd></a>
41
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/yaml"><kbd>YAML</kbd></a>
42
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/archimate"><kbd>ArchiMate</kbd></a>
43
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/chen"><kbd>Chen ER</kbd></a>
44
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/nwdiag"><kbd>Network</kbd></a>
45
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/salt"><kbd>Salt wireframe</kbd></a>
46
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/ebnf"><kbd>EBNF</kbd></a>
47
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/regex"><kbd>Regex</kbd></a>
48
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/dot"><kbd>Graphviz DOT</kbd></a>
49
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/chronology"><kbd>Chronology</kbd></a>
50
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/files"><kbd>Files</kbd></a>
51
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/chart"><kbd>Chart</kbd></a>
52
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/math"><kbd>AsciiMath</kbd></a>
53
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/latex"><kbd>LaTeX</kbd></a>
54
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/ditaa"><kbd>Ditaa</kbd></a>
55
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/legacy-activity"><kbd>Legacy activity</kbd></a>
56
+ <a href="https://grethel-labs.github.io/excaliplant/#gallery/creole"><kbd>Creole</kbd></a>
52
57
  </p>
53
58
 
54
59
  <p align="center">
55
- <a href="https://grethel-labs.github.io/excaliplant/"><b>▶ Click through all 41 examples in the interactive gallery</b></a><br />
56
- <sub>Every diagram is rendered by excaliplant from <a href="examples/"><code>examples/</code></a> — with PlantUML source, SVG and <code>.excalidraw</code> downloads.</sub>
60
+ <sub>Every diagram is rendered by excaliplant from <a href="examples/"><code>examples/</code></a> — with PlantUML source, SVG and <code>.excalidraw</code> downloads in the gallery.</sub>
57
61
  </p>
58
62
 
59
63
  ## Why excaliplant?
@@ -122,35 +126,35 @@ Each diagram type is a small module with four hooks — `detect`, `parse`, `layo
122
126
 
123
127
  | Diagram | Examples | Highlights |
124
128
  | --- | --- | --- |
125
- | [Sequence](https://grethel-labs.github.io/excaliplant/#sequence) | [4](docs/gallery.md#sequence) | Participants, all arrow styles, activations, notes, fragments, dividers, autonumber, boxes. |
126
- | [Class & IE](https://grethel-labs.github.io/excaliplant/#class) | [3](docs/gallery.md#class) | Classes, interfaces, enums, generics, members, packages, all UML relations, IE crow's feet. |
127
- | [Activity](https://grethel-labs.github.io/excaliplant/#activity) | [3](docs/gallery.md#activity) | New syntax with if/switch/while/repeat/fork/split, partitions, notes and swimlanes. |
128
- | [State](https://grethel-labs.github.io/excaliplant/#state) | [2](docs/gallery.md#state) | Composite states, concurrent regions, choice, fork/join, history, entry/exit actions. |
129
- | [Component & C4](https://grethel-labs.github.io/excaliplant/#component) | [2](docs/gallery.md#component) | Components, interfaces, ports, packages, nodes — and C4 via `!include <C4/...>`. |
130
- | [Use case](https://grethel-labs.github.io/excaliplant/#usecase) | [2](docs/gallery.md#usecase) | Actors, use cases, system boundaries, include/extend. |
131
- | [Deployment](https://grethel-labs.github.io/excaliplant/#deployment) | [2](docs/gallery.md#deployment) | Nodes, clouds, databases, queues, artifacts and nested deployment targets. |
132
- | [Object](https://grethel-labs.github.io/excaliplant/#object) | [1](docs/gallery.md#object) | Objects with fields, maps (`key => value`) and links. |
133
- | [Timing](https://grethel-labs.github.io/excaliplant/#timing) | [2](docs/gallery.md#timing) | Robust, concise, clock, binary and analog signals with messages and constraints. |
134
- | [Gantt](https://grethel-labs.github.io/excaliplant/#gantt) | [1](docs/gallery.md#gantt) | Tasks, dependencies, milestones, progress, resources, closed days, today marker. |
135
- | [Mind map](https://grethel-labs.github.io/excaliplant/#mindmap) | [1](docs/gallery.md#mindmap) | OrgMode/Markdown outlines on both sides, colours, boxless nodes. |
136
- | [WBS](https://grethel-labs.github.io/excaliplant/#wbs) | [1](docs/gallery.md#wbs) | Work breakdown structures as org charts. |
137
- | [JSON](https://grethel-labs.github.io/excaliplant/#json) | [1](docs/gallery.md#json) | JSON documents as linked tables with highlights. |
138
- | [YAML](https://grethel-labs.github.io/excaliplant/#yaml) | [1](docs/gallery.md#yaml) | YAML documents as linked tables. |
139
- | [ArchiMate](https://grethel-labs.github.io/excaliplant/#archimate) | [1](docs/gallery.md#archimate) | ArchiMate elements by layer with icons, junctions and `Rel_*` macros. |
140
- | [Chen ER](https://grethel-labs.github.io/excaliplant/#chen) | [1](docs/gallery.md#chen) | Chen ER diagrams: entities, weak entities, relationships, attributes, cardinalities. |
141
- | [Network](https://grethel-labs.github.io/excaliplant/#nwdiag) | [1](docs/gallery.md#nwdiag) | Networks, addresses, multi-homed nodes, groups and peer links. |
142
- | [Salt wireframe](https://grethel-labs.github.io/excaliplant/#salt) | [1](docs/gallery.md#salt) | Wireframes: grids, buttons, inputs, check boxes, trees, tabs, group boxes. |
143
- | [EBNF](https://grethel-labs.github.io/excaliplant/#ebnf) | [1](docs/gallery.md#ebnf) | EBNF grammars as railroad diagrams. |
144
- | [Regex](https://grethel-labs.github.io/excaliplant/#regex) | [1](docs/gallery.md#regex) | Regular expressions as railroad diagrams. |
145
- | [Graphviz DOT](https://grethel-labs.github.io/excaliplant/#dot) | [1](docs/gallery.md#dot) | Graphviz DOT graphs laid out with ELK. |
146
- | [Chronology](https://grethel-labs.github.io/excaliplant/#chronology) | [1](docs/gallery.md#chronology) | Events and spans on a time line with links. |
147
- | [Files](https://grethel-labs.github.io/excaliplant/#files) | [1](docs/gallery.md#files) | File trees from path lists with notes. |
148
- | [Chart](https://grethel-labs.github.io/excaliplant/#chart) | [1](docs/gallery.md#chart) | Bar, line, area and scatter charts. |
149
- | [AsciiMath](https://grethel-labs.github.io/excaliplant/#math) | [1](docs/gallery.md#math) | AsciiMath formulas. |
150
- | [LaTeX](https://grethel-labs.github.io/excaliplant/#latex) | [1](docs/gallery.md#latex) | LaTeX formulas. |
151
- | [Ditaa](https://grethel-labs.github.io/excaliplant/#ditaa) | [1](docs/gallery.md#ditaa) | ASCII art boxes, lines, arrows and colour tags. |
152
- | [Legacy activity](https://grethel-labs.github.io/excaliplant/#legacy-activity) | [1](docs/gallery.md#legacy-activity) | The classic `(*) --> "Activity"` syntax with sync bars and branches. |
153
- | [Creole](https://grethel-labs.github.io/excaliplant/#creole) | [1](docs/gallery.md#creole) | Rich text with headings, lists, tables and links. |
129
+ | [Sequence](https://grethel-labs.github.io/excaliplant/#gallery/sequence) | [4](docs/gallery.md#sequence) | Participants, all arrow styles, activations, notes, fragments, dividers, autonumber, boxes. |
130
+ | [Class & IE](https://grethel-labs.github.io/excaliplant/#gallery/class) | [3](docs/gallery.md#class) | Classes, interfaces, enums, generics, members, packages, all UML relations, IE crow's feet. |
131
+ | [Activity](https://grethel-labs.github.io/excaliplant/#gallery/activity) | [3](docs/gallery.md#activity) | New syntax with if/switch/while/repeat/fork/split, partitions, notes and swimlanes. |
132
+ | [State](https://grethel-labs.github.io/excaliplant/#gallery/state) | [2](docs/gallery.md#state) | Composite states, concurrent regions, choice, fork/join, history, entry/exit actions. |
133
+ | [Component & C4](https://grethel-labs.github.io/excaliplant/#gallery/component) | [2](docs/gallery.md#component) | Components, interfaces, ports, packages, nodes — and C4 via `!include <C4/...>`. |
134
+ | [Use case](https://grethel-labs.github.io/excaliplant/#gallery/usecase) | [2](docs/gallery.md#usecase) | Actors, use cases, system boundaries, include/extend. |
135
+ | [Deployment](https://grethel-labs.github.io/excaliplant/#gallery/deployment) | [2](docs/gallery.md#deployment) | Nodes, clouds, databases, queues, artifacts and nested deployment targets. |
136
+ | [Object](https://grethel-labs.github.io/excaliplant/#gallery/object) | [1](docs/gallery.md#object) | Objects with fields, maps (`key => value`) and links. |
137
+ | [Timing](https://grethel-labs.github.io/excaliplant/#gallery/timing) | [2](docs/gallery.md#timing) | Robust, concise, clock, binary and analog signals with messages and constraints. |
138
+ | [Gantt](https://grethel-labs.github.io/excaliplant/#gallery/gantt) | [1](docs/gallery.md#gantt) | Tasks, dependencies, milestones, progress, resources, closed days, today marker. |
139
+ | [Mind map](https://grethel-labs.github.io/excaliplant/#gallery/mindmap) | [1](docs/gallery.md#mindmap) | OrgMode/Markdown outlines on both sides, colours, boxless nodes. |
140
+ | [WBS](https://grethel-labs.github.io/excaliplant/#gallery/wbs) | [1](docs/gallery.md#wbs) | Work breakdown structures as org charts. |
141
+ | [JSON](https://grethel-labs.github.io/excaliplant/#gallery/json) | [1](docs/gallery.md#json) | JSON documents as linked tables with highlights. |
142
+ | [YAML](https://grethel-labs.github.io/excaliplant/#gallery/yaml) | [1](docs/gallery.md#yaml) | YAML documents as linked tables. |
143
+ | [ArchiMate](https://grethel-labs.github.io/excaliplant/#gallery/archimate) | [1](docs/gallery.md#archimate) | ArchiMate elements by layer with icons, junctions and `Rel_*` macros. |
144
+ | [Chen ER](https://grethel-labs.github.io/excaliplant/#gallery/chen) | [1](docs/gallery.md#chen) | Chen ER diagrams: entities, weak entities, relationships, attributes, cardinalities. |
145
+ | [Network](https://grethel-labs.github.io/excaliplant/#gallery/nwdiag) | [1](docs/gallery.md#nwdiag) | Networks, addresses, multi-homed nodes, groups and peer links. |
146
+ | [Salt wireframe](https://grethel-labs.github.io/excaliplant/#gallery/salt) | [1](docs/gallery.md#salt) | Wireframes: grids, buttons, inputs, check boxes, trees, tabs, group boxes. |
147
+ | [EBNF](https://grethel-labs.github.io/excaliplant/#gallery/ebnf) | [1](docs/gallery.md#ebnf) | EBNF grammars as railroad diagrams. |
148
+ | [Regex](https://grethel-labs.github.io/excaliplant/#gallery/regex) | [1](docs/gallery.md#regex) | Regular expressions as railroad diagrams. |
149
+ | [Graphviz DOT](https://grethel-labs.github.io/excaliplant/#gallery/dot) | [1](docs/gallery.md#dot) | Graphviz DOT graphs laid out with ELK. |
150
+ | [Chronology](https://grethel-labs.github.io/excaliplant/#gallery/chronology) | [1](docs/gallery.md#chronology) | Events and spans on a time line with links. |
151
+ | [Files](https://grethel-labs.github.io/excaliplant/#gallery/files) | [1](docs/gallery.md#files) | File trees from path lists with notes. |
152
+ | [Chart](https://grethel-labs.github.io/excaliplant/#gallery/chart) | [1](docs/gallery.md#chart) | Bar, line, area and scatter charts. |
153
+ | [AsciiMath](https://grethel-labs.github.io/excaliplant/#gallery/math) | [1](docs/gallery.md#math) | AsciiMath formulas. |
154
+ | [LaTeX](https://grethel-labs.github.io/excaliplant/#gallery/latex) | [1](docs/gallery.md#latex) | LaTeX formulas. |
155
+ | [Ditaa](https://grethel-labs.github.io/excaliplant/#gallery/ditaa) | [1](docs/gallery.md#ditaa) | ASCII art boxes, lines, arrows and colour tags. |
156
+ | [Legacy activity](https://grethel-labs.github.io/excaliplant/#gallery/legacy-activity) | [1](docs/gallery.md#legacy-activity) | The classic `(*) --> "Activity"` syntax with sync bars and branches. |
157
+ | [Creole](https://grethel-labs.github.io/excaliplant/#gallery/creole) | [1](docs/gallery.md#creole) | Rich text with headings, lists, tables and links. |
154
158
 
155
159
  ## PlantUML language support
156
160
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grethel-labs/excaliplant",
3
- "version": "1.2.2",
3
+ "version": "1.4.0",
4
4
  "description": "Render PlantUML as hand-drawn Excalidraw diagrams, SVG and PNG.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -39,6 +39,7 @@
39
39
  "test": "node scripts/test.mjs",
40
40
  "typecheck": "tsc -p tsconfig.json",
41
41
  "types": "tsc -p tsconfig.types.json",
42
+ "site": "node scripts/site.mjs _site",
42
43
  "docs": "node scripts/docs.mjs && node scripts/skills.mjs && node scripts/gen-mcp-examples.mjs",
43
44
  "docs:check": "node scripts/docs.mjs --check && node scripts/skills.mjs --check && node scripts/gen-mcp-examples.mjs --check",
44
45
  "format": "prettier --write .",
@@ -87,6 +88,7 @@
87
88
  },
88
89
  "devDependencies": {
89
90
  "@types/node": "^26.6.6",
91
+ "esbuild": "0.28.2",
90
92
  "prettier": "^3.10.1",
91
93
  "typescript": "^7.0.2"
92
94
  },
package/src/api.mjs CHANGED
@@ -183,3 +183,46 @@ export function renderPlantUml(source, options = {}) {
183
183
  doc.toPng = (/** @type {any} */ o) => result.then((r) => r.toPng(o));
184
184
  return doc;
185
185
  }
186
+
187
+ /** Small class diagram with a container, edge labels and multiplicities; exercises the hot ELK paths. */
188
+ const WARMUP_SOURCE = `@startuml
189
+ package core {
190
+ class Base {
191
+ +id : int
192
+ +run() : void
193
+ }
194
+ class Worker
195
+ }
196
+ class Client
197
+ Base <|-- Worker
198
+ Client "1" --> "*" Worker : uses
199
+ Client ..> Base : depends
200
+ @enduml`;
201
+
202
+ /** @type {Promise<void> | null} */
203
+ let warmupPromise = null;
204
+
205
+ /**
206
+ * Pre-load and pre-heat the layout engine so the first real graph render does
207
+ * not pay for it (loading ELK takes ~0.9 s, running it cold another ~0.6 s).
208
+ * Hosts such as the MCP server, the VS Code extension or the Obsidian plugin
209
+ * call this once at start-up, without awaiting it.
210
+ *
211
+ * Idempotent: concurrent and repeated calls share one promise. It has no
212
+ * observable side effects — the layout cache is bypassed and the rendered
213
+ * result is discarded — and never rejects: a failure is swallowed (and a later
214
+ * call tries again), because warming up must never break rendering.
215
+ * @returns {Promise<void>}
216
+ * @public
217
+ */
218
+ export function warmup() {
219
+ if (!warmupPromise) {
220
+ warmupPromise = render(WARMUP_SOURCE, { layoutCache: false }).then(
221
+ () => undefined,
222
+ () => {
223
+ warmupPromise = null;
224
+ },
225
+ );
226
+ }
227
+ return warmupPromise;
228
+ }
@@ -39,6 +39,21 @@ export const DEFAULT_LIMITS = Object.freeze({
39
39
  maxBlocks: 100,
40
40
  });
41
41
 
42
+ /**
43
+ * Budget of the process-wide graph layout cache (`diagrams/graph/elk_runner`).
44
+ * The cache is bounded twice: by entry count and by an estimate of the memory
45
+ * it holds, so it can never grow without limit. An entry larger than
46
+ * `maxEntryBytes` is not cached at all (it would evict everything else).
47
+ * Byte figures are estimates: two bytes per character of the key and of the
48
+ * serialized result.
49
+ * @type {Readonly<{ maxEntries: number, maxBytes: number, maxEntryBytes: number }>}
50
+ */
51
+ export const LAYOUT_CACHE_LIMITS = Object.freeze({
52
+ maxEntries: 64,
53
+ maxBytes: 16 * 1024 * 1024,
54
+ maxEntryBytes: 4 * 1024 * 1024,
55
+ });
56
+
42
57
  /**
43
58
  * Merge user overrides into the defaults, ignoring non-finite or negative values.
44
59
  * @param {Partial<Limits>} [overrides]
@@ -28,6 +28,7 @@ import { createDocument, validateDocument } from "../render/excalidraw.mjs";
28
28
  * @property {Date | null} [date] Date returned by `%date()`.
29
29
  * @property {string} [filename] Value of `%filename()`.
30
30
  * @property {string} [kind] Force a diagram module instead of auto-detection.
31
+ * @property {boolean} [layoutCache] Set to `false` to bypass the graph layout cache (default: on). The cache never changes the output; it only skips repeated ELK runs for identical graphs.
31
32
  */
32
33
 
33
34
  /**
@@ -94,7 +95,14 @@ export function parseBlock(block, registry, options = {}) {
94
95
  { sketch: options.sketch },
95
96
  );
96
97
  /** @type {import("./registry.mjs").ModuleContext} */
97
- const ctx = { diagnostics, limits, theme, pragmas, start: block.type };
98
+ const ctx = {
99
+ diagnostics,
100
+ limits,
101
+ theme,
102
+ pragmas,
103
+ start: block.type,
104
+ layoutCache: options.layoutCache !== false,
105
+ };
98
106
  const model = module.parse(page, ctx);
99
107
  applySkin(theme, model.meta.skin);
100
108
  return { module, model, ctx, pages: pages.length };
@@ -16,6 +16,7 @@
16
16
  * @property {Theme} theme Resolved theme (available in layout and draw).
17
17
  * @property {Map<string, string>} pragmas `!pragma` values from the preprocessor.
18
18
  * @property {string} start Block start keyword (`uml`, `json`, …).
19
+ * @property {boolean} [layoutCache] `false` disables the graph layout cache for this render.
19
20
  */
20
21
 
21
22
  /**
@@ -286,6 +286,6 @@ export default defineDiagram({
286
286
  title: "Graphviz DOT",
287
287
  starts: ["dot"],
288
288
  parse: parseDot,
289
- layout: (model, ctx) => layoutGraph(model, ctx.theme),
289
+ layout: (model, ctx) => layoutGraph(model, ctx.theme, {}, ctx),
290
290
  draw: (model, canvas) => drawGraph(model, canvas),
291
291
  });
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The only place that talks to ELK. Two jobs:
3
+ *
4
+ * 1. Load `elkjs` lazily. The 1.5 MB bundle costs ~0.85 s to evaluate, and only
5
+ * graph diagrams need it, so it is imported on the first layout that really
6
+ * has to run ELK (never for sequence, gantt, mindmap, … and never on a
7
+ * layout-cache hit).
8
+ * 2. Cache layouts. ELK is deterministic and the dominant cost of a render, so
9
+ * results are kept in a bounded LRU keyed by the complete ELK input graph
10
+ * (structure, sizes, labels and every layout option). Anything that is not
11
+ * part of that graph — theme, seed, colours, stroke style — does not change
12
+ * the key, so re-rendering the same diagram in another theme is a cache hit.
13
+ *
14
+ * The key is the serialized graph itself rather than a 32-bit hash: a hash
15
+ * collision would silently return the geometry of a different diagram.
16
+ * @module diagrams/graph/elk_runner
17
+ */
18
+
19
+ import { LAYOUT_CACHE_LIMITS } from "../../core/limits.mjs";
20
+
21
+ /** @type {Promise<any> | null} */
22
+ let elkPromise = null;
23
+ let elkLoaded = false;
24
+
25
+ /** @typedef {{ result: any, bytes: number }} CacheEntry */
26
+ /** Insertion order is recency order: the first key is the least recently used. @type {Map<string, CacheEntry>} */
27
+ const cache = new Map();
28
+ let cacheBytes = 0;
29
+ const stats = { hits: 0, misses: 0, elkRuns: 0 };
30
+
31
+ /**
32
+ * Load `elkjs` once and create one shared instance. A failed import is not
33
+ * remembered, so a later call can retry.
34
+ * @returns {Promise<any>}
35
+ */
36
+ function loadElk() {
37
+ if (!elkPromise) {
38
+ elkPromise = import("elkjs/lib/elk.bundled.js")
39
+ .then((mod) => {
40
+ elkLoaded = true;
41
+ return new /** @type {any} */ (mod).default();
42
+ })
43
+ .catch((err) => {
44
+ elkPromise = null;
45
+ throw err;
46
+ });
47
+ }
48
+ return elkPromise;
49
+ }
50
+
51
+ /**
52
+ * Whether `elkjs` has been imported in this process (diagnostics and tests).
53
+ * @returns {boolean}
54
+ */
55
+ export function isElkLoaded() {
56
+ return elkLoaded;
57
+ }
58
+
59
+ /**
60
+ * Drop every cached layout and reset the counters. Internal; used by tests.
61
+ */
62
+ export function clearLayoutCache() {
63
+ cache.clear();
64
+ cacheBytes = 0;
65
+ stats.hits = 0;
66
+ stats.misses = 0;
67
+ stats.elkRuns = 0;
68
+ }
69
+
70
+ /**
71
+ * Cache counters and current size. Internal; used by tests and the benchmark.
72
+ * @returns {{ hits: number, misses: number, elkRuns: number, entries: number, bytes: number }}
73
+ */
74
+ export function layoutCacheStats() {
75
+ return { ...stats, entries: cache.size, bytes: cacheBytes };
76
+ }
77
+
78
+ /**
79
+ * Deep copy of plain JSON data (objects, arrays, primitives), which is all ELK
80
+ * produces. Written by hand because `structuredClone` is not available in every
81
+ * host the library is bundled for (the Obsidian bundle runs in a sandbox
82
+ * without it); unlike `JSON.parse(JSON.stringify(x))` it keeps `-0`.
83
+ * @template T
84
+ * @param {T} value
85
+ * @returns {T}
86
+ */
87
+ function cloneJson(value) {
88
+ if (value === null || typeof value !== "object") return value;
89
+ if (Array.isArray(value)) return /** @type {any} */ (value.map(cloneJson));
90
+ /** @type {any} */
91
+ const out = {};
92
+ for (const key of Object.keys(value)) out[key] = cloneJson(/** @type {any} */ (value)[key]);
93
+ return out;
94
+ }
95
+
96
+ /**
97
+ * @param {string} key
98
+ * @param {any} result Freshly computed ELK result; a private copy is stored.
99
+ */
100
+ function remember(key, result) {
101
+ const { maxEntries, maxBytes, maxEntryBytes } = LAYOUT_CACHE_LIMITS;
102
+ const bytes = 2 * (key.length + JSON.stringify(result).length);
103
+ if (bytes > maxEntryBytes) return;
104
+ cache.set(key, { result: cloneJson(result), bytes });
105
+ cacheBytes += bytes;
106
+ while (cache.size > maxEntries || cacheBytes > maxBytes) {
107
+ const oldest = /** @type {string} */ (cache.keys().next().value);
108
+ cacheBytes -= /** @type {CacheEntry} */ (cache.get(oldest)).bytes;
109
+ cache.delete(oldest);
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Lay out an ELK graph. ELK writes its result into the object it is given, so
115
+ * callers must pass a graph they will not reuse. The returned object is always
116
+ * private to the caller: on a cache hit it is a deep copy, so mutating it can
117
+ * never change what later renders see.
118
+ * @param {any} graph ELK input graph (plain JSON; consumed by the call).
119
+ * @param {{ cache?: boolean }} [options] `cache: false` bypasses the cache entirely.
120
+ * @returns {Promise<any>}
121
+ */
122
+ export async function runElk(graph, options = {}) {
123
+ const useCache = options.cache !== false;
124
+ // The key has to be taken before ELK mutates the graph.
125
+ const key = useCache ? JSON.stringify(graph) : "";
126
+ if (useCache) {
127
+ const hit = cache.get(key);
128
+ if (hit) {
129
+ cache.delete(key);
130
+ cache.set(key, hit);
131
+ stats.hits++;
132
+ return cloneJson(hit.result);
133
+ }
134
+ stats.misses++;
135
+ }
136
+ const elk = await loadElk();
137
+ stats.elkRuns++;
138
+ const result = await elk.layout(graph);
139
+ if (useCache) remember(key, result);
140
+ return result;
141
+ }
@@ -5,18 +5,16 @@
5
5
  * @module diagrams/graph/layout
6
6
  */
7
7
 
8
- import ELK from "elkjs/lib/elk.bundled.js";
9
8
  import { layoutText } from "../../layout/measure.mjs";
10
9
  import { shape as shapeDef } from "../../draw/shapes.mjs";
11
10
  import { roleStyle } from "../../draw/theme.mjs";
12
11
  import { tidyRoutes } from "./route.mjs";
12
+ import { runElk } from "./elk_runner.mjs";
13
13
 
14
14
  /** @typedef {import("../../model/graph.mjs").GraphModel} GraphModel */
15
15
  /** @typedef {import("../../model/graph.mjs").GraphNode} GraphNode */
16
16
  /** @typedef {import("../../layout/measure.mjs").RichLayout} RichLayout */
17
17
 
18
- const elk = new /** @type {any} */ (ELK)();
19
-
20
18
  /**
21
19
  * @typedef {object} ClassGeo
22
20
  * @property {"class"} kind
@@ -266,9 +264,10 @@ function classGeometry(node, fs, stereo, hide) {
266
264
  * @param {GraphModel} model
267
265
  * @param {import("../../draw/theme.mjs").Theme} theme
268
266
  * @param {GraphLayoutOptions} [options]
267
+ * @param {{ layoutCache?: boolean }} [runtime] Per-render settings; `layoutCache: false` skips the layout cache.
269
268
  * @returns {Promise<GraphModel>}
270
269
  */
271
- export async function layoutGraph(model, theme, options = {}) {
270
+ export async function layoutGraph(model, theme, options = {}, runtime = {}) {
272
271
  sizeGraph(model, theme);
273
272
  const lr = model.direction === "LR";
274
273
  const linetype = (model.meta.skin.get("linetype") ?? "").toLowerCase();
@@ -489,7 +488,7 @@ export async function layoutGraph(model, theme, options = {}) {
489
488
  edges,
490
489
  };
491
490
 
492
- const result = await elk.layout(graph);
491
+ const result = await runElk(graph, { cache: runtime.layoutCache });
493
492
 
494
493
  /** @type {Map<string, { x: number, y: number }>} */
495
494
  const abs = new Map([["__root", { x: 0, y: 0 }]]);
@@ -38,7 +38,7 @@ export function graphModule(spec) {
38
38
  starts: spec.starts ?? ["uml"],
39
39
  detect: spec.detect,
40
40
  parse,
41
- layout: (model, ctx) => layoutGraph(model, ctx.theme, spec.layout),
41
+ layout: (model, ctx) => layoutGraph(model, ctx.theme, spec.layout, ctx),
42
42
  draw: (model, canvas) => drawGraph(model, canvas),
43
43
  });
44
44
  }
package/src/index.mjs CHANGED
@@ -10,6 +10,7 @@ export {
10
10
  detectKind,
11
11
  listDiagramTypes,
12
12
  renderPlantUml,
13
+ warmup,
13
14
  RenderResult,
14
15
  defaultRegistry,
15
16
  } from "./api.mjs";
package/src/mcp/cli.mjs CHANGED
@@ -25,6 +25,7 @@ Options:
25
25
  --include-dir <dir> Allow !include of files below <dir> (default: no includes)
26
26
  --max-input-bytes <n> PlantUML source size limit (default 2 MiB, max 64 MiB)
27
27
  --timeout <ms> Time limit per tool call (default 30000)
28
+ --no-warmup Do not pre-load the layout engine in the background at start-up
28
29
  -h, --help Show this help
29
30
  -v, --version Show the version
30
31
  `;
@@ -45,7 +46,7 @@ const MAX_INPUT_CEILING = 64 * 1024 * 1024;
45
46
  * @param {string[]} argv
46
47
  */
47
48
  function parseArgs(argv) {
48
- /** @type {{ http?: number, includeDir?: string, maxInputBytes?: number, timeoutMs?: number, help?: boolean, version?: boolean }} */
49
+ /** @type {{ http?: number, includeDir?: string, maxInputBytes?: number, timeoutMs?: number, warmup?: boolean, help?: boolean, version?: boolean }} */
49
50
  const opts = {};
50
51
  for (let i = 0; i < argv.length; i++) {
51
52
  const a = argv[i];
@@ -75,6 +76,9 @@ function parseArgs(argv) {
75
76
  case "--timeout":
76
77
  opts.timeoutMs = integer(next(), 10, 600_000);
77
78
  break;
79
+ case "--no-warmup":
80
+ opts.warmup = false;
81
+ break;
78
82
  case "-h":
79
83
  case "--help":
80
84
  opts.help = true;
@@ -143,6 +147,7 @@ export async function runMcpCli(argv, io) {
143
147
  includeDir: opts.includeDir,
144
148
  limits: opts.maxInputBytes ? { maxInputBytes: opts.maxInputBytes } : undefined,
145
149
  timeoutMs: opts.timeoutMs,
150
+ warmup: opts.warmup !== false,
146
151
  log,
147
152
  });
148
153
  if (opts.version) {
@@ -9,6 +9,8 @@
9
9
  */
10
10
 
11
11
  import { Worker } from "node:worker_threads";
12
+ import { warmup as warmUpRenderer } from "../api.mjs";
13
+ import { isElkLoaded } from "../diagrams/graph/elk_runner.mjs";
12
14
  import { runTool } from "./tools.mjs";
13
15
 
14
16
  /**
@@ -37,6 +39,10 @@ export class ExecutorError extends Error {
37
39
  /**
38
40
  * @typedef {object} Executor
39
41
  * @property {(tool: string, args: unknown, options: RunOptions) => Promise<import("./tools.mjs").CallToolResult>} run
42
+ * @property {() => Promise<boolean>} [warmup] Pre-load the layout engine where the
43
+ * tools run, in the background. Resolves with whether the engine is loaded
44
+ * afterwards (never rejects). Calls are idempotent and a tool call never has
45
+ * to wait for it.
40
46
  * @property {() => Promise<void>} close
41
47
  */
42
48
 
@@ -67,6 +73,11 @@ export function createInlineExecutor(env, log) {
67
73
  if (onAbort) signal?.removeEventListener("abort", onAbort);
68
74
  }
69
75
  },
76
+ async warmup() {
77
+ if (closed) return false;
78
+ await warmUpRenderer();
79
+ return isElkLoaded();
80
+ },
70
81
  async close() {
71
82
  closed = true;
72
83
  },
@@ -77,12 +88,15 @@ export function createInlineExecutor(env, log) {
77
88
  * @typedef {object} WorkerExecutorOptions
78
89
  * @property {number} [maxQueue] Pending calls beyond the running one before `busy` (default 16).
79
90
  * @property {number} [maxMemoryMb] Heap limit of the worker thread (default 768).
91
+ * @property {URL} [workerUrl] Worker entry point (default `./worker.mjs`); for tests.
80
92
  */
81
93
 
82
94
  /**
83
95
  * Executor backed by one lazily started worker thread. Calls run one at a
84
96
  * time; a timeout or cancellation terminates the thread and the next call
85
- * starts a fresh one.
97
+ * starts a fresh one. After `warmup()` was called, every worker (also a
98
+ * restarted one) pre-loads the layout engine in the background, concurrently
99
+ * with the first calls: a call never waits for it.
86
100
  * @param {import("./tools.mjs").ToolEnv} env
87
101
  * @param {(message: string) => void} log
88
102
  * @param {WorkerExecutorOptions} [options]
@@ -113,9 +127,62 @@ export function createWorkerExecutor(env, log, options = {}) {
113
127
  let timer = null;
114
128
  let seq = 0;
115
129
  let closed = false;
130
+ /** Warm every worker that is started (set by `warmup()`, cleared when warming fails). */
131
+ let warm = false;
132
+ /** @type {Map<Worker, { promise: Promise<boolean>, resolve: (loaded: boolean) => void, settled: boolean }>} */
133
+ const warming = new Map();
134
+
135
+ /**
136
+ * Ask `w` to pre-load the layout engine (once per worker).
137
+ * @param {Worker} w
138
+ */
139
+ function beginWarm(w) {
140
+ const known = warming.get(w);
141
+ if (known) return known.promise;
142
+ /** @type {(loaded: boolean) => void} */
143
+ let resolve = () => {};
144
+ const promise = new Promise((r) => (resolve = r));
145
+ warming.set(w, { promise, resolve, settled: false });
146
+ try {
147
+ w.postMessage({ warmup: true });
148
+ } catch {
149
+ settleWarm(w, false);
150
+ }
151
+ return promise;
152
+ }
153
+
154
+ /**
155
+ * @param {Worker} w
156
+ * @param {boolean} loaded
157
+ */
158
+ function settleWarm(w, loaded) {
159
+ const entry = warming.get(w);
160
+ if (!entry) return;
161
+ entry.settled = true;
162
+ entry.resolve(loaded);
163
+ // Keep the settled entry: the worker is not asked twice.
164
+ }
165
+
166
+ /** @param {Worker} w */
167
+ function warmSettled(w) {
168
+ return warming.get(w)?.settled === true;
169
+ }
170
+
171
+ /**
172
+ * After a job killed the worker, start the next one right away so the
173
+ * engine is loaded again before the next call arrives.
174
+ */
175
+ function rewarm() {
176
+ if (!warm || closed || worker || current) return;
177
+ try {
178
+ worker = startWorker();
179
+ } catch (error) {
180
+ log(`cannot start worker: ${error instanceof Error ? error.message : error}`);
181
+ }
182
+ }
116
183
 
117
184
  function startWorker() {
118
- const w = new Worker(new URL("./worker.mjs", import.meta.url), {
185
+ const w = new Worker(options.workerUrl ?? new URL("./worker.mjs", import.meta.url), {
119
186
  workerData: { env },
120
187
  resourceLimits: { maxOldGenerationSizeMb: maxMemoryMb },
121
188
  // Keep the worker's stdout away from ours: stdout carries the protocol.
@@ -126,6 +193,12 @@ export function createWorkerExecutor(env, log, options = {}) {
126
193
  w.stdout.on("data", (chunk) => log(String(chunk).trimEnd()));
127
194
  w.stderr.on("data", (chunk) => log(String(chunk).trimEnd()));
128
195
  w.on("message", (message) => {
196
+ if (message?.warmup) {
197
+ // A warm-up that did not load the engine is not retried on later workers.
198
+ if (!message.loaded) warm = false;
199
+ settleWarm(w, message.loaded === true);
200
+ return;
201
+ }
129
202
  if (w !== worker || !current || message?.id !== current.id) return;
130
203
  const job = current;
131
204
  finish();
@@ -137,8 +210,12 @@ export function createWorkerExecutor(env, log, options = {}) {
137
210
  if (w === worker) crash();
138
211
  });
139
212
  w.on("exit", () => {
213
+ // The thread died on its own (not stopped by us) while warming: do not warm again.
214
+ if (w === worker && warming.has(w) && !warmSettled(w)) warm = false;
215
+ settleWarm(w, false);
140
216
  if (w === worker) crash();
141
217
  });
218
+ if (warm) beginWarm(w);
142
219
  return w;
143
220
  }
144
221
 
@@ -158,6 +235,7 @@ export function createWorkerExecutor(env, log, options = {}) {
158
235
  finish();
159
236
  job.reject(new ExecutorError("crashed"));
160
237
  pump();
238
+ rewarm();
161
239
  }
162
240
 
163
241
  /**
@@ -173,6 +251,7 @@ export function createWorkerExecutor(env, log, options = {}) {
173
251
  finish();
174
252
  job.reject(new ExecutorError(reason));
175
253
  pump();
254
+ rewarm();
176
255
  }
177
256
 
178
257
  function pump() {
@@ -215,6 +294,17 @@ export function createWorkerExecutor(env, log, options = {}) {
215
294
  pump();
216
295
  });
217
296
  },
297
+ async warmup() {
298
+ if (closed) return false;
299
+ warm = true;
300
+ try {
301
+ worker ??= startWorker();
302
+ return await beginWarm(worker);
303
+ } catch (error) {
304
+ log(`cannot start worker: ${error instanceof Error ? error.message : error}`);
305
+ return false;
306
+ }
307
+ },
218
308
  async close() {
219
309
  closed = true;
220
310
  for (const job of queue.splice(0)) {
package/src/mcp/http.mjs CHANGED
@@ -168,6 +168,7 @@ export function serveHttp(server, options) {
168
168
  http.listen(options.port, HTTP_HOST, () => {
169
169
  http.off("error", reject);
170
170
  const address = /** @type {import("node:net").AddressInfo} */ (http.address());
171
+ setImmediate(() => void server.warmup());
171
172
  resolve({
172
173
  port: address.port,
173
174
  url: `http://${HTTP_HOST}:${address.port}${HTTP_PATH}`,
@@ -39,6 +39,9 @@ import { MAX_PNG_WIDTH, TOOLS, describeTool, errorResult, findTool } from "./too
39
39
  * @property {number} [maxOutputBytes] Largest result payload (default 8 MiB).
40
40
  * @property {number} [maxBatch] Largest JSON-RPC batch (default 32).
41
41
  * @property {"worker" | "inline" | import("./executor.mjs").Executor} [executor] Where tools run (default "worker").
42
+ * @property {boolean} [warmup] Pre-load the layout engine in the background once a
43
+ * transport starts serving (see `McpServer.warmup`). Default: off, so embedding
44
+ * and tests start nothing eagerly; `excaliplant-mcp` turns it on (`--no-warmup` off).
42
45
  * @property {(message: string) => void} [log] Receives diagnostics for stderr. Default: silent.
43
46
  */
44
47
 
@@ -60,6 +63,10 @@ import { MAX_PNG_WIDTH, TOOLS, describeTool, errorResult, findTool } from "./too
60
63
  * @property {number} maxMessageBytes
61
64
  * @property {(text: string, options?: HandleOptions) => Promise<HandleResult>} handleText Handle one raw JSON-RPC message or batch.
62
65
  * @property {(message: unknown, options?: HandleOptions) => Promise<{ response: object | null, status: number }>} handleMessage
66
+ * @property {() => Promise<boolean>} warmup Start loading the layout engine where tools run (the
67
+ * worker thread) without blocking anything: requests are answered meanwhile and a tool call
68
+ * never waits for it. Transports call this once they serve. Resolves with whether the engine
69
+ * is loaded (false when disabled, closed or failed); never rejects.
63
70
  * @property {() => Promise<void>} close Stop the executor and cancel everything in flight.
64
71
  */
65
72
 
@@ -390,6 +397,15 @@ export function createServer(options = {}) {
390
397
  maxMessageBytes,
391
398
  handleText,
392
399
  handleMessage,
400
+ async warmup() {
401
+ if (!options.warmup || closed) return false;
402
+ try {
403
+ return (await executor.warmup?.()) === true;
404
+ } catch (error) {
405
+ log(`warm-up failed: ${error instanceof Error ? error.message : error}`);
406
+ return false;
407
+ }
408
+ },
393
409
  async close() {
394
410
  closed = true;
395
411
  for (const controller of inflight.values()) controller.abort();
package/src/mcp/stdio.mjs CHANGED
@@ -135,6 +135,8 @@ export function serveStdio(server, { stdin, stdout, stderr, signal }) {
135
135
 
136
136
  return new Promise((resolve) => {
137
137
  let finished = false;
138
+ // After the first reads are scheduled; answers never wait for it.
139
+ setImmediate(() => void server.warmup());
138
140
  const finish = async () => {
139
141
  if (finished) return;
140
142
  finished = true;
@@ -5,6 +5,8 @@
5
5
  */
6
6
 
7
7
  import { parentPort, workerData } from "node:worker_threads";
8
+ import { warmup } from "../api.mjs";
9
+ import { isElkLoaded } from "../diagrams/graph/elk_runner.mjs";
8
10
  import { runTool } from "./tools.mjs";
9
11
 
10
12
  // The worker's stderr is forwarded to the server's stderr by the parent.
@@ -12,7 +14,13 @@ const log = (/** @type {string} */ message) => process.stderr.write(`${message}\
12
14
 
13
15
  parentPort?.on(
14
16
  "message",
15
- async (/** @type {{ id: number, tool: string, args: unknown }} */ job) => {
17
+ async (/** @type {{ id: number, tool: string, args: unknown, warmup?: boolean }} */ job) => {
18
+ if (job.warmup) {
19
+ // Runs concurrently with jobs: both share the one layout-engine import.
20
+ await warmup();
21
+ parentPort?.postMessage({ warmup: true, loaded: isElkLoaded() });
22
+ return;
23
+ }
16
24
  const result = await runTool(job.tool, job.args, workerData.env, log);
17
25
  parentPort?.postMessage({ id: job.id, result });
18
26
  },
package/types/api.d.mts CHANGED
@@ -112,3 +112,17 @@ export declare function renderPlantUml(source: string, options?: ApiOptions): Pr
112
112
  toSvg: (o?: import("./render/svg.mjs").SvgOptions) => Promise<string>;
113
113
  toPng: (o?: import("./render/png.mjs").PngOptions) => Promise<Buffer>;
114
114
  };
115
+ /**
116
+ * Pre-load and pre-heat the layout engine so the first real graph render does
117
+ * not pay for it (loading ELK takes ~0.9 s, running it cold another ~0.6 s).
118
+ * Hosts such as the MCP server, the VS Code extension or the Obsidian plugin
119
+ * call this once at start-up, without awaiting it.
120
+ *
121
+ * Idempotent: concurrent and repeated calls share one promise. It has no
122
+ * observable side effects — the layout cache is bypassed and the rendered
123
+ * result is discarded — and never rejects: a failure is swallowed (and a later
124
+ * call tries again), because warming up must never break rendering.
125
+ * @returns {Promise<void>}
126
+ * @public
127
+ */
128
+ export declare function warmup(): Promise<void>;
@@ -76,6 +76,20 @@ export type Limits = {
76
76
  */
77
77
  /** @type {Readonly<Limits>} */
78
78
  export declare const DEFAULT_LIMITS: Readonly<Limits>;
79
+ /**
80
+ * Budget of the process-wide graph layout cache (`diagrams/graph/elk_runner`).
81
+ * The cache is bounded twice: by entry count and by an estimate of the memory
82
+ * it holds, so it can never grow without limit. An entry larger than
83
+ * `maxEntryBytes` is not cached at all (it would evict everything else).
84
+ * Byte figures are estimates: two bytes per character of the key and of the
85
+ * serialized result.
86
+ * @type {Readonly<{ maxEntries: number, maxBytes: number, maxEntryBytes: number }>}
87
+ */
88
+ export declare const LAYOUT_CACHE_LIMITS: Readonly<{
89
+ maxEntries: number;
90
+ maxBytes: number;
91
+ maxEntryBytes: number;
92
+ }>;
79
93
  /**
80
94
  * Merge user overrides into the defaults, ignoring non-finite or negative values.
81
95
  * @param {Partial<Limits>} [overrides]
@@ -44,6 +44,10 @@ export type RenderOptions = {
44
44
  * Force a diagram module instead of auto-detection.
45
45
  */
46
46
  kind?: string;
47
+ /**
48
+ * Set to `false` to bypass the graph layout cache (default: on). The cache never changes the output; it only skips repeated ELK runs for identical graphs.
49
+ */
50
+ layoutCache?: boolean;
47
51
  };
48
52
  export type BlockOutput = {
49
53
  kind: string;
@@ -65,6 +69,7 @@ export type BlockOutput = {
65
69
  * @property {Date | null} [date] Date returned by `%date()`.
66
70
  * @property {string} [filename] Value of `%filename()`.
67
71
  * @property {string} [kind] Force a diagram module instead of auto-detection.
72
+ * @property {boolean} [layoutCache] Set to `false` to bypass the graph layout cache (default: on). The cache never changes the output; it only skips repeated ELK runs for identical graphs.
68
73
  */
69
74
  /**
70
75
  * @typedef {object} BlockOutput
@@ -21,6 +21,10 @@ export type ModuleContext = {
21
21
  * Block start keyword (`uml`, `json`, …).
22
22
  */
23
23
  start: string;
24
+ /**
25
+ * `false` disables the graph layout cache for this render.
26
+ */
27
+ layoutCache?: boolean;
24
28
  };
25
29
  export type DiagramModule = {
26
30
  /**
@@ -68,6 +72,7 @@ export type DiagramModule = {
68
72
  * @property {Theme} theme Resolved theme (available in layout and draw).
69
73
  * @property {Map<string, string>} pragmas `!pragma` values from the preprocessor.
70
74
  * @property {string} start Block start keyword (`uml`, `json`, …).
75
+ * @property {boolean} [layoutCache] `false` disables the graph layout cache for this render.
71
76
  */
72
77
  /**
73
78
  * A diagram module. Models must expose a `meta` property created with
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The only place that talks to ELK. Two jobs:
3
+ *
4
+ * 1. Load `elkjs` lazily. The 1.5 MB bundle costs ~0.85 s to evaluate, and only
5
+ * graph diagrams need it, so it is imported on the first layout that really
6
+ * has to run ELK (never for sequence, gantt, mindmap, … and never on a
7
+ * layout-cache hit).
8
+ * 2. Cache layouts. ELK is deterministic and the dominant cost of a render, so
9
+ * results are kept in a bounded LRU keyed by the complete ELK input graph
10
+ * (structure, sizes, labels and every layout option). Anything that is not
11
+ * part of that graph — theme, seed, colours, stroke style — does not change
12
+ * the key, so re-rendering the same diagram in another theme is a cache hit.
13
+ *
14
+ * The key is the serialized graph itself rather than a 32-bit hash: a hash
15
+ * collision would silently return the geometry of a different diagram.
16
+ * @module diagrams/graph/elk_runner
17
+ */
18
+ export type CacheEntry = {
19
+ result: any;
20
+ bytes: number;
21
+ };
22
+ /**
23
+ * Whether `elkjs` has been imported in this process (diagnostics and tests).
24
+ * @returns {boolean}
25
+ */
26
+ export declare function isElkLoaded(): boolean;
27
+ /**
28
+ * Drop every cached layout and reset the counters. Internal; used by tests.
29
+ */
30
+ export declare function clearLayoutCache(): void;
31
+ /**
32
+ * Cache counters and current size. Internal; used by tests and the benchmark.
33
+ * @returns {{ hits: number, misses: number, elkRuns: number, entries: number, bytes: number }}
34
+ */
35
+ export declare function layoutCacheStats(): {
36
+ hits: number;
37
+ misses: number;
38
+ elkRuns: number;
39
+ entries: number;
40
+ bytes: number;
41
+ };
42
+ /**
43
+ * Lay out an ELK graph. ELK writes its result into the object it is given, so
44
+ * callers must pass a graph they will not reuse. The returned object is always
45
+ * private to the caller: on a cache hit it is a deep copy, so mutating it can
46
+ * never change what later renders see.
47
+ * @param {any} graph ELK input graph (plain JSON; consumed by the call).
48
+ * @param {{ cache?: boolean }} [options] `cache: false` bypasses the cache entirely.
49
+ * @returns {Promise<any>}
50
+ */
51
+ export declare function runElk(graph: any, options?: {
52
+ cache?: boolean;
53
+ }): Promise<any>;
@@ -73,6 +73,9 @@ export type GraphLayoutOptions = {
73
73
  * @param {GraphModel} model
74
74
  * @param {import("../../draw/theme.mjs").Theme} theme
75
75
  * @param {GraphLayoutOptions} [options]
76
+ * @param {{ layoutCache?: boolean }} [runtime] Per-render settings; `layoutCache: false` skips the layout cache.
76
77
  * @returns {Promise<GraphModel>}
77
78
  */
78
- export declare function layoutGraph(model: GraphModel, theme: import("../../draw/theme.mjs").Theme, options?: GraphLayoutOptions): Promise<GraphModel>;
79
+ export declare function layoutGraph(model: GraphModel, theme: import("../../draw/theme.mjs").Theme, options?: GraphLayoutOptions, runtime?: {
80
+ layoutCache?: boolean;
81
+ }): Promise<GraphModel>;
package/types/index.d.mts CHANGED
@@ -2,7 +2,7 @@
2
2
  * excaliplant — render PlantUML as hand-drawn Excalidraw diagrams, SVG and PNG.
3
3
  * @module excaliplant
4
4
  */
5
- export { render, renderAll, parse, detectKind, listDiagramTypes, renderPlantUml, RenderResult, defaultRegistry, } from "./api.mjs";
5
+ export { render, renderAll, parse, detectKind, listDiagramTypes, renderPlantUml, warmup, RenderResult, defaultRegistry, } from "./api.mjs";
6
6
  export { DiagramRegistry, defineDiagram } from "./core/registry.mjs";
7
7
  export { DEFAULT_LIMITS } from "./core/limits.mjs";
8
8
  export { ExcaliplantError, ParseError, LimitError } from "./core/errors.mjs";
@@ -32,6 +32,13 @@ export type RunOptions = {
32
32
  };
33
33
  export type Executor = {
34
34
  run: (tool: string, args: unknown, options: RunOptions) => Promise<import("./tools.mjs").CallToolResult>;
35
+ /**
36
+ * Pre-load the layout engine where the
37
+ * tools run, in the background. Resolves with whether the engine is loaded
38
+ * afterwards (never rejects). Calls are idempotent and a tool call never has
39
+ * to wait for it.
40
+ */
41
+ warmup?: () => Promise<boolean>;
35
42
  close: () => Promise<void>;
36
43
  };
37
44
  /**
@@ -42,6 +49,10 @@ export type Executor = {
42
49
  /**
43
50
  * @typedef {object} Executor
44
51
  * @property {(tool: string, args: unknown, options: RunOptions) => Promise<import("./tools.mjs").CallToolResult>} run
52
+ * @property {() => Promise<boolean>} [warmup] Pre-load the layout engine where the
53
+ * tools run, in the background. Resolves with whether the engine is loaded
54
+ * afterwards (never rejects). Calls are idempotent and a tool call never has
55
+ * to wait for it.
45
56
  * @property {() => Promise<void>} close
46
57
  */
47
58
  /**
@@ -59,16 +70,23 @@ export type WorkerExecutorOptions = {
59
70
  * Heap limit of the worker thread (default 768).
60
71
  */
61
72
  maxMemoryMb?: number;
73
+ /**
74
+ * Worker entry point (default `./worker.mjs`); for tests.
75
+ */
76
+ workerUrl?: URL;
62
77
  };
63
78
  /**
64
79
  * @typedef {object} WorkerExecutorOptions
65
80
  * @property {number} [maxQueue] Pending calls beyond the running one before `busy` (default 16).
66
81
  * @property {number} [maxMemoryMb] Heap limit of the worker thread (default 768).
82
+ * @property {URL} [workerUrl] Worker entry point (default `./worker.mjs`); for tests.
67
83
  */
68
84
  /**
69
85
  * Executor backed by one lazily started worker thread. Calls run one at a
70
86
  * time; a timeout or cancellation terminates the thread and the next call
71
- * starts a fresh one.
87
+ * starts a fresh one. After `warmup()` was called, every worker (also a
88
+ * restarted one) pre-loads the layout engine in the background, concurrently
89
+ * with the first calls: a call never waits for it.
72
90
  * @param {import("./tools.mjs").ToolEnv} env
73
91
  * @param {(message: string) => void} log
74
92
  * @param {WorkerExecutorOptions} [options]
@@ -41,6 +41,12 @@ export type ServerOptions = {
41
41
  * Where tools run (default "worker").
42
42
  */
43
43
  executor?: "worker" | "inline" | import("./executor.mjs").Executor;
44
+ /**
45
+ * Pre-load the layout engine in the background once a
46
+ * transport starts serving (see `McpServer.warmup`). Default: off, so embedding
47
+ * and tests start nothing eagerly; `excaliplant-mcp` turns it on (`--no-warmup` off).
48
+ */
49
+ warmup?: boolean;
44
50
  /**
45
51
  * Receives diagnostics for stderr. Default: silent.
46
52
  */
@@ -80,6 +86,13 @@ export type McpServer = {
80
86
  response: object | null;
81
87
  status: number;
82
88
  }>;
89
+ /**
90
+ * Start loading the layout engine where tools run (the
91
+ * worker thread) without blocking anything: requests are answered meanwhile and a tool call
92
+ * never waits for it. Transports call this once they serve. Resolves with whether the engine
93
+ * is loaded (false when disabled, closed or failed); never rejects.
94
+ */
95
+ warmup: () => Promise<boolean>;
83
96
  /**
84
97
  * Stop the executor and cancel everything in flight.
85
98
  */