@senad-d/drawme 0.1.11 → 0.2.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 CHANGED
@@ -1,269 +1,44 @@
1
- /**
2
- * draw.io desktop CLI wrapper: binary resolution + export. Encodes the tricky
3
- * flag knowledge for focused previews vs final export, the vision width cap,
4
- * `-e` PNG IEND repair, page indexing, and headless-Linux handling so callers never
5
- * hand-build a draw.io command line.
6
- */
7
- import { spawn } from "node:child_process";
8
- import { existsSync, realpathSync } from "node:fs";
9
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
- import { basename, dirname, extname, join, resolve } from "node:path";
11
- import { platform, tmpdir } from "node:os";
12
- import { repairPng } from "./png";
13
- import { enhanceAnimatedSvg, type AnimatedSvgSummary } from "./animation";
14
- import { DEFAULT_FIT_MARGIN } from "./fitcanvas";
1
+ /** Public draw.io facade and verified export publication boundary. */
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ type BigIntStats, accessSync, chmodSync, chownSync, constants, existsSync, lstatSync, readlinkSync,
5
+ realpathSync, renameSync, statSync, unlinkSync,
6
+ } from "node:fs";
7
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
8
+ import { basename, dirname, join, sep } from "node:path";
15
9
  import { DOMParser } from "@xmldom/xmldom";
16
- import { type DomEl, childrenByTag, firstByTag } from "./dom";
10
+ import { enhanceAnimatedSvg, type AnimatedSvgSummary } from "./animation";
11
+ import { readDiagramXml, sessionPath, withDiagramFiles } from "./diagram-files";
12
+ import { type DomEl, childrenByTag, firstByTag, graphModel } from "./dom";
13
+ import {
14
+ type ExportFormat, type ExportMode, type ExportOptions, type ExportPlan,
15
+ MAX_FINAL_RASTER_PIXELS, MAX_REVIEW_SIDE, planExport,
16
+ } from "./export-plan";
17
17
  import { collectCellsWithIds, contentBounds } from "./geometry";
18
+ import { inspectPng, repairPng } from "./png";
19
+ import { INDEX_MIN, invokeRenderer, rendererUnavailable, resolveBinary, supportsPageIndex } from "./renderer";
20
+ import { assertStandaloneImages } from "./svg-helpers";
18
21
  import { finishSvgFile } from "./svgexport";
19
22
 
20
- export type ExportFormat = "png" | "svg" | "pdf" | "jpg";
21
- export type ExportMode = "preview" | "final";
22
-
23
- export interface DrawioInfo {
24
- available: boolean;
25
- binary?: string;
26
- version?: string;
27
- major?: number;
28
- /** Mermaid import and the `--layout` pass both need draw.io v30+. */
29
- supportsMermaid?: boolean;
30
- supportsLayout?: boolean;
31
- }
32
-
33
- export interface ExportOptions {
34
- input: string;
35
- format?: ExportFormat;
36
- mode?: ExportMode;
37
- output?: string;
38
- scale?: number;
39
- width?: number;
40
- height?: number;
41
- transparent?: boolean;
42
- border?: number;
43
- pageIndex?: number;
44
- embed?: boolean;
45
- /** Require and verify animation in a final SVG, compiling portable page sequences when present. */
46
- animated?: boolean;
47
- binary?: string;
48
- }
49
-
50
- export interface ExportPlan {
51
- format: ExportFormat;
52
- mode: ExportMode;
53
- embed: boolean;
54
- animated: boolean;
55
- output: string;
56
- /** Export flags ending with `-o <output>`. The input path is appended after these. */
57
- args: string[];
58
- input: string;
59
- /** Flags that must go AFTER the input path on Linux (draw.io argument-parsing quirk). */
60
- linuxExtra: string[];
61
- /** SVG only: outer margin DrawMe adds after export (draw.io's own SVG border is uneven). */
62
- svgMargin: number;
63
- }
64
-
65
- /** Candidate binary names and paths in resolution order. */
66
- const CANDIDATES = [
67
- "drawio", // Homebrew cask, jgraph .deb/.rpm, Arch AUR
68
- "draw.io", // older builds / custom symlinks
69
- "/Applications/draw.io.app/Contents/MacOS/draw.io", // macOS .app bundle
70
- String.raw`C:\Program Files\draw.io\draw.io.exe`, // Windows
71
- String.raw`C:\Program Files (x86)\draw.io\draw.io.exe`,
72
- "/mnt/c/Program Files/draw.io/draw.io.exe", // WSL2
73
- ];
74
-
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 }> {
81
- return new Promise((resolve, reject) => {
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;
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 }));
113
- });
114
- });
115
- }
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
-
126
- function parseMajor(version: string): number {
127
- const m = /(\d+)/.exec(version);
128
- return m ? Number.parseInt(m[1], 10) : 0;
129
- }
130
-
131
- /**
132
- * Resolve the draw.io CLI. Tries an explicit `override` first, then the standard
133
- * candidates. Absolute paths are existence-checked before spawning; PATH names are
134
- * probed with `--version` (a short timeout guards the sandbox-hang case).
135
- */
136
- export async function resolveBinary(override?: string): Promise<DrawioInfo> {
137
- const candidates = override ? [override, ...CANDIDATES] : CANDIDATES;
138
- const tried = new Set<string>();
139
- for (const bin of candidates) {
140
- if (tried.has(bin)) continue;
141
- tried.add(bin);
142
- const looksLikePath = bin.includes("/") || bin.includes("\\");
143
- if (looksLikePath && !existsSync(bin)) continue;
144
- try {
145
- const { stdout } = await run(bin, ["--version"], 15_000);
146
- const version = stdout.trim().split(/\r?\n/)[0] ?? "";
147
- if (version) {
148
- const major = parseMajor(version);
149
- return { available: true, binary: bin, version, major, supportsMermaid: major >= 30, supportsLayout: major >= 30 };
150
- }
151
- } catch {
152
- // not this one — try the next candidate
153
- }
154
- }
155
- return { available: false };
156
- }
157
-
158
- /** Derive a default output path next to the input, using the `.drawio.png` convention when embedding. */
159
- export function deriveOutput(input: string, format: ExportFormat, embed: boolean): string {
160
- const dir = dirname(input);
161
- const ext = extname(input);
162
- const base = ext ? basename(input).slice(0, -ext.length) : basename(input);
163
- if (format === "png" && embed) return join(dir, `${base}.drawio.png`);
164
- return join(dir, `${base}.${format}`);
165
- }
166
-
167
- /**
168
- * Build the full export plan (no side effects) so the argument logic is unit-testable.
169
- *
170
- * Export planning rules:
171
- * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
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)
174
- * - animated → final SVG only; defaults the format to SVG and verifies motion after export
175
- * - `--width` and `-s` are never combined; an explicit width/height wins
176
- * - `-t` (transparent) is PNG-only; `--page-index` is 1-based
177
- * - the outer margin defaults to the canvas-fit margin in diagram units. draw.io
178
- * applies `-b` unevenly with `-s` (left/top get border × scale) and with SVG
179
- * (the canvas grows by 3 × border), so a scaled raster is sized with `--width`
180
- * from `contentWidth`, and SVG is exported borderless and padded afterwards.
181
- */
182
- export function planExport(
183
- opts: ExportOptions,
184
- plat: string = platform(),
185
- isRoot = false,
186
- contentWidth?: number,
187
- contentHeight?: number,
188
- ): ExportPlan {
189
- const animated = opts.animated ?? false;
190
- const format = opts.format ?? (animated ? "svg" : "png");
191
- const mode = opts.mode ?? "final";
192
- if (animated && format !== "svg") throw new Error("animated export requires format='svg'");
193
- if (animated && mode !== "final") throw new Error("animated export requires mode='final'; use a PNG preview for review");
194
- const embed = opts.embed ?? (mode === "final" && format !== "jpg");
195
- const output = opts.output ?? deriveOutput(opts.input, format, embed);
196
- const raster = format === "png" || format === "jpg";
197
-
198
- const margin = opts.border ?? DEFAULT_FIT_MARGIN;
199
- const args: string[] = ["-x", "-f", format];
200
- if (embed) args.push("-e");
201
- const border = planExportSize(opts, mode, raster, margin, args, contentWidth, contentHeight);
202
- // draw.io crops exports to the content, so the border is the image's only outer margin.
203
- args.push("-b", String(format === "svg" ? 0 : border));
204
- if (opts.transparent && format === "png") args.push("-t");
205
- if (opts.pageIndex != null) args.push("--page-index", String(opts.pageIndex));
206
- args.push("-o", output);
207
-
208
- // On Linux these must trail the input filename, or draw.io treats them as the input.
209
- const linuxExtra: string[] = [];
210
- if (plat === "linux") {
211
- linuxExtra.push("--disable-gpu");
212
- if (isRoot) linuxExtra.push("--no-sandbox");
213
- }
214
- return { format, mode, embed, animated, output, args, input: opts.input, linuxExtra, svgMargin: format === "svg" ? margin : 0 };
215
- }
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
-
228
- function planExportSize(
229
- opts: ExportOptions, mode: ExportMode, raster: boolean, margin: number, args: string[],
230
- contentWidth?: number, contentHeight?: number,
231
- ): number {
232
- if (opts.width != null) args.push("--width", String(opts.width));
233
- else if (opts.height != null) args.push("--height", String(opts.height));
234
- else if (raster) {
235
- if (mode === "preview") args.push("--width", "2000");
236
- else {
237
- const scale = cappedScale(opts.scale ?? 2, margin, contentWidth, contentHeight);
238
- if (contentWidth !== undefined && contentWidth > 0 && scale !== 1) {
239
- // With --width the border is in output pixels and applied evenly.
240
- const border = Math.round(margin * scale);
241
- args.push("--width", String(Math.round(contentWidth * scale + 2 * border)));
242
- return border;
243
- }
244
- args.push("-s", String(scale));
245
- }
246
- }
247
- return margin;
248
- }
23
+ export * from "./editable-import";
24
+ export * from "./export-plan";
25
+ export * from "./renderer";
249
26
 
250
27
  export interface ExportResult {
251
28
  output: string;
252
29
  format: ExportFormat;
253
30
  mode: ExportMode;
254
31
  embed: boolean;
255
- /** True only when animated SVG export was explicitly requested and verified. */
32
+ /** True only when native animated SVG export was explicitly requested and verified. */
256
33
  animated: boolean;
257
34
  animation?: AnimatedSvgSummary;
258
35
  binary: string;
259
36
  version?: string;
260
37
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
261
38
  repaired: boolean;
262
- /**
263
- * True when this preview replaced an earlier tracked preview for the same
264
- * source — including a re-export over the same output path, where nothing is
265
- * removed from disk. Always false for final exports.
266
- */
39
+ /** Exact verified bytes of an unembedded PNG, whether or not it is a preview. */
40
+ artifactSha256?: string;
41
+ /** True when a preview replaced an earlier tracked preview of the same source. */
267
42
  replacedPreview: boolean;
268
43
  /** Superseded preview artifacts removed after this successful preview or final export. */
269
44
  removedPreviews: string[];
@@ -272,19 +47,22 @@ export interface ExportResult {
272
47
  command: string;
273
48
  }
274
49
 
275
- /** Successful preview outputs still present, grouped by their canonical source path. */
276
- const previewOutputs = new Map<string, Map<string, string>>();
277
- /** Serialize exports per source so concurrent preview calls cannot leave multiple latest artifacts. */
278
- const exportQueues = new Map<string, Promise<void>>();
50
+ export interface PreparedExport {
51
+ readonly publicationDestination: string;
52
+ commit(): ExportResult;
53
+ dispose(): Promise<void>;
54
+ }
279
55
 
280
- function sourceKey(input: string): string {
281
- try {
282
- return realpathSync(input);
283
- } catch {
284
- return resolve(input);
285
- }
56
+ interface TrackedPreview {
57
+ displayPath: string;
58
+ /** Never unlink the target of a user-supplied output symlink. */
59
+ removable: boolean;
60
+ file: BigIntStats;
286
61
  }
287
62
 
63
+ /** Preview ownership snapshots, grouped by canonical source and destination. */
64
+ const previewOutputs = new Map<string, Map<string, TrackedPreview>>();
65
+
288
66
  interface PreviewCleanup {
289
67
  removed: string[];
290
68
  warnings: string[];
@@ -292,359 +70,339 @@ interface PreviewCleanup {
292
70
  replaced: boolean;
293
71
  }
294
72
 
295
- /**
296
- * Keep the newly exported preview and retire every older tracked preview for the
297
- * same source. Cleanup happens only after the replacement exists, so a failed
298
- * export never destroys the last usable review image.
299
- */
300
- async function replaceTrackedPreview(input: string, latestOutput: string): Promise<PreviewCleanup> {
301
- const key = sourceKey(input);
302
- const previous = previewOutputs.get(key) ?? new Map<string, string>();
303
- const latestPath = resolve(latestOutput);
304
- const retained = new Map<string, string>([[latestPath, latestOutput]]);
305
- const removed: string[] = [];
306
- const warnings: string[] = [];
307
-
308
- const cleanup = await deletePreviewFiles(previous, latestPath);
309
- for (const result of cleanup) {
310
- if (result.warning !== undefined) {
311
- retained.set(result.path, result.displayPath);
312
- warnings.push(result.warning);
313
- } else if (result.existed) removed.push(result.displayPath);
314
- }
73
+ function fileAt(path: string): BigIntStats | undefined {
74
+ return lstatSync(path, { bigint: true, throwIfNoEntry: false });
75
+ }
315
76
 
316
- previewOutputs.set(key, retained);
317
- return { removed, warnings, replaced: previous.size > 0 };
77
+ function sameFile(a: BigIntStats, b: BigIntStats): boolean {
78
+ return a.dev === b.dev && a.ino === b.ino;
318
79
  }
319
80
 
320
- async function removeTrackedPreviews(input: string, finalOutput: string): Promise<PreviewCleanup> {
321
- const key = sourceKey(input);
322
- const previews = previewOutputs.get(key);
323
- if (!previews) return { removed: [], warnings: [], replaced: false };
81
+ function stillOwned(current: BigIntStats | undefined, tracked: TrackedPreview): boolean {
82
+ return current?.isFile() === true && sameFile(current, tracked.file) && current.ctimeNs === tracked.file.ctimeNs &&
83
+ current.mtimeNs === tracked.file.mtimeNs && current.size === tracked.file.size;
84
+ }
324
85
 
325
- previewOutputs.delete(key);
326
- const finalPath = resolve(finalOutput);
86
+ /** Check and unlink without yielding to another export between those operations. */
87
+ function retirePreviews(key: string, destination: string, latest: TrackedPreview | undefined): PreviewCleanup {
327
88
  const removed: string[] = [];
328
89
  const warnings: string[] = [];
329
- const retry = new Map<string, string>();
330
-
331
- const cleanup = await deletePreviewFiles(previews, finalPath);
332
- for (const result of cleanup) {
333
- if (result.warning !== undefined) {
334
- retry.set(result.path, result.displayPath);
335
- warnings.push(result.warning);
336
- } else if (result.existed) removed.push(result.displayPath);
90
+ const retained = new Map<string, TrackedPreview>();
91
+ let replaced = false;
92
+ if (latest) retained.set(destination, latest);
93
+ for (const [path, preview] of previewOutputs.get(key) ?? []) {
94
+ if (path === destination) continue;
95
+ try {
96
+ const current = fileAt(path);
97
+ if (current && !current.isFile()) {
98
+ warnings.push(`${preview.displayPath}: no longer a regular file; left in place`);
99
+ } else if (stillOwned(current, preview)) {
100
+ replaced = true;
101
+ if (preview.removable) {
102
+ unlinkSync(path);
103
+ removed.push(preview.displayPath);
104
+ }
105
+ }
106
+ } catch (error) {
107
+ retained.set(path, preview);
108
+ warnings.push(`${preview.displayPath}: ${(error as Error).message}`);
109
+ }
337
110
  }
338
-
339
- if (retry.size > 0) previewOutputs.set(key, retry);
340
- return { removed, warnings, replaced: false };
341
- }
342
-
343
- interface PreviewDeletion {
344
- path: string;
345
- displayPath: string;
346
- existed: boolean;
347
- warning?: string;
111
+ if (retained.size > 0) previewOutputs.set(key, retained);
112
+ else previewOutputs.delete(key);
113
+ return { removed, warnings, replaced: latest !== undefined && replaced };
348
114
  }
349
115
 
350
- /** Independent file deletions run concurrently; receipts retain insertion order. */
351
- async function deletePreviewFiles(previews: Map<string, string>, protectedPath: string): Promise<PreviewDeletion[]> {
352
- return Promise.all(
353
- [...previews].filter(([path]) => path !== protectedPath).map(async ([path, displayPath]) => {
354
- const existed = existsSync(path);
355
- try {
356
- await rm(path, { force: true });
357
- return { path, displayPath, existed };
358
- } catch (error) {
359
- const message = error instanceof Error ? error.message : String(error);
360
- return { path, displayPath, existed, warning: `${displayPath}: ${message}` };
361
- }
362
- }),
363
- );
116
+ function diagramPages(xml: string): DomEl[] {
117
+ const root = new DOMParser({ onError(level) {
118
+ if (level !== "warning") throw new Error("invalid diagram XML");
119
+ } }).parseFromString(xml, "text/xml").documentElement as unknown as DomEl | null;
120
+ if (!root) return [];
121
+ return root.tagName === "mxGraphModel" || root.tagName === "diagram" ? [root] : childrenByTag(root, "diagram");
364
122
  }
365
123
 
366
- async function withSourceExportQueue<T>(input: string, action: () => Promise<T>): Promise<T> {
367
- const key = sourceKey(input);
368
- const previous = exportQueues.get(key) ?? Promise.resolve();
369
- let release = (): void => {};
370
- const current = new Promise<void>((resolveCurrent) => {
371
- release = resolveCurrent;
372
- });
373
- const tail = previous.then(() => current);
374
- exportQueues.set(key, tail);
375
-
376
- await previous;
377
- try {
378
- return await action();
379
- } finally {
380
- release();
381
- if (exportQueues.get(key) === tail) exportQueues.delete(key);
382
- }
124
+ function measurePage(page: DomEl | undefined): { width: number; height: number } | undefined {
125
+ const model = page && graphModel(page);
126
+ if (!model) return undefined;
127
+ const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
128
+ const bounds = contentBounds(cells, ids);
129
+ return bounds ? { width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY } : undefined;
383
130
  }
384
131
 
385
- /** Size of the visible content of a page in diagram units, or undefined when it cannot be measured. */
132
+ /** Size of visible page content, or undefined for a missing or unmeasurable page. */
386
133
  export async function pageContentSize(input: string, pageIndex: number): Promise<{ width: number; height: number } | undefined> {
387
- try {
388
- const root = new DOMParser().parseFromString(await readFile(input, "utf8"), "text/xml").documentElement as unknown as DomEl | null;
389
- if (!root) return undefined;
390
- const pages = childrenByTag(root, "diagram");
391
- const page = pages.length > 0 ? pages[pageIndex - 1] : root;
392
- const model = page && (page.tagName === "mxGraphModel" ? page : firstByTag(page, "mxGraphModel"));
393
- if (!model) return undefined;
394
- const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
395
- const bounds = contentBounds(cells, ids);
396
- return bounds ? { width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY } : undefined;
397
- } catch {
398
- return undefined;
134
+ return measurePage(diagramPages(await readDiagramXml(input))[pageIndex - 1]);
135
+ }
136
+
137
+ /** Internal alias guard also used for a storyboard generated from a diagram. */
138
+ export function rejectSourceAlias(input: string, output: string): void {
139
+ const source = statSync(input, { bigint: true });
140
+ const destination = statSync(output, { bigint: true, throwIfNoEntry: false });
141
+ if (destination && sameFile(source, destination)) throw new Error(`output aliases the input file: ${output}`);
142
+ }
143
+
144
+ function publicationPath(output: string): string {
145
+ let path = output;
146
+ const seen = new Set<string>();
147
+ for (;;) {
148
+ if (path.endsWith("/") || path.endsWith(sep)) throw new Error(`export destination must name a file: ${output}`);
149
+ const parent = realpathSync.native(dirname(path));
150
+ const entry = join(parent, basename(path));
151
+ if (!fileAt(entry)?.isSymbolicLink()) return entry;
152
+ if (seen.has(entry)) throw new Error(`export destination has a symlink loop: ${output}`);
153
+ seen.add(entry);
154
+ path = sessionPath(parent, readlinkSync(entry));
399
155
  }
400
156
  }
401
157
 
402
- function isRootUser(): boolean {
403
- const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
404
- return typeof getuid === "function" && getuid() === 0;
158
+ function checkDestination(destination: string): BigIntStats | undefined {
159
+ const existing = fileAt(destination);
160
+ if (existing && !existing.isFile()) throw new Error(`export destination is not a regular file: ${destination}`);
161
+ accessSync(dirname(destination), constants.W_OK | constants.X_OK);
162
+ if (existing) accessSync(destination, constants.W_OK);
163
+ return existing;
405
164
  }
406
165
 
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
-
424
- /** Run the export, wrapping in `xvfb-run` on headless Linux and falling back to a direct call if it's absent. */
425
- async function invoke(binary: string, fullArgs: string[]): Promise<string> {
426
- if (platform() === "linux" && !process.env.DISPLAY) {
427
- const screen = `-screen 0 ${xvfbScreen(fullArgs)}`;
428
- try {
429
- await run("xvfb-run", ["-a", `--server-args=${screen}`, binary, ...fullArgs]);
430
- return `xvfb-run -a --server-args="${screen}" ${binary} ${fullArgs.join(" ")}`;
431
- } catch (e) {
432
- if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
433
- // xvfb-run not installed — fall through to a direct call
166
+ /** Renaming over a file must not broaden access to its contents. */
167
+ function preserveFileAccess(existing: BigIntStats, staged: string): void {
168
+ const rendered = statSync(staged, { bigint: true });
169
+ if (existing.uid !== rendered.uid || existing.gid !== rendered.gid) {
170
+ chownSync(staged, Number(existing.uid), Number(existing.gid));
171
+ }
172
+ chmodSync(staged, Number(existing.mode & 0o777n));
173
+ }
174
+
175
+ function checkPublication(
176
+ plan: ExportPlan, key: string, destination: string, implicitPreview: boolean,
177
+ ) {
178
+ if (publicationPath(plan.output) !== destination) throw new Error(`export destination changed: ${plan.output}`);
179
+ rejectSourceAlias(plan.input, destination);
180
+ const existing = checkDestination(destination);
181
+ const linked = fileAt(plan.output)?.isSymbolicLink() === true;
182
+ const previous = plan.mode === "preview" ? previewOutputs.get(key)?.get(destination) : undefined;
183
+ const replaced = previous !== undefined && stillOwned(existing, previous);
184
+ if (implicitPreview && (linked || (existing && !(replaced && previous?.removable)))) {
185
+ throw new Error(`preview destination is already in use: ${plan.output}; choose an explicit output`);
186
+ }
187
+ return { existing, linked, replaced };
188
+ }
189
+
190
+ function requireRenderedFile(plan: ExportPlan, staged: string): BigIntStats {
191
+ const file = fileAt(staged);
192
+ if (!file) throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
193
+ if (!file.isFile()) throw new Error(`draw.io output is not a regular file: ${plan.output}`);
194
+ return file;
195
+ }
196
+
197
+ interface RasterSize { width: number; height: number }
198
+
199
+ /** Read the SOF dimensions, skipping length-prefixed JPEG marker segments, not searching compressed data. */
200
+ function jpegSize(data: Buffer): RasterSize | undefined {
201
+ if (data.length < 4 || data.readUInt16BE(0) !== 0xffd8 || data.readUInt16BE(data.length - 2) !== 0xffd9) return;
202
+ let offset = 2;
203
+ let size: RasterSize | undefined;
204
+ while (offset + 3 < data.length && data[offset++] === 0xff) {
205
+ while (data[offset] === 0xff) offset++;
206
+ const marker = data[offset++];
207
+ if (offset + 2 > data.length || marker === 0 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) return;
208
+ const length = data.readUInt16BE(offset);
209
+ if (length < 2 || offset + length > data.length - 2) return;
210
+ if (marker === 0xda) return length >= 6 && offset + length < data.length - 2 ? size : undefined;
211
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
212
+ if (size || length < 11 || length !== 8 + 3 * data[offset + 7]) return;
213
+ const height = data.readUInt16BE(offset + 3);
214
+ const width = data.readUInt16BE(offset + 5);
215
+ if (!width || !height) return;
216
+ size = { width, height };
434
217
  }
218
+ offset += length;
435
219
  }
436
- await run(binary, fullArgs);
437
- return `${binary} ${fullArgs.join(" ")}`;
438
220
  }
439
221
 
440
- /**
441
- * Export a `.drawio` file to PNG/SVG/PDF/JPG. Resolves the binary, runs the CLI,
442
- * and (for embedded PNG) repairs the truncated IEND chunk. Throws on missing
443
- * input, missing CLI, or a failed export.
444
- */
445
- export async function exportDiagram(opts: ExportOptions): Promise<ExportResult> {
446
- if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
447
- return withSourceExportQueue(opts.input, () => exportDiagramQueued(opts));
222
+ function exceedsReview(plan: ExportPlan, size: RasterSize): boolean {
223
+ return plan.mode === "preview" && Math.max(size.width, size.height) > MAX_REVIEW_SIDE;
448
224
  }
449
225
 
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 });
226
+ async function verifyRenderedFile(plan: ExportPlan, staged: string): Promise<{
227
+ repaired: boolean; artifactSha256?: string; oversized?: RasterSize;
228
+ }> {
229
+ requireRenderedFile(plan, staged);
230
+ if (plan.format === "png") {
231
+ if (plan.embed) return { repaired: await repairPng(staged, true) };
232
+ const data = await readFile(staged);
233
+ const png = inspectPng(data);
234
+ if (png.editable) throw new Error("draw.io returned editable metadata in an unembedded PNG");
235
+ if (exceedsReview(plan, png)) return { repaired: false, oversized: png };
236
+ return { repaired: false, artifactSha256: createHash("sha256").update(data).digest("hex") };
458
237
  }
459
- }
460
-
461
- async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
462
- const info = await resolveBinary(opts.binary);
463
- if (!info.available || !info.binary) {
464
- throw new Error(
465
- "draw.io CLI not found. Install draw.io desktop (macOS: `brew install --cask drawio`; " +
466
- "others: https://github.com/jgraph/drawio-desktop/releases), or pass an explicit `binary` path.",
467
- );
468
- }
469
-
470
- const content = await pageContentSize(opts.input, opts.pageIndex ?? 1);
471
- const plan = planExport(opts, platform(), isRootUser(), content?.width, content?.height);
472
- const fullArgs = [...plan.args, plan.input, ...plan.linuxExtra];
473
-
474
- const command = await invokeExport(info.binary, fullArgs);
475
- if (!existsSync(plan.output)) {
476
- throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
477
- }
478
-
479
- const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
480
- // Every SVG gets an even outer margin and shows its authored colors, matching PNG/PDF output in any viewer.
481
238
  if (plan.format === "svg") {
482
239
  try {
483
- await finishSvgFile(plan.output, plan.svgMargin);
240
+ await finishSvgFile(staged, plan.svgMargin);
484
241
  } catch (error) {
485
- await rm(plan.output, { force: true });
486
242
  throw new Error(`SVG post-processing failed: ${(error as Error).message}`, { cause: error });
487
243
  }
488
- }
489
- let animation: AnimatedSvgSummary | undefined;
490
- if (plan.animated) {
491
- try {
492
- animation = await enhanceAnimatedSvg(plan.input, plan.output, opts.pageIndex ?? 1);
493
- } catch (error) {
494
- await rm(plan.output, { force: true });
495
- throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
244
+ } else {
245
+ const data = await readFile(staged);
246
+ if (plan.format === "jpg") {
247
+ const size = jpegSize(data);
248
+ if (!size) throw new Error(`draw.io output is not a complete JPG: ${plan.output}`);
249
+ if (size.width * size.height > MAX_FINAL_RASTER_PIXELS) {
250
+ throw new Error(`draw.io output exceeds the ${MAX_FINAL_RASTER_PIXELS}-pixel JPG limit`);
251
+ }
252
+ if (exceedsReview(plan, size)) return { repaired: false, oversized: size };
253
+ } else if (data.subarray(0, 5).toString("ascii") !== "%PDF-" || !data.subarray(-32).toString("ascii").trimEnd().endsWith("%%EOF")) {
254
+ throw new Error(`draw.io output is not a complete PDF: ${plan.output}`);
496
255
  }
497
256
  }
498
- const cleanup =
499
- plan.mode === "preview"
500
- ? await replaceTrackedPreview(plan.input, plan.output)
501
- : await removeTrackedPreviews(plan.input, plan.output);
502
- return {
503
- output: plan.output,
504
- format: plan.format,
505
- mode: plan.mode,
506
- embed: plan.embed,
507
- animated: plan.animated,
508
- animation,
509
- binary: info.binary,
510
- version: info.version,
511
- repaired,
512
- replacedPreview: cleanup.replaced,
513
- removedPreviews: cleanup.removed,
514
- previewCleanupWarnings: cleanup.warnings,
515
- command,
516
- };
517
- }
518
-
519
- // --- Mermaid → .drawio conversion + ELK auto-layout (both need draw.io v30+) ---
520
-
521
- /** Default `.drawio` output path derived from a source file. */
522
- function drawioOutputFor(src: string): string {
523
- const dir = dirname(src);
524
- const ext = extname(src);
525
- const base = ext ? basename(src).slice(0, -ext.length) : basename(src);
526
- return join(dir, `${base}.drawio`);
257
+ return { repaired: false };
527
258
  }
528
259
 
529
- async function requireBinary(minMajor: number, feature: string, override?: string): Promise<DrawioInfo & { binary: string }> {
530
- const info = await resolveBinary(override);
531
- if (!info.available || !info.binary) {
532
- throw new Error(
533
- "draw.io CLI not found. Install draw.io desktop (macOS: `brew install --cask drawio`; " +
534
- "others: https://github.com/jgraph/drawio-desktop/releases), or pass an explicit `binary` path.",
535
- );
536
- }
537
- if ((info.major ?? 0) < minMajor) {
538
- throw new Error(
539
- `${feature} needs draw.io v${minMajor}+, but ${info.version} is installed. Upgrade with \`brew upgrade --cask drawio\`.`,
540
- );
260
+ async function invokeExport(binary: string, args: string[], signal: AbortSignal | undefined): Promise<string> {
261
+ try {
262
+ return await invokeRenderer(binary, args, signal);
263
+ } catch (error) {
264
+ if (error instanceof Error && error.name === "AbortError") throw error;
265
+ // Runtime supplies only a safe launch/exit/timeout error; child exceptions and output are not its cause.
266
+ throw new Error(`draw.io export failed: ${(error as Error).message}`, { cause: error });
541
267
  }
542
- return info as DrawioInfo & { binary: string };
543
268
  }
544
269
 
545
- /** Args for a Mermaid → .drawio conversion (pure, for testing). */
546
- export function mermaidArgs(mmdPath: string, output: string): string[] {
547
- return ["-x", "-f", "xml", "-o", output, mmdPath];
270
+ async function renderVerified(plan: ExportPlan, staged: string, input: string, binary: string, signal?: AbortSignal) {
271
+ // draw.io selects the encoder from the staged suffix even when -f is given.
272
+ const args = [...plan.args.slice(0, -1), staged, input, ...plan.linuxExtra];
273
+ for (let attempt = 0; ; attempt++) {
274
+ signal?.throwIfAborted();
275
+ const command = await invokeExport(binary, args, signal);
276
+ signal?.throwIfAborted();
277
+ const { oversized, ...verified } = await verifyRenderedFile(plan, staged);
278
+ if (!oversized) return { ...verified, command };
279
+ // Correct for the actual aspect of unmeasurable content (e.g. compressed pages).
280
+ // An uncooperative renderer gets at most one retry, and must create fresh output.
281
+ const axis = args.findIndex((arg) => arg === "--width" || arg === "--height");
282
+ const border = Number(args[args.indexOf("-b") + 1]);
283
+ const requested = Number(args[axis + 1]);
284
+ const smaller = Math.floor(requested * (MAX_REVIEW_SIDE - 2) / Math.max(oversized.width, oversized.height));
285
+ if (attempt || axis < 0 || smaller <= 2 * border || smaller >= requested) {
286
+ throw new Error(`draw.io preview exceeds the ${MAX_REVIEW_SIDE}px review side limit`);
287
+ }
288
+ args[axis + 1] = String(smaller);
289
+ unlinkSync(staged);
290
+ }
548
291
  }
549
292
 
550
- export interface MermaidOptions {
551
- /** Path to a `.mmd` file. */
552
- input?: string;
553
- /** Inline Mermaid text (written to a temp `.mmd`); used when `input` is omitted. */
554
- mermaid?: string;
555
- output?: string;
556
- binary?: string;
557
- }
558
- export interface MermaidResult {
559
- output: string;
560
- binary: string;
561
- version?: string;
562
- command: string;
293
+ async function finalizeAnimatedSvg(
294
+ plan: ExportPlan, input: string, staged: string, pageIndex: number | undefined, finishStagedSvg?: (path: string) => Promise<void>,
295
+ ): Promise<AnimatedSvgSummary | undefined> {
296
+ if (plan.format !== "svg" || !(plan.animated || finishStagedSvg)) return;
297
+ try {
298
+ const animation = plan.animated ? await enhanceAnimatedSvg(input, staged, pageIndex) : undefined;
299
+ await finishStagedSvg?.(staged);
300
+ requireRenderedFile(plan, staged);
301
+ assertStandaloneImages(await readFile(staged, "utf8"));
302
+ return animation;
303
+ } catch (error) {
304
+ throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
305
+ }
563
306
  }
564
307
 
565
- /**
566
- * Convert Mermaid text to a native `.drawio` (structure + automatic layout) via
567
- * the CLI. Requires draw.io v30+. Never applies `--layout` afterwards — the
568
- * conversion is already laid out.
569
- */
570
- export async function convertMermaid(opts: MermaidOptions): Promise<MermaidResult> {
571
- const info = await requireBinary(30, "Mermaid conversion", opts.binary);
308
+ /** Render and verify privately. Callers must already hold the needed diagram reservations. */
309
+ export async function prepareExport(
310
+ opts: ExportOptions, renderInput: string, finishStagedSvg?: (path: string) => Promise<void>,
311
+ ): Promise<PreparedExport> {
312
+ const { signal } = opts;
313
+ signal?.throwIfAborted();
314
+ const cwd = process.cwd();
315
+ const source = sessionPath(cwd, opts.input);
316
+ const renderPath = sessionPath(cwd, renderInput);
317
+ const explicit = opts.output === undefined ? undefined : sessionPath(cwd, opts.output);
318
+ if (explicit !== undefined) {
319
+ // Preserve alias rejection even if the request also has a conflicting suffix.
320
+ rejectSourceAlias(source, explicit);
321
+ checkDestination(publicationPath(explicit));
322
+ }
323
+ if (opts.pageIndex !== undefined && (!Number.isSafeInteger(opts.pageIndex) || opts.pageIndex <= 0)) {
324
+ throw new Error("pageIndex must be a positive integer");
325
+ }
326
+ const pages = diagramPages(await readDiagramXml(renderPath));
327
+ if (opts.pageIndex !== undefined && opts.pageIndex > pages.length) {
328
+ throw new Error(`pageIndex ${opts.pageIndex} is out of range (${pages.length} pages)`);
329
+ }
330
+ const content = measurePage(pages[(opts.pageIndex ?? 1) - 1]);
331
+ // Keep the caller's spelling in receipts; only filesystem/CLI operands are anchored.
332
+ const plan = planExport(opts, undefined, false, content?.width, content?.height);
333
+ const output = plan.output;
334
+ plan.input = source;
335
+ plan.output = sessionPath(cwd, output);
336
+ const destination = publicationPath(plan.output);
337
+ const key = realpathSync.native(source);
338
+ const implicitPreview = plan.mode === "preview" && explicit === undefined;
339
+ checkPublication(plan, key, destination, implicitPreview);
340
+
341
+ const info = await resolveBinary(opts.binary, signal);
342
+ const { binary } = info;
343
+ if (!info.available || !binary) throw new Error(rendererUnavailable(info));
344
+ if (opts.pageIndex !== undefined && !supportsPageIndex(info.version)) {
345
+ throw new Error(`explicit pageIndex requires draw.io ${INDEX_MIN} or later (found ${info.version ?? "unknown version"})`);
346
+ }
572
347
 
573
- let mmdPath = opts.input;
574
- let tempDir: string | undefined;
348
+ signal?.throwIfAborted();
349
+ const stageDir = await mkdtemp(join(dirname(destination), ".drawme-export-"));
350
+ const staged = join(stageDir, `artifact.${plan.format}`);
351
+ const dispose = () => rm(stageDir, { recursive: true, force: true });
575
352
  try {
576
- if (!mmdPath) {
577
- if (!opts.mermaid?.trim()) {
578
- throw new Error("provide either `input` (a .mmd file path) or `mermaid` (inline Mermaid text)");
353
+ const verified = await renderVerified(plan, staged, renderPath, binary, signal);
354
+ const animation = await finalizeAnimatedSvg(plan, renderPath, staged, opts.pageIndex, finishStagedSvg);
355
+ const stagedFile = requireRenderedFile(plan, staged);
356
+ const check = () => {
357
+ signal?.throwIfAborted();
358
+ const currentStage = requireRenderedFile(plan, staged);
359
+ if (!sameFile(stagedFile, currentStage) || stagedFile.size !== currentStage.size || stagedFile.mtimeNs !== currentStage.mtimeNs) {
360
+ throw new Error(`verified draw.io output changed before publication: ${output}`);
579
361
  }
580
- tempDir = await mkdtemp(join(tmpdir(), "drawme-mmd-"));
581
- mmdPath = join(tempDir, "diagram.mmd");
582
- await writeFile(mmdPath, opts.mermaid, "utf8");
583
- } else if (!existsSync(mmdPath)) {
584
- throw new Error(`input file not found: ${mmdPath}`);
585
- }
586
- const output = opts.output ?? (opts.input ? drawioOutputFor(opts.input) : join(process.cwd(), "diagram.drawio"));
587
- const command = await invoke(info.binary, mermaidArgs(mmdPath, output));
588
- if (!existsSync(output)) throw new Error(`conversion produced no output: ${output}`);
589
- return { output, binary: info.binary, version: info.version, command };
590
- } finally {
591
- if (tempDir) await rm(tempDir, { recursive: true, force: true });
362
+ const current = checkPublication(plan, key, destination, implicitPreview);
363
+ if (current.existing) preserveFileAccess(current.existing, staged);
364
+ return current;
365
+ };
366
+ check();
367
+ return {
368
+ get publicationDestination() {
369
+ // Paired callers can recheck both targets before touching either public file.
370
+ check();
371
+ return destination;
372
+ },
373
+ commit() {
374
+ const { linked, replaced } = check();
375
+ signal?.throwIfAborted();
376
+ renameSync(staged, destination);
377
+ const published = plan.mode === "preview" ? fileAt(destination) : undefined;
378
+ const latest = published && sameFile(published, stagedFile)
379
+ ? { displayPath: output, removable: !linked, file: published }
380
+ : undefined;
381
+ const cleanup = retirePreviews(key, destination, latest);
382
+ return {
383
+ ...verified, output, format: plan.format, mode: plan.mode, embed: plan.embed, animated: plan.animated,
384
+ animation, binary, version: info.version, replacedPreview: replaced || cleanup.replaced,
385
+ removedPreviews: cleanup.removed, previewCleanupWarnings: cleanup.warnings,
386
+ };
387
+ },
388
+ dispose,
389
+ };
390
+ } catch (error) {
391
+ await dispose();
392
+ throw error;
592
393
  }
593
394
  }
594
395
 
595
- /** ELK layout presets the CLI accepts. Any other value opens a modal that hangs headless runs. */
596
- export const LAYOUT_PRESETS = ["verticalFlow", "horizontalFlow", "verticalTree", "horizontalTree", "radialTree", "organic"] as const;
597
- export type LayoutPreset = (typeof LAYOUT_PRESETS)[number];
598
-
599
- /** Args for an ELK `--layout` pass (pure, for testing). */
600
- export function layoutArgs(input: string, preset: LayoutPreset, output: string): string[] {
601
- return ["-x", "-f", "xml", "--layout", preset, "-o", output, input];
602
- }
603
-
604
- export interface LayoutOptions {
605
- input: string;
606
- preset: LayoutPreset;
607
- /** Defaults to a sibling `<name>.layout.drawio` (never overwrites the input unless you pass it explicitly). */
608
- output?: string;
609
- binary?: string;
610
- }
611
- export interface LayoutResult {
612
- output: string;
613
- preset: LayoutPreset;
614
- binary: string;
615
- version?: string;
616
- command: string;
617
- }
618
-
619
- /**
620
- * Re-place nodes and route edges with an ELK layout preset via the CLI. Requires
621
- * draw.io v30+. The preset is validated against a strict allowlist first — an
622
- * unknown value would open a modal error dialog that hangs a headless run.
623
- */
624
- export async function applyLayout(opts: LayoutOptions): Promise<LayoutResult> {
625
- if (!LAYOUT_PRESETS.includes(opts.preset)) {
626
- throw new Error(`unknown layout preset '${opts.preset}'. Allowed: ${LAYOUT_PRESETS.join(", ")}`);
627
- }
396
+ /** Reserve the source once and commit matched, verified bytes before retiring previews. */
397
+ export async function exportDiagram(opts: ExportOptions, finishStagedSvg?: (path: string) => Promise<void>): Promise<ExportResult> {
398
+ opts.signal?.throwIfAborted();
628
399
  if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
629
- const info = await requireBinary(30, "The --layout pass", opts.binary);
630
- const output = opts.output ?? join(dirname(opts.input), `${basename(opts.input, extname(opts.input))}.layout.drawio`);
631
- const command = await invoke(info.binary, layoutArgs(opts.input, opts.preset, output));
632
- if (!existsSync(output)) throw new Error(`layout produced no output: ${output}`);
633
- return { output, preset: opts.preset, binary: info.binary, version: info.version, command };
634
- }
635
-
636
- /** Open a file in the OS default handler (draw.io desktop for `.drawio`). No version gate. */
637
- export async function openFile(path: string): Promise<{ opener: string }> {
638
- if (!existsSync(path)) throw new Error(`file not found: ${path}`);
639
- const plat = platform();
640
- if (plat === "darwin") {
641
- await run("open", [path], 15_000);
642
- return { opener: "open" };
643
- }
644
- if (plat === "win32") {
645
- await run("cmd", ["/c", "start", "", path], 15_000);
646
- return { opener: "start" };
647
- }
648
- await run("xdg-open", [path], 15_000);
649
- return { opener: "xdg-open" };
400
+ return withDiagramFiles([opts.input], opts.signal, async () => {
401
+ const prepared = await prepareExport(opts, opts.input, finishStagedSvg);
402
+ try {
403
+ return prepared.commit();
404
+ } finally {
405
+ await prepared.dispose();
406
+ }
407
+ });
650
408
  }