@senad-d/drawme 0.1.11 → 0.3.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/png.ts CHANGED
@@ -1,39 +1,238 @@
1
- /**
2
- * Repair the truncated IEND chunk in draw.io `-e` PNG exports.
3
- *
4
- * draw.io's CLI emits `-e` (embedded-XML) PNGs with the 4-byte IEND length
5
- * field present but the trailing 8 bytes of "IEND" type + CRC missing, so strict
6
- * PNG decoders and vision APIs reject the file (draw.io-desktop issue #8).
7
- * SVG/PDF are unaffected.
8
- *
9
- * Idempotent: a no-op once the file already ends with a valid IEND chunk, so it
10
- * is safe to run unconditionally after every `-e` PNG export.
11
- */
1
+ import { isUtf8 } from "node:buffer";
12
2
  import { readFile, writeFile } from "node:fs/promises";
3
+ import { crc32, inflateSync, type Inflate } from "node:zlib";
4
+ import { DEFAULT_XML_BYTES } from "./diagram-files";
5
+ import { MAX_FINAL_RASTER_PIXELS } from "./export-plan";
13
6
 
14
- /** A complete, valid IEND chunk: length(0) + "IEND" + CRC 0xAE426082. */
15
- const IEND = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]);
16
- /** The bare 4-byte length field draw.io leaves behind when it truncates. */
17
- const LEN_FIELD = Buffer.from([0x00, 0x00, 0x00, 0x00]);
18
-
19
- /**
20
- * Return a repaired copy of `data`, or `null` if it already ends with a valid
21
- * IEND chunk (no change needed). Pure — no filesystem access, for easy testing.
22
- */
23
- export function repairPngBuffer(data: Buffer): Buffer | null {
24
- if (data.length >= IEND.length && data.subarray(data.length - IEND.length).equals(IEND)) {
25
- return null;
26
- }
27
- const body =
28
- data.length >= LEN_FIELD.length && data.subarray(data.length - LEN_FIELD.length).equals(LEN_FIELD)
29
- ? data.subarray(0, data.length - LEN_FIELD.length)
30
- : data;
31
- return Buffer.concat([body, IEND]);
32
- }
33
-
34
- /** Repair the PNG at `path` in place. Returns true if the file was changed. */
35
- export async function repairPng(path: string): Promise<boolean> {
36
- const fixed = repairPngBuffer(await readFile(path));
7
+ const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
8
+ const IEND = Buffer.from([0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]);
9
+ // Draw.io's zTXt payload URI-encodes the UTF-8 source (at most three bytes per input byte).
10
+ const MAX_TEXT_BYTES = 3 * DEFAULT_XML_BYTES;
11
+
12
+ const COLOR_TYPES = new Map([
13
+ [0, { channels: 1, depths: [1, 2, 4, 8, 16] }], // grayscale
14
+ [2, { channels: 3, depths: [8, 16] }], // RGB
15
+ [3, { channels: 1, depths: [1, 2, 4, 8] }], // palette index
16
+ [4, { channels: 2, depths: [8, 16] }], // grayscale + alpha
17
+ [6, { channels: 4, depths: [8, 16] }], // RGBA
18
+ ]);
19
+
20
+ // Pass layout: starting x/y and x/y stride. Each pass has its own row filters.
21
+ const ADAM7 = [
22
+ [0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2],
23
+ ];
24
+
25
+ function badPng(): Error {
26
+ return new Error("draw.io output is not a complete PNG");
27
+ }
28
+
29
+ function readChunk(data: Buffer, offset: number) {
30
+ const size = data.readUInt32BE(offset);
31
+ const crcOffset = offset + 8 + size;
32
+ if (size > 0x7fff_ffff || crcOffset + 4 > data.length) throw badPng();
33
+ const type = data.toString("latin1", offset + 4, offset + 8);
34
+ if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type) || crc32(data.subarray(offset + 4, crcOffset)) !== data.readUInt32BE(crcOffset)) {
35
+ throw badPng();
36
+ }
37
+ return { type, body: data.subarray(offset + 8, crcOffset), next: crcOffset + 4 };
38
+ }
39
+
40
+ function readHeader(data: Buffer) {
41
+ if (data.length < 33 || !data.subarray(0, SIGNATURE.length).equals(SIGNATURE)) throw badPng();
42
+ const { type, body, next } = readChunk(data, SIGNATURE.length);
43
+ if (type !== "IHDR" || body.length !== 13) throw badPng();
44
+ const width = body.readUInt32BE(0);
45
+ const height = body.readUInt32BE(4);
46
+ const [depth, color, compression, filter, interlace] = body.subarray(8);
47
+ const mode = COLOR_TYPES.get(color);
48
+ if (!width || !height || width > 0x7fff_ffff || height > 0x7fff_ffff || !mode?.depths.includes(depth)
49
+ || compression !== 0 || filter !== 0 || interlace > 1) throw badPng();
50
+ if (width * height > MAX_FINAL_RASTER_PIXELS) {
51
+ throw new Error(`draw.io output exceeds the ${MAX_FINAL_RASTER_PIXELS}-pixel PNG limit`);
52
+ }
53
+ return { width, height, depth, color, bitsPerPixel: depth * mode.channels, interlace, next };
54
+ }
55
+
56
+ type Header = ReturnType<typeof readHeader>;
57
+
58
+ function inflateBounded(input: Buffer, maxBytes: number): Buffer {
59
+ // info=true returns the zlib engine as well as output, but the Node type declares Buffer only.
60
+ let output: { buffer: Buffer; engine: Inflate };
61
+ try {
62
+ output = inflateSync(input, { info: true, maxOutputLength: Math.max(1, maxBytes) }) as unknown as typeof output;
63
+ } catch {
64
+ throw badPng();
65
+ }
66
+ if (output.engine.bytesWritten !== input.length || output.buffer.length > maxBytes) throw badPng();
67
+ return output.buffer;
68
+ }
69
+
70
+ function paeth(left: number, above: number, diagonal: number): number {
71
+ const guess = left + above - diagonal;
72
+ const a = Math.abs(guess - left);
73
+ const b = Math.abs(guess - above);
74
+ const c = Math.abs(guess - diagonal);
75
+ return a <= b && a <= c ? left : b <= c ? above : diagonal;
76
+ }
77
+
78
+ /** Indexed rows with fewer than 2^depth entries can contain invalid samples after unfiltering. */
79
+ function checkIndices(pixels: Buffer, start: number, previous: number | undefined, width: number, depth: number, filter: number, entries: number): void {
80
+ const mask = (1 << depth) - 1;
81
+ const bytes = Math.ceil(width * depth / 8);
82
+ for (let i = 0; i < bytes && filter !== 0; i++) {
83
+ const left = i === 0 ? 0 : pixels[start + i - 1];
84
+ const above = previous === undefined ? 0 : pixels[previous + i];
85
+ const diagonal = previous === undefined || i === 0 ? 0 : pixels[previous + i - 1];
86
+ const bias = filter === 1 ? left : filter === 2 ? above : filter === 3 ? (left + above) >> 1 : paeth(left, above, diagonal);
87
+ pixels[start + i] = (pixels[start + i] + bias) & 0xff;
88
+ }
89
+ for (let bit = 0; bit < width * depth; bit += depth) {
90
+ const sample = (pixels[start + (bit >> 3)] >> (8 - depth - (bit & 7))) & mask;
91
+ if (sample >= entries) throw badPng();
92
+ }
93
+ }
94
+
95
+ function checkScanlines(header: Header, idat: Buffer[], paletteEntries: number): void {
96
+ const passes = (header.interlace ? ADAM7 : [[0, 0, 1, 1]]).flatMap(([x, y, dx, dy]) => {
97
+ const width = Math.ceil((header.width - x) / dx);
98
+ const height = Math.ceil((header.height - y) / dy);
99
+ return width > 0 && height > 0 ? [{ width, height, rowBytes: Math.ceil(width * header.bitsPerPixel / 8) }] : [];
100
+ });
101
+ const expected = passes.reduce((bytes, pass) => bytes + (1 + pass.rowBytes) * pass.height, 0);
102
+ const pixels = inflateBounded(idat.length === 1 ? idat[0] : Buffer.concat(idat), expected);
103
+ if (pixels.length !== expected) throw badPng();
104
+ const checkPalette = header.color === 3 && paletteEntries < 2 ** header.depth;
105
+ let offset = 0;
106
+ for (const { width, height, rowBytes } of passes) {
107
+ for (let row = 0; row < height; row++) {
108
+ const filter = pixels[offset];
109
+ if (filter > 4) throw badPng();
110
+ if (checkPalette) checkIndices(pixels, offset + 1, row === 0 ? undefined : offset - rowBytes, width, header.depth, filter, paletteEntries);
111
+ offset += 1 + rowBytes;
112
+ }
113
+ }
114
+ }
115
+
116
+ function checkTransparency(body: Buffer, header: Header, paletteEntries: number): void {
117
+ if (header.color === 3) {
118
+ if (!body.length || body.length > paletteEntries) throw badPng();
119
+ return;
120
+ }
121
+ const length = header.color === 0 ? 2 : header.color === 2 ? 6 : 0;
122
+ if (!length || body.length !== length) throw badPng();
123
+ for (let offset = 0; offset < length; offset += 2) {
124
+ if (body.readUInt16BE(offset) >= 2 ** header.depth) throw badPng();
125
+ }
126
+ }
127
+
128
+ function internationalText(fields: Buffer, remaining: number): Buffer {
129
+ const flag = fields[0];
130
+ if (fields.length < 4 || (flag !== 0 && flag !== 1) || (flag === 1 && fields[1] !== 0)) throw badPng();
131
+ const languageEnd = fields.indexOf(0, 2);
132
+ if (languageEnd < 0 || !/^[A-Za-z0-9-]*$/.test(fields.toString("latin1", 2, languageEnd))) throw badPng();
133
+ const translationEnd = fields.indexOf(0, languageEnd + 1);
134
+ if (translationEnd < 0 || !isUtf8(fields.subarray(languageEnd + 1, translationEnd))) throw badPng();
135
+ const text = fields.subarray(translationEnd + 1);
136
+ const decoded = flag === 1 ? inflateBounded(text, remaining) : text;
137
+ if (!isUtf8(decoded)) throw badPng();
138
+ return decoded;
139
+ }
140
+
141
+ function readText(type: string, body: Buffer, remaining: number) {
142
+ const end = body.subarray(0, 80).indexOf(0);
143
+ if (end < 1) throw badPng();
144
+ const key = body.toString("latin1", 0, end);
145
+ if (key !== key.trim() || /[^\x20-\x7e\xa1-\xff]|\x20{2}/u.test(key)) throw badPng();
146
+ const fields = body.subarray(end + 1);
147
+ let text = fields;
148
+ if (type === "zTXt") {
149
+ if (fields[0] !== 0) throw badPng();
150
+ text = inflateBounded(fields.subarray(1), remaining);
151
+ } else if (type === "iTXt") {
152
+ text = internationalText(fields, remaining);
153
+ }
154
+ if (text.length > remaining || text.includes(0)) throw badPng();
155
+ // Both are draw.io's recognized editable-metadata keys. Text mentioning the
156
+ // name elsewhere (e.g. in a comment or image bytes) is not editable metadata.
157
+ return { editable: key === "mxGraphModel" || key === "mxfile", length: text.length };
158
+ }
159
+
160
+ interface PngInfo {
161
+ width: number;
162
+ height: number;
163
+ editable: boolean;
164
+ }
165
+
166
+ function inspect(data: Buffer, allowMissingTail: boolean): PngInfo & { complete: boolean; end: number } {
167
+ const header = readHeader(data);
168
+ const idat: Buffer[] = [];
169
+ let offset = header.next;
170
+ let imageStarted = false;
171
+ let imageEnded = false;
172
+ let paletteEntries = 0;
173
+ let transparency = false;
174
+ let remainingText = MAX_TEXT_BYTES;
175
+ let editable = false;
176
+ while (offset + 12 <= data.length) {
177
+ const { type, body, next } = readChunk(data, offset);
178
+ if (type === "IEND") break;
179
+ if (type !== "IDAT" && imageStarted) imageEnded = true;
180
+ switch (type) {
181
+ case "PLTE":
182
+ if (imageStarted || transparency || paletteEntries || header.color === 0 || header.color === 4
183
+ || !body.length || body.length % 3 || body.length > 256 * 3) throw badPng();
184
+ paletteEntries = body.length / 3;
185
+ if (header.color === 3 && paletteEntries > 2 ** header.depth) throw badPng();
186
+ break;
187
+ case "tRNS":
188
+ if (imageStarted || transparency) throw badPng();
189
+ checkTransparency(body, header, paletteEntries);
190
+ transparency = true;
191
+ break;
192
+ case "IDAT":
193
+ if (imageEnded || (header.color === 3 && !paletteEntries)) throw badPng();
194
+ imageStarted = true;
195
+ if (body.length) idat.push(body);
196
+ break;
197
+ case "tEXt":
198
+ case "zTXt":
199
+ case "iTXt": {
200
+ const text = readText(type, body, remainingText);
201
+ remainingText -= text.length;
202
+ editable ||= text.editable;
203
+ break;
204
+ }
205
+ default:
206
+ // IHDR must not repeat, and an unknown critical chunk may change pixel decoding.
207
+ if (type[0] === type[0].toUpperCase()) throw badPng();
208
+ }
209
+ offset = next;
210
+ }
211
+ const tail = data.subarray(offset);
212
+ const complete = tail.equals(IEND);
213
+ if (!complete && !(allowMissingTail && (tail.length === 0 || (tail.length === 4 && tail.readUInt32BE(0) === 0)))) throw badPng();
214
+ if (!idat.length) throw badPng();
215
+ checkScanlines(header, idat, paletteEntries);
216
+ return { width: header.width, height: header.height, editable, complete, end: offset };
217
+ }
218
+
219
+ /** Verify the complete PNG, including its decoded scanlines and draw.io metadata. */
220
+ export function inspectPng(data: Buffer): PngInfo {
221
+ const { width, height, editable } = inspect(data, false);
222
+ return { width, height, editable };
223
+ }
224
+
225
+ /** Repair only the missing IEND tail of otherwise valid draw.io -e output. */
226
+ export function repairPngBuffer(data: Buffer, embedded = true): Buffer | null {
227
+ const { complete, end } = inspect(data, embedded);
228
+ if (complete) return null;
229
+ // draw.io-desktop issue #8: sometimes only the four-byte IEND length remains.
230
+ return Buffer.concat([data.subarray(0, end), IEND]);
231
+ }
232
+
233
+ /** Verify the PNG and return whether its truncated tail had to be repaired. */
234
+ export async function repairPng(path: string, embedded = true): Promise<boolean> {
235
+ const fixed = repairPngBuffer(await readFile(path), embedded);
37
236
  if (!fixed) return false;
38
237
  await writeFile(path, fixed);
39
238
  return true;
@@ -0,0 +1,361 @@
1
+ import { spawn } from "node:child_process";
2
+ import { addAbortListener } from "node:events";
3
+ import { existsSync, realpathSync, statSync } from "node:fs";
4
+ import { platform, release } from "node:os";
5
+ import { extname, isAbsolute, win32 } from "node:path";
6
+ import type { Readable } from "node:stream";
7
+ import { sessionPath } from "./diagram-files";
8
+
9
+ export interface DrawioInfo {
10
+ available: boolean;
11
+ binary?: string;
12
+ version?: string;
13
+ major?: number;
14
+ supportsMermaid?: boolean;
15
+ supportsLayout?: boolean;
16
+ unavailableReason?: "root" | "wsl-windows" | "not-found";
17
+ }
18
+
19
+ export const FEATURE_MIN = "30.2.4";
20
+ export const INDEX_MIN = "32.4.1";
21
+
22
+ const PIPE_BYTES = 8192;
23
+ const RENDER_TIMEOUT = 120_000;
24
+ const PROBE_TIMEOUT = 15_000;
25
+ const TERMINATION_GRACE = 5_000;
26
+ const LAUNCH_OBSERVATION = 500;
27
+
28
+ class ProcessFailure extends Error {
29
+ constructor(message: string, readonly code?: number | "ENOENT") {
30
+ super(message);
31
+ }
32
+ }
33
+
34
+ function startFailure(operation: string, error: unknown): ProcessFailure {
35
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
36
+ const why = code === "ENOENT" ? "executable not found"
37
+ : code === "EACCES" || code === "EPERM" ? "permission denied" : "could not execute the program";
38
+ return new ProcessFailure(`${operation} could not start: ${why}`, code === "ENOENT" ? code : undefined);
39
+ }
40
+
41
+ function exitFailure(operation: string, code: number | null, signal: NodeJS.Signals | null): ProcessFailure {
42
+ const why = signal ?? (code === null ? "an unknown status" : `code ${code}`);
43
+ return new ProcessFailure(`${operation} exited with ${why}`, code ?? undefined);
44
+ }
45
+
46
+ function abortError(operation: string): DOMException {
47
+ return new DOMException(`${operation} canceled`, "AbortError");
48
+ }
49
+
50
+ function checkAborted(signal: AbortSignal | undefined, operation: string): void {
51
+ if (signal?.aborted) throw abortError(operation);
52
+ }
53
+
54
+ interface CapturedPipe {
55
+ bytes: Buffer;
56
+ truncated: boolean;
57
+ }
58
+
59
+ function drainPipe(pipe: Readable): () => CapturedPipe {
60
+ const bytes = Buffer.allocUnsafe(PIPE_BYTES);
61
+ let length = 0;
62
+ let truncated = false;
63
+ pipe.on("data", (chunk: Buffer) => {
64
+ const count = Math.min(chunk.length, bytes.length - length);
65
+ length += chunk.copy(bytes, length, 0, count);
66
+ if (count < chunk.length) truncated = true;
67
+ });
68
+ return () => ({ bytes: bytes.subarray(0, length), truncated });
69
+ }
70
+
71
+ function pipeText({ bytes }: CapturedPipe): string {
72
+ const text = bytes.toString("utf8");
73
+ if (Buffer.byteLength(text) <= PIPE_BYTES) return text;
74
+ // Invalid UTF-8 (including a code point cut by the cap) can expand when decoded.
75
+ const bounded = Buffer.allocUnsafe(PIPE_BYTES);
76
+ return bounded.toString("utf8", 0, bounded.write(text));
77
+ }
78
+
79
+ function killTree(pid: number | undefined, group: boolean, signal: NodeJS.Signals): void {
80
+ if (pid === undefined) return;
81
+ try {
82
+ process.kill(group ? -pid : pid, signal);
83
+ } catch {
84
+ // Already gone.
85
+ }
86
+ }
87
+
88
+ async function captureCommand(
89
+ bin: string,
90
+ args: string[],
91
+ timeout: number,
92
+ signal: AbortSignal | undefined,
93
+ operation: string,
94
+ ): Promise<{ stdout: CapturedPipe; stderr: CapturedPipe }> {
95
+ checkAborted(signal, operation);
96
+ const group = platform() !== "win32";
97
+ let child;
98
+ try {
99
+ child = spawn(bin, args, { detached: group, stdio: ["ignore", "pipe", "pipe"] });
100
+ } catch (error) {
101
+ throw startFailure(operation, error);
102
+ }
103
+ const stdout = drainPipe(child.stdout);
104
+ const stderr = drainPipe(child.stderr);
105
+
106
+ return new Promise((resolve, reject) => {
107
+ let settled = false;
108
+ let stopped: Error | undefined;
109
+ let killTimer: NodeJS.Timeout | undefined;
110
+ const forceKill = () => {
111
+ if (killTimer === undefined) return;
112
+ clearTimeout(killTimer);
113
+ killTimer = undefined;
114
+ // On early close the leader is reaped, but its process group may still have members.
115
+ killTree(child.pid, group, "SIGKILL");
116
+ };
117
+ const stop = (error: Error) => {
118
+ if (settled || stopped) return;
119
+ stopped = error;
120
+ killTimer = setTimeout(forceKill, TERMINATION_GRACE);
121
+ killTree(child.pid, group, "SIGTERM");
122
+ };
123
+ const timer = setTimeout(() => stop(new Error(`${operation} timed out after ${timeout / 1000}s`)), timeout);
124
+ const abort = signal && addAbortListener(signal, () => stop(abortError(operation)));
125
+ const finish = (error: Error | undefined) => {
126
+ if (settled) return;
127
+ settled = true;
128
+ clearTimeout(timer);
129
+ abort?.[Symbol.dispose]();
130
+ if (group) forceKill();
131
+ else clearTimeout(killTimer);
132
+ if (error) reject(error);
133
+ else resolve({ stdout: stdout(), stderr: stderr() });
134
+ };
135
+ child.on("error", (error) => finish(stopped ?? startFailure(operation, error)));
136
+ child.once("close", (code, exitSignal) => finish(stopped ?? (code === 0 ? undefined : exitFailure(operation, code, exitSignal))));
137
+ });
138
+ }
139
+
140
+ /** Drain both pipes, with a bounded prefix per pipe. On POSIX, cancellation targets the full process group. */
141
+ export async function run(
142
+ bin: string,
143
+ args: string[],
144
+ timeout = RENDER_TIMEOUT,
145
+ signal?: AbortSignal,
146
+ ): Promise<{ stdout: string; stderr: string }> {
147
+ const result = await captureCommand(bin, args, timeout, signal, "command");
148
+ checkAborted(signal, "command");
149
+ return { stdout: pipeText(result.stdout), stderr: pipeText(result.stderr) };
150
+ }
151
+
152
+ type VersionParts = [number, number, number];
153
+
154
+ function versionParts(version: string): VersionParts | undefined {
155
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version);
156
+ if (!match || match[0] !== version) return undefined;
157
+ const parts: VersionParts = [Number(match[1]), Number(match[2]), Number(match[3])];
158
+ return parts.every(Number.isSafeInteger) ? parts : undefined;
159
+ }
160
+
161
+ function versionAtLeast(current: VersionParts, floor: string): boolean {
162
+ const min = versionParts(floor)!;
163
+ for (const [i, part] of current.entries()) {
164
+ if (part !== min[i]) return part > min[i];
165
+ }
166
+ return true;
167
+ }
168
+
169
+ export function supportsPageIndex(version: string | undefined): boolean {
170
+ const parts = version && versionParts(version);
171
+ return !!parts && versionAtLeast(parts, INDEX_MIN);
172
+ }
173
+
174
+ /** Startup logs may precede the version; don't guess from a partial or ambiguous line. */
175
+ function probeVersion(stdout: CapturedPipe): { version: string; parts: VersionParts } | undefined {
176
+ if (stdout.truncated) return undefined;
177
+ let found: { version: string; parts: VersionParts } | undefined;
178
+ for (const version of stdout.bytes.toString("utf8").split(/\r?\n/)) {
179
+ const parts = versionParts(version);
180
+ if (parts) {
181
+ if (found) return undefined;
182
+ found = { version, parts };
183
+ }
184
+ }
185
+ return found;
186
+ }
187
+
188
+ export function rendererUnavailable(info: DrawioInfo): string {
189
+ if (info.unavailableReason === "root") {
190
+ return "DrawMe will not run draw.io as root on Linux. Run Pi as an unprivileged user to keep the renderer sandbox enabled.";
191
+ }
192
+ if (info.unavailableReason === "wsl-windows") {
193
+ return "DrawMe cannot use the Windows draw.io renderer from WSL. Install native Linux draw.io in WSL and use Xvfb when headless.";
194
+ }
195
+ return "draw.io CLI not found or could not start. Install draw.io Desktop (macOS: `brew install --cask drawio`; " +
196
+ "other platforms: https://github.com/jgraph/drawio-desktop/releases). On headless Linux install Xvfb, " +
197
+ "or select an installed renderer with an absolute DRAWME_DRAWIO_BINARY path in Pi's launch environment.";
198
+ }
199
+
200
+ export function assertRendererUser(plat: string, isRoot: boolean): void {
201
+ if (plat === "linux" && isRoot) throw new Error(rendererUnavailable({ available: false, unavailableReason: "root" }));
202
+ }
203
+
204
+ function isRootUser(): boolean {
205
+ return process.getuid?.() === 0 || process.geteuid?.() === 0;
206
+ }
207
+
208
+ function isWsl(plat: string): boolean {
209
+ return plat === "linux" && (!!process.env.WSL_INTEROP || !!process.env.WSL_DISTRO_NAME || /microsoft/i.test(release()));
210
+ }
211
+
212
+ /** Floor at 1280x1024; leave room for the larger requested raster axis, capped at 8192. */
213
+ export function xvfbScreen(args: string[]): string {
214
+ const want = Math.max(flagNumber(args, "--width"), flagNumber(args, "--height"));
215
+ const side = want > 0 ? Math.min(8192, want + 256) : 0;
216
+ return `${Math.max(1280, side)}x${Math.max(1024, side)}x24`;
217
+ }
218
+
219
+ function flagNumber(args: string[], flag: string): number {
220
+ const i = args.indexOf(flag);
221
+ return i >= 0 ? Number(args[i + 1]) || 0 : 0;
222
+ }
223
+
224
+ /** The same preparation for probes and real work. The display command is never executed. */
225
+ async function executeRenderer(
226
+ binary: string,
227
+ args: string[],
228
+ timeout: number,
229
+ signal: AbortSignal | undefined,
230
+ operation: string,
231
+ ): Promise<{ command: string; stdout: CapturedPipe }> {
232
+ if (platform() === "linux" && !process.env.DISPLAY) {
233
+ const screen = `-screen 0 ${xvfbScreen(args)}`;
234
+ try {
235
+ const { stdout } = await captureCommand("xvfb-run", ["-a", `--server-args=${screen}`, binary, ...args], timeout, signal, operation);
236
+ return { command: `xvfb-run -a --server-args="${screen}" ${binary} ${args.join(" ")}`, stdout };
237
+ } catch (error) {
238
+ // A present wrapper that failed isn't permission to launch directly.
239
+ if (!(error instanceof ProcessFailure && error.code === "ENOENT")) throw error;
240
+ }
241
+ }
242
+ const { stdout } = await captureCommand(binary, args, timeout, signal, operation);
243
+ return { command: `${binary} ${args.join(" ")}`, stdout };
244
+ }
245
+
246
+ function candidatesFor(plat: string): string[] {
247
+ const candidates = ["drawio", "draw.io"];
248
+ if (plat === "darwin") candidates.push("/Applications/draw.io.app/Contents/MacOS/draw.io");
249
+ if (plat === "win32") {
250
+ candidates.push(String.raw`C:\Program Files\draw.io\draw.io.exe`, String.raw`C:\Program Files (x86)\draw.io\draw.io.exe`);
251
+ }
252
+ return candidates;
253
+ }
254
+
255
+ /** Only trusted code or an absolute path configured in Pi's launch environment can override discovery. */
256
+ export async function resolveBinary(trustedOverride?: string, signal?: AbortSignal): Promise<DrawioInfo> {
257
+ const operation = "draw.io version probe";
258
+ checkAborted(signal, operation);
259
+ const plat = platform();
260
+ if (plat === "linux" && isRootUser()) return { available: false, unavailableReason: "root" };
261
+ const wsl = isWsl(plat);
262
+ const configured = process.env.DRAWME_DRAWIO_BINARY;
263
+ const preferred = trustedOverride || (configured && isAbsolute(configured) ? configured : undefined);
264
+ const candidates = new Set(preferred ? [preferred, ...candidatesFor(plat)] : candidatesFor(plat));
265
+ for (const bin of candidates) {
266
+ checkAborted(signal, operation);
267
+ if (wsl && /\.exe$/i.test(bin)) continue;
268
+ if ((bin.includes("/") || bin.includes("\\")) && !existsSync(bin)) continue;
269
+ try {
270
+ const { stdout } = await executeRenderer(bin, ["--version"], PROBE_TIMEOUT, signal, operation);
271
+ checkAborted(signal, operation);
272
+ const found = probeVersion(stdout);
273
+ if (found) {
274
+ const supportsFeatures = versionAtLeast(found.parts, FEATURE_MIN);
275
+ return {
276
+ available: true, binary: bin, version: found.version, major: found.parts[0],
277
+ supportsMermaid: supportsFeatures, supportsLayout: supportsFeatures,
278
+ };
279
+ }
280
+ } catch (error) {
281
+ if (error instanceof Error && error.name === "AbortError") throw error;
282
+ // Didn't identify this candidate; try the next one unless canceled.
283
+ }
284
+ }
285
+ checkAborted(signal, operation);
286
+ return { available: false, unavailableReason: wsl ? "wsl-windows" : "not-found" };
287
+ }
288
+
289
+ /** Run a selected renderer. Callers must anchor local file operands, not flags or inline content. */
290
+ export async function invokeRenderer(binary: string, args: string[], signal?: AbortSignal): Promise<string> {
291
+ const operation = "draw.io renderer";
292
+ checkAborted(signal, operation);
293
+ const plat = platform();
294
+ assertRendererUser(plat, isRootUser());
295
+ if (isWsl(plat) && /\.exe$/i.test(binary)) {
296
+ throw new Error(rendererUnavailable({ available: false, unavailableReason: "wsl-windows" }));
297
+ }
298
+ const { command } = await executeRenderer(binary, args, RENDER_TIMEOUT, signal, operation);
299
+ checkAborted(signal, operation);
300
+ return command;
301
+ }
302
+
303
+ const DOCUMENT_EXTENSIONS = new Set([".drawio", ".png", ".svg", ".pdf", ".jpg", ".jpeg"]);
304
+
305
+ function launchXdgOpen(document: string): Promise<void> {
306
+ const operation = "xdg-open";
307
+ const failure = (error: Error) => new Error(`${error.message}. Check that xdg-open and a desktop file association are available.`);
308
+ return new Promise((resolve, reject) => {
309
+ let child;
310
+ try {
311
+ child = spawn(operation, [document], { detached: true, stdio: "ignore" });
312
+ } catch (error) {
313
+ reject(failure(startFailure(operation, error)));
314
+ return;
315
+ }
316
+ let timer: NodeJS.Timeout | undefined;
317
+ child.once("spawn", () => {
318
+ timer = setTimeout(() => {
319
+ // A foreground viewer is legitimate. Keep no Node handle and never signal it.
320
+ child.unref();
321
+ resolve();
322
+ }, LAUNCH_OBSERVATION);
323
+ });
324
+ child.on("error", (error) => {
325
+ clearTimeout(timer);
326
+ reject(failure(startFailure(operation, error)));
327
+ });
328
+ child.once("exit", (code, signal) => {
329
+ clearTimeout(timer);
330
+ if (code === 0) resolve();
331
+ else reject(failure(exitFailure(operation, code, signal)));
332
+ });
333
+ });
334
+ }
335
+
336
+ /** Hand an existing diagram or export to its default application; no renderer or version gate. */
337
+ export async function openFile(path: string): Promise<{ opener: string }> {
338
+ const input = sessionPath(process.cwd(), path);
339
+ if (!existsSync(input)) throw new Error(`file not found: ${path}`);
340
+ const document = realpathSync.native(input);
341
+ if (!statSync(document).isFile()) throw new Error(`not a regular file: ${path}`);
342
+ if (!DOCUMENT_EXTENSIONS.has(extname(document).toLowerCase())) {
343
+ throw new Error(`not a supported diagram or export: ${path}`);
344
+ }
345
+
346
+ const plat = platform();
347
+ if (plat === "darwin") {
348
+ await captureCommand("open", [document], PROBE_TIMEOUT, undefined, "open");
349
+ return { opener: "open" };
350
+ }
351
+ if (plat === "win32") {
352
+ const root = process.env.SystemRoot;
353
+ if (!root || !win32.isAbsolute(root)) throw new Error("Windows SystemRoot is not configured");
354
+ // Call the system's file-association helper directly, not cmd.exe's start command.
355
+ await captureCommand(win32.join(root, "System32", "rundll32.exe"),
356
+ ["shell32.dll,ShellExec_RunDLL", document], PROBE_TIMEOUT, undefined, "rundll32");
357
+ return { opener: "rundll32" };
358
+ }
359
+ await launchXdgOpen(document);
360
+ return { opener: "xdg-open" };
361
+ }