@senad-d/drawme 0.1.3 → 0.1.5
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/CHANGELOG.md +39 -2
- package/README.md +34 -23
- package/assets/references/troubleshooting.md +3 -3
- package/assets/references/xml-authoring.md +21 -1
- package/docs/{agent-guide.md → reference.md} +66 -140
- package/docs/visual-review-implementation-tasks.md +271 -0
- package/example/drawme-extension-waterfall-overview.drawio +72 -0
- package/example/drawme-how-it-works.drawio +127 -77
- package/example/drawme-installation-guide.drawio +98 -64
- package/package.json +1 -1
- package/src/drawio.ts +67 -15
- package/src/fitcanvas.ts +172 -0
- package/src/geometry.ts +259 -0
- package/src/index.ts +107 -15
- package/src/validate.ts +405 -223
- package/src/workflow.ts +86 -21
package/src/geometry.ts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared `.drawio` geometry: cell collection, absolute rectangles, explicit
|
|
3
|
+
* edge routes, and visible content bounds. Used by the structural validator
|
|
4
|
+
* and the canvas-fit tool so both agree on what "content" means.
|
|
5
|
+
*/
|
|
6
|
+
import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
|
|
7
|
+
|
|
8
|
+
/** [x, y, width, height]. width/height may be NaN when the source omits them. */
|
|
9
|
+
export type Rect = [number, number, number, number];
|
|
10
|
+
export type Point = [number, number];
|
|
11
|
+
export type ById = Map<string, DomEl>;
|
|
12
|
+
|
|
13
|
+
export interface ContentBounds {
|
|
14
|
+
minX: number;
|
|
15
|
+
minY: number;
|
|
16
|
+
maxX: number;
|
|
17
|
+
maxY: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Python `float()` semantics: accepts nan/inf, strict-numeric otherwise; else undefined (≈ ValueError). */
|
|
21
|
+
export function pyFloat(s: string): number | undefined {
|
|
22
|
+
const t = s.trim().toLowerCase();
|
|
23
|
+
if (t === "nan" || t === "+nan" || t === "-nan") return Number.NaN;
|
|
24
|
+
if (t === "inf" || t === "+inf" || t === "infinity" || t === "+infinity") return Infinity;
|
|
25
|
+
if (t === "-inf" || t === "-infinity") return -Infinity;
|
|
26
|
+
if (!/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(t)) return undefined;
|
|
27
|
+
const n = Number(t);
|
|
28
|
+
return Number.isNaN(n) ? undefined : n;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function hasInvalidNumber(values: number[]): boolean {
|
|
32
|
+
return values.some((value) => !Number.isFinite(value));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function rect(cell: DomEl): Rect | null {
|
|
36
|
+
const gy = firstByTag(cell, "mxGeometry");
|
|
37
|
+
if (!gy) return null;
|
|
38
|
+
const x = pyFloat(attr(gy, "x") ?? "0");
|
|
39
|
+
const y = pyFloat(attr(gy, "y") ?? "0");
|
|
40
|
+
const w = pyFloat(attr(gy, "width") ?? "nan");
|
|
41
|
+
const h = pyFloat(attr(gy, "height") ?? "nan");
|
|
42
|
+
if (x === undefined || y === undefined || w === undefined || h === undefined) return null;
|
|
43
|
+
return [x, y, w, h];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function geometryIsRelative(cell: DomEl): boolean {
|
|
47
|
+
return firstByTag(cell, "mxGeometry")?.getAttribute("relative") === "1";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** True for separate edge-label vertices. */
|
|
51
|
+
export function isEdgeLabel(cell: DomEl): boolean {
|
|
52
|
+
return (attr(cell, "style") ?? "").includes("edgeLabel");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function isVisible(cell: DomEl, byId: ById): boolean {
|
|
56
|
+
let current: DomEl | undefined = cell;
|
|
57
|
+
const seen = new Set<string>();
|
|
58
|
+
while (current) {
|
|
59
|
+
if (attr(current, "visible") === "0") return false;
|
|
60
|
+
const parent = attr(current, "parent");
|
|
61
|
+
if (!parent || seen.has(parent)) break;
|
|
62
|
+
seen.add(parent);
|
|
63
|
+
current = byId.get(parent);
|
|
64
|
+
}
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function styleNum(style: string | null, key: string): number | undefined {
|
|
69
|
+
for (const part of (style ?? "").split(";")) {
|
|
70
|
+
if (part.startsWith(key + "=")) return pyFloat(part.split("=").slice(1).join("="));
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Absolute (x, y, w, h) of a non-relative vertex, summing parent-container offsets. */
|
|
76
|
+
export function absRect(cell: DomEl, byId: ById): Rect | null {
|
|
77
|
+
const r = rect(cell);
|
|
78
|
+
if (r === null || hasInvalidNumber(r)) return null;
|
|
79
|
+
let [x, y] = r;
|
|
80
|
+
const [, , w, h] = r;
|
|
81
|
+
let parent = attr(cell, "parent");
|
|
82
|
+
const seen = new Set<string>();
|
|
83
|
+
while (parent && byId.has(parent) && !seen.has(parent)) {
|
|
84
|
+
seen.add(parent);
|
|
85
|
+
const p = byId.get(parent)!;
|
|
86
|
+
if (p.getAttribute("vertex") === "1" && !geometryIsRelative(p)) {
|
|
87
|
+
const pr = rect(p);
|
|
88
|
+
if (pr && !hasInvalidNumber(pr)) {
|
|
89
|
+
x += pr[0];
|
|
90
|
+
y += pr[1];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
parent = attr(p, "parent");
|
|
94
|
+
}
|
|
95
|
+
return [x, y, w, h];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Absolute point where `edge` meets its source/target vertex (honours exit/entry). */
|
|
99
|
+
export function endpoint(edge: DomEl, end: "source" | "target", byId: ById): Point | null {
|
|
100
|
+
const vid = attr(edge, end);
|
|
101
|
+
if (!vid || !byId.has(vid)) return null;
|
|
102
|
+
const box = absRect(byId.get(vid)!, byId);
|
|
103
|
+
if (box === null) return null;
|
|
104
|
+
const [x, y, w, h] = box;
|
|
105
|
+
const style = attr(edge, "style") ?? "";
|
|
106
|
+
const fx = styleNum(style, end === "source" ? "exitX" : "entryX");
|
|
107
|
+
const fy = styleNum(style, end === "source" ? "exitY" : "entryY");
|
|
108
|
+
return [x + (fx ?? 0.5) * w, y + (fy ?? 0.5) * h];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function edgeWaypoints(edge: DomEl): Point[] {
|
|
112
|
+
const gy = firstByTag(edge, "mxGeometry");
|
|
113
|
+
if (!gy) return [];
|
|
114
|
+
const arr = firstByTag(gy, "Array");
|
|
115
|
+
if (!arr) return [];
|
|
116
|
+
const points: Point[] = [];
|
|
117
|
+
for (const point of childrenByTag(arr, "mxPoint")) {
|
|
118
|
+
const x = pyFloat(attr(point, "x") ?? "");
|
|
119
|
+
const y = pyFloat(attr(point, "y") ?? "");
|
|
120
|
+
if (x !== undefined && y !== undefined && Number.isFinite(x) && Number.isFinite(y)) points.push([x, y]);
|
|
121
|
+
}
|
|
122
|
+
return points;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. */
|
|
126
|
+
export function edgeRoute(edge: DomEl, byId: ById): Point[] | null {
|
|
127
|
+
const waypoints = edgeWaypoints(edge);
|
|
128
|
+
if (waypoints.length === 0) return null;
|
|
129
|
+
const source = endpoint(edge, "source", byId);
|
|
130
|
+
const target = endpoint(edge, "target", byId);
|
|
131
|
+
if (source === null || target === null) return null;
|
|
132
|
+
return [source, ...waypoints, target];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function routeMidpoint(points: Point[]): Point {
|
|
136
|
+
const lengths: number[] = [];
|
|
137
|
+
let total = 0;
|
|
138
|
+
for (let i = 0; i < points.length - 1; i++) {
|
|
139
|
+
const length = Math.hypot(points[i + 1][0] - points[i][0], points[i + 1][1] - points[i][1]);
|
|
140
|
+
lengths.push(length);
|
|
141
|
+
total += length;
|
|
142
|
+
}
|
|
143
|
+
let remaining = total / 2;
|
|
144
|
+
for (let i = 0; i < lengths.length; i++) {
|
|
145
|
+
if (remaining <= lengths[i]) {
|
|
146
|
+
const fraction = lengths[i] === 0 ? 0 : remaining / lengths[i];
|
|
147
|
+
return [
|
|
148
|
+
points[i][0] + fraction * (points[i + 1][0] - points[i][0]),
|
|
149
|
+
points[i][1] + fraction * (points[i + 1][1] - points[i][1]),
|
|
150
|
+
];
|
|
151
|
+
}
|
|
152
|
+
remaining -= lengths[i];
|
|
153
|
+
}
|
|
154
|
+
return points.at(-1) ?? [0, 0];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Conservative box for a separately sized label on an explicitly routed edge. */
|
|
158
|
+
export function explicitEdgeLabelRect(cell: DomEl, byId: ById): Rect | null {
|
|
159
|
+
if (!isEdgeLabel(cell)) return null;
|
|
160
|
+
const local = rect(cell);
|
|
161
|
+
const parent = attr(cell, "parent");
|
|
162
|
+
const edge = parent ? byId.get(parent) : undefined;
|
|
163
|
+
if (!local || hasInvalidNumber(local) || edge?.getAttribute("edge") !== "1") return null;
|
|
164
|
+
const route = edgeRoute(edge, byId);
|
|
165
|
+
if (!route) return null;
|
|
166
|
+
const [midX, midY] = routeMidpoint(route);
|
|
167
|
+
const geometry = firstByTag(cell, "mxGeometry");
|
|
168
|
+
const offset = geometry
|
|
169
|
+
? childrenByTag(geometry, "mxPoint").find((point) => attr(point, "as") === "offset")
|
|
170
|
+
: undefined;
|
|
171
|
+
const offsetX = offset ? pyFloat(attr(offset, "x") ?? "0") : 0;
|
|
172
|
+
const offsetY = offset ? pyFloat(attr(offset, "y") ?? "0") : 0;
|
|
173
|
+
if (offsetX === undefined || offsetY === undefined || !Number.isFinite(offsetX) || !Number.isFinite(offsetY)) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
return [midX + offsetX - local[2] / 2, midY + offsetY - local[3] / 2, local[2], local[3]];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Fold UserObject/object wrappers into their inner mxCell so wrapper ids resolve. */
|
|
180
|
+
export function collectCells(root: DomEl | null): DomEl[] {
|
|
181
|
+
const cells: DomEl[] = [];
|
|
182
|
+
for (const child of root ? elemChildren(root) : []) {
|
|
183
|
+
if (child.tagName === "mxCell") cells.push(child);
|
|
184
|
+
else if (child.tagName === "UserObject" || child.tagName === "object") {
|
|
185
|
+
const inner = firstByTag(child, "mxCell");
|
|
186
|
+
if (inner) {
|
|
187
|
+
inner.setAttribute("id", attr(child, "id") ?? "");
|
|
188
|
+
cells.push(inner);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return cells;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Non-mutating variant of collectCells for callers that serialize the DOM
|
|
197
|
+
* afterwards: wrapper ids resolve through the returned map instead of being
|
|
198
|
+
* written onto the inner mxCell.
|
|
199
|
+
*/
|
|
200
|
+
export function collectCellsWithIds(root: DomEl | null): { cells: DomEl[]; ids: ById } {
|
|
201
|
+
const cells: DomEl[] = [];
|
|
202
|
+
const ids: ById = new Map();
|
|
203
|
+
for (const child of root ? elemChildren(root) : []) {
|
|
204
|
+
let cell: DomEl | null = null;
|
|
205
|
+
let id: string | null = null;
|
|
206
|
+
if (child.tagName === "mxCell") {
|
|
207
|
+
cell = child;
|
|
208
|
+
id = attr(child, "id");
|
|
209
|
+
} else if (child.tagName === "UserObject" || child.tagName === "object") {
|
|
210
|
+
const inner = firstByTag(child, "mxCell");
|
|
211
|
+
if (inner) {
|
|
212
|
+
cell = inner;
|
|
213
|
+
id = attr(child, "id");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (cell) {
|
|
217
|
+
cells.push(cell);
|
|
218
|
+
ids.set(id ?? "", cell);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { cells, ids };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function addRectToBounds(bounds: ContentBounds | null, box: Rect): ContentBounds {
|
|
225
|
+
const [x, y, width, height] = box;
|
|
226
|
+
const next = bounds ?? { minX: x, minY: y, maxX: x + width, maxY: y + height };
|
|
227
|
+
next.minX = Math.min(next.minX, x);
|
|
228
|
+
next.minY = Math.min(next.minY, y);
|
|
229
|
+
next.maxX = Math.max(next.maxX, x + width);
|
|
230
|
+
next.maxY = Math.max(next.maxY, y + height);
|
|
231
|
+
return next;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function addPointToBounds(bounds: ContentBounds | null, point: Point): ContentBounds {
|
|
235
|
+
return addRectToBounds(bounds, [point[0], point[1], 0, 0]);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function contentRect(cell: DomEl, ids: ById): Rect | null {
|
|
239
|
+
if (cell.getAttribute("vertex") !== "1") return null;
|
|
240
|
+
if (isEdgeLabel(cell)) return explicitEdgeLabelRect(cell, ids);
|
|
241
|
+
if (geometryIsRelative(cell)) return null;
|
|
242
|
+
return absRect(cell, ids);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function contentWaypoints(cell: DomEl): Point[] {
|
|
246
|
+
return cell.getAttribute("edge") === "1" ? edgeWaypoints(cell) : [];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Visible vertices/containers, practical edge-label boxes, and explicit waypoints. */
|
|
250
|
+
export function contentBounds(cells: DomEl[], ids: ById): ContentBounds | null {
|
|
251
|
+
let bounds: ContentBounds | null = null;
|
|
252
|
+
for (const cell of cells) {
|
|
253
|
+
if (!isVisible(cell, ids)) continue;
|
|
254
|
+
const box = contentRect(cell, ids);
|
|
255
|
+
if (box && !hasInvalidNumber(box)) bounds = addRectToBounds(bounds, box);
|
|
256
|
+
for (const point of contentWaypoints(cell)) bounds = addPointToBounds(bounds, point);
|
|
257
|
+
}
|
|
258
|
+
return bounds;
|
|
259
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -4,14 +4,16 @@
|
|
|
4
4
|
* CLI. It exposes the authoring workflow as plain commands and model-callable
|
|
5
5
|
* tools.
|
|
6
6
|
*
|
|
7
|
-
* Tools: drawio_check · drawio_export · drawio_validate ·
|
|
8
|
-
*
|
|
7
|
+
* Tools: drawio_check · drawio_export · drawio_validate · drawio_fit_canvas
|
|
8
|
+
* drawio_from_mermaid · drawio_layout · drawio_shapesearch
|
|
9
|
+
* drawio_explain · drawio_open
|
|
9
10
|
* Commands: /drawme · /drawme-check · /drawme-export
|
|
10
11
|
*/
|
|
11
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
12
13
|
import { Type, type Static } from "typebox";
|
|
13
14
|
import { fileURLToPath } from "node:url";
|
|
14
15
|
import { dirname, resolve } from "node:path";
|
|
16
|
+
import { readFile } from "node:fs/promises";
|
|
15
17
|
import {
|
|
16
18
|
applyLayout,
|
|
17
19
|
convertMermaid,
|
|
@@ -23,13 +25,13 @@ import {
|
|
|
23
25
|
type LayoutPreset,
|
|
24
26
|
} from "./drawio";
|
|
25
27
|
import { validateFile } from "./validate";
|
|
28
|
+
import { fitCanvasFile } from "./fitcanvas";
|
|
26
29
|
import { searchShapes } from "./shapesearch";
|
|
27
30
|
import { explainFile } from "./explain";
|
|
28
31
|
import { drawmeWorkflow } from "./workflow";
|
|
29
32
|
|
|
30
33
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
31
34
|
const REF_DIR = resolve(HERE, "..", "assets", "references");
|
|
32
|
-
const AGENT_REFERENCE_PATH = resolve(HERE, "..", "docs", "agent-guide.md");
|
|
33
35
|
|
|
34
36
|
const FORMAT = Type.Union([Type.Literal("png"), Type.Literal("svg"), Type.Literal("pdf"), Type.Literal("jpg")]);
|
|
35
37
|
const MODE = Type.Union([Type.Literal("preview"), Type.Literal("final")]);
|
|
@@ -53,6 +55,28 @@ export type DrawioExportInput = Static<typeof exportParams>;
|
|
|
53
55
|
|
|
54
56
|
const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
|
|
55
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Whether the active model accepts image blocks. Unknown models fail open
|
|
60
|
+
* (attach the image) like Pi's built-in read tool; the provider layer replaces
|
|
61
|
+
* unsupported images with a text placeholder, so failing open is always safe.
|
|
62
|
+
*/
|
|
63
|
+
function modelSupportsImages(ctx: ExtensionContext | undefined): boolean {
|
|
64
|
+
return ctx?.model?.input.includes("image") ?? true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function exportResult(text: string, result: Awaited<ReturnType<typeof exportDiagram>>, attachImage: boolean) {
|
|
68
|
+
const content: (
|
|
69
|
+
| { type: "text"; text: string }
|
|
70
|
+
| { type: "image"; data: string; mimeType: "image/png" }
|
|
71
|
+
)[] = [{ type: "text", text }];
|
|
72
|
+
const imageAttached = result.mode === "preview" && result.format === "png" && attachImage;
|
|
73
|
+
if (imageAttached) {
|
|
74
|
+
const png = await readFile(result.output);
|
|
75
|
+
content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
|
|
76
|
+
}
|
|
77
|
+
return { content, details: { ...result, imageAttached } };
|
|
78
|
+
}
|
|
79
|
+
|
|
56
80
|
export default function drawme(pi: ExtensionAPI): void {
|
|
57
81
|
pi.registerTool({
|
|
58
82
|
name: "drawio_check",
|
|
@@ -82,13 +106,14 @@ export default function drawme(pi: ExtensionAPI): void {
|
|
|
82
106
|
name: "drawio_export",
|
|
83
107
|
label: "draw.io: export",
|
|
84
108
|
description:
|
|
85
|
-
"Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI.
|
|
109
|
+
"Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. A successful mode:'preview' PNG is clean, width-capped, and never embedded; when the current model can view images it is attached to the tool result for visual review, and the result text always states whether it was attached. 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
110
|
promptSnippet:
|
|
87
|
-
"Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview'
|
|
111
|
+
"Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' attaches the review image when the current model can view images — the result text says so — and removes the previous preview file; mode:'final' creates the deliverable and cleans the remaining preview).",
|
|
88
112
|
parameters: exportParams,
|
|
89
|
-
async execute(_id, params) {
|
|
113
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
90
114
|
try {
|
|
91
115
|
const r = await exportDiagram(params as ExportOptions);
|
|
116
|
+
const canView = modelSupportsImages(ctx);
|
|
92
117
|
const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed}`];
|
|
93
118
|
if (r.repaired) lines.push("(repaired truncated -e PNG IEND chunk)");
|
|
94
119
|
if (r.removedPreviews.length > 0) lines.push(`Removed preview artifact(s): ${r.removedPreviews.join(", ")}`);
|
|
@@ -97,7 +122,14 @@ export default function drawme(pi: ExtensionAPI): void {
|
|
|
97
122
|
}
|
|
98
123
|
const versionSuffix = r.version ? ` (${r.version})` : "";
|
|
99
124
|
lines.push(`binary=${r.binary}${versionSuffix}`);
|
|
100
|
-
|
|
125
|
+
if (r.mode === "preview" && r.format === "png") {
|
|
126
|
+
lines.push(
|
|
127
|
+
canView
|
|
128
|
+
? "Preview image attached below. Critique it category by category before editing the source."
|
|
129
|
+
: "Preview image NOT attached: the current model cannot view images. Do not describe or judge the render; review structurally with drawio_validate and drawio_explain, and share the exported path so the user can view it.",
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
return exportResult(lines.join("\n"), r, canView);
|
|
101
133
|
} catch (e) {
|
|
102
134
|
return textResult(`Export failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
103
135
|
}
|
|
@@ -108,20 +140,66 @@ export default function drawme(pi: ExtensionAPI): void {
|
|
|
108
140
|
name: "drawio_validate",
|
|
109
141
|
label: "draw.io: validate",
|
|
110
142
|
description:
|
|
111
|
-
"Structurally lint a .drawio file: errors for dangling
|
|
112
|
-
promptSnippet: "Lint a .drawio
|
|
143
|
+
"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. Compressed pages cannot be linted and are reported as skipped. Fix boundary/margin/empty-space warnings (and make room for overlapping elements) by spreading elements and running drawio_fit_canvas — never by shrinking content. Run after every source edit and before exporting.",
|
|
144
|
+
promptSnippet: "Lint a .drawio after every source edit and before exporting.",
|
|
113
145
|
parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
|
|
114
146
|
async execute(_id, params) {
|
|
115
147
|
const r = await validateFile(params.input);
|
|
116
148
|
const lines = [
|
|
117
|
-
|
|
118
|
-
...r.errors.map((
|
|
119
|
-
|
|
149
|
+
`Errors (${r.errors.length}):`,
|
|
150
|
+
...(r.errors.length > 0 ? r.errors.map((error) => `- ${error}`) : ["- none"]),
|
|
151
|
+
`Actionable warnings (${r.warnings.length}):`,
|
|
152
|
+
...(r.warnings.length > 0 ? r.warnings.map((warning) => `- ${warning}`) : ["- none"]),
|
|
153
|
+
`Informational observations (${r.observations.length}):`,
|
|
154
|
+
...(r.observations.length > 0 ? r.observations.map((observation) => `- ${observation}`) : ["- none"]),
|
|
155
|
+
`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)`,
|
|
156
|
+
`${r.errors.length} error(s), ${r.warnings.length} unresolved warning(s)`,
|
|
120
157
|
];
|
|
121
158
|
return textResult(lines.join("\n"), r);
|
|
122
159
|
},
|
|
123
160
|
});
|
|
124
161
|
|
|
162
|
+
pi.registerTool({
|
|
163
|
+
name: "drawio_fit_canvas",
|
|
164
|
+
label: "draw.io: fit canvas",
|
|
165
|
+
description:
|
|
166
|
+
"Resize each page's canvas to fit its content: sets pageWidth/pageHeight to the content bounding box plus a margin (default 40px) and shifts content so it starts exactly at that margin. Grows cramped pages and tightens oversized ones without changing element sizes or relative positions. Use when validation reports boundary, outer-margin, or empty-space warnings, or when elements need more room — spread elements apart, then fit the canvas; never shrink or cram elements to fit a page. Deterministic, no draw.io CLI. Skips compressed pages and intentional infinite canvases (page=\"0\"). Writes in place unless `output` is given; treat the result as a source edit and validate it.",
|
|
167
|
+
promptSnippet:
|
|
168
|
+
"Fit each page's canvas to its content plus a margin (default 40px) — enlarge the page instead of cramming elements; validate after.",
|
|
169
|
+
parameters: Type.Object({
|
|
170
|
+
input: Type.String({ description: "Path to the .drawio file" }),
|
|
171
|
+
margin: Type.Optional(Type.Number({ description: "Outer margin in px between content and page edge (default 40)" })),
|
|
172
|
+
output: Type.Optional(Type.String({ description: "Output path (default: overwrite the input)" })),
|
|
173
|
+
}),
|
|
174
|
+
async execute(_id, params) {
|
|
175
|
+
try {
|
|
176
|
+
const r = await fitCanvasFile(params);
|
|
177
|
+
const lines = r.pages.map((page) => {
|
|
178
|
+
if (page.status === "skipped") return `page '${page.page}': skipped (${page.reason ?? "unknown"})`;
|
|
179
|
+
const beforeText =
|
|
180
|
+
page.before?.width !== undefined && page.before?.height !== undefined
|
|
181
|
+
? `${page.before.width}x${page.before.height}`
|
|
182
|
+
: "unset";
|
|
183
|
+
const afterText = `${page.after!.width}x${page.after!.height}`;
|
|
184
|
+
if (page.status === "unchanged") return `page '${page.page}': already fitted (${afterText})`;
|
|
185
|
+
const shiftText =
|
|
186
|
+
page.shift && (page.shift.dx !== 0 || page.shift.dy !== 0)
|
|
187
|
+
? `, content shifted by (${page.shift.dx}, ${page.shift.dy})`
|
|
188
|
+
: "";
|
|
189
|
+
return `page '${page.page}': ${beforeText} → ${afterText} (margin ${r.margin}px${shiftText})`;
|
|
190
|
+
});
|
|
191
|
+
lines.push(
|
|
192
|
+
r.changed
|
|
193
|
+
? `Wrote ${r.output}. This is a source edit: run drawio_validate next, then re-export the preview.`
|
|
194
|
+
: "No changes were needed.",
|
|
195
|
+
);
|
|
196
|
+
return textResult(lines.join("\n"), r);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
return textResult(`Fit canvas failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
|
|
125
203
|
pi.registerTool({
|
|
126
204
|
name: "drawio_from_mermaid",
|
|
127
205
|
label: "draw.io: from Mermaid",
|
|
@@ -201,7 +279,7 @@ export default function drawme(pi: ExtensionAPI): void {
|
|
|
201
279
|
name: "drawio_explain",
|
|
202
280
|
label: "draw.io: explain",
|
|
203
281
|
description:
|
|
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.",
|
|
282
|
+
"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. Compressed pages cannot be described.",
|
|
205
283
|
promptSnippet: "Describe an existing .drawio as Markdown (components + relations).",
|
|
206
284
|
parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
|
|
207
285
|
async execute(_id, params) {
|
|
@@ -239,7 +317,21 @@ export default function drawme(pi: ExtensionAPI): void {
|
|
|
239
317
|
ctx.ui.notify("Usage: /drawme <description of the diagram to create>", "info");
|
|
240
318
|
return;
|
|
241
319
|
}
|
|
242
|
-
|
|
320
|
+
const readReference = async (name: string): Promise<string | null> => {
|
|
321
|
+
try {
|
|
322
|
+
return await readFile(resolve(REF_DIR, name), "utf8");
|
|
323
|
+
} catch {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
const cli = await resolveBinary();
|
|
328
|
+
pi.sendUserMessage(
|
|
329
|
+
drawmeWorkflow(desc, REF_DIR, cli, {
|
|
330
|
+
diagramTypes: await readReference("diagram-types.md"),
|
|
331
|
+
xmlAuthoring: await readReference("xml-authoring.md"),
|
|
332
|
+
mermaidAuthoring: cli.supportsMermaid ? await readReference("mermaid-authoring.md") : null,
|
|
333
|
+
}),
|
|
334
|
+
);
|
|
243
335
|
},
|
|
244
336
|
});
|
|
245
337
|
|