@senad-d/drawme 0.1.2 → 0.1.3

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,14 +1,13 @@
1
1
  /**
2
2
  * draw.io desktop CLI wrapper: binary resolution + export. Encodes the tricky
3
- * flag knowledge from the skill (preview vs final export, the vision width cap,
4
- * the `-e` PNG IEND repair, page indexing, Linux-headless quirks) so callers
5
- * never hand-build a draw.io command line. Local-only — the only process it
6
- * spawns is the draw.io CLI (and, on headless Linux, `xvfb-run`). No network.
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
5
+ * hand-build a draw.io command line.
7
6
  */
8
7
  import { execFile } from "node:child_process";
9
- import { existsSync } from "node:fs";
8
+ import { existsSync, realpathSync } from "node:fs";
10
9
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
11
- import { basename, dirname, extname, join } from "node:path";
10
+ import { basename, dirname, extname, join, resolve } from "node:path";
12
11
  import { platform, tmpdir } from "node:os";
13
12
  import { repairPng } from "./png";
14
13
 
@@ -52,7 +51,7 @@ export interface ExportPlan {
52
51
  linuxExtra: string[];
53
52
  }
54
53
 
55
- /** Candidate binary names/paths, in resolution order (matches the skill's Step 1). */
54
+ /** Candidate binary names and paths in resolution order. */
56
55
  const CANDIDATES = [
57
56
  "drawio", // Homebrew cask, jgraph .deb/.rpm, Arch AUR
58
57
  "draw.io", // older builds / custom symlinks
@@ -120,7 +119,7 @@ export function deriveOutput(input: string, format: ExportFormat, embed: boolean
120
119
  /**
121
120
  * Build the full export plan (no side effects) so the argument logic is unit-testable.
122
121
  *
123
- * Rules baked in from the skill:
122
+ * Export planning rules:
124
123
  * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
125
124
  * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
126
125
  * - `--width` and `-s` are never combined; an explicit width/height wins
@@ -164,9 +163,61 @@ export interface ExportResult {
164
163
  version?: string;
165
164
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
166
165
  repaired: boolean;
166
+ /** Preview artifacts for this source that were removed after a successful final export. */
167
+ removedPreviews: string[];
168
+ /** Best-effort cleanup failures; the final export itself still succeeded. */
169
+ previewCleanupWarnings: string[];
167
170
  command: string;
168
171
  }
169
172
 
173
+ /** Successful preview outputs, grouped by their canonical source path. */
174
+ const previewOutputs = new Map<string, Map<string, string>>();
175
+
176
+ function sourceKey(input: string): string {
177
+ try {
178
+ return realpathSync(input);
179
+ } catch {
180
+ return resolve(input);
181
+ }
182
+ }
183
+
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);
188
+ }
189
+
190
+ async function removeTrackedPreviews(
191
+ input: string,
192
+ finalOutput: string,
193
+ ): Promise<{ removed: string[]; warnings: string[] }> {
194
+ const key = sourceKey(input);
195
+ const previews = previewOutputs.get(key);
196
+ if (!previews) return { removed: [], warnings: [] };
197
+
198
+ previewOutputs.delete(key);
199
+ const finalPath = resolve(finalOutput);
200
+ const removed: string[] = [];
201
+ const warnings: string[] = [];
202
+ const retry = new Map<string, string>();
203
+
204
+ for (const [path, displayPath] of previews) {
205
+ if (path === finalPath) continue;
206
+ const existed = existsSync(path);
207
+ try {
208
+ await rm(path, { force: true });
209
+ if (existed) removed.push(displayPath);
210
+ } catch (error) {
211
+ retry.set(path, displayPath);
212
+ const message = error instanceof Error ? error.message : String(error);
213
+ warnings.push(`${displayPath}: ${message}`);
214
+ }
215
+ }
216
+
217
+ if (retry.size > 0) previewOutputs.set(key, retry);
218
+ return { removed, warnings };
219
+ }
220
+
170
221
  function isRootUser(): boolean {
171
222
  const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
172
223
  return typeof getuid === "function" && getuid() === 0;
@@ -217,6 +268,9 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
217
268
  }
218
269
 
219
270
  const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
271
+ if (plan.mode === "preview") trackPreview(plan.input, plan.output);
272
+ const cleanup =
273
+ plan.mode === "final" ? await removeTrackedPreviews(plan.input, plan.output) : { removed: [], warnings: [] };
220
274
  return {
221
275
  output: plan.output,
222
276
  format: plan.format,
@@ -225,6 +279,8 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
225
279
  binary: info.binary,
226
280
  version: info.version,
227
281
  repaired,
282
+ removedPreviews: cleanup.removed,
283
+ previewCleanupWarnings: cleanup.warnings,
228
284
  command,
229
285
  };
230
286
  }
package/src/explain.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  /**
2
- * Describe a `.drawio` as structured Markdown — a pure-TypeScript port of the
3
- * skill's `scripts/explain.py`. The inverse of authoring: it lists components
4
- * (grouped by container/swimlane/tier), the relations between them (edge labels
5
- * become the relation verb), and a per-page breakdown for multi-page files.
6
- * Handy for a README/PR summary or a text-only read-back. Local-only, no network.
2
+ * Describe a `.drawio` as structured Markdown. The inverse of authoring: it
3
+ * lists components (grouped by container/swimlane/tier), the relations between
4
+ * them (edge labels become the relation verb), and a per-page breakdown for
5
+ * multi-page files. Handy for a README/PR summary or a text-only read-back.
7
6
  */
8
7
  import { readFile } from "node:fs/promises";
9
8
  import { basename } from "node:path";
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * DrawMe — a native Pi extension that turns natural-language descriptions into
3
3
  * `.drawio` diagrams and exports them to PNG/SVG/PDF/JPG via the draw.io desktop
4
- * CLI. It exposes the skill's workflow as plain commands + tools instead of a
5
- * skill, and does zero network I/O (see the audit note in the README).
4
+ * CLI. It exposes the authoring workflow as plain commands and model-callable
5
+ * tools.
6
6
  *
7
7
  * Tools: drawio_check · drawio_export · drawio_validate · drawio_from_mermaid
8
8
  * drawio_layout · drawio_shapesearch · drawio_explain · drawio_open
@@ -82,14 +82,19 @@ export default function drawme(pi: ExtensionAPI): void {
82
82
  name: "drawio_export",
83
83
  label: "draw.io: export",
84
84
  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). Runs entirely locally.",
86
- promptSnippet: "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' for self-check, mode:'final' for the deliverable).",
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.",
86
+ promptSnippet:
87
+ "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' for self-check, mode:'final' for the deliverable and automatic preview cleanup).",
87
88
  parameters: exportParams,
88
89
  async execute(_id, params) {
89
90
  try {
90
91
  const r = await exportDiagram(params as ExportOptions);
91
92
  const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed}`];
92
93
  if (r.repaired) lines.push("(repaired truncated -e PNG IEND chunk)");
94
+ if (r.removedPreviews.length > 0) lines.push(`Removed preview artifact(s): ${r.removedPreviews.join(", ")}`);
95
+ if (r.previewCleanupWarnings.length > 0) {
96
+ lines.push(`Preview cleanup warning(s): ${r.previewCleanupWarnings.join("; ")}`);
97
+ }
93
98
  const versionSuffix = r.version ? ` (${r.version})` : "";
94
99
  lines.push(`binary=${r.binary}${versionSuffix}`);
95
100
  return textResult(lines.join("\n"), r);
@@ -178,7 +183,7 @@ export default function drawme(pi: ExtensionAPI): void {
178
183
  name: "drawio_shapesearch",
179
184
  label: "draw.io: shape search",
180
185
  description:
181
- "Find the exact official draw.io style= string for a shape by keyword (e.g. 'aws lambda', 'uml actor', 'k8s pod'). Covers 10k+ AWS/Azure/GCP/Cisco/Kubernetes/UML/BPMN/network shapes. Use this instead of guessing a style= when a diagram needs a specific vendor or notation shape. Local index, no network.",
186
+ "Find the exact official draw.io style= string for a shape by keyword (e.g. 'aws lambda', 'uml actor', 'k8s pod'). Covers 10k+ AWS/Azure/GCP/Cisco/Kubernetes/UML/BPMN/network shapes from a bundled index. Use this instead of guessing a style= when a diagram needs a specific vendor or notation shape.",
182
187
  promptSnippet: "Look up the exact official style= string for a draw.io shape by keyword.",
183
188
  parameters: Type.Object({
184
189
  query: Type.String({ description: "Keywords, e.g. 'aws lambda' or 'uml actor'" }),
@@ -196,7 +201,7 @@ export default function drawme(pi: ExtensionAPI): void {
196
201
  name: "drawio_explain",
197
202
  label: "draw.io: explain",
198
203
  description:
199
- "Describe an existing .drawio as structured Markdown (components grouped by container, relations with edge-label verbs, per page). Useful for a README/PR summary or to read a diagram back before editing. Pure-local, no draw.io CLI needed.",
204
+ "Describe an existing .drawio as structured Markdown (components grouped by container, relations with edge-label verbs, per page). Useful for a README/PR summary or to read a diagram back before editing. No draw.io CLI needed.",
200
205
  promptSnippet: "Describe an existing .drawio as Markdown (components + relations).",
201
206
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
202
207
  async execute(_id, params) {
@@ -213,7 +218,7 @@ export default function drawme(pi: ExtensionAPI): void {
213
218
  name: "drawio_open",
214
219
  label: "draw.io: open",
215
220
  description:
216
- "Open a .drawio source or an exported file in the OS default application (draw.io desktop for .drawio) so the user can fine-tune it. Local action, no network.",
221
+ "Open a .drawio source or an exported file in the OS default application (draw.io desktop for .drawio) so the user can fine-tune it.",
217
222
  promptSnippet: "Open a .drawio or exported file in the desktop app.",
218
223
  parameters: Type.Object({ path: Type.String({ description: "File to open" }) }),
219
224
  async execute(_id, params) {
package/src/png.ts CHANGED
@@ -4,11 +4,10 @@
4
4
  * draw.io's CLI emits `-e` (embedded-XML) PNGs with the 4-byte IEND length
5
5
  * field present but the trailing 8 bytes of "IEND" type + CRC missing, so strict
6
6
  * PNG decoders and vision APIs reject the file (draw.io-desktop issue #8).
7
- * SVG/PDF are unaffected. Ported 1:1 from the skill's `scripts/repair_png.py`.
7
+ * SVG/PDF are unaffected.
8
8
  *
9
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. Local-only, no
11
- * network.
10
+ * is safe to run unconditionally after every `-e` PNG export.
12
11
  */
13
12
  import { readFile, writeFile } from "node:fs/promises";
14
13
 
@@ -1,13 +1,11 @@
1
1
  /**
2
- * Search 10k+ official draw.io shapes for their exact `style=` strings — a
3
- * pure-TypeScript port of the skill's `scripts/shapesearch.py`, over the bundled
4
- * `assets/data/shape-index.json.gz` (upstream draw.io shape data; see the notice
5
- * beside it). Resolves a keyword query (e.g. "aws lambda", "uml actor") to the
6
- * real palette style so a diagram uses the official shape instead of a guess.
7
- * Local-only, no network.
2
+ * Search 10k+ official draw.io shapes for their exact `style=` strings using the
3
+ * bundled `assets/data/shape-index.json.gz` file (upstream draw.io shape data;
4
+ * see the notice beside it). Resolves a keyword query such as "aws lambda" or
5
+ * "uml actor" to the real palette style instead of a guess.
8
6
  *
9
- * Algorithm mirrors upstream (tag map with exact + Soundex matching, strict AND
10
- * first, scored OR fallback) plus the skill's verbatim-title tiebreaker.
7
+ * Uses a tag map with exact + Soundex matching, strict AND first, a scored OR
8
+ * fallback, and a verbatim-title tiebreaker.
11
9
  */
12
10
  import { readFileSync } from "node:fs";
13
11
  import { gunzipSync } from "node:zlib";
package/src/validate.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  /**
2
- * Deterministic structural linter for `.drawio` files — a pure-TypeScript port of
3
- * the skill's `scripts/validate.py`. Catches the class of mistakes a vision
2
+ * Deterministic structural linter for `.drawio` files. Catches mistakes a vision
4
3
  * self-check is slow and unreliable at: dangling edge endpoints, duplicate or
5
4
  * reserved ids, broken parent references, and (as warnings) off-grid geometry,
6
5
  * overlapping sibling nodes, and edge-routing defects. Runs without launching
7
- * draw.io. Local-only, no network.
6
+ * draw.io.
8
7
  */
9
8
  import { readFile } from "node:fs/promises";
10
9
  import { DOMParser } from "@xmldom/xmldom";
@@ -34,7 +33,7 @@ function pyFloat(s: string): number | undefined {
34
33
  return Number.isNaN(n) ? undefined : n;
35
34
  }
36
35
 
37
- /** Python `repr()` of an optional attribute, for message parity with validate.py. */
36
+ /** Quote an optional attribute consistently in diagnostic messages. */
38
37
  function repr(s: string | null): string {
39
38
  return s === null ? "None" : `'${s}'`;
40
39
  }
package/src/workflow.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * Builds the message the `/drawme` command injects to drive the diagram
3
- * workflow. It steers the model through the skill's author→validate→preview→
4
- * self-check→final loop while pointing it at the DrawMe tools and the bundled,
5
- * network-free authoring references.
3
+ * workflow. It steers the model through the author→validate→preview→self-check→
4
+ * final loop while pointing it at the DrawMe tools and bundled references.
6
5
  */
7
6
  export function drawmeWorkflow(description: string, refDir: string, agentReferencePath: string): string {
8
7
  const quoted = description.replaceAll("\n", "\n> ");
@@ -17,7 +16,7 @@ export function drawmeWorkflow(description: string, refDir: string, agentReferen
17
16
  agentReferencePath +
18
17
  "`, the official DrawMe extension reference for agent behavior, tool options, decision rules, and limitations.",
19
18
  "",
20
- "Produce a `.drawio` file and export it, following the workflow below. For anything that touches the draw.io CLI, use the DrawMe tools — do NOT shell out to `drawio` yourself. Everything runs locally; there is no network access.",
19
+ "Produce a `.drawio` file and export it, following the workflow below. For anything that touches the draw.io CLI, use the DrawMe tools — do NOT shell out to `drawio` yourself.",
21
20
  "",
22
21
  "1. **Check** — call `drawio_check` once (note the version: v30+ unlocks Mermaid conversion and the auto-layout pass). If the CLI is unavailable, still author the `.drawio` XML, tell the user how to install draw.io / open the file, and skip the export + self-check steps.",
23
22
  "2. **Plan** — choose the diagram type, shapes, relationships, and layout direction (LR or TB). For a specific type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart, SysML, BPMN, network, swimlane), read `" +
@@ -33,6 +32,6 @@ export function drawmeWorkflow(description: string, refDir: string, agentReferen
33
32
  refDir +
34
33
  "/troubleshooting.md`.",
35
34
  "6. **Review** — show the PNG to the user, apply targeted XML edits from their feedback, and re-preview until they approve.",
36
- "7. **Final export** — call `drawio_export` with `mode: \"final\"` for each requested format (default PNG; SVG/PDF/JPG on request). Report the `.drawio` source path and every exported file path, and offer to open the source in the desktop app with `drawio_open` for fine-tuning.",
35
+ "7. **Final export** — call `drawio_export` with `mode: \"final\"` for each requested format (default PNG; SVG/PDF/JPG on request). The first successful final export automatically removes preview artifacts created for the same source; do not delete them yourself or report them as retained outputs. Report the `.drawio` source path and every final exported file path, and offer to open the source in the desktop app with `drawio_open` for fine-tuning.",
37
36
  ].join("\n");
38
37
  }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2023"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "noEmit": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "resolveJsonModule": true,
13
+ "verbatimModuleSyntax": true,
14
+ "forceConsistentCasingInFileNames": true
15
+ },
16
+ "include": ["src", "tests"]
17
+ }