@senad-d/drawme 0.1.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/src/drawio.ts ADDED
@@ -0,0 +1,363 @@
1
+ /**
2
+ * draw.io desktop CLI wrapper: binary resolution + export. Encodes the tricky
3
+ * flag knowledge from the skill (preview vs final export, the vision width cap,
4
+ * the `-e` PNG IEND repair, page indexing, Linux-headless quirks) so callers
5
+ * never hand-build a draw.io command line. Local-only — the only process it
6
+ * spawns is the draw.io CLI (and, on headless Linux, `xvfb-run`). No network.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { existsSync } from "node:fs";
10
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
11
+ import { basename, dirname, extname, join } from "node:path";
12
+ import { platform, tmpdir } from "node:os";
13
+ import { repairPng } from "./png";
14
+
15
+ export type ExportFormat = "png" | "svg" | "pdf" | "jpg";
16
+ export type ExportMode = "preview" | "final";
17
+
18
+ export interface DrawioInfo {
19
+ available: boolean;
20
+ binary?: string;
21
+ version?: string;
22
+ major?: number;
23
+ /** Mermaid import and the `--layout` pass both need draw.io v30+. */
24
+ supportsMermaid?: boolean;
25
+ supportsLayout?: boolean;
26
+ }
27
+
28
+ export interface ExportOptions {
29
+ input: string;
30
+ format?: ExportFormat;
31
+ mode?: ExportMode;
32
+ output?: string;
33
+ scale?: number;
34
+ width?: number;
35
+ height?: number;
36
+ transparent?: boolean;
37
+ border?: number;
38
+ pageIndex?: number;
39
+ embed?: boolean;
40
+ binary?: string;
41
+ }
42
+
43
+ export interface ExportPlan {
44
+ format: ExportFormat;
45
+ mode: ExportMode;
46
+ embed: boolean;
47
+ output: string;
48
+ /** Export flags ending with `-o <output>`. The input path is appended after these. */
49
+ args: string[];
50
+ input: string;
51
+ /** Flags that must go AFTER the input path on Linux (draw.io argument-parsing quirk). */
52
+ linuxExtra: string[];
53
+ }
54
+
55
+ /** Candidate binary names/paths, in resolution order (matches the skill's Step 1). */
56
+ const CANDIDATES = [
57
+ "drawio", // Homebrew cask, jgraph .deb/.rpm, Arch AUR
58
+ "draw.io", // older builds / custom symlinks
59
+ "/Applications/draw.io.app/Contents/MacOS/draw.io", // macOS .app bundle
60
+ String.raw`C:\Program Files\draw.io\draw.io.exe`, // Windows
61
+ String.raw`C:\Program Files (x86)\draw.io\draw.io.exe`,
62
+ "/mnt/c/Program Files/draw.io/draw.io.exe", // WSL2
63
+ ];
64
+
65
+ function run(bin: string, args: string[], timeout = 120_000): Promise<{ stdout: string; stderr: string }> {
66
+ return new Promise((resolve, reject) => {
67
+ execFile(bin, args, { timeout, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
68
+ if (err) {
69
+ (err as NodeJS.ErrnoException & { stderr?: string }).stderr = stderr?.toString();
70
+ const reason = err instanceof Error ? err : new Error("draw.io process failed with an unknown error");
71
+ reject(reason);
72
+ } else {
73
+ resolve({ stdout: stdout.toString(), stderr: stderr?.toString() ?? "" });
74
+ }
75
+ });
76
+ });
77
+ }
78
+
79
+ function parseMajor(version: string): number {
80
+ const m = /(\d+)/.exec(version);
81
+ return m ? Number.parseInt(m[1], 10) : 0;
82
+ }
83
+
84
+ /**
85
+ * Resolve the draw.io CLI. Tries an explicit `override` first, then the standard
86
+ * candidates. Absolute paths are existence-checked before spawning; PATH names are
87
+ * probed with `--version` (a short timeout guards the sandbox-hang case).
88
+ */
89
+ export async function resolveBinary(override?: string): Promise<DrawioInfo> {
90
+ const candidates = override ? [override, ...CANDIDATES] : CANDIDATES;
91
+ const tried = new Set<string>();
92
+ for (const bin of candidates) {
93
+ if (tried.has(bin)) continue;
94
+ tried.add(bin);
95
+ const looksLikePath = bin.includes("/") || bin.includes("\\");
96
+ if (looksLikePath && !existsSync(bin)) continue;
97
+ try {
98
+ const { stdout } = await run(bin, ["--version"], 15_000);
99
+ const version = stdout.trim().split(/\r?\n/)[0] ?? "";
100
+ if (version) {
101
+ const major = parseMajor(version);
102
+ return { available: true, binary: bin, version, major, supportsMermaid: major >= 30, supportsLayout: major >= 30 };
103
+ }
104
+ } catch {
105
+ // not this one — try the next candidate
106
+ }
107
+ }
108
+ return { available: false };
109
+ }
110
+
111
+ /** Derive a default output path next to the input, using the `.drawio.png` convention when embedding. */
112
+ export function deriveOutput(input: string, format: ExportFormat, embed: boolean): string {
113
+ const dir = dirname(input);
114
+ const ext = extname(input);
115
+ const base = ext ? basename(input).slice(0, -ext.length) : basename(input);
116
+ if (format === "png" && embed) return join(dir, `${base}.drawio.png`);
117
+ return join(dir, `${base}.${format}`);
118
+ }
119
+
120
+ /**
121
+ * Build the full export plan (no side effects) so the argument logic is unit-testable.
122
+ *
123
+ * Rules baked in from the skill:
124
+ * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
125
+ * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
126
+ * - `--width` and `-s` are never combined; an explicit width/height wins
127
+ * - `-t` (transparent) is PNG-only; `--page-index` is 1-based
128
+ */
129
+ export function planExport(opts: ExportOptions, plat: string = platform(), isRoot = false): ExportPlan {
130
+ const format = opts.format ?? "png";
131
+ const mode = opts.mode ?? "final";
132
+ const embed = opts.embed ?? (mode === "final" && format !== "jpg");
133
+ const output = opts.output ?? deriveOutput(opts.input, format, embed);
134
+ const raster = format === "png" || format === "jpg";
135
+
136
+ const args: string[] = ["-x", "-f", format];
137
+ if (embed) args.push("-e");
138
+ if (opts.width != null) args.push("--width", String(opts.width));
139
+ else if (opts.height != null) args.push("--height", String(opts.height));
140
+ else if (raster) {
141
+ if (mode === "preview") args.push("--width", "2000");
142
+ else args.push("-s", String(opts.scale ?? 2));
143
+ }
144
+ args.push("-b", String(opts.border ?? 10));
145
+ if (opts.transparent && format === "png") args.push("-t");
146
+ if (opts.pageIndex != null) args.push("--page-index", String(opts.pageIndex));
147
+ args.push("-o", output);
148
+
149
+ // On Linux these must trail the input filename, or draw.io treats them as the input.
150
+ const linuxExtra: string[] = [];
151
+ if (plat === "linux") {
152
+ linuxExtra.push("--disable-gpu");
153
+ if (isRoot) linuxExtra.push("--no-sandbox");
154
+ }
155
+ return { format, mode, embed, output, args, input: opts.input, linuxExtra };
156
+ }
157
+
158
+ export interface ExportResult {
159
+ output: string;
160
+ format: ExportFormat;
161
+ mode: ExportMode;
162
+ embed: boolean;
163
+ binary: string;
164
+ version?: string;
165
+ /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
166
+ repaired: boolean;
167
+ command: string;
168
+ }
169
+
170
+ function isRootUser(): boolean {
171
+ const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
172
+ return typeof getuid === "function" && getuid() === 0;
173
+ }
174
+
175
+ /** Run the export, wrapping in `xvfb-run` on headless Linux and falling back to a direct call if it's absent. */
176
+ async function invoke(binary: string, fullArgs: string[]): Promise<string> {
177
+ if (platform() === "linux" && !process.env.DISPLAY) {
178
+ try {
179
+ await run("xvfb-run", ["-a", "--server-args=-screen 0 1280x1024x24", binary, ...fullArgs]);
180
+ return `xvfb-run -a --server-args="-screen 0 1280x1024x24" ${binary} ${fullArgs.join(" ")}`;
181
+ } catch (e) {
182
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
183
+ // xvfb-run not installed — fall through to a direct call
184
+ }
185
+ }
186
+ await run(binary, fullArgs);
187
+ return `${binary} ${fullArgs.join(" ")}`;
188
+ }
189
+
190
+ /**
191
+ * Export a `.drawio` file to PNG/SVG/PDF/JPG. Resolves the binary, runs the CLI,
192
+ * and (for embedded PNG) repairs the truncated IEND chunk. Throws on missing
193
+ * input, missing CLI, or a failed export.
194
+ */
195
+ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult> {
196
+ if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
197
+ const info = await resolveBinary(opts.binary);
198
+ if (!info.available || !info.binary) {
199
+ throw new Error(
200
+ "draw.io CLI not found. Install draw.io desktop (macOS: `brew install --cask drawio`; " +
201
+ "others: https://github.com/jgraph/drawio-desktop/releases), or pass an explicit `binary` path.",
202
+ );
203
+ }
204
+
205
+ const plan = planExport(opts, platform(), isRootUser());
206
+ const fullArgs = [...plan.args, plan.input, ...plan.linuxExtra];
207
+
208
+ let command: string;
209
+ try {
210
+ command = await invoke(info.binary, fullArgs);
211
+ } catch (e) {
212
+ const detail = ((e as { stderr?: string }).stderr || (e as Error).message || String(e)).trim();
213
+ throw new Error(`draw.io export failed: ${detail}`, { cause: e });
214
+ }
215
+ if (!existsSync(plan.output)) {
216
+ throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
217
+ }
218
+
219
+ const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
220
+ return {
221
+ output: plan.output,
222
+ format: plan.format,
223
+ mode: plan.mode,
224
+ embed: plan.embed,
225
+ binary: info.binary,
226
+ version: info.version,
227
+ repaired,
228
+ command,
229
+ };
230
+ }
231
+
232
+ // --- Mermaid → .drawio conversion + ELK auto-layout (both need draw.io v30+) ---
233
+
234
+ /** Default `.drawio` output path derived from a source file. */
235
+ function drawioOutputFor(src: string): string {
236
+ const dir = dirname(src);
237
+ const ext = extname(src);
238
+ const base = ext ? basename(src).slice(0, -ext.length) : basename(src);
239
+ return join(dir, `${base}.drawio`);
240
+ }
241
+
242
+ async function requireBinary(minMajor: number, feature: string, override?: string): Promise<DrawioInfo & { binary: string }> {
243
+ const info = await resolveBinary(override);
244
+ if (!info.available || !info.binary) {
245
+ throw new Error(
246
+ "draw.io CLI not found. Install draw.io desktop (macOS: `brew install --cask drawio`; " +
247
+ "others: https://github.com/jgraph/drawio-desktop/releases), or pass an explicit `binary` path.",
248
+ );
249
+ }
250
+ if ((info.major ?? 0) < minMajor) {
251
+ throw new Error(
252
+ `${feature} needs draw.io v${minMajor}+, but ${info.version} is installed. Upgrade with \`brew upgrade --cask drawio\`.`,
253
+ );
254
+ }
255
+ return info as DrawioInfo & { binary: string };
256
+ }
257
+
258
+ /** Args for a Mermaid → .drawio conversion (pure, for testing). */
259
+ export function mermaidArgs(mmdPath: string, output: string): string[] {
260
+ return ["-x", "-f", "xml", "-o", output, mmdPath];
261
+ }
262
+
263
+ export interface MermaidOptions {
264
+ /** Path to a `.mmd` file. */
265
+ input?: string;
266
+ /** Inline Mermaid text (written to a temp `.mmd`); used when `input` is omitted. */
267
+ mermaid?: string;
268
+ output?: string;
269
+ binary?: string;
270
+ }
271
+ export interface MermaidResult {
272
+ output: string;
273
+ binary: string;
274
+ version?: string;
275
+ command: string;
276
+ }
277
+
278
+ /**
279
+ * Convert Mermaid text to a native `.drawio` (structure + automatic layout) via
280
+ * the CLI. Requires draw.io v30+. Never applies `--layout` afterwards — the
281
+ * conversion is already laid out.
282
+ */
283
+ export async function convertMermaid(opts: MermaidOptions): Promise<MermaidResult> {
284
+ const info = await requireBinary(30, "Mermaid conversion", opts.binary);
285
+
286
+ let mmdPath = opts.input;
287
+ let tempDir: string | undefined;
288
+ try {
289
+ if (!mmdPath) {
290
+ if (!opts.mermaid?.trim()) {
291
+ throw new Error("provide either `input` (a .mmd file path) or `mermaid` (inline Mermaid text)");
292
+ }
293
+ tempDir = await mkdtemp(join(tmpdir(), "drawme-mmd-"));
294
+ mmdPath = join(tempDir, "diagram.mmd");
295
+ await writeFile(mmdPath, opts.mermaid, "utf8");
296
+ } else if (!existsSync(mmdPath)) {
297
+ throw new Error(`input file not found: ${mmdPath}`);
298
+ }
299
+ const output = opts.output ?? (opts.input ? drawioOutputFor(opts.input) : join(process.cwd(), "diagram.drawio"));
300
+ const command = await invoke(info.binary, mermaidArgs(mmdPath, output));
301
+ if (!existsSync(output)) throw new Error(`conversion produced no output: ${output}`);
302
+ return { output, binary: info.binary, version: info.version, command };
303
+ } finally {
304
+ if (tempDir) await rm(tempDir, { recursive: true, force: true });
305
+ }
306
+ }
307
+
308
+ /** ELK layout presets the CLI accepts. Any other value opens a modal that hangs headless runs. */
309
+ export const LAYOUT_PRESETS = ["verticalFlow", "horizontalFlow", "verticalTree", "horizontalTree", "radialTree", "organic"] as const;
310
+ export type LayoutPreset = (typeof LAYOUT_PRESETS)[number];
311
+
312
+ /** Args for an ELK `--layout` pass (pure, for testing). */
313
+ export function layoutArgs(input: string, preset: LayoutPreset, output: string): string[] {
314
+ return ["-x", "-f", "xml", "--layout", preset, "-o", output, input];
315
+ }
316
+
317
+ export interface LayoutOptions {
318
+ input: string;
319
+ preset: LayoutPreset;
320
+ /** Defaults to a sibling `<name>.layout.drawio` (never overwrites the input unless you pass it explicitly). */
321
+ output?: string;
322
+ binary?: string;
323
+ }
324
+ export interface LayoutResult {
325
+ output: string;
326
+ preset: LayoutPreset;
327
+ binary: string;
328
+ version?: string;
329
+ command: string;
330
+ }
331
+
332
+ /**
333
+ * Re-place nodes and route edges with an ELK layout preset via the CLI. Requires
334
+ * draw.io v30+. The preset is validated against a strict allowlist first — an
335
+ * unknown value would open a modal error dialog that hangs a headless run.
336
+ */
337
+ export async function applyLayout(opts: LayoutOptions): Promise<LayoutResult> {
338
+ if (!LAYOUT_PRESETS.includes(opts.preset)) {
339
+ throw new Error(`unknown layout preset '${opts.preset}'. Allowed: ${LAYOUT_PRESETS.join(", ")}`);
340
+ }
341
+ if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
342
+ const info = await requireBinary(30, "The --layout pass", opts.binary);
343
+ const output = opts.output ?? join(dirname(opts.input), `${basename(opts.input, extname(opts.input))}.layout.drawio`);
344
+ const command = await invoke(info.binary, layoutArgs(opts.input, opts.preset, output));
345
+ if (!existsSync(output)) throw new Error(`layout produced no output: ${output}`);
346
+ return { output, preset: opts.preset, binary: info.binary, version: info.version, command };
347
+ }
348
+
349
+ /** Open a file in the OS default handler (draw.io desktop for `.drawio`). No version gate. */
350
+ export async function openFile(path: string): Promise<{ opener: string }> {
351
+ if (!existsSync(path)) throw new Error(`file not found: ${path}`);
352
+ const plat = platform();
353
+ if (plat === "darwin") {
354
+ await run("open", [path], 15_000);
355
+ return { opener: "open" };
356
+ }
357
+ if (plat === "win32") {
358
+ await run("cmd", ["/c", "start", "", path], 15_000);
359
+ return { opener: "start" };
360
+ }
361
+ await run("xdg-open", [path], 15_000);
362
+ return { opener: "xdg-open" };
363
+ }
package/src/explain.ts ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Describe a `.drawio` as structured Markdown — a pure-TypeScript port of the
3
+ * skill's `scripts/explain.py`. The inverse of authoring: it lists components
4
+ * (grouped by container/swimlane/tier), the relations between them (edge labels
5
+ * become the relation verb), and a per-page breakdown for multi-page files.
6
+ * Handy for a README/PR summary or a text-only read-back. Local-only, no network.
7
+ */
8
+ import { readFile } from "node:fs/promises";
9
+ import { basename } from "node:path";
10
+ import { DOMParser } from "@xmldom/xmldom";
11
+ import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
12
+
13
+ // style fragment -> human noun. First match wins; order matters (specific first).
14
+ const SHAPE_TYPES: [string, string][] = [
15
+ ["mxgraph.aws", "AWS"],
16
+ ["img/lib/azure", "Azure"],
17
+ ["mxgraph.gcp", "GCP"],
18
+ ["mxgraph.kubernetes", "Kubernetes"],
19
+ ["umlActor", "actor"],
20
+ ["shape=actor", "actor"],
21
+ ["shape=cylinder", "data store"],
22
+ ["shape=datastore", "data store"],
23
+ ["shape=cloud", "cloud"],
24
+ ["rhombus", "decision"],
25
+ ["mscae", "Azure"],
26
+ ["shape=process", "process"],
27
+ ["shape=hexagon", "queue"],
28
+ ];
29
+
30
+ /** Decode the HTML entities draw.io may leave in a doubly-encoded label. */
31
+ function decodeEntities(s: string): string {
32
+ return s
33
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(Number.parseInt(h, 16)))
34
+ .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number.parseInt(d, 10)))
35
+ .replaceAll("&quot;", '"')
36
+ .replaceAll("&apos;", "'")
37
+ .replaceAll("&lt;", "<")
38
+ .replaceAll("&gt;", ">")
39
+ .replaceAll("&nbsp;", " ")
40
+ .replaceAll("&amp;", "&");
41
+ }
42
+
43
+ /** Strip tag-shaped spans in linear time while preserving unmatched delimiters. */
44
+ function stripTags(text: string): string {
45
+ const parts: string[] = [];
46
+ let copiedThrough = 0;
47
+ let tagStart = -1;
48
+
49
+ for (let i = 0; i < text.length; i += 1) {
50
+ if (text[i] === "<" && tagStart === -1) {
51
+ tagStart = i;
52
+ } else if (text[i] === ">" && tagStart !== -1) {
53
+ if (i > tagStart + 1) {
54
+ parts.push(text.slice(copiedThrough, tagStart));
55
+ copiedThrough = i + 1;
56
+ }
57
+ tagStart = -1;
58
+ }
59
+ }
60
+
61
+ parts.push(text.slice(copiedThrough));
62
+ return parts.join("");
63
+ }
64
+
65
+ /** Strip HTML tags/entities draw.io stores in labels; collapse whitespace. */
66
+ function clean(text: string | null): string {
67
+ if (!text) return "";
68
+ const withLineBreaks = text.replace(/<br\s*\/?>/gi, " ");
69
+ return decodeEntities(stripTags(withLineBreaks)).replace(/\s+/g, " ").trim();
70
+ }
71
+
72
+ function shapeOf(style: string): string | null {
73
+ for (const [frag, noun] of SHAPE_TYPES) if ((style || "").includes(frag)) return noun;
74
+ return null;
75
+ }
76
+
77
+ interface Entry {
78
+ cell: DomEl;
79
+ id: string | null;
80
+ label: string;
81
+ }
82
+
83
+ /** Entries for a page, unwrapping UserObject/object wrappers; null for a compressed/empty page. */
84
+ function cellsOf(page: DomEl): Entry[] | null {
85
+ const model = firstByTag(page, "mxGraphModel");
86
+ const root = model ? firstByTag(model, "root") : null;
87
+ if (!root) return null;
88
+ const out: Entry[] = [];
89
+ for (const child of elemChildren(root)) {
90
+ if (child.tagName === "mxCell") {
91
+ out.push({ cell: child, id: attr(child, "id"), label: clean(attr(child, "value")) });
92
+ } else if (child.tagName === "UserObject" || child.tagName === "object") {
93
+ const inner = firstByTag(child, "mxCell");
94
+ if (inner) {
95
+ inner.setAttribute("id", attr(child, "id") ?? "");
96
+ out.push({ cell: inner, id: attr(child, "id"), label: clean(attr(child, "label") ?? attr(child, "value")) });
97
+ }
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+
103
+ interface PageIndex {
104
+ /** cell id -> cleaned label */
105
+ label: Map<string | null, string>;
106
+ /** cell id -> style string */
107
+ style: Map<string | null, string>;
108
+ /** ids of vertices that are a parent of some other cell */
109
+ containers: Set<string>;
110
+ }
111
+
112
+ /** Index a page's cells: labels, styles, and which vertices act as containers. */
113
+ function indexPage(cells: Entry[]): PageIndex {
114
+ const label = new Map<string | null, string>();
115
+ const style = new Map<string | null, string>();
116
+ const parents = new Set<string>();
117
+ for (const e of cells) {
118
+ label.set(e.id, e.label);
119
+ style.set(e.id, attr(e.cell, "style") ?? "");
120
+ const p = attr(e.cell, "parent");
121
+ if (p) parents.add(p);
122
+ }
123
+ const containers = new Set<string>();
124
+ for (const e of cells) {
125
+ if (e.cell.getAttribute("vertex") === "1" && e.id !== null && parents.has(e.id)) containers.add(e.id);
126
+ }
127
+ return { label, style, containers };
128
+ }
129
+
130
+ /** Leaf vertices: real nodes (not containers, not edge labels). */
131
+ function leafEntries(cells: Entry[], idx: PageIndex): Entry[] {
132
+ return cells.filter(
133
+ (e) =>
134
+ e.cell.getAttribute("vertex") === "1" &&
135
+ (e.id === null || !idx.containers.has(e.id)) &&
136
+ !(idx.style.get(e.id) ?? "").includes("edgeLabel"),
137
+ );
138
+ }
139
+
140
+ /** Group leaves by their container's label (else "Ungrouped"), keeping first-seen order. */
141
+ function groupLeaves(leaves: Entry[], idx: PageIndex): { groups: Map<string, string[]>; order: string[] } {
142
+ const groups = new Map<string, string[]>();
143
+ const order: string[] = [];
144
+ for (const e of leaves) {
145
+ const parent = attr(e.cell, "parent");
146
+ const named = parent !== null && idx.containers.has(parent) ? idx.label.get(parent) || "" : "";
147
+ const gname = named || "Ungrouped";
148
+ if (!groups.has(gname)) {
149
+ groups.set(gname, []);
150
+ order.push(gname);
151
+ }
152
+ const typ = shapeOf(idx.style.get(e.id) ?? "");
153
+ const name = idx.label.get(e.id) || `(unlabeled ${e.id})`;
154
+ groups.get(gname)!.push(name + (typ ? ` _${typ}_` : ""));
155
+ }
156
+ return { groups, order };
157
+ }
158
+
159
+ function renderComponents(leaves: Entry[], groups: Map<string, string[]>, order: string[]): string[] {
160
+ const lines: string[] = [`### Components (${leaves.length})`, ""];
161
+ const single = order.length === 1 && order[0] === "Ungrouped";
162
+ for (const gname of order) {
163
+ if (single) {
164
+ for (const item of groups.get(gname)!) lines.push(`- ${item}`);
165
+ } else {
166
+ lines.push(`- **${gname}**`);
167
+ for (const item of groups.get(gname)!) lines.push(` - ${item}`);
168
+ }
169
+ }
170
+ lines.push("");
171
+ return lines;
172
+ }
173
+
174
+ function renderRelations(cells: Entry[], idx: PageIndex): string[] {
175
+ const rels: string[] = [];
176
+ for (const e of cells) {
177
+ if (e.cell.getAttribute("edge") !== "1") continue;
178
+ const s = idx.label.get(attr(e.cell, "source"));
179
+ const t = idx.label.get(attr(e.cell, "target"));
180
+ if (!s || !t) continue; // dangling endpoint — skip
181
+ const verb = clean(attr(e.cell, "value"));
182
+ rels.push(verb ? `- ${s} —${verb}→ ${t}` : `- ${s} → ${t}`);
183
+ }
184
+ return [`### Relations (${rels.length})`, "", ...(rels.length ? rels : ["_(none)_"]), ""];
185
+ }
186
+
187
+ function describePage(page: DomEl): string[] {
188
+ const cells = cellsOf(page);
189
+ if (cells === null) return ["_(compressed page — cannot describe)_"];
190
+ const idx = indexPage(cells);
191
+ const leaves = leafEntries(cells, idx);
192
+ const { groups, order } = groupLeaves(leaves, idx);
193
+ return [...renderComponents(leaves, groups, order), ...renderRelations(cells, idx)];
194
+ }
195
+
196
+ /** Describe a `.drawio` XML string as Markdown. */
197
+ export function explainXml(xml: string, title = "diagram"): string {
198
+ const doc = new DOMParser().parseFromString(xml, "text/xml");
199
+ const rootEl = doc.documentElement as unknown as DomEl | null;
200
+ if (!rootEl) throw new Error("no root element (malformed XML)");
201
+ const pageList = childrenByTag(rootEl, "diagram");
202
+ const pages = pageList.length ? pageList : [rootEl];
203
+
204
+ const lines: string[] = [`# ${title}`, ""];
205
+ pages.forEach((page, i) => {
206
+ if (pages.length > 1) {
207
+ const name = attr(page, "name");
208
+ lines.push(name ? `## Page ${i + 1}: ${name}` : `## Page ${i + 1}`, "");
209
+ }
210
+ lines.push(...describePage(page));
211
+ });
212
+ return lines.join("\n").trimEnd() + "\n";
213
+ }
214
+
215
+ /** Read a `.drawio` file and describe it as Markdown. */
216
+ export async function explainFile(path: string): Promise<string> {
217
+ const xml = await readFile(path, "utf8");
218
+ const title = basename(path).replace(/\.[^.]*$/, "");
219
+ return explainXml(xml, title);
220
+ }