@senad-d/drawme 0.1.9 → 0.1.11

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/package.json +2 -2
  3. package/src/drawio.ts +101 -27
package/CHANGELOG.md CHANGED
@@ -6,6 +6,19 @@ All notable changes to this project are documented here. The format is based on
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.1.11] - 2026-11-09
10
+
11
+ ### Fixed
12
+
13
+ - Final PNG/JPG exports use the selected page's content width and height to lower the raster scale when needed, targeting a six-million-pixel budget to avoid draw.io `UnknownVizError` failures. Explicit width and height requests remain unchanged.
14
+
15
+ ## [0.1.10] - 2026-10-27
16
+
17
+ ### Fixed
18
+
19
+ - Headless Linux exports size the Xvfb screen to the requested raster (floor 1280x1024, cap 8192) instead of a fixed 1280x1024: a final PNG wider than the screen made draw.io fail with `UnknownVizError` and hang until the timeout.
20
+ - A timed-out export now ends its whole process tree (xvfb-run, Xvfb, draw.io) instead of leaving orphans, and the failure message keeps draw.io's stderr next to the timeout reason.
21
+
9
22
  ## [0.1.9] - 2026-10-11
10
23
 
11
24
  ### Fixed
@@ -135,6 +148,8 @@ Initial release: DrawMe as a native Pi extension for authoring, validating, and
135
148
  - Tooling: ESLint flat config, custom `format:check`, `check:golden` asset-integrity check, Vitest suite
136
149
  with real-CLI integration tests, CI, SonarCloud, and release workflows.
137
150
 
138
- [Unreleased]: https://github.com/senad-d/DrawMe/compare/v0.1.9...HEAD
151
+ [Unreleased]: https://github.com/senad-d/DrawMe/compare/v0.1.11...HEAD
152
+ [0.1.11]: https://github.com/senad-d/DrawMe/compare/v0.1.10...v0.1.11
153
+ [0.1.10]: https://github.com/senad-d/DrawMe/compare/v0.1.9...v0.1.10
139
154
  [0.1.9]: https://github.com/senad-d/DrawMe/compare/v0.0.1...v0.1.9
140
155
  [0.0.1]: https://github.com/senad-d/DrawMe/releases/tag/v0.0.1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senad-d/drawme",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Pi extension for authoring, validating, and exporting editable draw.io diagrams from natural-language descriptions.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -79,7 +79,7 @@
79
79
  "@vitest/coverage-v8": "^5.0.0",
80
80
  "eslint": "^10.8.0",
81
81
  "globals": "^17.8.0",
82
- "typebox": "1.3.25",
82
+ "typebox": "1.4.4",
83
83
  "typescript": "~6.0.3",
84
84
  "typescript-eslint": "^8.10.0",
85
85
  "vitest": "^5.0.0"
package/src/drawio.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * `-e` PNG IEND repair, page indexing, and headless-Linux handling so callers never
5
5
  * hand-build a draw.io command line.
6
6
  */
7
- import { execFile } from "node:child_process";
7
+ import { spawn } from "node:child_process";
8
8
  import { existsSync, realpathSync } from "node:fs";
9
9
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
10
  import { basename, dirname, extname, join, resolve } from "node:path";
@@ -72,20 +72,57 @@ const CANDIDATES = [
72
72
  "/mnt/c/Program Files/draw.io/draw.io.exe", // WSL2
73
73
  ];
74
74
 
75
- function run(bin: string, args: string[], timeout = 120_000): Promise<{ stdout: string; stderr: string }> {
75
+ /**
76
+ * Run a command and collect its output. Off Windows the child leads its own process
77
+ * group, so a timeout ends the whole tree (xvfb-run, Xvfb, Electron), not only the
78
+ * direct child: SIGTERM first so xvfb-run can clean up, SIGKILL after a grace period.
79
+ */
80
+ export function run(bin: string, args: string[], timeout = 120_000): Promise<{ stdout: string; stderr: string }> {
76
81
  return new Promise((resolve, reject) => {
77
- execFile(bin, args, { timeout, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
78
- if (err) {
79
- (err as NodeJS.ErrnoException & { stderr?: string }).stderr = stderr?.toString();
80
- const reason = err instanceof Error ? err : new Error("draw.io process failed with an unknown error");
81
- reject(reason);
82
- } else {
83
- resolve({ stdout: stdout.toString(), stderr: stderr?.toString() ?? "" });
82
+ const group = platform() !== "win32";
83
+ const child = spawn(bin, args, { detached: group, stdio: ["ignore", "pipe", "pipe"] });
84
+ let stdout = "";
85
+ let stderr = "";
86
+ let timedOut = false;
87
+ let killTimer: NodeJS.Timeout | undefined;
88
+ child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
89
+ child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
90
+ const timer = setTimeout(() => {
91
+ timedOut = true;
92
+ killTree(child.pid, group, "SIGTERM");
93
+ killTimer = setTimeout(() => killTree(child.pid, group, "SIGKILL"), 5_000);
94
+ }, timeout);
95
+ child.on("error", (err) => {
96
+ clearTimeout(timer);
97
+ reject(Object.assign(err, { stderr }));
98
+ });
99
+ child.on("close", (code, signal) => {
100
+ clearTimeout(timer);
101
+ if (timedOut) {
102
+ // Reap anything in the group that ignored SIGTERM.
103
+ clearTimeout(killTimer);
104
+ killTree(child.pid, group, "SIGKILL");
105
+ }
106
+ if (code === 0 && !timedOut) {
107
+ resolve({ stdout, stderr });
108
+ return;
84
109
  }
110
+ const exitReason = signal ?? `code ${code}`;
111
+ const why = timedOut ? `timed out after ${timeout / 1000}s` : `exited with ${exitReason}`;
112
+ reject(Object.assign(new Error(`${bin} ${why}`), { code, signal, stderr }));
85
113
  });
86
114
  });
87
115
  }
88
116
 
117
+ function killTree(pid: number | undefined, group: boolean, signal: NodeJS.Signals): void {
118
+ if (pid === undefined) return;
119
+ try {
120
+ process.kill(group ? -pid : pid, signal);
121
+ } catch {
122
+ // already gone
123
+ }
124
+ }
125
+
89
126
  function parseMajor(version: string): number {
90
127
  const m = /(\d+)/.exec(version);
91
128
  return m ? Number.parseInt(m[1], 10) : 0;
@@ -132,7 +169,8 @@ export function deriveOutput(input: string, format: ExportFormat, embed: boolean
132
169
  *
133
170
  * Export planning rules:
134
171
  * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
135
- * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
172
+ * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2, lowered so the
173
+ * raster stays within MAX_FINAL_RASTER_PIXELS (larger rasters fail with UnknownVizError)
136
174
  * - animated → final SVG only; defaults the format to SVG and verifies motion after export
137
175
  * - `--width` and `-s` are never combined; an explicit width/height wins
138
176
  * - `-t` (transparent) is PNG-only; `--page-index` is 1-based
@@ -146,6 +184,7 @@ export function planExport(
146
184
  plat: string = platform(),
147
185
  isRoot = false,
148
186
  contentWidth?: number,
187
+ contentHeight?: number,
149
188
  ): ExportPlan {
150
189
  const animated = opts.animated ?? false;
151
190
  const format = opts.format ?? (animated ? "svg" : "png");
@@ -159,7 +198,7 @@ export function planExport(
159
198
  const margin = opts.border ?? DEFAULT_FIT_MARGIN;
160
199
  const args: string[] = ["-x", "-f", format];
161
200
  if (embed) args.push("-e");
162
- const border = planExportSize(opts, mode, raster, contentWidth, margin, args);
201
+ const border = planExportSize(opts, mode, raster, margin, args, contentWidth, contentHeight);
163
202
  // draw.io crops exports to the content, so the border is the image's only outer margin.
164
203
  args.push("-b", String(format === "svg" ? 0 : border));
165
204
  if (opts.transparent && format === "png") args.push("-t");
@@ -175,16 +214,27 @@ export function planExport(
175
214
  return { format, mode, embed, animated, output, args, input: opts.input, linuxExtra, svgMargin: format === "svg" ? margin : 0 };
176
215
  }
177
216
 
217
+ /** Pixel budget for a final raster; draw.io fails with UnknownVizError on much larger images. */
218
+ export const MAX_FINAL_RASTER_PIXELS = 6_000_000;
219
+
220
+ /** The requested scale, lowered so the bordered raster stays within MAX_FINAL_RASTER_PIXELS. */
221
+ export function cappedScale(scale: number, margin: number, contentWidth?: number, contentHeight?: number): number {
222
+ if (!contentWidth || !contentHeight || contentWidth <= 0 || contentHeight <= 0) return scale;
223
+ const area = (contentWidth + 2 * margin) * (contentHeight + 2 * margin);
224
+ const max = Math.floor(Math.sqrt(MAX_FINAL_RASTER_PIXELS / area) * 100) / 100;
225
+ return Math.min(scale, max);
226
+ }
227
+
178
228
  function planExportSize(
179
- opts: ExportOptions, mode: ExportMode, raster: boolean, contentWidth: number | undefined,
180
- margin: number, args: string[],
229
+ opts: ExportOptions, mode: ExportMode, raster: boolean, margin: number, args: string[],
230
+ contentWidth?: number, contentHeight?: number,
181
231
  ): number {
182
232
  if (opts.width != null) args.push("--width", String(opts.width));
183
233
  else if (opts.height != null) args.push("--height", String(opts.height));
184
234
  else if (raster) {
185
235
  if (mode === "preview") args.push("--width", "2000");
186
236
  else {
187
- const scale = opts.scale ?? 2;
237
+ const scale = cappedScale(opts.scale ?? 2, margin, contentWidth, contentHeight);
188
238
  if (contentWidth !== undefined && contentWidth > 0 && scale !== 1) {
189
239
  // With --width the border is in output pixels and applied evenly.
190
240
  const border = Math.round(margin * scale);
@@ -332,8 +382,8 @@ async function withSourceExportQueue<T>(input: string, action: () => Promise<T>)
332
382
  }
333
383
  }
334
384
 
335
- /** Width of the visible content of a page in diagram units, or undefined when it cannot be measured. */
336
- export async function pageContentWidth(input: string, pageIndex: number): Promise<number | undefined> {
385
+ /** Size of the visible content of a page in diagram units, or undefined when it cannot be measured. */
386
+ export async function pageContentSize(input: string, pageIndex: number): Promise<{ width: number; height: number } | undefined> {
337
387
  try {
338
388
  const root = new DOMParser().parseFromString(await readFile(input, "utf8"), "text/xml").documentElement as unknown as DomEl | null;
339
389
  if (!root) return undefined;
@@ -343,7 +393,7 @@ export async function pageContentWidth(input: string, pageIndex: number): Promis
343
393
  if (!model) return undefined;
344
394
  const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
345
395
  const bounds = contentBounds(cells, ids);
346
- return bounds ? bounds.maxX - bounds.minX : undefined;
396
+ return bounds ? { width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY } : undefined;
347
397
  } catch {
348
398
  return undefined;
349
399
  }
@@ -354,12 +404,30 @@ function isRootUser(): boolean {
354
404
  return typeof getuid === "function" && getuid() === 0;
355
405
  }
356
406
 
407
+ /**
408
+ * Xvfb screen for an export: draw.io fails (UnknownVizError, then hangs) when the
409
+ * requested raster is wider than the virtual screen. The height is unknown when only
410
+ * a width is requested, so the larger requested side sizes both, plus a margin,
411
+ * floored at 1280x1024 and capped at 8192.
412
+ */
413
+ export function xvfbScreen(args: string[]): string {
414
+ const want = Math.max(flagNumber(args, "--width"), flagNumber(args, "--height"));
415
+ const side = want > 0 ? Math.min(8192, want + 256) : 0;
416
+ return `${Math.max(1280, side)}x${Math.max(1024, side)}x24`;
417
+ }
418
+
419
+ function flagNumber(args: string[], flag: string): number {
420
+ const i = args.indexOf(flag);
421
+ return i >= 0 ? Number(args[i + 1]) || 0 : 0;
422
+ }
423
+
357
424
  /** Run the export, wrapping in `xvfb-run` on headless Linux and falling back to a direct call if it's absent. */
358
425
  async function invoke(binary: string, fullArgs: string[]): Promise<string> {
359
426
  if (platform() === "linux" && !process.env.DISPLAY) {
427
+ const screen = `-screen 0 ${xvfbScreen(fullArgs)}`;
360
428
  try {
361
- await run("xvfb-run", ["-a", "--server-args=-screen 0 1280x1024x24", binary, ...fullArgs]);
362
- return `xvfb-run -a --server-args="-screen 0 1280x1024x24" ${binary} ${fullArgs.join(" ")}`;
429
+ await run("xvfb-run", ["-a", `--server-args=${screen}`, binary, ...fullArgs]);
430
+ return `xvfb-run -a --server-args="${screen}" ${binary} ${fullArgs.join(" ")}`;
363
431
  } catch (e) {
364
432
  if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
365
433
  // xvfb-run not installed — fall through to a direct call
@@ -379,6 +447,17 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
379
447
  return withSourceExportQueue(opts.input, () => exportDiagramQueued(opts));
380
448
  }
381
449
 
450
+ async function invokeExport(binary: string, args: string[]): Promise<string> {
451
+ try {
452
+ return await invoke(binary, args);
453
+ } catch (e) {
454
+ const message = e instanceof Error ? e.message : String(e);
455
+ const stderr = (e as { stderr?: string }).stderr?.trim();
456
+ const detail = stderr ? `${message}\n${stderr}` : message;
457
+ throw new Error(`draw.io export failed: ${detail}`, { cause: e });
458
+ }
459
+ }
460
+
382
461
  async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
383
462
  const info = await resolveBinary(opts.binary);
384
463
  if (!info.available || !info.binary) {
@@ -388,16 +467,11 @@ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
388
467
  );
389
468
  }
390
469
 
391
- const plan = planExport(opts, platform(), isRootUser(), await pageContentWidth(opts.input, opts.pageIndex ?? 1));
470
+ const content = await pageContentSize(opts.input, opts.pageIndex ?? 1);
471
+ const plan = planExport(opts, platform(), isRootUser(), content?.width, content?.height);
392
472
  const fullArgs = [...plan.args, plan.input, ...plan.linuxExtra];
393
473
 
394
- let command: string;
395
- try {
396
- command = await invoke(info.binary, fullArgs);
397
- } catch (e) {
398
- const detail = ((e as { stderr?: string }).stderr || (e as Error).message || String(e)).trim();
399
- throw new Error(`draw.io export failed: ${detail}`, { cause: e });
400
- }
474
+ const command = await invokeExport(info.binary, fullArgs);
401
475
  if (!existsSync(plan.output)) {
402
476
  throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
403
477
  }