@senad-d/drawme 0.1.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/LICENSE +21 -0
- package/README.md +254 -0
- package/assets/data/SHAPE-INDEX-NOTICE.md +17 -0
- package/assets/data/shape-index.json.gz +0 -0
- package/assets/references/diagram-types.md +205 -0
- package/assets/references/mermaid-authoring.md +56 -0
- package/assets/references/troubleshooting.md +63 -0
- package/assets/references/xml-authoring.md +205 -0
- package/package.json +67 -0
- package/src/dom.ts +51 -0
- package/src/drawio.ts +363 -0
- package/src/explain.ts +220 -0
- package/src/index.ts +267 -0
- package/src/png.ts +41 -0
- package/src/shapesearch.ts +217 -0
- package/src/validate.ts +376 -0
- package/src/workflow.ts +34 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DrawMe — a native Pi extension that turns natural-language descriptions into
|
|
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).
|
|
6
|
+
*
|
|
7
|
+
* Tools: drawio_check · drawio_export · drawio_validate
|
|
8
|
+
* Commands: /drawme · /drawme-check · /drawme-export
|
|
9
|
+
*/
|
|
10
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { Type, type Static } from "typebox";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { dirname, resolve } from "node:path";
|
|
14
|
+
import {
|
|
15
|
+
applyLayout,
|
|
16
|
+
convertMermaid,
|
|
17
|
+
exportDiagram,
|
|
18
|
+
openFile,
|
|
19
|
+
resolveBinary,
|
|
20
|
+
type ExportFormat,
|
|
21
|
+
type ExportOptions,
|
|
22
|
+
type LayoutPreset,
|
|
23
|
+
} from "./drawio";
|
|
24
|
+
import { validateFile } from "./validate";
|
|
25
|
+
import { searchShapes } from "./shapesearch";
|
|
26
|
+
import { explainFile } from "./explain";
|
|
27
|
+
import { drawmeWorkflow } from "./workflow";
|
|
28
|
+
|
|
29
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
const REF_DIR = resolve(HERE, "..", "assets", "references");
|
|
31
|
+
|
|
32
|
+
const FORMAT = Type.Union([Type.Literal("png"), Type.Literal("svg"), Type.Literal("pdf"), Type.Literal("jpg")]);
|
|
33
|
+
const MODE = Type.Union([Type.Literal("preview"), Type.Literal("final")]);
|
|
34
|
+
|
|
35
|
+
const exportParams = Type.Object({
|
|
36
|
+
input: Type.String({ description: "Path to the .drawio source file" }),
|
|
37
|
+
format: Type.Optional(FORMAT),
|
|
38
|
+
mode: Type.Optional(MODE),
|
|
39
|
+
output: Type.Optional(Type.String({ description: "Output path; defaults next to the input" })),
|
|
40
|
+
scale: Type.Optional(Type.Number({ description: "Raster scale for a final PNG/JPG (default 2)" })),
|
|
41
|
+
width: Type.Optional(Type.Number({ description: "Target width in px; overrides scale. Preview uses 2000" })),
|
|
42
|
+
transparent: Type.Optional(Type.Boolean({ description: "Transparent background (PNG only)" })),
|
|
43
|
+
border: Type.Optional(Type.Number({ description: "Border in px (default 10)" })),
|
|
44
|
+
pageIndex: Type.Optional(Type.Number({ description: "1-based page to export from a multi-page file" })),
|
|
45
|
+
embed: Type.Optional(
|
|
46
|
+
Type.Boolean({ description: "Embed diagram XML for an editable output. Default: on for final PNG/SVG/PDF, off for preview" }),
|
|
47
|
+
),
|
|
48
|
+
binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
|
|
49
|
+
});
|
|
50
|
+
export type DrawioExportInput = Static<typeof exportParams>;
|
|
51
|
+
|
|
52
|
+
const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
|
|
53
|
+
|
|
54
|
+
export default function drawme(pi: ExtensionAPI): void {
|
|
55
|
+
pi.registerTool({
|
|
56
|
+
name: "drawio_check",
|
|
57
|
+
label: "draw.io: check CLI",
|
|
58
|
+
description:
|
|
59
|
+
"Detect the draw.io desktop CLI: returns the binary path, version, and whether it supports Mermaid import / the --layout pass (both need v30+). Call before exporting.",
|
|
60
|
+
promptSnippet: "Check whether the draw.io CLI is available before exporting a diagram.",
|
|
61
|
+
parameters: Type.Object({ binary: Type.Optional(Type.String({ description: "Explicit binary path to test first" })) }),
|
|
62
|
+
async execute(_id, params) {
|
|
63
|
+
const info = await resolveBinary(params.binary);
|
|
64
|
+
if (!info.available) {
|
|
65
|
+
return textResult(
|
|
66
|
+
"draw.io CLI not found. Install with `brew install --cask drawio` (macOS) or from " +
|
|
67
|
+
"https://github.com/jgraph/drawio-desktop/releases. You can still author .drawio XML without it.",
|
|
68
|
+
info,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return textResult(
|
|
72
|
+
`draw.io available: ${info.binary}\nversion: ${info.version} (major ${info.major})\n` +
|
|
73
|
+
`Mermaid import / --layout: ${info.supportsMermaid ? "supported (v30+)" : "unsupported (needs v30+)"}`,
|
|
74
|
+
info,
|
|
75
|
+
);
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
pi.registerTool({
|
|
80
|
+
name: "drawio_export",
|
|
81
|
+
label: "draw.io: export",
|
|
82
|
+
description:
|
|
83
|
+
"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.",
|
|
84
|
+
promptSnippet: "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' for self-check, mode:'final' for the deliverable).",
|
|
85
|
+
parameters: exportParams,
|
|
86
|
+
async execute(_id, params) {
|
|
87
|
+
try {
|
|
88
|
+
const r = await exportDiagram(params as ExportOptions);
|
|
89
|
+
const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed}`];
|
|
90
|
+
if (r.repaired) lines.push("(repaired truncated -e PNG IEND chunk)");
|
|
91
|
+
const versionSuffix = r.version ? ` (${r.version})` : "";
|
|
92
|
+
lines.push(`binary=${r.binary}${versionSuffix}`);
|
|
93
|
+
return textResult(lines.join("\n"), r);
|
|
94
|
+
} catch (e) {
|
|
95
|
+
return textResult(`Export failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
pi.registerTool({
|
|
101
|
+
name: "drawio_validate",
|
|
102
|
+
label: "draw.io: validate",
|
|
103
|
+
description:
|
|
104
|
+
"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.",
|
|
105
|
+
promptSnippet: "Lint a .drawio for structural errors before exporting.",
|
|
106
|
+
parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
|
|
107
|
+
async execute(_id, params) {
|
|
108
|
+
const r = await validateFile(params.input);
|
|
109
|
+
const lines = [
|
|
110
|
+
...r.warnings.map((w) => `warning: ${w}`),
|
|
111
|
+
...r.errors.map((e) => `error: ${e}`),
|
|
112
|
+
`${r.errors.length} error(s), ${r.warnings.length} warning(s)`,
|
|
113
|
+
];
|
|
114
|
+
return textResult(lines.join("\n"), r);
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
pi.registerTool({
|
|
119
|
+
name: "drawio_from_mermaid",
|
|
120
|
+
label: "draw.io: from Mermaid",
|
|
121
|
+
description:
|
|
122
|
+
"Convert Mermaid text to a native .drawio (structure + automatic layout) via the CLI. Best for standard diagram types (flowchart, sequence, class, state, ER, gantt, mindmap) with no custom styling. Requires draw.io v30+ (check with drawio_check). Provide `mermaid` (inline text) or `input` (a .mmd path).",
|
|
123
|
+
promptSnippet: "Convert Mermaid text into a native .drawio with automatic layout (needs draw.io v30+).",
|
|
124
|
+
parameters: Type.Object({
|
|
125
|
+
mermaid: Type.Optional(Type.String({ description: "Inline Mermaid diagram text" })),
|
|
126
|
+
input: Type.Optional(Type.String({ description: "Path to a .mmd file (alternative to `mermaid`)" })),
|
|
127
|
+
output: Type.Optional(Type.String({ description: "Output .drawio path" })),
|
|
128
|
+
binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
|
|
129
|
+
}),
|
|
130
|
+
async execute(_id, params) {
|
|
131
|
+
try {
|
|
132
|
+
const r = await convertMermaid(params);
|
|
133
|
+
const versionSuffix = r.version ? ` (${r.version})` : "";
|
|
134
|
+
return textResult(`Converted Mermaid → ${r.output}\nbinary=${r.binary}${versionSuffix}`, r);
|
|
135
|
+
} catch (e) {
|
|
136
|
+
return textResult(`Mermaid conversion failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
pi.registerTool({
|
|
142
|
+
name: "drawio_layout",
|
|
143
|
+
label: "draw.io: auto-layout",
|
|
144
|
+
description:
|
|
145
|
+
"Re-place nodes and route edges in a .drawio using an ELK layout preset via the CLI — for large or graph-heavy diagrams you don't want to hand-place. Requires draw.io v30+. Writes a sibling <name>.layout.drawio by default (pass `output` to overwrite the input).",
|
|
146
|
+
promptSnippet: "Auto-lay-out a large .drawio with an ELK preset (needs draw.io v30+).",
|
|
147
|
+
parameters: Type.Object({
|
|
148
|
+
input: Type.String({ description: "Path to the .drawio file" }),
|
|
149
|
+
preset: Type.Union([
|
|
150
|
+
Type.Literal("verticalFlow"),
|
|
151
|
+
Type.Literal("horizontalFlow"),
|
|
152
|
+
Type.Literal("verticalTree"),
|
|
153
|
+
Type.Literal("horizontalTree"),
|
|
154
|
+
Type.Literal("radialTree"),
|
|
155
|
+
Type.Literal("organic"),
|
|
156
|
+
]),
|
|
157
|
+
output: Type.Optional(Type.String({ description: "Output path (default: sibling .layout.drawio)" })),
|
|
158
|
+
binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
|
|
159
|
+
}),
|
|
160
|
+
async execute(_id, params) {
|
|
161
|
+
try {
|
|
162
|
+
const r = await applyLayout({
|
|
163
|
+
input: params.input,
|
|
164
|
+
preset: params.preset as LayoutPreset,
|
|
165
|
+
output: params.output,
|
|
166
|
+
binary: params.binary,
|
|
167
|
+
});
|
|
168
|
+
return textResult(`Laid out (${r.preset}) → ${r.output}`, r);
|
|
169
|
+
} catch (e) {
|
|
170
|
+
return textResult(`Layout failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
pi.registerTool({
|
|
176
|
+
name: "drawio_shapesearch",
|
|
177
|
+
label: "draw.io: shape search",
|
|
178
|
+
description:
|
|
179
|
+
"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.",
|
|
180
|
+
promptSnippet: "Look up the exact official style= string for a draw.io shape by keyword.",
|
|
181
|
+
parameters: Type.Object({
|
|
182
|
+
query: Type.String({ description: "Keywords, e.g. 'aws lambda' or 'uml actor'" }),
|
|
183
|
+
limit: Type.Optional(Type.Number({ description: "Max results (default 10)" })),
|
|
184
|
+
}),
|
|
185
|
+
async execute(_id, params) {
|
|
186
|
+
const matches = searchShapes(params.query, params.limit ?? 10);
|
|
187
|
+
if (matches.length === 0) return textResult(`No shapes matched "${params.query}".`, { matches });
|
|
188
|
+
const lines = matches.map((m) => `${m.title} (${m.w}x${m.h})\n ${m.style}`);
|
|
189
|
+
return textResult(lines.join("\n"), { matches });
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
pi.registerTool({
|
|
194
|
+
name: "drawio_explain",
|
|
195
|
+
label: "draw.io: explain",
|
|
196
|
+
description:
|
|
197
|
+
"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.",
|
|
198
|
+
promptSnippet: "Describe an existing .drawio as Markdown (components + relations).",
|
|
199
|
+
parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
|
|
200
|
+
async execute(_id, params) {
|
|
201
|
+
try {
|
|
202
|
+
const md = await explainFile(params.input);
|
|
203
|
+
return textResult(md, { markdown: md });
|
|
204
|
+
} catch (e) {
|
|
205
|
+
return textResult(`Explain failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
pi.registerTool({
|
|
211
|
+
name: "drawio_open",
|
|
212
|
+
label: "draw.io: open",
|
|
213
|
+
description:
|
|
214
|
+
"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.",
|
|
215
|
+
promptSnippet: "Open a .drawio or exported file in the desktop app.",
|
|
216
|
+
parameters: Type.Object({ path: Type.String({ description: "File to open" }) }),
|
|
217
|
+
async execute(_id, params) {
|
|
218
|
+
try {
|
|
219
|
+
const r = await openFile(params.path);
|
|
220
|
+
return textResult(`Opened ${params.path} (${r.opener})`, r);
|
|
221
|
+
} catch (e) {
|
|
222
|
+
return textResult(`Open failed: ${(e as Error).message}`, { error: (e as Error).message });
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
pi.registerCommand("drawme", {
|
|
228
|
+
description: "Generate a .drawio diagram from a natural-language description",
|
|
229
|
+
handler: async (args, ctx) => {
|
|
230
|
+
const desc = args.trim();
|
|
231
|
+
if (!desc) {
|
|
232
|
+
ctx.ui.notify("Usage: /drawme <description of the diagram to create>", "info");
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
pi.sendUserMessage(drawmeWorkflow(desc, REF_DIR));
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
pi.registerCommand("drawme-check", {
|
|
240
|
+
description: "Check whether the draw.io CLI is available",
|
|
241
|
+
handler: async (_args, ctx) => {
|
|
242
|
+
const info = await resolveBinary();
|
|
243
|
+
ctx.ui.notify(
|
|
244
|
+
info.available ? `draw.io ${info.version} — ${info.binary}` : "draw.io CLI not found (macOS: brew install --cask drawio)",
|
|
245
|
+
info.available ? "info" : "error",
|
|
246
|
+
);
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
pi.registerCommand("drawme-export", {
|
|
251
|
+
description: "Export a .drawio file: /drawme-export <file> [png|svg|pdf|jpg]",
|
|
252
|
+
handler: async (args, ctx) => {
|
|
253
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
254
|
+
if (parts.length === 0) {
|
|
255
|
+
ctx.ui.notify("Usage: /drawme-export <file> [png|svg|pdf|jpg]", "info");
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const [input, format = "png"] = parts;
|
|
259
|
+
try {
|
|
260
|
+
const r = await exportDiagram({ input, format: format as ExportFormat, mode: "final" });
|
|
261
|
+
ctx.ui.notify(`Exported ${r.output}${r.repaired ? " (repaired PNG)" : ""}`, "info");
|
|
262
|
+
} catch (e) {
|
|
263
|
+
ctx.ui.notify(`Export failed: ${(e as Error).message}`, "error");
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
});
|
|
267
|
+
}
|
package/src/png.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
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. Ported 1:1 from the skill's `scripts/repair_png.py`.
|
|
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. Local-only, no
|
|
11
|
+
* network.
|
|
12
|
+
*/
|
|
13
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
14
|
+
|
|
15
|
+
/** A complete, valid IEND chunk: length(0) + "IEND" + CRC 0xAE426082. */
|
|
16
|
+
const IEND = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]);
|
|
17
|
+
/** The bare 4-byte length field draw.io leaves behind when it truncates. */
|
|
18
|
+
const LEN_FIELD = Buffer.from([0x00, 0x00, 0x00, 0x00]);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Return a repaired copy of `data`, or `null` if it already ends with a valid
|
|
22
|
+
* IEND chunk (no change needed). Pure — no filesystem access, for easy testing.
|
|
23
|
+
*/
|
|
24
|
+
export function repairPngBuffer(data: Buffer): Buffer | null {
|
|
25
|
+
if (data.length >= IEND.length && data.subarray(data.length - IEND.length).equals(IEND)) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const body =
|
|
29
|
+
data.length >= LEN_FIELD.length && data.subarray(data.length - LEN_FIELD.length).equals(LEN_FIELD)
|
|
30
|
+
? data.subarray(0, data.length - LEN_FIELD.length)
|
|
31
|
+
: data;
|
|
32
|
+
return Buffer.concat([body, IEND]);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Repair the PNG at `path` in place. Returns true if the file was changed. */
|
|
36
|
+
export async function repairPng(path: string): Promise<boolean> {
|
|
37
|
+
const fixed = repairPngBuffer(await readFile(path));
|
|
38
|
+
if (!fixed) return false;
|
|
39
|
+
await writeFile(path, fixed);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
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.
|
|
8
|
+
*
|
|
9
|
+
* Algorithm mirrors upstream (tag map with exact + Soundex matching, strict AND
|
|
10
|
+
* first, scored OR fallback) plus the skill's verbatim-title tiebreaker.
|
|
11
|
+
*/
|
|
12
|
+
import { readFileSync } from "node:fs";
|
|
13
|
+
import { gunzipSync } from "node:zlib";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
import { dirname, resolve } from "node:path";
|
|
16
|
+
|
|
17
|
+
export interface Shape {
|
|
18
|
+
style: string;
|
|
19
|
+
w: number;
|
|
20
|
+
h: number;
|
|
21
|
+
title: string;
|
|
22
|
+
tags?: string;
|
|
23
|
+
type?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface ShapeMatch {
|
|
26
|
+
style: string;
|
|
27
|
+
w: number;
|
|
28
|
+
h: number;
|
|
29
|
+
title: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const SOUNDEX_MAP = "01230120022455012603010202"; // A..Z digit codes
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Strip a trailing run of dots followed by digits before Soundex (e.g. "s3" → "s",
|
|
36
|
+
* "ec2" → "ec"). Equivalent to the old /\.*\d*$/ but linear (no backtracking).
|
|
37
|
+
*/
|
|
38
|
+
function stripTrail(name: string): string {
|
|
39
|
+
let end = name.length;
|
|
40
|
+
while (end > 0 && name[end - 1] >= "0" && name[end - 1] <= "9") end--;
|
|
41
|
+
while (end > 0 && name[end - 1] === ".") end--;
|
|
42
|
+
return name.slice(0, end);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function soundex(name: string): string {
|
|
46
|
+
if (!name) return "";
|
|
47
|
+
const s: string[] = [name[0].toUpperCase()];
|
|
48
|
+
for (const ch of name.slice(1)) {
|
|
49
|
+
const c = (ch.toUpperCase().codePointAt(0) ?? 0) - 65;
|
|
50
|
+
if (c >= 0 && c <= 25 && SOUNDEX_MAP[c] !== "0") {
|
|
51
|
+
const code = SOUNDEX_MAP[c];
|
|
52
|
+
if (code !== s.at(-1)) {
|
|
53
|
+
s.push(code);
|
|
54
|
+
if (s.length > 4) break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
while (s.length < 4) s.push("0");
|
|
59
|
+
return s.slice(0, 4).join("");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function buildTagMap(shapes: Shape[]): Map<string, Set<number>> {
|
|
63
|
+
const tagMap = new Map<string, Set<number>>();
|
|
64
|
+
const add = (key: string, i: number) => {
|
|
65
|
+
let set = tagMap.get(key);
|
|
66
|
+
if (!set) {
|
|
67
|
+
set = new Set();
|
|
68
|
+
tagMap.set(key, set);
|
|
69
|
+
}
|
|
70
|
+
set.add(i);
|
|
71
|
+
};
|
|
72
|
+
for (let i = 0; i < shapes.length; i++) {
|
|
73
|
+
const raw = shapes[i].tags;
|
|
74
|
+
if (!raw) continue;
|
|
75
|
+
const seen = new Set<string>();
|
|
76
|
+
for (const token of raw.toLowerCase().replace(/[/,()]/g, " ").split(" ")) {
|
|
77
|
+
if (token.length < 2 || seen.has(token)) continue;
|
|
78
|
+
seen.add(token);
|
|
79
|
+
add(token, i);
|
|
80
|
+
const sx = soundex(stripTrail(token));
|
|
81
|
+
if (sx && sx !== token && !seen.has(sx)) {
|
|
82
|
+
seen.add(sx);
|
|
83
|
+
add(sx, i);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return tagMap;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function splitCompound(token: string): string[] {
|
|
91
|
+
const spaced = token
|
|
92
|
+
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
|
93
|
+
.replace(/([a-zA-Z])(\d)/g, "$1 $2")
|
|
94
|
+
.replace(/(\d)([a-zA-Z])/g, "$1 $2");
|
|
95
|
+
return spaced
|
|
96
|
+
.trim()
|
|
97
|
+
.toLowerCase()
|
|
98
|
+
.split(/\s+/)
|
|
99
|
+
.filter((p) => p.length >= 2);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface TermMatch {
|
|
103
|
+
exact: Set<number>;
|
|
104
|
+
phonetic: Set<number>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function matchTerm(tagMap: Map<string, Set<number>>, term: string): TermMatch {
|
|
108
|
+
const exact = new Set<number>(tagMap.get(term) ?? new Set<number>());
|
|
109
|
+
let phonetic = new Set<number>();
|
|
110
|
+
const sx = soundex(stripTrail(term));
|
|
111
|
+
if (sx && sx !== term) {
|
|
112
|
+
phonetic = new Set([...(tagMap.get(sx) ?? new Set<number>())].filter((i) => !exact.has(i)));
|
|
113
|
+
}
|
|
114
|
+
return { exact, phonetic };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Sub-terms for a raw query word: its compound splits, else the whole word if long enough. */
|
|
118
|
+
function pickTerms(subs: string[], raw: string): string[] {
|
|
119
|
+
if (subs.length) return subs;
|
|
120
|
+
return raw.length >= 2 ? [raw] : [];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Tokenize the query into unique search terms (compound-split, deduped, order-preserving). */
|
|
124
|
+
function parseTerms(query: string): string[] {
|
|
125
|
+
const terms: string[] = [];
|
|
126
|
+
const seen = new Set<string>();
|
|
127
|
+
for (const raw of query.toLowerCase().split(/\s+/).filter(Boolean)) {
|
|
128
|
+
for (const t of pickTerms(splitCompound(raw), raw)) {
|
|
129
|
+
if (!seen.has(t)) {
|
|
130
|
+
seen.add(t);
|
|
131
|
+
terms.push(t);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return terms;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Strict AND across all terms (exact ∪ phonetic per term). Null when there are no terms. */
|
|
139
|
+
function intersectAll(termMatches: TermMatch[]): Set<number> | null {
|
|
140
|
+
let andSet: Set<number> | null = null;
|
|
141
|
+
for (const { exact, phonetic } of termMatches) {
|
|
142
|
+
const combined = new Set<number>([...exact, ...phonetic]);
|
|
143
|
+
if (andSet === null) {
|
|
144
|
+
andSet = combined;
|
|
145
|
+
} else {
|
|
146
|
+
const prev: Set<number> = andSet;
|
|
147
|
+
andSet = new Set<number>([...prev].filter((i) => combined.has(i)));
|
|
148
|
+
}
|
|
149
|
+
if (andSet.size === 0) break;
|
|
150
|
+
}
|
|
151
|
+
return andSet;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Score: +1.0 exact, +0.5 Soundex-only, per term. Restrict to `pool` (AND results) if given. */
|
|
155
|
+
function scoreMatches(termMatches: TermMatch[], pool: Set<number> | null): Map<number, number> {
|
|
156
|
+
const scores = new Map<number, number>();
|
|
157
|
+
for (const { exact, phonetic } of termMatches) {
|
|
158
|
+
for (const idx of exact) if (pool === null || pool.has(idx)) scores.set(idx, (scores.get(idx) ?? 0) + 1.0);
|
|
159
|
+
for (const idx of phonetic)
|
|
160
|
+
if ((pool === null || pool.has(idx)) && !exact.has(idx)) scores.set(idx, (scores.get(idx) ?? 0) + 0.5);
|
|
161
|
+
}
|
|
162
|
+
return scores;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Rank scored shapes: by score, then verbatim-title hits, then title, then index. */
|
|
166
|
+
function rankMatches(scores: Map<number, number>, shapes: Shape[], terms: string[], limit: number): ShapeMatch[] {
|
|
167
|
+
const termSet = new Set(terms);
|
|
168
|
+
const titleHits = (idx: number): number => {
|
|
169
|
+
const toks = new Set(shapes[idx].title.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));
|
|
170
|
+
let n = 0;
|
|
171
|
+
for (const t of termSet) if (toks.has(t)) n++;
|
|
172
|
+
return n;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const ranked = [...scores.keys()].sort((a, b) => {
|
|
176
|
+
const ds = (scores.get(b) ?? 0) - (scores.get(a) ?? 0);
|
|
177
|
+
if (ds !== 0) return ds;
|
|
178
|
+
const dh = titleHits(b) - titleHits(a);
|
|
179
|
+
if (dh !== 0) return dh;
|
|
180
|
+
const ta = shapes[a].title.toLowerCase();
|
|
181
|
+
const tb = shapes[b].title.toLowerCase();
|
|
182
|
+
if (ta < tb) return -1;
|
|
183
|
+
if (ta > tb) return 1;
|
|
184
|
+
return a - b;
|
|
185
|
+
});
|
|
186
|
+
return ranked.slice(0, limit).map((i) => ({ style: shapes[i].style, w: shapes[i].w, h: shapes[i].h, title: shapes[i].title }));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function search(shapes: Shape[], tagMap: Map<string, Set<number>>, query: string, limit: number): ShapeMatch[] {
|
|
190
|
+
if (!query) return [];
|
|
191
|
+
const terms = parseTerms(query);
|
|
192
|
+
if (!terms.length) return [];
|
|
193
|
+
|
|
194
|
+
const termMatches = terms.map((t) => matchTerm(tagMap, t));
|
|
195
|
+
const andSet = intersectAll(termMatches);
|
|
196
|
+
const pool = andSet?.size ? andSet : null; // AND results if any, else OR across all terms
|
|
197
|
+
const scores = scoreMatches(termMatches, pool);
|
|
198
|
+
return rankMatches(scores, shapes, terms, limit);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const INDEX_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "..", "assets", "data", "shape-index.json.gz");
|
|
202
|
+
let cachedShapes: Shape[] | null = null;
|
|
203
|
+
let cachedTagMap: Map<string, Set<number>> | null = null;
|
|
204
|
+
|
|
205
|
+
function load(): { shapes: Shape[]; tagMap: Map<string, Set<number>> } {
|
|
206
|
+
if (!cachedShapes || !cachedTagMap) {
|
|
207
|
+
cachedShapes = JSON.parse(gunzipSync(readFileSync(INDEX_PATH)).toString("utf8")) as Shape[];
|
|
208
|
+
cachedTagMap = buildTagMap(cachedShapes);
|
|
209
|
+
}
|
|
210
|
+
return { shapes: cachedShapes, tagMap: cachedTagMap };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Search the bundled shape index; returns up to `limit` matches ranked by relevance. */
|
|
214
|
+
export function searchShapes(query: string, limit = 10): ShapeMatch[] {
|
|
215
|
+
const { shapes, tagMap } = load();
|
|
216
|
+
return search(shapes, tagMap, query, limit);
|
|
217
|
+
}
|