@senad-d/drawme 0.1.3 → 0.1.4

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,7 +1,7 @@
1
1
  /**
2
2
  * draw.io desktop CLI wrapper: binary resolution + export. Encodes the tricky
3
- * flag knowledge for preview vs final export, the vision width cap, `-e` PNG
4
- * IEND repair, page indexing, and headless-Linux handling so callers never
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
5
  * hand-build a draw.io command line.
6
6
  */
7
7
  import { execFile } from "node:child_process";
@@ -163,15 +163,17 @@ export interface ExportResult {
163
163
  version?: string;
164
164
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
165
165
  repaired: boolean;
166
- /** Preview artifacts for this source that were removed after a successful final export. */
166
+ /** Superseded preview artifacts removed after this successful preview or final export. */
167
167
  removedPreviews: string[];
168
- /** Best-effort cleanup failures; the final export itself still succeeded. */
168
+ /** Best-effort preview cleanup failures; the export itself still succeeded. */
169
169
  previewCleanupWarnings: string[];
170
170
  command: string;
171
171
  }
172
172
 
173
- /** Successful preview outputs, grouped by their canonical source path. */
173
+ /** Successful preview outputs still present, grouped by their canonical source path. */
174
174
  const previewOutputs = new Map<string, Map<string, string>>();
175
+ /** Serialize exports per source so concurrent preview calls cannot leave multiple latest artifacts. */
176
+ const exportQueues = new Map<string, Promise<void>>();
175
177
 
176
178
  function sourceKey(input: string): string {
177
179
  try {
@@ -181,16 +183,42 @@ function sourceKey(input: string): string {
181
183
  }
182
184
  }
183
185
 
184
- function trackPreview(input: string, output: string): void {
185
- const previews = previewOutputs.get(sourceKey(input)) ?? new Map<string, string>();
186
- previews.set(resolve(output), output);
187
- previewOutputs.set(sourceKey(input), previews);
186
+ interface PreviewCleanup {
187
+ removed: string[];
188
+ warnings: string[];
188
189
  }
189
190
 
190
- async function removeTrackedPreviews(
191
- input: string,
192
- finalOutput: string,
193
- ): Promise<{ removed: string[]; warnings: string[] }> {
191
+ /**
192
+ * Keep the newly exported preview and retire every older tracked preview for the
193
+ * same source. Cleanup happens only after the replacement exists, so a failed
194
+ * export never destroys the last usable review image.
195
+ */
196
+ async function replaceTrackedPreview(input: string, latestOutput: string): Promise<PreviewCleanup> {
197
+ const key = sourceKey(input);
198
+ const previous = previewOutputs.get(key) ?? new Map<string, string>();
199
+ const latestPath = resolve(latestOutput);
200
+ const retained = new Map<string, string>([[latestPath, latestOutput]]);
201
+ const removed: string[] = [];
202
+ const warnings: string[] = [];
203
+
204
+ for (const [path, displayPath] of previous) {
205
+ if (path === latestPath) continue;
206
+ const existed = existsSync(path);
207
+ try {
208
+ await rm(path, { force: true });
209
+ if (existed) removed.push(displayPath);
210
+ } catch (error) {
211
+ retained.set(path, displayPath);
212
+ const message = error instanceof Error ? error.message : String(error);
213
+ warnings.push(`${displayPath}: ${message}`);
214
+ }
215
+ }
216
+
217
+ previewOutputs.set(key, retained);
218
+ return { removed, warnings };
219
+ }
220
+
221
+ async function removeTrackedPreviews(input: string, finalOutput: string): Promise<PreviewCleanup> {
194
222
  const key = sourceKey(input);
195
223
  const previews = previewOutputs.get(key);
196
224
  if (!previews) return { removed: [], warnings: [] };
@@ -218,6 +246,25 @@ async function removeTrackedPreviews(
218
246
  return { removed, warnings };
219
247
  }
220
248
 
249
+ async function withSourceExportQueue<T>(input: string, action: () => Promise<T>): Promise<T> {
250
+ const key = sourceKey(input);
251
+ const previous = exportQueues.get(key) ?? Promise.resolve();
252
+ let release = (): void => {};
253
+ const current = new Promise<void>((resolveCurrent) => {
254
+ release = resolveCurrent;
255
+ });
256
+ const tail = previous.then(() => current);
257
+ exportQueues.set(key, tail);
258
+
259
+ await previous;
260
+ try {
261
+ return await action();
262
+ } finally {
263
+ release();
264
+ if (exportQueues.get(key) === tail) exportQueues.delete(key);
265
+ }
266
+ }
267
+
221
268
  function isRootUser(): boolean {
222
269
  const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
223
270
  return typeof getuid === "function" && getuid() === 0;
@@ -245,6 +292,10 @@ async function invoke(binary: string, fullArgs: string[]): Promise<string> {
245
292
  */
246
293
  export async function exportDiagram(opts: ExportOptions): Promise<ExportResult> {
247
294
  if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
295
+ return withSourceExportQueue(opts.input, () => exportDiagramQueued(opts));
296
+ }
297
+
298
+ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
248
299
  const info = await resolveBinary(opts.binary);
249
300
  if (!info.available || !info.binary) {
250
301
  throw new Error(
@@ -268,9 +319,10 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
268
319
  }
269
320
 
270
321
  const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
271
- if (plan.mode === "preview") trackPreview(plan.input, plan.output);
272
322
  const cleanup =
273
- plan.mode === "final" ? await removeTrackedPreviews(plan.input, plan.output) : { removed: [], warnings: [] };
323
+ plan.mode === "preview"
324
+ ? await replaceTrackedPreview(plan.input, plan.output)
325
+ : await removeTrackedPreviews(plan.input, plan.output);
274
326
  return {
275
327
  output: plan.output,
276
328
  format: plan.format,
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
12
  import { Type, type Static } from "typebox";
13
13
  import { fileURLToPath } from "node:url";
14
14
  import { dirname, resolve } from "node:path";
15
+ import { readFile } from "node:fs/promises";
15
16
  import {
16
17
  applyLayout,
17
18
  convertMermaid,
@@ -53,6 +54,18 @@ export type DrawioExportInput = Static<typeof exportParams>;
53
54
 
54
55
  const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
55
56
 
57
+ async function exportResult(text: string, result: Awaited<ReturnType<typeof exportDiagram>>) {
58
+ const content: (
59
+ | { type: "text"; text: string }
60
+ | { type: "image"; data: string; mimeType: "image/png" }
61
+ )[] = [{ type: "text", text }];
62
+ if (result.mode === "preview" && result.format === "png") {
63
+ const png = await readFile(result.output);
64
+ content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
65
+ }
66
+ return { content, details: result };
67
+ }
68
+
56
69
  export default function drawme(pi: ExtensionAPI): void {
57
70
  pi.registerTool({
58
71
  name: "drawio_check",
@@ -82,9 +95,9 @@ export default function drawme(pi: ExtensionAPI): void {
82
95
  name: "drawio_export",
83
96
  label: "draw.io: export",
84
97
  description:
85
- "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. Use mode:'preview' for a clean, width-capped PNG to self-check with vision (never embedded), and mode:'final' for the deliverable (embedded editable output; the truncated -e PNG IEND chunk is auto-repaired). A successful final export automatically removes preview artifacts previously created for the same source.",
98
+ "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. A successful mode:'preview' PNG is clean, width-capped, never embedded, and attached to the text/metadata tool result for focused visual review. Each successful preview removes the prior preview artifact for the same source, leaving only the latest file. mode:'final' creates the deliverable (embedded editable output; truncated PNG IEND is repaired) and removes the remaining preview.",
86
99
  promptSnippet:
87
- "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' for self-check, mode:'final' for the deliverable and automatic preview cleanup).",
100
+ "Export a .drawio to PNG/SVG/PDF/JPG (each mode:'preview' call attaches the latest review image and removes the previous preview file; mode:'final' creates the deliverable and cleans the remaining preview).",
88
101
  parameters: exportParams,
89
102
  async execute(_id, params) {
90
103
  try {
@@ -97,7 +110,7 @@ export default function drawme(pi: ExtensionAPI): void {
97
110
  }
98
111
  const versionSuffix = r.version ? ` (${r.version})` : "";
99
112
  lines.push(`binary=${r.binary}${versionSuffix}`);
100
- return textResult(lines.join("\n"), r);
113
+ return exportResult(lines.join("\n"), r);
101
114
  } catch (e) {
102
115
  return textResult(`Export failed: ${(e as Error).message}`, { error: (e as Error).message });
103
116
  }
@@ -108,15 +121,20 @@ export default function drawme(pi: ExtensionAPI): void {
108
121
  name: "drawio_validate",
109
122
  label: "draw.io: validate",
110
123
  description:
111
- "Structurally lint a .drawio file: errors for dangling edge endpoints, duplicate/reserved ids, broken parents, and missing geometry; warnings for overlapping nodes, off-canvas shapes, and edges that route through shapes or cross each other. Deterministic and does not launch draw.io. Run before exporting.",
112
- promptSnippet: "Lint a .drawio for structural errors before exporting.",
124
+ "Structurally lint a .drawio file: errors for dangling endpoints, duplicate/reserved ids, broken parents, and missing/malformed vertex or edge geometry; actionable warnings for overlap, page/containment bounds, conservative readability defects, and explicit routes through shapes or across edges. Reports observations and a readability score. Deterministic and does not launch draw.io. Run after every source edit and before exporting.",
125
+ promptSnippet: "Lint a .drawio after every source edit and before exporting.",
113
126
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
114
127
  async execute(_id, params) {
115
128
  const r = await validateFile(params.input);
116
129
  const lines = [
117
- ...r.warnings.map((w) => `warning: ${w}`),
118
- ...r.errors.map((e) => `error: ${e}`),
119
- `${r.errors.length} error(s), ${r.warnings.length} warning(s)`,
130
+ `Errors (${r.errors.length}):`,
131
+ ...(r.errors.length > 0 ? r.errors.map((error) => `- ${error}`) : ["- none"]),
132
+ `Actionable warnings (${r.warnings.length}):`,
133
+ ...(r.warnings.length > 0 ? r.warnings.map((warning) => `- ${warning}`) : ["- none"]),
134
+ `Informational observations (${r.observations.length}):`,
135
+ ...(r.observations.length > 0 ? r.observations.map((observation) => `- ${observation}`) : ["- none"]),
136
+ `Readability score: ${r.score.total} (route-through=${r.score.through}, crossings=${r.score.crossings}, overlaps=${r.score.overlaps}; lower is better for variants of this graph)`,
137
+ `${r.errors.length} error(s), ${r.warnings.length} unresolved warning(s)`,
120
138
  ];
121
139
  return textResult(lines.join("\n"), r);
122
140
  },