@grethel-labs/excaliplant 0.1.0 → 0.1.2

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
@@ -1,22 +1,104 @@
1
+
1
2
  # excaliplant
2
3
 
3
- PlantUML → Excalidraw renderer with a plugin-based parser. Standalone library.
4
+ > PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.  ·  **v0.1.2**  ·  73 tests  ·  MIT
5
+
6
+ `@grethel-labs/excaliplant` takes PlantUML source, runs it through a plugin-based
7
+ parser, lays it out with [ELK](https://github.com/kieler/elkjs), and
8
+ emits a `.excalidraw` JSON document — opening cleanly in any
9
+ Excalidraw front-end. Optional helpers convert the result to SVG or
10
+ PNG so the same pipeline can also produce static documentation
11
+ artefacts.
12
+
13
+ <table>
14
+ <tr>
15
+ <td align="center" width="50%">
16
+ <a href="docs/ressources/generated/png/modules.png"><img src="docs/ressources/generated/png/modules.png" alt="Module structure" width="380"/></a><br/>
17
+ <sub><b>Module structure</b> — rendered by excaliplant itself</sub>
18
+ </td>
19
+ <td align="center" width="50%">
20
+ <a href="docs/ressources/generated/png/sequence.png"><img src="docs/ressources/generated/png/sequence.png" alt="renderPlantUml flow" width="380"/></a><br/>
21
+ <sub><b>renderPlantUml flow</b> — rendered by excaliplant itself</sub>
22
+ </td>
23
+ </tr>
24
+ </table>
25
+
26
+ > ⚠️ This README is generated. Edit
27
+ > [`docs/README.template.md.njk`](./docs/README.template.md.njk) and
28
+ > run `npm run build:docs`.
29
+
30
+ ---
31
+
32
+ ## How to use
33
+
34
+ ### Install
35
+
36
+ ```sh
37
+ npm install @grethel-labs/excaliplant
38
+ ```
39
+
40
+ `@resvg/resvg-js` is pulled in as a runtime dependency so the SVG and
41
+ PNG export paths work out of the box.
42
+
43
+ ### Render PlantUML to an Excalidraw document
44
+
45
+ ```js
46
+ import { renderPlantUml } from "@grethel-labs/excaliplant";
47
+
48
+ const excalidraw = await renderPlantUml(plantumlText, { sourceLabel: "demo" });
49
+ // → write `excalidraw` to disk as <name>.excalidraw, or hand it to an
50
+ // Excalidraw embed.
51
+ ```
52
+
53
+ ### Render to SVG / PNG
54
+
55
+ ```js
56
+ import {
57
+ renderPlantUml,
58
+ excalidrawJsonToCanvasSvg,
59
+ svgToPng,
60
+ } from "@grethel-labs/excaliplant";
61
+
62
+ const doc = await renderPlantUml(plantumlText);
63
+ const svg = excalidrawJsonToCanvasSvg(doc, { width: 1200 });
64
+ const png = svgToPng(svg, { width: 4800 }); // 4× SVG width
65
+ ```
66
+
67
+ Lower-level entry points are also exported:
68
+
69
+ | Export | Purpose |
70
+ | ------------------------------- | ------------------------------------------------ |
71
+ | `parsePlantUml(text)` | PlantUML → `Diagram` model |
72
+ | `layoutDiagram(diagram)` | Sizing + ELK layout + edge routing |
73
+ | `exportDiagram(diagram)` | Diagram → Excalidraw JSON |
74
+ | `excalidrawToSvg(doc)` | Excalidraw JSON → tightly-cropped SVG |
75
+ | `excalidrawJsonToCanvasSvg(…)` | …same, letter-boxed onto a fixed-aspect canvas |
76
+ | `svgToPng(svg)` | Rasterise SVG to PNG (`@resvg/resvg-js`) |
77
+
78
+ ### Run the tests
79
+
80
+ ```sh
81
+ npm test
82
+ ```
83
+
84
+ Ships with **73 tests** across functional, edge-case,
85
+ security (XSS / ReDoS / prototype-pollution), and self-introspection
86
+ suites.
4
87
 
5
- <!-- BEGIN:version -->
6
- **Version:** `0.1.0`
7
- <!-- END:version -->
88
+ ---
8
89
 
9
- ## Self-rendered diagrams
90
+ ## Self-rendered architecture diagrams
10
91
 
11
- The diagrams below are generated **by excaliplant itself** at build time
12
- (`npm run build:docs`) from PlantUML sources that describe this very
13
- repository. The doc snippets under each image are extracted from the
14
- source code via `@diagram` JSDoc tags.
92
+ The diagrams below are produced **by excaliplant itself** at build
93
+ time from PlantUML sources that describe this very repository. The
94
+ text under each image is extracted from the source via `@diagram`
95
+ JSDoc tags.
15
96
 
16
- <!-- BEGIN:diagrams -->
17
97
  ### Module structure
18
98
 
19
- ![Module structure](./docs/modules.svg)
99
+ ![Module structure](docs/ressources/generated/png/modules.png)
100
+
101
+ _Sources: [PlantUML](docs/ressources/generated/puml/modules.puml) · [SVG](docs/ressources/generated/svg/modules.svg)_
20
102
 
21
103
  The module graph reflects how the source is laid out under
22
104
  [`src/`](./src/). Note in particular how the parser is split into a
@@ -25,7 +107,9 @@ each plugin handling one PlantUML construct.
25
107
 
26
108
  ### renderPlantUml flow
27
109
 
28
- ![renderPlantUml flow](./docs/sequence.svg)
110
+ ![renderPlantUml flow](docs/ressources/generated/png/sequence.png)
111
+
112
+ _Sources: [PlantUML](docs/ressources/generated/puml/sequence.puml) · [SVG](docs/ressources/generated/svg/sequence.svg)_
29
113
 
30
114
  The call graph for `renderPlantUml(text)` walks three subsystems:
31
115
 
@@ -42,7 +126,9 @@ The call graph for `renderPlantUml(text)` walks three subsystems:
42
126
 
43
127
  ### Parser plugins
44
128
 
45
- ![Parser plugins](./docs/plugins.svg)
129
+ ![Parser plugins](docs/ressources/generated/png/plugins.png)
130
+
131
+ _Sources: [PlantUML](docs/ressources/generated/puml/plugins.puml) · [SVG](docs/ressources/generated/svg/plugins.svg)_
46
132
 
47
133
  Each parser plugin is a tiny self-contained file that handles ONE
48
134
  PlantUML construct. The engine offers each input line to plugins
@@ -52,12 +138,86 @@ To add support for a new PlantUML keyword, drop a new file in
52
138
  `src/parser/plugins/` and append it to the default array in
53
139
  [`plantuml.mjs`](./src/parser/plantuml.mjs). No engine change required.
54
140
 
55
- <!-- END:diagrams -->
141
+ ## Pipeline
142
+
143
+ ```text
144
+ PlantUML text
145
+ │ parsePlantUml()
146
+ ▼
147
+ Diagram (planes, subplanes, boxes, connections)
148
+ │ layoutDiagram() (sizing → ELK layered + orthogonal routing → chamfer)
149
+ ▼
150
+ Diagram with absolute positions and edge paths
151
+ │ exportDiagram()
152
+ ▼
153
+ Excalidraw JSON
154
+ │ excalidrawJsonToCanvasSvg() (optional)
155
+ ▼
156
+ SVG ── svgToPng() ──▶ PNG (both optional, no headless browser)
157
+ ```
158
+
159
+ ## Repository layout
160
+
161
+ ```text
162
+ excaliplant
163
+ ├── docs
164
+ │ ├── ressources
165
+ │ ├── scripts
166
+ │ │ ├── build-docs.mjs
167
+ │ │ ├── config.mjs
168
+ │ │ ├── extract-docs.mjs
169
+ │ │ ├── file-tree.mjs
170
+ │ │ └── self-diagrams.mjs
171
+ │ └── README.template.md.njk
172
+ ├── scripts
173
+ │ ├── auto-patch-deps.mjs
174
+ │ └── smoke.mjs
175
+ ├── src
176
+ │ ├── layout
177
+ │ │ ├── elk_layout.mjs
178
+ │ │ ├── sequence_layout.mjs
179
+ │ │ └── sizing.mjs
180
+ │ ├── model
181
+ │ │ └── diagram.mjs
182
+ │ ├── parser
183
+ │ │ ├── plugins
184
+ │ │ │ ├── component
185
+ │ │ │ └── sequence
186
+ │ │ ├── component_context.mjs
187
+ │ │ ├── engine.mjs
188
+ │ │ ├── plantuml.mjs
189
+ │ │ ├── sequence_context.mjs
190
+ │ │ └── utils.mjs
191
+ │ ├── render
192
+ │ │ ├── canvas_svg.mjs
193
+ │ │ ├── excalidraw.mjs
194
+ │ │ ├── png.mjs
195
+ │ │ ├── sequence_render.mjs
196
+ │ │ └── svg.mjs
197
+ │ └── style
198
+ │ ├── colors.mjs
199
+ │ └── text.mjs
200
+ ├── tests
201
+ │ ├── edge_cases.test.mjs
202
+ │ ├── functional_more.test.mjs
203
+ │ ├── plantuml.test.mjs
204
+ │ ├── security.test.mjs
205
+ │ └── self_introspection.test.mjs
206
+ ├── LICENSE
207
+ ├── README.md
208
+ ├── index.mjs
209
+ ├── package.json
210
+ ├── tsconfig.json
211
+ └── typedoc.json
212
+ ```
213
+
214
+ Generated artefacts (`docs/ressources/generated/`, `docs/api/`) live
215
+ in `.gitignore` — they are rebuilt by `npm run build:docs` and
216
+ `npm run build:api`.
56
217
 
57
218
  ## Module documentation
58
219
 
59
- <!-- BEGIN:module-docs -->
60
- #### layout
220
+ ### layout
61
221
 
62
222
  Layout chooses positions for every shape and routes every edge.
63
223
  Component / use-case / deployment diagrams flow through ELK
@@ -70,7 +230,7 @@ tabular (lifelines on the X axis, time on the Y axis), so a
70
230
  deterministic ~90-line algorithm produces better, more compact
71
231
  results than a force-directed solver could.
72
232
 
73
- #### model
233
+ ### model
74
234
 
75
235
  Input-agnostic diagram model. Two top-level kinds:
76
236
 
@@ -84,7 +244,7 @@ pipeline; the parser is just one possible source. Callers can
84
244
  also build a `Diagram` programmatically and feed it to
85
245
  `renderDiagram()`.
86
246
 
87
- #### parser/engine
247
+ ### parser/engine
88
248
 
89
249
  A ~50-line line-walker. The engine itself knows nothing about
90
250
  PlantUML syntax; that lives entirely in plugins. Block plugins
@@ -92,6 +252,7 @@ PlantUML syntax; that lives entirely in plugins. Block plugins
92
252
  subsequent lines until they release.
93
253
 
94
254
  Plugin contract:
255
+
95
256
  ```js
96
257
  {
97
258
  name,
@@ -100,7 +261,7 @@ Plugin contract:
100
261
  }
101
262
  ```
102
263
 
103
- #### render
264
+ ### render
104
265
 
105
266
  Emits Excalidraw JSON. Each model shape is dispatched to a
106
267
  dedicated `renderXxx()` function that produces one or more
@@ -110,193 +271,6 @@ that any Excalidraw front-end can open. The companion module
110
271
  [`src/render/svg.mjs`](./src/render/svg.mjs) converts the same
111
272
  JSON to SVG for the build-time documentation pipeline.
112
273
 
113
- <!-- END:module-docs -->
274
+ ## License
114
275
 
115
- ## Pipeline
116
-
117
- ```
118
- PlantUML text
119
- │ parsePlantUml()
120
- ▼
121
- Diagram (planes, subplanes, boxes, connections)
122
- │ layoutDiagram() (sizing → ELK layered + orthogonal routing → chamfer)
123
- ▼
124
- Diagram with absolute positions and edge paths
125
- │ exportDiagram()
126
- ▼
127
- Excalidraw JSON
128
- ```
129
-
130
- ## API
131
-
132
- ```js
133
- import { renderPlantUml } from "./index.mjs";
134
-
135
- const excalidraw = await renderPlantUml(plantumlText, { sourceLabel: "demo" });
136
- ```
137
-
138
- Lower-level entry points (`parsePlantUml`, `layoutDiagram`,
139
- `exportDiagram`, `renderDiagram`) are also exported. The model classes
140
- (`Diagram`, `Plane`, `Subplane`, `Box`, `Connection`) are exported for
141
- callers that want to construct shapes programmatically.
142
-
143
- ## Supported PlantUML subset
144
-
145
- ### Component / use-case / deployment diagrams
146
-
147
- ```plantuml
148
- @startuml
149
- title "<free text>"
150
-
151
- ' --- containers (any nest the others) -------------------------------
152
- package "<Title>" as <id> { ... }
153
- frame "<Title>" as <id> { ... }
154
- folder "<Title>" as <id> { ... }
155
- node "<Title>" as <id> { ... }
156
- rectangle "<Title>" as <id> { ... }
157
- together { ... }
158
-
159
- ' --- shapes --------------------------------------------------------
160
- [Title] as <id> [: description]
161
- component "Title" <<stereo>> as <id> [: description]
162
- rectangle "Title" as <id>
163
- actor "Title" as <id> ' or just `actor User`
164
- usecase "Title" as <id> ' or `(Title) as <id>`
165
- database "Title" as <id>
166
- node "Title" as <id> ' (no `{}` → 3-D box shape)
167
- cloud "Title" as <id>
168
- interface "Title" as <id> ' rendered as a small "lollipop" circle
169
- entity "Title" as <id>
170
- class "Title" as <id> { member; member }
171
-
172
- ' --- connections ---------------------------------------------------
173
- a --> b : label ' solid arrow
174
- a <-- b
175
- a <--> b
176
- a -up-> b ' direction hint (up|down|left|right)
177
- a ..> b ' dependency (dashed)
178
- a <|-- b ' inheritance (triangle on parent)
179
- a ..|> b ' realization (dashed + triangle)
180
- a *-- b ' composition (filled diamond)
181
- a o-- b ' aggregation (open diamond)
182
-
183
- ' --- notes ---------------------------------------------------------
184
- note left of <id> : text
185
- note right of <id> : text
186
- note top of <id> : text
187
- note bottom of <id> : text
188
- note "free standing text" as N1
189
- N1 .. <id>
190
-
191
- ' Multi-line text everywhere via \n.
192
- @enduml
193
- ```
194
-
195
- ### Sequence diagrams
196
-
197
- The parser auto-switches to the sequence pipeline as soon as it sees a
198
- `participant`/`boundary`/`control`/`collections`/`queue` keyword.
199
-
200
- ```plantuml
201
- @startuml
202
- title "Login flow"
203
- actor User
204
- participant "Web UI" as ui
205
- participant Auth as auth
206
- database DB
207
-
208
- User -> ui : open page
209
- ui -> auth : login(name, pwd)
210
- auth -> DB : SELECT user
211
- DB --> auth : row ' dashed = reply
212
- auth --> ui : ok\n(token)
213
- ui --> User : show home
214
- auth -> auth : audit ' self-message (loop arrow)
215
-
216
- note right of auth : token has\n5 min ttl
217
- note over ui, auth : TLS only
218
- @enduml
219
- ```
220
-
221
- Sequence diagrams use a separate, deterministic tabular layout (no ELK),
222
- since lifelines + time form a strictly tabular structure.
223
-
224
- ## Architecture
225
-
226
- The parser is built around a tiny line-driven engine plus a list of
227
- self-contained **plugins** (one per PlantUML construct):
228
-
229
- ```
230
- src/parser/
231
- ├── engine.mjs ← ~50 lines, walks lines + dispatches to plugins
232
- ├── utils.mjs ← shared regexes / helpers (slug, classifyArrow, …)
233
- ├── component_context.mjs ← mutable state for component-style parses
234
- ├── sequence_context.mjs ← mutable state for sequence parses
235
- ├── plantuml.mjs ← entry: dispatch + plugin registry
236
- └── plugins/
237
- ├── component/
238
- │ ├── preamble.mjs ← title, closing brace
239
- │ ├── containers.mjs ← package / frame / folder / node / rectangle / together
240
- │ ├── shapes.mjs ← [X], (Y), shape keywords, class { members }
241
- │ ├── connections.mjs ← all arrow flavours
242
- │ └── notes.mjs ← note of, free notes, multi-line note blocks
243
- └── sequence/
244
- ├── preamble.mjs ← title
245
- ├── participants.mjs
246
- ├── messages.mjs
247
- └── notes.mjs ← side / over notes (single + multi-line)
248
- ```
249
-
250
- A plugin is just `{ name, tryLine?(line, ctx), tryStart?(line, ctx) }`
251
- — see `engine.mjs` for the full contract. Block plugins (notes, class
252
- bodies) take over the engine until they decide to release.
253
-
254
- ### Adding a new construct
255
-
256
- 1. Create a new plugin file in `plugins/component/` or `plugins/sequence/`.
257
- 2. Register it in `DEFAULT_COMPONENT_PLUGINS` / `DEFAULT_SEQUENCE_PLUGINS`
258
- in `plantuml.mjs`. Order matters only when several plugins might match
259
- the same line.
260
-
261
- ### Injecting plugins from outside
262
-
263
- Without forking, callers can append their own plugins:
264
-
265
- ```js
266
- parsePlantUml(src, {
267
- plugins: {
268
- component: [...DEFAULT_COMPONENT_PLUGINS, myCustomPlugin],
269
- },
270
- });
271
- ```
272
-
273
- ## Dependencies
274
-
275
- - [`elkjs`](https://www.npmjs.com/package/elkjs) — Eclipse Layout Kernel
276
- (port to JS). Provides hierarchical layered layout + orthogonal edge
277
- routing.
278
- - Excalidraw is consumed via its **file-format API**: this lib emits
279
- the JSON document that any Excalidraw front-end can open. We do not
280
- bundle the Excalidraw React component (47 MB, browser/DOM-bound;
281
- not usable in Node).
282
-
283
- ### Why not delegate parsing / rendering to a third-party library?
284
-
285
- We evaluated:
286
-
287
- | Candidate | Outcome |
288
- |---|---|
289
- | `plantuml-parser` (Enteee) | Drops `title`, `note`, `actor`/`database`/`cloud`/`entity`/`rectangle` shape declarations, sequence participants, and `-up->` direction hints — too lossy to replace our parser without re-introducing the same regex code as a "supplementary scanner". |
290
- | `@excalidraw/excalidraw` | 47 MB React component, depends on `window` / `canvas`. Not usable in a Node library. |
291
- | `@excalidraw/utils` | 96 MB, same DOM dependencies. Not usable. |
292
- | `@excalidraw/mermaid-to-excalidraw` | Mermaid-only input; doesn't expose a generic skeleton API. |
293
-
294
- So instead we make our **own** parser easy to extend (plugin
295
- architecture above) and our renderer talks to Excalidraw via its
296
- documented JSON file format.
297
-
298
- ## Tests
299
-
300
- ```sh
301
- npm test
302
- ```
276
+ MIT © grethel-labs
package/index.mjs CHANGED
@@ -53,6 +53,13 @@ import { exportDiagram } from "./src/render/excalidraw.mjs";
53
53
  export { parsePlantUml } from "./src/parser/plantuml.mjs";
54
54
  export { layoutDiagram } from "./src/layout/elk_layout.mjs";
55
55
  export { exportDiagram } from "./src/render/excalidraw.mjs";
56
+ export { excalidrawToSvg } from "./src/render/svg.mjs";
57
+ export {
58
+ excalidrawJsonToCanvasSvg,
59
+ DEFAULT_CANVAS_WIDTH,
60
+ DEFAULT_ASPECT_RATIO,
61
+ } from "./src/render/canvas_svg.mjs";
62
+ export { svgToPng } from "./src/render/png.mjs";
56
63
  export {
57
64
  Box, Connection, Diagram, Plane, Subplane,
58
65
  Participant, Message, SequenceDiagram, SequenceNote,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grethel-labs/excaliplant",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
@@ -15,11 +15,14 @@
15
15
  "./parser/plantuml": "./src/parser/plantuml.mjs",
16
16
  "./layout": "./src/layout/elk_layout.mjs",
17
17
  "./render": "./src/render/excalidraw.mjs",
18
+ "./render/svg": "./src/render/svg.mjs",
19
+ "./render/canvas-svg": "./src/render/canvas_svg.mjs",
20
+ "./render/png": "./src/render/png.mjs",
18
21
  "./model": "./src/model/diagram.mjs"
19
22
  },
20
23
  "scripts": {
21
- "test": "node --test tests/*.test.mjs",
22
- "build:docs": "node scripts/build-docs.mjs",
24
+ "test": "node --test tests/edge_cases.test.mjs tests/functional_more.test.mjs tests/plantuml.test.mjs tests/security.test.mjs tests/self_introspection.test.mjs",
25
+ "build:docs": "node docs/scripts/build-docs.mjs",
23
26
  "build:api": "typedoc",
24
27
  "build": "npm run build:docs && npm run build:api",
25
28
  "prepublishOnly": "npm test && npm run build"
@@ -41,13 +44,16 @@
41
44
  "access": "public"
42
45
  },
43
46
  "dependencies": {
44
- "elkjs": "^0.9.3"
47
+ "@resvg/resvg-js": "^2.6.2",
48
+ "elkjs": "^0.11.1"
45
49
  },
46
50
  "engines": {
47
51
  "node": ">=18"
48
52
  },
49
53
  "license": "MIT",
50
54
  "devDependencies": {
55
+ "nunjucks": "^3.2.4",
56
+ "tree-node-cli": "^1.6.0",
51
57
  "typedoc": "^0.28.19"
52
58
  }
53
59
  }
@@ -12,6 +12,7 @@
12
12
  * subsequent lines until they release.
13
13
  *
14
14
  * Plugin contract:
15
+ *
15
16
  * ```js
16
17
  * {
17
18
  * name,
@@ -0,0 +1,70 @@
1
+ // Canvas-letterboxed SVG export.
2
+ //
3
+ // Wraps the plain `excalidrawToSvg` output in a fixed-aspect canvas
4
+ // so multiple diagrams render at the same proportions (useful when
5
+ // embedding several PNGs side-by-side in a document).
6
+ //
7
+ // This is part of the optional rendering API. The plain SVG path has
8
+ // no extra runtime dependencies; the PNG path
9
+ // (`./png.mjs`) needs `@resvg/resvg-js` to be installed.
10
+
11
+ import { excalidrawToSvg } from "./svg.mjs";
12
+
13
+ export const DEFAULT_CANVAS_WIDTH = 1200;
14
+ export const DEFAULT_ASPECT_RATIO = { w: 4, h: 3 };
15
+
16
+ /**
17
+ * Convert an Excalidraw JSON document to an SVG that has been
18
+ * letter-boxed onto a fixed-aspect canvas.
19
+ *
20
+ * @param {object} doc Excalidraw JSON document.
21
+ * @param {object} [opts]
22
+ * @param {{w:number,h:number}} [opts.aspect] Canvas aspect ratio.
23
+ * @param {number} [opts.width] Canvas width in px.
24
+ * @param {string} [opts.background] Canvas background fill.
25
+ * @param {number} [opts.padding] Inner SVG padding.
26
+ * @returns {string} A canvas-sized SVG document.
27
+ */
28
+ export function excalidrawJsonToCanvasSvg(doc, opts = {}) {
29
+ const aspect = opts.aspect ?? DEFAULT_ASPECT_RATIO;
30
+ const width = opts.width ?? DEFAULT_CANVAS_WIDTH;
31
+ const height = Math.round((width * aspect.h) / aspect.w);
32
+ const background = opts.background ?? "#ffffff";
33
+ const padding = opts.padding ?? 16;
34
+
35
+ const inner = excalidrawToSvg(doc, { padding });
36
+ const innerVb = parseViewBox(inner);
37
+ if (!innerVb) return blankCanvas(width, height, background);
38
+
39
+ const scale = Math.min(width / innerVb.w, height / innerVb.h);
40
+ const drawnW = innerVb.w * scale;
41
+ const drawnH = innerVb.h * scale;
42
+ const offsetX = (width - drawnW) / 2;
43
+ const offsetY = (height - drawnH) / 2;
44
+
45
+ const innerBody = inner.replace(/^<svg[^>]*>/, "").replace(/<\/svg>\s*$/, "");
46
+
47
+ return [
48
+ `<svg xmlns="http://www.w3.org/2000/svg" `
49
+ + `width="${width}" height="${height}" `
50
+ + `viewBox="0 0 ${width} ${height}">`,
51
+ `<rect width="${width}" height="${height}" fill="${background}"/>`,
52
+ `<g transform="translate(${offsetX} ${offsetY}) scale(${scale}) `
53
+ + `translate(${-innerVb.x} ${-innerVb.y})">`,
54
+ innerBody,
55
+ `</g>`,
56
+ `</svg>`,
57
+ ].join("");
58
+ }
59
+
60
+ function parseViewBox(svgText) {
61
+ const m = svgText.match(/viewBox="([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)"/);
62
+ if (!m) return null;
63
+ return { x: +m[1], y: +m[2], w: +m[3], h: +m[4] };
64
+ }
65
+
66
+ function blankCanvas(w, h, bg) {
67
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" `
68
+ + `viewBox="0 0 ${w} ${h}">`
69
+ + `<rect width="${w}" height="${h}" fill="${bg}"/></svg>`;
70
+ }
@@ -0,0 +1,28 @@
1
+ // PNG rasterisation for SVGs produced by `./svg.mjs` or
2
+ // `./canvas_svg.mjs`.
3
+ //
4
+ // Uses `@resvg/resvg-js` (a runtime dependency of this package). No
5
+ // headless browser is involved.
6
+
7
+ import { Resvg } from "@resvg/resvg-js";
8
+
9
+ const DEFAULT_PNG_WIDTH = 4800; // 4× the default 1200 SVG canvas.
10
+
11
+ /**
12
+ * Rasterise an SVG document to PNG.
13
+ *
14
+ * @param {string} svgText
15
+ * @param {object} [opts]
16
+ * @param {number} [opts.width=4800] Output PNG width in px.
17
+ * @param {string} [opts.background="#ffffff"]
18
+ * @returns {Buffer} PNG bytes.
19
+ */
20
+ export function svgToPng(svgText, opts = {}) {
21
+ const width = opts.width ?? DEFAULT_PNG_WIDTH;
22
+ const resvg = new Resvg(svgText, {
23
+ fitTo: { mode: "width", value: width },
24
+ background: opts.background ?? "#ffffff",
25
+ font: { loadSystemFonts: true },
26
+ });
27
+ return resvg.render().asPng();
28
+ }