-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1310 lines (1194 loc) · 40.8 KB
/
cli.ts
File metadata and controls
1310 lines (1194 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { readFileSync, watch } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { basename, dirname, join } from "node:path";
import { stdin, stdout, stderr, exit, env } from "node:process";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { createHash } from "node:crypto";
import { extractDiagrams, normalizeDiagram } from "@mermkit/core";
import { render, renderForTerminal } from "@mermkit/render";
const PACKAGE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version as string;
type Flags = Record<string, string | boolean>;
const [command, ...rest] = process.argv.slice(2);
const { flags } = parseArgs(rest);
if (!command || isHelp(command, flags)) {
printHelp();
exit(0);
}
main().catch((error) => {
stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
exit(1);
});
async function main(): Promise<void> {
switch (command) {
case "render":
await cmdRender(flags);
return;
case "extract":
await cmdExtract(flags);
return;
case "term":
await cmdTerm(flags);
return;
case "doctor":
await cmdDoctor(flags);
return;
case "serve":
await cmdServe(flags);
return;
case "preview":
await cmdPreview(flags);
return;
case "tool-schema":
await cmdToolSchema(flags);
return;
case "mcp":
await cmdMcp();
return;
default:
stderr.write(`unknown command: ${command}\n`);
printHelp();
exit(1);
}
}
async function cmdRender(flags: Flags): Promise<void> {
const format = getFlag(flags, "format") ?? "svg";
if (format === "term") {
await cmdTerm(flags);
return;
}
const input = await readInput(flags);
const outPath = getFlag(flags, "out");
const outDir = getFlag(flags, "out-dir") ?? getFlag(flags, "outDir");
const quiet = Boolean(flags.quiet);
const asJson = Boolean(flags.json);
const manifestPath = getFlag(flags, "out-manifest");
const diagrams = extractDiagrams(input);
const list = diagrams.length > 0 ? diagrams : [selectDiagram(input)];
if (list.length > 1 && !outDir) {
throw new Error("multiple diagrams detected; use --out-dir to render all");
}
if (outDir) {
await ensureDir(outDir);
const outputs: string[] = [];
const manifestEntries: ManifestEntry[] = [];
for (const diagram of list) {
const result = await renderDiagram(diagram, format, flags);
const filename = `${diagram.id}.${format}`;
const fullPath = join(outDir, filename);
await writeFile(fullPath, result.bytes);
outputs.push(fullPath);
manifestEntries.push({
id: diagram.id,
inputHash: hashDiagram(diagram.source),
output: fullPath,
format,
mime: result.mime,
warnings: result.warnings
});
if (!quiet && result.warnings.length > 0) {
stderr.write(result.warnings.map((warning) => `warning: ${warning}`).join("\n") + "\n");
}
}
if (asJson) {
stdout.write(`${JSON.stringify({ format, files: outputs })}\n`);
} else if (!quiet) {
stdout.write(outputs.map((file) => `${file}\n`).join(""));
}
if (manifestPath) {
await writeManifest(manifestPath, manifestEntries);
}
return;
}
const diagram = list[0];
const result = await renderDiagram(diagram, format, flags);
if (outPath) {
await ensureDir(dirname(outPath));
await writeFile(outPath, result.bytes);
if (manifestPath) {
await writeManifest(manifestPath, [
{
id: diagram.id,
inputHash: hashDiagram(diagram.source),
output: outPath,
format,
mime: result.mime,
warnings: result.warnings
}
]);
}
} else if (!asJson) {
stdout.write(Buffer.from(result.bytes));
}
if (!quiet && result.warnings.length > 0) {
stderr.write(result.warnings.map((warning) => `warning: ${warning}`).join("\n") + "\n");
}
if (asJson) {
const payload = {
format,
out: outPath,
bytes: outPath ? undefined : Buffer.from(result.bytes).toString("base64"),
mime: result.mime,
warnings: result.warnings
};
stdout.write(`${JSON.stringify(payload)}\n`);
}
if (!outPath && !outDir && manifestPath) {
await writeManifest(manifestPath, [
{
id: diagram.id,
inputHash: hashDiagram(diagram.source),
output: "<stdout>",
format,
mime: result.mime,
warnings: result.warnings
}
]);
}
}
async function cmdExtract(flags: Flags): Promise<void> {
const input = await readInput(flags);
const diagrams = extractDiagrams(input);
const outDir = getFlag(flags, "out-dir") ?? getFlag(flags, "outDir");
const quiet = Boolean(flags.quiet);
if (!outDir) {
throw new Error("extract requires --out-dir");
}
await ensureDir(outDir);
const outputs: string[] = [];
for (const diagram of diagrams) {
const filename = `${diagram.id}.mmd`;
const fullPath = join(outDir, filename);
await writeFile(fullPath, diagram.source, "utf8");
outputs.push(fullPath);
}
if (flags.json) {
stdout.write(`${JSON.stringify({ count: outputs.length, files: outputs })}\n`);
return;
}
if (!quiet) {
stdout.write(outputs.map((file) => `${file}\n`).join(""));
if (outputs.length === 0) stdout.write("no diagrams found\n");
}
}
async function cmdToolSchema(flags: Flags): Promise<void> {
const format = getFlag(flags, "format") ?? "generic";
const schema = buildToolSchema(format);
stdout.write(`${JSON.stringify(schema, null, 2)}\n`);
}
async function cmdTerm(flags: Flags): Promise<void> {
const input = await readInput(flags);
const diagram = selectDiagram(input);
const result = await renderForTerminal(diagram, detectCapabilities(), {
preferAscii: Boolean(flags.ascii)
});
if (result.text) stdout.write(`${result.text}\n`);
if (!flags.quiet && result.warnings.length > 0) {
stderr.write(result.warnings.map((warning) => `warning: ${warning}`).join("\n") + "\n");
}
}
async function cmdDoctor(flags: Flags): Promise<void> {
const embedded = await checkEmbedded();
const mmdc = await checkMmdc();
const sharp = await hasModule("sharp");
const terminal = detectCapabilities();
const payload = {
engines: {
embedded,
mmdc,
sharp: { ok: sharp }
},
terminal,
node: process.version,
platform: process.platform
};
if (flags.json) {
stdout.write(`${JSON.stringify(payload)}\n`);
return;
}
stdout.write("mermkit doctor\n\n");
stdout.write(`node: ${payload.node}\n`);
stdout.write(`platform: ${payload.platform}\n\n`);
stdout.write("engines:\n");
stdout.write(` embedded: ${embedded.ok ? "ok" : "missing"} (mermaid=${embedded.mermaid}, jsdom=${embedded.jsdom}, dompurify=${embedded.dompurify})\n`);
stdout.write(` mmdc: ${mmdc.ok ? `ok (${mmdc.path})` : "missing"}\n`);
stdout.write(` sharp: ${sharp ? "ok" : "missing"}\n\n`);
stdout.write("terminal:\n");
stdout.write(` kitty: ${terminal.kitty ? "yes" : "no"}\n`);
stdout.write(` iterm2: ${terminal.iterm2 ? "yes" : "no"}\n`);
stdout.write(` wezterm: ${terminal.wezterm ? "yes" : "no"}\n`);
stdout.write(` unicode: ${terminal.unicode ? "yes" : "no"}\n`);
}
async function cmdPreview(flags: Flags): Promise<void> {
const inputPath = getFlag(flags, "in");
const useStdin = Boolean(flags.stdin);
if (!inputPath && !useStdin) {
throw new Error("preview requires --in <file> or --stdin");
}
const initialSource = useStdin ? await readStdin() : await readFile(inputPath!, "utf8");
let fileSource = initialSource;
let source = initialSource;
let sourceMode: "file" | "manual" = useStdin ? "manual" : "file";
let lastError: string | null = null;
let lastUpdated = Date.now();
if (inputPath) {
const watcher = watch(inputPath, { persistent: true }, async () => {
try {
fileSource = await readFile(inputPath, "utf8");
if (sourceMode === "file") {
source = fileSource;
lastError = null;
lastUpdated = Date.now();
}
} catch (error) {
lastError = errorMessage(error);
}
});
process.on("exit", () => watcher.close());
}
const defaultFormat = (getFlag(flags, "format") ?? "svg") as "svg" | "png";
if (defaultFormat !== "svg" && defaultFormat !== "png") {
throw new Error("preview supports only svg or png output");
}
const host = getFlag(flags, "host") ?? "127.0.0.1";
const port = parseNumber(getFlag(flags, "port")) ?? 7070;
const defaultTheme = (getFlag(flags, "theme") as "light" | "dark" | "custom" | undefined) ?? undefined;
const scale = parseNumber(getFlag(flags, "scale"));
const background = getFlag(flags, "background") ?? "transparent";
const defaultEngine = getFlag(flags, "engine") ?? undefined;
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>mermkit preview</title>
<style>
:root { color-scheme: light dark; }
body { margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: #111; color: #f2f2f2; }
header { padding: 12px 16px; font-size: 14px; background: #1a1a1a; display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
header strong { font-weight: 600; }
#status { opacity: 0.7; }
label { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: #b5b5b5; }
select { background: #121212; color: #f2f2f2; border: 1px solid #333; border-radius: 6px; padding: 4px 8px; font-size: 13px; }
button { background: #202020; color: #f2f2f2; border: 1px solid #333; border-radius: 6px; padding: 4px 10px; font-size: 12px; cursor: pointer; }
button:disabled { opacity: 0.4; cursor: default; }
input[type="file"] { color: #b5b5b5; font-size: 12px; }
main { padding: 16px; }
img { max-width: 100%; height: auto; display: block; border: 1px solid #333; background: #fff; }
.error { color: #ff9b9b; }
</style>
</head>
<body>
<header>
<strong>mermkit preview</strong>
<label>format
<select id="format">
<option value="svg">svg</option>
<option value="png">png</option>
</select>
</label>
<label>theme
<select id="theme">
<option value="">default</option>
<option value="light">light</option>
<option value="dark">dark</option>
<option value="custom">custom</option>
</select>
</label>
<label>engine
<select id="engine">
<option value="">auto</option>
<option value="embedded">embedded</option>
<option value="mmdc">mmdc</option>
<option value="ascii">ascii</option>
<option value="stub">stub</option>
</select>
</label>
<label>preset
<select id="preset">
<option value="">custom</option>
<option value="light">light</option>
<option value="dark">dark</option>
</select>
</label>
<label>file
<input id="file" type="file" accept=".mmd,.md,.mdx,.markdown,.txt" />
</label>
<button id="reset" type="button">use watched file</button>
<div id="status">loading…</div>
</header>
<main>
<img id="diagram" alt="diagram preview" />
</main>
<script>
const img = document.getElementById("diagram");
const statusEl = document.getElementById("status");
const formatEl = document.getElementById("format");
const themeEl = document.getElementById("theme");
const engineEl = document.getElementById("engine");
const presetEl = document.getElementById("preset");
const fileEl = document.getElementById("file");
const resetEl = document.getElementById("reset");
const canReset = ${JSON.stringify(Boolean(inputPath))};
const state = {
format: ${JSON.stringify(defaultFormat)},
theme: ${JSON.stringify(defaultTheme ?? "")},
engine: ${JSON.stringify(defaultEngine ?? "")}
};
formatEl.value = state.format;
themeEl.value = state.theme;
engineEl.value = state.engine;
resetEl.disabled = !canReset;
function buildParams() {
const params = new URLSearchParams();
if (state.format) params.set("format", state.format);
if (state.theme) params.set("theme", state.theme);
if (state.engine) params.set("engine", state.engine);
return params;
}
function onChange() {
state.format = formatEl.value;
state.theme = themeEl.value;
state.engine = engineEl.value;
refresh();
}
formatEl.addEventListener("change", onChange);
themeEl.addEventListener("change", onChange);
engineEl.addEventListener("change", onChange);
presetEl.addEventListener("change", () => {
const value = presetEl.value;
if (value === "light" || value === "dark") {
themeEl.value = value;
} else {
themeEl.value = "";
}
onChange();
});
fileEl.addEventListener("change", async () => {
const file = fileEl.files && fileEl.files[0];
if (!file) return;
const text = await file.text();
await fetch("/source", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ source: text })
});
refresh();
});
resetEl.addEventListener("click", async () => {
if (!canReset) return;
await fetch("/reset", { method: "POST" });
refresh();
});
async function refresh() {
const params = buildParams();
params.set("ts", Date.now());
img.src = "/diagram?" + params.toString();
try {
const res = await fetch("/status");
const data = await res.json();
if (data.ok) {
const mode = data.mode ? " (" + data.mode + ")" : "";
statusEl.textContent = "updated " + new Date(data.updatedAt).toLocaleTimeString() + mode;
statusEl.className = "";
} else {
statusEl.textContent = data.error || "render error";
statusEl.className = "error";
}
} catch (err) {
statusEl.textContent = "preview server error";
statusEl.className = "error";
}
}
setInterval(refresh, 1000);
refresh();
</script>
</body>
</html>`;
const server = createServer(async (req, res) => {
if (!req.url) {
res.statusCode = 400;
res.end("missing url");
return;
}
const url = new URL(req.url, `http://${host}:${port}`);
if (url.pathname === "/diagram") {
res.setHeader("Cache-Control", "no-store");
if (lastError) {
res.statusCode = 500;
res.end(lastError);
return;
}
try {
const formatParam = url.searchParams.get("format") ?? defaultFormat;
const themeParam = url.searchParams.get("theme") ?? defaultTheme ?? "";
const engineParam = url.searchParams.get("engine");
const format = formatParam === "png" ? "png" : "svg";
const theme =
themeParam === "light" || themeParam === "dark" || themeParam === "custom"
? themeParam
: undefined;
const engine = (engineParam ?? defaultEngine) || undefined;
const diagram = selectDiagram(source);
const result = await render(diagram, { format, theme, scale, background, engine });
res.statusCode = 200;
res.setHeader("Content-Type", result.mime);
res.end(Buffer.from(result.bytes));
lastError = null;
return;
} catch (error) {
lastError = errorMessage(error);
res.statusCode = 500;
res.end(lastError);
return;
}
}
if (url.pathname === "/source" && req.method === "POST") {
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
req.on("end", () => {
try {
const body = Buffer.concat(chunks).toString("utf8");
let nextSource: string | null = null;
try {
const payload = JSON.parse(body) as { source?: string };
if (payload.source) nextSource = payload.source;
} catch {
nextSource = body;
}
if (!nextSource) {
res.statusCode = 400;
res.end("missing source");
return;
}
source = nextSource;
sourceMode = "manual";
lastError = null;
lastUpdated = Date.now();
res.statusCode = 200;
res.end("ok");
} catch (error) {
res.statusCode = 400;
res.end(errorMessage(error));
}
});
return;
}
if (url.pathname === "/reset" && req.method === "POST") {
if (!inputPath) {
res.statusCode = 400;
res.end("no watched file");
return;
}
source = fileSource;
sourceMode = "file";
lastError = null;
lastUpdated = Date.now();
res.statusCode = 200;
res.end("ok");
return;
}
if (url.pathname === "/status") {
res.setHeader("Content-Type", "application/json");
res.end(
JSON.stringify({
ok: !lastError,
error: lastError,
updatedAt: lastUpdated,
mode: sourceMode
})
);
return;
}
res.statusCode = 200;
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(html);
});
server.listen(port, host, () => {
stdout.write(`preview: http://${host}:${port}\n`);
if (inputPath) stdout.write(`watching: ${inputPath}\n`);
});
}
type ServeRequest =
| {
id?: string;
action: "render";
diagram: string;
options?: {
format?: "svg" | "png" | "pdf";
theme?: "light" | "dark" | "custom";
scale?: number;
background?: "transparent" | string;
engine?: string;
};
}
| {
id?: string;
action: "renderBatch";
diagrams: Array<{ id?: string; source: string }>;
options?: {
format?: "svg" | "png" | "pdf";
theme?: "light" | "dark" | "custom";
scale?: number;
background?: "transparent" | string;
engine?: string;
};
}
| {
id?: string;
action: "extract";
markdown: string;
}
| {
id?: string;
action: "term";
diagram: string;
}
| {
id?: string;
action: "schema";
format?: string;
};
type ServeResponse = {
id?: string;
ok: boolean;
result?: unknown;
error?: string;
};
async function cmdServe(_flags: Flags): Promise<void> {
const rl = createInterface({ input: stdin, crlfDelay: Infinity });
for await (const line of rl) {
const trimmed = line.trim();
if (!trimmed) continue;
let request: ServeRequest;
try {
request = JSON.parse(trimmed) as ServeRequest;
} catch (error) {
writeServeResponse({ ok: false, error: `invalid JSON: ${errorMessage(error)}` });
continue;
}
const id = request.id;
try {
if (request.action === "render") {
const options = request.options ?? {};
const diagram = { id: id ?? "diagram-1", source: normalizeDiagram(request.diagram) };
const result = await render(diagram, {
format: options.format ?? "svg",
theme: options.theme,
scale: options.scale,
background: options.background ?? "transparent",
engine: options.engine
});
writeServeResponse({
id,
ok: true,
result: {
mime: result.mime,
warnings: result.warnings,
bytes: Buffer.from(result.bytes).toString("base64")
}
});
continue;
}
if (request.action === "renderBatch") {
const options = request.options ?? {};
const results: Array<{ id: string; ok: boolean; result?: { mime: string; warnings: string[]; bytes: string }; error?: string }> = [];
for (const item of request.diagrams) {
const diagramId = item.id ?? `diagram-${results.length + 1}`;
try {
const diagram = { id: diagramId, source: normalizeDiagram(item.source) };
const result = await render(diagram, {
format: options.format ?? "svg",
theme: options.theme,
scale: options.scale,
background: options.background ?? "transparent",
engine: options.engine
});
results.push({
id: diagramId,
ok: true,
result: {
mime: result.mime,
warnings: result.warnings,
bytes: Buffer.from(result.bytes).toString("base64")
}
});
} catch (error) {
results.push({
id: diagramId,
ok: false,
error: errorMessage(error)
});
}
}
writeServeResponse({
id,
ok: true,
result: {
results
}
});
continue;
}
if (request.action === "extract") {
const diagrams = extractDiagrams(request.markdown);
writeServeResponse({
id,
ok: true,
result: {
diagrams
}
});
continue;
}
if (request.action === "term") {
const diagram = { id: id ?? "diagram-1", source: normalizeDiagram(request.diagram) };
const result = await renderForTerminal(diagram, detectCapabilities());
writeServeResponse({
id,
ok: true,
result: {
text: result.text,
mime: result.mime,
warnings: result.warnings,
bytes: result.imageBytes ? Buffer.from(result.imageBytes).toString("base64") : undefined
}
});
continue;
}
if (request.action === "schema") {
const schema = buildToolSchema(request.format ?? "generic");
writeServeResponse({
id,
ok: true,
result: schema
});
continue;
}
writeServeResponse({ id, ok: false, error: "unknown action" });
} catch (error) {
writeServeResponse({ id, ok: false, error: errorMessage(error) });
}
}
}
function writeServeResponse(response: ServeResponse): void {
stdout.write(`${JSON.stringify(response)}\n`);
}
type JsonRpcRequest = {
jsonrpc?: string;
id?: string | number;
method: string;
params?: Record<string, unknown>;
};
type JsonRpcResponse = {
jsonrpc: "2.0";
id: string | number;
result?: unknown;
error?: { code: number; message: string };
};
function writeMcpResponse(response: JsonRpcResponse): void {
stdout.write(`${JSON.stringify(response)}\n`);
}
function shouldRespondToId(id: unknown): id is string | number {
return typeof id === "string" || typeof id === "number";
}
function maybeWriteMcpResponse(
id: unknown,
response: Omit<JsonRpcResponse, "id">
): void {
if (!shouldRespondToId(id)) return;
writeMcpResponse({ ...response, id });
}
const MCP_TOOL_NAME_MAP = new Map<string, string>();
function toMcpToolName(name: string): string {
return name.replace(/\./g, "_");
}
function getMcpToolNameMap(): Map<string, string> {
if (MCP_TOOL_NAME_MAP.size === 0) {
for (const tool of buildToolDefinitions()) {
MCP_TOOL_NAME_MAP.set(toMcpToolName(tool.name), tool.name);
}
}
return MCP_TOOL_NAME_MAP;
}
function resolveMcpToolName(name: unknown): string | undefined {
if (typeof name !== "string") return undefined;
if (name.includes(".")) return name;
return getMcpToolNameMap().get(name) ?? name;
}
function buildMcpToolDefinitions(): Array<{ name: string; description: string; inputSchema: Record<string, unknown> }> {
return buildToolDefinitions().map((tool) => ({
name: toMcpToolName(tool.name),
description: tool.description,
inputSchema: tool.parameters
}));
}
async function cmdMcp(): Promise<void> {
const rl = createInterface({ input: stdin, crlfDelay: Infinity });
for await (const line of rl) {
const trimmed = line.trim();
if (!trimmed) continue;
let request: JsonRpcRequest;
try {
request = JSON.parse(trimmed) as JsonRpcRequest;
} catch (error) {
stderr.write(`mcp parse error: ${errorMessage(error)}\n`);
continue;
}
const id = request.id;
if (!request.method || typeof request.method !== "string") {
maybeWriteMcpResponse(id, {
jsonrpc: "2.0",
error: { code: -32600, message: "invalid request: missing method" }
});
continue;
}
if (request.method === "initialize") {
maybeWriteMcpResponse(id, {
jsonrpc: "2.0",
result: {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: { name: "mermkit", version: PACKAGE_VERSION }
}
});
continue;
}
if (request.method === "tools/list") {
maybeWriteMcpResponse(id, {
jsonrpc: "2.0",
result: { tools: buildMcpToolDefinitions() }
});
continue;
}
if (request.method === "tools/call") {
const params = request.params ?? {};
const toolName = resolveMcpToolName((params as { name?: unknown }).name);
const toolInput = ((params as { input?: unknown; arguments?: unknown }).input ??
(params as { arguments?: unknown }).arguments ??
{}) as Record<string, unknown>;
try {
if (!toolName) {
throw new Error("invalid request: tools/call requires a tool name");
}
const content = await executeMcpTool(toolName, toolInput);
maybeWriteMcpResponse(id, { jsonrpc: "2.0", result: { content } });
} catch (error) {
maybeWriteMcpResponse(id, {
jsonrpc: "2.0",
result: {
content: [{ type: "text", text: `error: ${errorMessage(error)}` }],
isError: true
}
});
}
continue;
}
maybeWriteMcpResponse(id, {
jsonrpc: "2.0",
error: { code: -32601, message: `method not found: ${request.method}` }
});
}
}
async function executeMcpTool(name: string, input: Record<string, unknown>): Promise<Array<{ type: string; [key: string]: unknown }>> {
if (name === "mermkit.render") {
if (typeof input.diagram !== "string") {
throw new Error("diagram is required and must be a string");
}
const source = input.diagram;
const options = (input.options ?? {}) as Record<string, unknown>;
const diagram = { id: "diagram-1", source: normalizeDiagram(source) };
const result = await render(diagram, {
format: (options.format as "svg" | "png" | "pdf" | "ascii") ?? "svg",
theme: options.theme as "light" | "dark" | "custom" | undefined,
scale: options.scale as number | undefined,
background: (options.background as string) ?? "transparent",
engine: options.engine as string | undefined
});
const format = (options.format as string) ?? "svg";
if (format === "ascii") {
return [{ type: "text", text: new TextDecoder().decode(result.bytes) }];
}
const mimeType = result.mime ?? "application/octet-stream";
return [{ type: "image", data: Buffer.from(result.bytes).toString("base64"), mimeType }];
}
if (name === "mermkit.renderBatch") {
if (!Array.isArray(input.diagrams)) {
throw new Error("diagrams is required and must be an array");
}
const diagrams = input.diagrams as Array<{ id?: string; source?: string }>;
const options = (input.options ?? {}) as Record<string, unknown>;
const results: Array<{ type: string; [key: string]: unknown }> = [];
for (let i = 0; i < diagrams.length; i++) {
const item = diagrams[i];
const diagramId = item.id ?? `diagram-${i + 1}`;
try {
if (typeof item.source !== "string") {
throw new Error("diagram source must be a string");
}
const diagram = { id: diagramId, source: normalizeDiagram(item.source) };
const result = await render(diagram, {
format: (options.format as "svg" | "png" | "pdf" | "ascii") ?? "svg",
theme: options.theme as "light" | "dark" | "custom" | undefined,
scale: options.scale as number | undefined,
background: (options.background as string) ?? "transparent",
engine: options.engine as string | undefined
});
const format = (options.format as string) ?? "svg";
if (format === "ascii") {
results.push({ type: "text", text: `[${diagramId}]\n${new TextDecoder().decode(result.bytes)}` });
} else {
const mimeType = result.mime ?? "application/octet-stream";
results.push({ type: "image", data: Buffer.from(result.bytes).toString("base64"), mimeType });
}
} catch (error) {
results.push({ type: "text", text: `[${diagramId}] error: ${errorMessage(error)}` });
}
}
return results;
}
if (name === "mermkit.extract") {
if (typeof input.markdown !== "string") {
throw new Error("markdown is required and must be a string");
}
const markdown = input.markdown;
const diagrams = extractDiagrams(markdown);
const text = diagrams.map((d) => `[${d.id}]\n${d.source}`).join("\n\n");
return [{ type: "text", text: text || "no diagrams found" }];
}
if (name === "mermkit.term") {
if (typeof input.diagram !== "string") {
throw new Error("diagram is required and must be a string");
}
const source = input.diagram;
const diagram = { id: "diagram-1", source: normalizeDiagram(source) };
const result = await renderForTerminal(diagram, detectCapabilities());
return [{ type: "text", text: result.text ?? "unable to render for terminal" }];
}
if (name === "mermkit.schema") {
const format = (input.format as string) ?? "generic";
const schema = buildToolSchema(format);
return [{ type: "text", text: JSON.stringify(schema, null, 2) }];
}
throw new Error(`unknown tool: ${name}`);
}
function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
function selectDiagram(input: string) {
const diagrams = extractDiagrams(input);
if (diagrams.length > 0) return diagrams[0];
return { id: "diagram-1", source: normalizeDiagram(input) };
}
async function renderDiagram(diagram: { id: string; source: string }, format: string, flags: Flags) {
const asciiOptions: Record<string, unknown> = {};
if (flags.ascii) asciiOptions.useAscii = true;
if (flags.coords) asciiOptions.showCoords = true;
const paddingX = parseNumber(getFlag(flags, "padding-x"));
if (paddingX !== undefined) asciiOptions.paddingBetweenX = paddingX;
const paddingY = parseNumber(getFlag(flags, "padding-y"));
if (paddingY !== undefined) asciiOptions.paddingBetweenY = paddingY;
const borderPadding = parseNumber(getFlag(flags, "border-padding"));
if (borderPadding !== undefined) asciiOptions.boxBorderPadding = borderPadding;
try {
return await render(diagram as { id: string; source: string }, {
format: format as "svg" | "png" | "pdf" | "ascii",
theme: (getFlag(flags, "theme") as "light" | "dark" | "custom" | undefined) ?? undefined,
scale: parseNumber(getFlag(flags, "scale")),
background: getFlag(flags, "background") ?? "transparent",
engine: getFlag(flags, "engine") ?? undefined,
ascii: asciiOptions
});
} catch (error) {
if (format === "ascii" || format === "term") throw error;
const fallback = await render(diagram as { id: string; source: string }, {
format: "ascii",
ascii: asciiOptions
});
fallback.warnings.unshift(`render failed; falling back to ASCII: ${errorMessage(error)}`);
return fallback;