yuhwa 1.0.2 → 1.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.
Files changed (51) hide show
  1. package/README.md +13 -12
  2. package/client.d.ts +9 -1
  3. package/dist/astro.d.ts +2 -2
  4. package/dist/astro.js +8 -1
  5. package/dist/browser.d.ts +11 -5
  6. package/dist/browser.js +27 -7
  7. package/dist/cli.js +602 -44
  8. package/dist/editor/assets/index-BGtCSg84.js +689 -0
  9. package/dist/editor/assets/lsp.worker-DUpBJRU2.js +26 -0
  10. package/dist/editor/index.html +5 -4
  11. package/dist/figure-db587hh6.d.ts +48 -0
  12. package/dist/{index-Dl845tUQ.d.ts → index-CAO4FUcz.d.ts} +48 -7
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/ironmark.d.ts +4 -2
  16. package/dist/ironmark.js +18 -7
  17. package/dist/llms.txt +12 -8
  18. package/dist/lsp-browser.d.ts +2 -2
  19. package/dist/lsp-browser.js +1 -1
  20. package/dist/lsp-node.js +40 -182
  21. package/dist/lsp-server.d.ts +1 -1
  22. package/dist/lsp-server.js +1 -1
  23. package/dist/lsp.d.ts +1 -1
  24. package/dist/lsp.js +1 -1
  25. package/dist/markdown-it.d.ts +2 -1
  26. package/dist/markdown-it.js +7 -6
  27. package/dist/node-DPojgovD.js +224 -0
  28. package/dist/remark.d.ts +2 -1
  29. package/dist/remark.js +16 -5
  30. package/dist/{server-DJC_fQMe.d.ts → server-BSHSx8uo.d.ts} +2 -2
  31. package/dist/{server-DmQuHQrG.js → server-CT_mbBNZ.js} +1 -1
  32. package/dist/{service-BYS9Qfkq.js → service-CNM6Z-RH.js} +81 -16
  33. package/dist/{service-ClZ8clSQ.d.ts → service-DquYYTVG.d.ts} +1 -1
  34. package/dist/{shared-qo_r6RUN.js → shared-B2rP00uA.js} +2292 -429
  35. package/dist/{src-wk7tBpWs.js → src-hrqH-a8K.js} +2094 -407
  36. package/dist/style.css +14 -0
  37. package/dist/vite.d.ts +1 -1
  38. package/dist/vite.js +19 -12
  39. package/dist/vuepress.d.ts +3 -1
  40. package/dist/vuepress.js +7 -2
  41. package/dist/yuhwa.iife.js +90 -65
  42. package/dist/zoom-CCSUbX1X.d.ts +49 -0
  43. package/dist/zoom-QeqB6QlH.js +275 -0
  44. package/dist/zoom-script-CVdAzMhX.js +51 -0
  45. package/dist/zoom.d.ts +35 -0
  46. package/dist/zoom.js +19 -0
  47. package/package.json +10 -2
  48. package/dist/editor/assets/index-BQLsumas.js +0 -587
  49. package/dist/editor/assets/lsp.worker-RlPj9blG.js +0 -26
  50. package/dist/figure-BZHIKnxv.d.ts +0 -27
  51. package/dist/node-Bneu5eJV.js +0 -108
package/dist/cli.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
- import { C as PANEL_PROPS, D as TONES, E as THEME_NAMES, T as THEME_KEYS, a as canvasMeasure, b as GROUP_PROPS, c as KNOWN_SETTINGS, f as isYuhwaPath, n as render$1, o as registry, p as joinPath$1, r as toSource, s as diskResolve, t as VERSION, u as SETTING_VALUES, v as EDGE_PROPS, w as SHAPES, x as NODE_PROPS, y as ENUMS } from "./shared-qo_r6RUN.js";
3
+ import { A as THEME_KEYS, C as ENUMS, D as PANEL_PROPS, M as TONES, N as isSafeCss, O as SHAPES, S as EDGE_PROPS, T as NODE_PROPS, _ as joinPath$1, a as tidy, c as toSource, d as registry, f as KNOWN_SETTINGS, g as isYuhwaPath, i as format, j as THEME_NAMES, k as esc, l as canvasMeasure, m as SETTING_VALUES, o as diskResolve, s as render$1, t as VERSION, u as optionKind, w as GROUP_PROPS } from "./shared-B2rP00uA.js";
4
4
  import { createServer } from "node:http";
5
5
  import { basename, dirname, extname, join, resolve, sep } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { spawn } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
8
9
  import { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
9
10
  // src/markdown.ts
10
11
  /**
@@ -23,10 +24,15 @@ import { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
23
24
  */
24
25
  const COMMENT_OPEN = /^<!--\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
25
26
  const FENCE_OPEN = /^(```+|~~~+)\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
26
- function imageRef(name, lightPath, darkPath) {
27
- if (darkPath) return `<picture><source media="(prefers-color-scheme: dark)" srcset="${darkPath}"><img alt="${name}" src="${lightPath}"></picture>`;
28
- return `![${name}](${lightPath})`;
27
+ function imageRef(name, lightPath, darkPath, href) {
28
+ if (darkPath) {
29
+ const pic = `<picture><source media="(prefers-color-scheme: dark)" srcset="${darkPath}"><img alt="${name}" src="${lightPath}"></picture>`;
30
+ return href ? `<a href="${href.replace(/"/g, "%22")}">${pic}</a>` : pic;
31
+ }
32
+ return href ? `[![${name}](${lightPath})](${href})` : `![${name}](${lightPath})`;
29
33
  }
34
+ /** an image reference without the link `view` wraps it in */
35
+ const unlinked = (ref) => ref.match(/^\[(!\[[^\]]*\]\([^)]*\))\]\([^)]*\)$/)?.[1] ?? ref.match(/^<a href="[^"]*">(<picture>.*<\/picture>)<\/a>$/)?.[1] ?? ref;
30
36
  function findBlocks(md, baseName = "diagram", outDir = "diagrams") {
31
37
  const lines = md.split("\n");
32
38
  const blocks = [];
@@ -64,7 +70,7 @@ function findBlocks(md, baseName = "diagram", outDir = "diagrams") {
64
70
  };
65
71
  let k = j + 1;
66
72
  while (k < lines.length && lines[k].trim() === "" && k <= j + 1) k++;
67
- const candidate = lines[k]?.trim();
73
+ const candidate = unlinked(lines[k]?.trim() ?? "");
68
74
  const path = joinPath(outDir, `${n}.svg`);
69
75
  if (candidate === imageRef(n, path) || candidate === imageRef(n, path, joinPath(outDir, `${n}.dark.svg`))) b.image = [k, k];
70
76
  blocks.push(b);
@@ -96,7 +102,8 @@ function processMarkdown(md, opts = {}) {
96
102
  path: lightPath,
97
103
  svg: light.svg + "\n"
98
104
  });
99
- let ref = imageRef(b.name, lightPath);
105
+ const href = light.diagram.imports?.length ? void 0 : opts.view?.(b.source);
106
+ let ref = imageRef(b.name, lightPath, void 0, href);
100
107
  if (opts.dark) {
101
108
  const dark = render$1(b.source, {
102
109
  ...io,
@@ -107,7 +114,7 @@ function processMarkdown(md, opts = {}) {
107
114
  path: darkPath,
108
115
  svg: dark.svg + "\n"
109
116
  });
110
- ref = imageRef(b.name, lightPath, darkPath);
117
+ ref = imageRef(b.name, lightPath, darkPath, href);
111
118
  }
112
119
  const replacement = [];
113
120
  if (b.kind === "fence" && !opts.keepFences) replacement.push(`<!--yuhwa ${b.name}`, ...b.source.split("\n"), "-->");
@@ -136,9 +143,18 @@ function replaceBlockSource(md, index, source) {
136
143
  const list = (xs) => [...xs].join(", ");
137
144
  const code = (xs) => list([...xs].map((x) => "`" + x + "`"));
138
145
  const panels = [...registry.panels.values()];
146
+ const PLACEHOLDER = {
147
+ color: "<colour>",
148
+ number: "N",
149
+ text: "…"
150
+ };
139
151
  const settings = list([...KNOWN_SETTINGS].map((k) => SETTING_VALUES[k] ? `${k} (${SETTING_VALUES[k].join("|")})` : k));
140
152
  const panelLines = panels.map((p) => {
141
- const header = Object.entries(p.options ?? {}).map(([k, v]) => v.length ? `${k}: ${v.join("|")}` : `${k}: …`);
153
+ const header = Object.entries(p.options ?? {}).map(([k, v]) => {
154
+ const o = optionKind(v);
155
+ if (o.kind === "select") return `${k}: ${o.values.join("|")}`;
156
+ return o.kind === "flag" ? k : `${k}: ${PLACEHOLDER[o.kind]}`;
157
+ });
142
158
  const body = p.guide ?? (p.syntax ? "`" + p.syntax + "`" : "");
143
159
  return `- \`${p.name}\`: ${body}${header.length ? ` Header: ${code(header)}.` : ""}`;
144
160
  }).join("\n");
@@ -149,7 +165,7 @@ yuhwa is a text diagram language that renders to a self-contained SVG. One
149
165
  statement per line. \`//\` at line start or after a space starts a comment, so
150
166
  URLs in labels stay text. There is no \`#\` comment.
151
167
 
152
- Workflow: write the source, run \`yuhwa check file.yuhwa --json\` (or read the
168
+ Workflow: write the source, run \`yuhwa check file.yu --json\` (or read the
153
169
  \`diagnostics\` of \`render\`), fix every error and warning, then render. Done
154
170
  when it reports 0 diagnostics; they name the fix ("did you mean ...").
155
171
 
@@ -196,7 +212,7 @@ orders --> queue "Events" [shape: hexagon]: publish [flow: true]
196
212
  \`$a\`. \`name(x, "Label, with comma", b: y)\` stamps it out. Use one per
197
213
  repeated shape of nodes instead of copying lines.
198
214
  - Group: \`group id "Label" .class [props] { ... }\`, may nest. \`group "Label" {\`
199
- gets a slug id. Edges connect nodes only, never groups.
215
+ gets a slug id. Edges connect nodes and panel ids (\`plan -> sales\`), never groups.
200
216
  - Props: \`[key: value, key: "a, b", flag]\`; a bare flag means true, a bare
201
217
  value names its key: \`[cylinder, amber, dashed]\`.
202
218
  - Props on their own lines: a \`key: value\` line indented under a node, edge,
@@ -231,6 +247,9 @@ orders --> queue "Events" [shape: hexagon]: publish [flow: true]
231
247
  \`sub\` is a second, smaller line; \`icon\` an emoji before the label; \`link\`
232
248
  makes a node clickable; \`flow: true\` animates an edge; \`constraint: false\`
233
249
  keeps an edge out of the layout; \`shape: text\` is an annotation without a box.
250
+ \`below: <id>\`, \`above\`, \`right-of\`, \`left-of\` and \`rank\` place a node next to another
251
+ node without drawing an edge; do not use invisible edges for that. The \`max-width: <px>\` setting
252
+ wraps the ranks of a right or left diagram into rows that fit that width.
234
253
  \`frame: <kind> <text>\` draws window chrome: ${list(registry.frames.keys())}.
235
254
 
236
255
  ## Card bodies
@@ -285,10 +304,10 @@ ${panelLines}
285
304
 
286
305
  ## Imports
287
306
 
288
- \`import "./shared.yuhwa"\` at top level pulls in another file's classes,
307
+ \`import "./shared.yu"\` at top level pulls in another file's classes,
289
308
  nodes, groups, edges, panels, variables and components; paths resolve against
290
309
  the importing file, and the importing file wins on conflicts.
291
- \`import { api, .svc as .service, $brand } from "./x.yuhwa"\` takes only those.
310
+ \`import { api, .svc as .service, $brand } from "./x.yu"\` takes only those.
292
311
  A file with \`export api, .svc\` (or \`export\` before a declaration:
293
312
  \`export def ...\`, \`export $x: 1\`, \`export theme brand {\`) offers only those.
294
313
  Custom themes come along with every import. Settings stay in their file unless
@@ -348,6 +367,363 @@ panel. \`yuhwa convert file.mmd\` prints the yuhwa source.
348
367
  Keep labels short and put detail in \`sub\`. One colour per kind of thing,
349
368
  defined once as a class. 5 to 20 nodes read best; split larger systems.
350
369
  `;
370
+ // src/zoom.ts
371
+ /** Make the diagram inside `host` pannable and zoomable. Calling it again replaces the earlier viewer. */
372
+ function zoomable(host, opts = {}) {
373
+ host.yuhwaZoom?.destroy();
374
+ const doc = host.ownerDocument;
375
+ const win = doc.defaultView ?? window;
376
+ if (!doc.getElementById("yuhwa-zoom-css")) {
377
+ const css = doc.createElement("style");
378
+ css.id = "yuhwa-zoom-css";
379
+ css.textContent = `
380
+ .yuhwa-zoom{position:relative;display:block;overflow:hidden;touch-action:pan-x pan-y;-webkit-user-select:none;user-select:none;outline:none}
381
+ .yuhwa-zoom:focus-visible{box-shadow:0 0 0 2px Highlight}
382
+ .yuhwa-zoom[data-zoomed]{cursor:grab;touch-action:none}
383
+ .yuhwa-zoom[data-dragging]{cursor:grabbing}
384
+ .yuhwa-zoom-stage{transform-origin:0 0}
385
+ .yuhwa-zoom-stage.yuhwa-zoom-anim{transition:transform .18s ease-out}
386
+ .yuhwa-zoom-fixed .yuhwa-zoom-stage,.yuhwa-zoom:fullscreen .yuhwa-zoom-stage{height:100%;display:flex;align-items:center;justify-content:center}
387
+ .yuhwa-zoom-fixed .yuhwa-zoom-stage :is(svg,img),.yuhwa-zoom:fullscreen .yuhwa-zoom-stage :is(svg,img){max-width:100%;max-height:100%;width:auto;height:auto}
388
+ .yuhwa-zoom:fullscreen{background:var(--yuhwa-zoom-bg,Canvas)}
389
+ .yuhwa-zoom-stage img{-webkit-user-drag:none}
390
+ .yuhwa-zoom-bar{position:absolute;top:8px;right:8px;display:flex;align-items:center;gap:2px;padding:3px;border-radius:8px;background:color-mix(in srgb,Canvas 86%,transparent);box-shadow:0 1px 4px rgba(0,0,0,.18);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);opacity:0;transition:opacity .15s;font:500 12px/1 system-ui,sans-serif;color:CanvasText;cursor:default}
391
+ .yuhwa-zoom:hover .yuhwa-zoom-bar,.yuhwa-zoom:focus-within .yuhwa-zoom-bar,.yuhwa-zoom[data-zoomed] .yuhwa-zoom-bar{opacity:1}
392
+ @media (hover:none){.yuhwa-zoom-bar{opacity:1}}
393
+ .yuhwa-zoom-bar button{all:unset;box-sizing:border-box;min-width:28px;height:28px;padding:0 6px;display:grid;place-items:center;border-radius:6px;cursor:pointer;font-variant-numeric:tabular-nums}
394
+ .yuhwa-zoom-bar button:hover{background:color-mix(in srgb,CanvasText 10%,transparent)}
395
+ .yuhwa-zoom-bar button:focus-visible{outline:2px solid Highlight}
396
+ .yuhwa-zoom-bar button:disabled{opacity:.35;cursor:default;background:none}
397
+ .yuhwa-zoom-hint{position:absolute;left:50%;bottom:10px;transform:translateX(-50%);padding:5px 10px;border-radius:6px;background:rgba(20,20,20,.78);color:#fff;font:12px/1.3 system-ui,sans-serif;white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .2s}
398
+ .yuhwa-zoom-hint[data-show]{opacity:1}
399
+ @media (prefers-reduced-motion:reduce){.yuhwa-zoom-stage.yuhwa-zoom-anim,.yuhwa-zoom-hint,.yuhwa-zoom-bar{transition:none}}`;
400
+ doc.head.append(css);
401
+ }
402
+ const min = opts.min ?? 1;
403
+ const max = Math.max(opts.max ?? 8, min);
404
+ let s = 1;
405
+ let x = 0;
406
+ let y = 0;
407
+ const addedTabIndex = !host.hasAttribute("tabindex");
408
+ const oldHeight = host.style.height;
409
+ host.classList.add("yuhwa-zoom");
410
+ if (opts.height) {
411
+ host.classList.add("yuhwa-zoom-fixed");
412
+ host.style.height = opts.height;
413
+ }
414
+ if (addedTabIndex) host.tabIndex = 0;
415
+ const stage = doc.createElement("div");
416
+ stage.className = "yuhwa-zoom-stage";
417
+ stage.append(...host.childNodes);
418
+ host.append(stage);
419
+ const icon = (d) => `<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="${d}" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
420
+ const button = (label, html, onClick) => {
421
+ const b = doc.createElement("button");
422
+ b.type = "button";
423
+ b.title = label;
424
+ b.setAttribute("aria-label", label);
425
+ b.innerHTML = html;
426
+ b.addEventListener("click", (e) => {
427
+ e.stopPropagation();
428
+ onClick();
429
+ });
430
+ return b;
431
+ };
432
+ const bar = doc.createElement("div");
433
+ bar.className = "yuhwa-zoom-bar";
434
+ const minus = button("Zoom out (−)", icon("M3.5 8h9"), () => zoom(1 / 1.5, void 0, true));
435
+ const pct = button("Reset zoom (0)", "100%", () => reset());
436
+ const plus = button("Zoom in (+)", icon("M3.5 8h9M8 3.5v9"), () => zoom(1.5, void 0, true));
437
+ bar.append(minus, pct, plus);
438
+ if (!!(doc.fullscreenEnabled && host.requestFullscreen)) bar.append(button("Full screen", icon("M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"), () => doc.fullscreenElement === host ? doc.exitFullscreen() : host.requestFullscreen().catch(() => {})));
439
+ if (opts.controls !== false) host.append(bar);
440
+ const hint = doc.createElement("div");
441
+ hint.className = "yuhwa-zoom-hint";
442
+ hint.setAttribute("aria-hidden", "true");
443
+ hint.textContent = /Mac|iP/.test(win.navigator.platform) ? "Pinch or ⌘ + scroll to zoom" : "Ctrl + scroll to zoom";
444
+ host.append(hint);
445
+ let hintTimer = 0;
446
+ const showHint = () => {
447
+ hint.setAttribute("data-show", "");
448
+ win.clearTimeout(hintTimer);
449
+ hintTimer = win.setTimeout(() => hint.removeAttribute("data-show"), 1400);
450
+ };
451
+ const apply = (animate = false) => {
452
+ const w = host.clientWidth;
453
+ const h = host.clientHeight;
454
+ const ex = w - w * s;
455
+ const ey = h - h * s;
456
+ x = Math.min(Math.max(x, Math.min(0, ex)), Math.max(0, ex));
457
+ y = Math.min(Math.max(y, Math.min(0, ey)), Math.max(0, ey));
458
+ stage.classList.toggle("yuhwa-zoom-anim", animate);
459
+ stage.style.transform = s === 1 && !x && !y ? "" : `translate(${x}px, ${y}px) scale(${s})`;
460
+ host.toggleAttribute("data-zoomed", s > 1.001);
461
+ const label = `${Math.round(s * 100)}%`;
462
+ if (pct.textContent !== label) pct.textContent = label;
463
+ minus.disabled = s <= min + .001;
464
+ plus.disabled = s >= max - .001;
465
+ };
466
+ const zoom = (factor, at, animate = false) => {
467
+ const p = at ?? {
468
+ x: host.clientWidth / 2,
469
+ y: host.clientHeight / 2
470
+ };
471
+ const next = Math.min(max, Math.max(min, s * factor));
472
+ x = p.x - (p.x - x) * next / s;
473
+ y = p.y - (p.y - y) * next / s;
474
+ s = next;
475
+ apply(animate);
476
+ };
477
+ const reset = (animate = true) => {
478
+ s = 1;
479
+ x = y = 0;
480
+ apply(animate);
481
+ };
482
+ const local = (e) => {
483
+ const r = host.getBoundingClientRect();
484
+ return {
485
+ x: e.clientX - r.left,
486
+ y: e.clientY - r.top
487
+ };
488
+ };
489
+ const onWheel = (e) => {
490
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? host.clientHeight : 1;
491
+ const dx = e.deltaX * unit;
492
+ const dy = e.deltaY * unit;
493
+ if (e.ctrlKey || e.metaKey || opts.wheel || doc.fullscreenElement === host) {
494
+ e.preventDefault();
495
+ zoom(Math.exp(-dy * (Math.abs(dy) < 50 ? .01 : .002)), local(e));
496
+ } else if (s > 1.001) {
497
+ const ox = x;
498
+ const oy = y;
499
+ x -= dx;
500
+ y -= dy;
501
+ apply();
502
+ if (x !== ox || y !== oy) e.preventDefault();
503
+ } else if (Math.abs(dy) > Math.abs(dx)) showHint();
504
+ };
505
+ const points = /* @__PURE__ */ new Map();
506
+ let pinch = null;
507
+ let moved = 0;
508
+ const pinchState = () => {
509
+ const [a, b] = [...points.values()];
510
+ return {
511
+ d: Math.hypot(a.x - b.x, a.y - b.y) || 1,
512
+ x: (a.x + b.x) / 2,
513
+ y: (a.y + b.y) / 2
514
+ };
515
+ };
516
+ const onDown = (e) => {
517
+ if (e.pointerType === "mouse" && e.button !== 0 || bar.contains(e.target)) return;
518
+ if (points.size === 0) moved = 0;
519
+ points.set(e.pointerId, local(e));
520
+ if (points.size === 2) {
521
+ pinch = pinchState();
522
+ for (const id of points.keys()) host.setPointerCapture?.(id);
523
+ } else if (points.size === 1 && s > 1.001) {
524
+ host.setPointerCapture?.(e.pointerId);
525
+ host.setAttribute("data-dragging", "");
526
+ }
527
+ };
528
+ const onMove = (e) => {
529
+ const last = points.get(e.pointerId);
530
+ if (!last) return;
531
+ const p = local(e);
532
+ points.set(e.pointerId, p);
533
+ if (points.size >= 2 && pinch) {
534
+ const now = pinchState();
535
+ x += now.x - pinch.x;
536
+ y += now.y - pinch.y;
537
+ zoom(now.d / pinch.d, now);
538
+ moved += Math.abs(now.d - pinch.d) + Math.abs(now.x - pinch.x) + Math.abs(now.y - pinch.y);
539
+ pinch = now;
540
+ } else if (host.hasAttribute("data-dragging")) {
541
+ x += p.x - last.x;
542
+ y += p.y - last.y;
543
+ moved += Math.abs(p.x - last.x) + Math.abs(p.y - last.y);
544
+ apply();
545
+ }
546
+ };
547
+ const onUp = (e) => {
548
+ points.delete(e.pointerId);
549
+ pinch = points.size >= 2 ? pinchState() : null;
550
+ if (points.size === 0) host.removeAttribute("data-dragging");
551
+ };
552
+ const onClick = (e) => {
553
+ if (moved > 4 && !bar.contains(e.target)) {
554
+ e.preventDefault();
555
+ e.stopPropagation();
556
+ }
557
+ };
558
+ const onDblClick = (e) => {
559
+ if (bar.contains(e.target)) return;
560
+ e.preventDefault();
561
+ if (s >= max - .001) reset();
562
+ else zoom(2, local(e), true);
563
+ };
564
+ const onKey = (e) => {
565
+ if (e.target !== host || e.altKey || e.ctrlKey || e.metaKey) return;
566
+ const step = 60;
567
+ const moves = {
568
+ ArrowLeft: [step, 0],
569
+ ArrowRight: [-60, 0],
570
+ ArrowUp: [0, step],
571
+ ArrowDown: [0, -60]
572
+ };
573
+ if (e.key === "+" || e.key === "=") zoom(1.5, void 0, true);
574
+ else if (e.key === "-" || e.key === "_") zoom(1 / 1.5, void 0, true);
575
+ else if (e.key === "0") reset();
576
+ else if (moves[e.key] && s > 1.001) {
577
+ const ox = x;
578
+ const oy = y;
579
+ x += moves[e.key][0];
580
+ y += moves[e.key][1];
581
+ apply(true);
582
+ if (x === ox && y === oy) return;
583
+ } else return;
584
+ e.preventDefault();
585
+ };
586
+ const onDragStart = (e) => e.preventDefault();
587
+ const off = new AbortController();
588
+ const signal = off.signal;
589
+ host.addEventListener("wheel", onWheel, {
590
+ passive: false,
591
+ signal
592
+ });
593
+ host.addEventListener("pointerdown", onDown, { signal });
594
+ host.addEventListener("pointermove", onMove, { signal });
595
+ host.addEventListener("pointerup", onUp, { signal });
596
+ host.addEventListener("pointercancel", onUp, { signal });
597
+ host.addEventListener("click", onClick, {
598
+ capture: true,
599
+ signal
600
+ });
601
+ host.addEventListener("dblclick", onDblClick, { signal });
602
+ host.addEventListener("keydown", onKey, { signal });
603
+ host.addEventListener("dragstart", onDragStart, { signal });
604
+ doc.addEventListener("fullscreenchange", () => reset(false), { signal });
605
+ const resize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => apply());
606
+ resize?.observe(host);
607
+ apply();
608
+ const api = {
609
+ get scale() {
610
+ return s;
611
+ },
612
+ zoom: (factor, at) => zoom(factor, at, true),
613
+ reset: () => reset(),
614
+ destroy() {
615
+ off.abort();
616
+ resize?.disconnect();
617
+ win.clearTimeout(hintTimer);
618
+ bar.remove();
619
+ hint.remove();
620
+ if (stage.parentNode === host) {
621
+ host.append(...stage.childNodes);
622
+ stage.remove();
623
+ }
624
+ host.classList.remove("yuhwa-zoom", "yuhwa-zoom-fixed");
625
+ host.removeAttribute("data-zoomed");
626
+ host.removeAttribute("data-dragging");
627
+ host.style.height = oldHeight;
628
+ if (addedTabIndex) host.removeAttribute("tabindex");
629
+ delete host.yuhwaZoom;
630
+ }
631
+ };
632
+ host.yuhwaZoom = api;
633
+ return api;
634
+ }
635
+ /**
636
+ * The `height` of a `zoom` flag or attribute: empty means the diagram's own
637
+ * height, a bare number means pixels, anything else is a CSS length.
638
+ */
639
+ function zoomHeight(value) {
640
+ const v = value?.trim();
641
+ if (!v || v === "true") return void 0;
642
+ return /^\d+(\.\d+)?$/.test(v) ? `${v}px` : v;
643
+ }
644
+ // src/cli/blocks.ts
645
+ /**
646
+ * Finds the diagrams in a Markdown page for `yuhwa check` and `yuhwa render`:
647
+ * fenced blocks in one of `languages` and the `<!--yuhwa name … -->` comments
648
+ * that `yuhwa md` writes. Fences in other languages are skipped whole, so a
649
+ * ```markdown fence that shows a yuhwa block is not checked.
650
+ */
651
+ /** fence languages read by default; `--lang` overrides them */
652
+ const MD_LANGUAGES = ["yuhwa", "yu"];
653
+ const isMarkdown = (file) => /\.(md|mdx|markdown)$/i.test(file);
654
+ const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)(.*)$/;
655
+ function pageBlocks(md, languages = MD_LANGUAGES) {
656
+ const lines = md.split("\n");
657
+ const blocks = [];
658
+ for (let i = 0; i < lines.length; i++) {
659
+ const line = lines[i].replace(/\r$/, "");
660
+ let close;
661
+ let lang;
662
+ let meta = "";
663
+ let m = line.match(FENCE);
664
+ if (m) {
665
+ const fence = m[1];
666
+ const closer = new RegExp(`^ {0,3}${fence[0]}{${fence.length},}\\s*$`);
667
+ close = (l) => closer.test(l);
668
+ lang = m[2];
669
+ meta = m[3].trim();
670
+ } else if (m = line.match(COMMENT_OPEN)) {
671
+ close = (l) => l.trim() === "-->";
672
+ lang = "comment";
673
+ meta = m[1] ?? "";
674
+ } else continue;
675
+ let j = i + 1;
676
+ while (j < lines.length && !close(lines[j].replace(/\r$/, ""))) j++;
677
+ if (j >= lines.length) break;
678
+ if (lang === "comment" || languages.includes(lang) && !/(^|\s)no-render(\s|$)/.test(meta)) {
679
+ const name = meta.split(/\s+/).find((w) => w && w !== "no-code");
680
+ blocks.push({
681
+ index: blocks.length,
682
+ lang,
683
+ ...name ? { name } : {},
684
+ line: i + 1,
685
+ source: lines.slice(i + 1, j).join("\n")
686
+ });
687
+ }
688
+ i = j;
689
+ }
690
+ return blocks;
691
+ }
692
+ /** parses `--lang yuhwa,yu` */
693
+ function parseLanguages(v) {
694
+ if (typeof v !== "string") return MD_LANGUAGES;
695
+ const langs = v.split(",").map((s) => s.trim()).filter(Boolean);
696
+ if (!langs.length) throw new Error("--lang: give at least one fence language, e.g. --lang yuhwa,yu");
697
+ return langs;
698
+ }
699
+ // src/cli/view.ts
700
+ /**
701
+ * A standalone HTML page that shows one diagram in a full-window pan and zoom
702
+ * viewer: the SVG and the viewer script inline, nothing to load. Written by
703
+ * `yuhwa render -o x.html` and served by `yuhwa serve` under `/view`.
704
+ */
705
+ /** the viewer script, stringified once */
706
+ const SCRIPT = `(${zoomable})(document.getElementById('diagram'), { height: '100%', wheel: true });`;
707
+ function viewerPage(svg, opts = {}) {
708
+ const title = esc(opts.title ?? "diagram");
709
+ const bg = opts.background && isSafeCss(opts.background) ? opts.background : "#ffffff";
710
+ return `<!doctype html>
711
+ <html lang="en">
712
+ <head>
713
+ <meta charset="utf-8">
714
+ <meta name="viewport" content="width=device-width, initial-scale=1">
715
+ <title>${title}</title>
716
+ <style>html,body{margin:0;height:100%;background:${bg}}#diagram{height:100%;--yuhwa-zoom-bg:${bg}}</style>
717
+ </head>
718
+ <body>
719
+ <div id="diagram" role="group" aria-label="${title}">
720
+ ${svg}
721
+ </div>
722
+ <script${opts.nonce ? ` nonce="${esc(opts.nonce)}"` : ""}>${SCRIPT}<\/script>
723
+ </body>
724
+ </html>
725
+ `;
726
+ }
351
727
  // src/cli/server.ts
352
728
  /**
353
729
  * HTTP render service. Any tool that can show an image URL can show a diagram:
@@ -355,6 +731,8 @@ defined once as a class. 5 to 20 nodes read best; split larger systems.
355
731
  * GET /svg?src=<urlencoded source>[&theme=midnight]
356
732
  * GET /svg/<base64url source>[.svg]
357
733
  * GET /yuhwa/svg/<deflate + base64url source> (Kroki-compatible)
734
+ * GET /view?src=…, /view/<base64url>, /yuhwa/view/<deflate + base64url>
735
+ * the same as a page with pan and zoom
358
736
  * POST /svg body: source (yuhwa, Mermaid or JSON)
359
737
  * POST /check body: source → { ok, format, diagnostics }
360
738
  * GET /llms.txt language reference for AI tools
@@ -365,6 +743,13 @@ const MAX_BODY = 1 << 20;
365
743
  function encodeSource(source) {
366
744
  return deflateSync(Buffer.from(source, "utf8"), { level: 9 }).toString("base64url");
367
745
  }
746
+ /** the hosted viewer: a static page that decodes the hash, so it needs no server */
747
+ const VIEWER = "https://ph1p.github.io/yuhwa/view/";
748
+ /** a link to a page that pans and zooms `source`: your `yuhwa serve` at `base`, else the hosted viewer */
749
+ function viewUrl(source, base) {
750
+ const enc = encodeSource(source);
751
+ return base ? `${base.replace(/\/$/, "")}/yuhwa/view/${enc}` : `${VIEWER}#z=${enc}`;
752
+ }
368
753
  function decodeSource(encoded, compressed) {
369
754
  const buf = Buffer.from(encoded.replace(/\.svg$/, ""), "base64url");
370
755
  if (!compressed) return buf.toString("utf8");
@@ -405,7 +790,8 @@ const HOME = (origin) => `<!doctype html><meta charset="utf-8"><title>yuhwa rend
405
790
  <ul>
406
791
  <li><code>GET /svg?src=…&amp;theme=…</code> URL-encoded source</li>
407
792
  <li><code>GET /svg/&lt;base64url&gt;</code> base64url source</li>
408
- <li><code>GET /yuhwa/svg/&lt;deflate+base64url&gt;</code> Kroki-compatible; <code>yuhwa url file.yuhwa</code> prints one</li>
793
+ <li><code>GET /yuhwa/svg/&lt;deflate+base64url&gt;</code> Kroki-compatible; <code>yuhwa url file.yu</code> prints one</li>
794
+ <li><code>GET /view?src=…</code>, <code>/view/&lt;base64url&gt;</code>, <code>/yuhwa/view/&lt;deflate+base64url&gt;</code> the same diagram as a page you can pan and zoom; <code>yuhwa url --view --base …</code> prints one</li>
409
795
  <li><code>POST /svg</code> source as body</li>
410
796
  <li><code>POST /check</code> JSON diagnostics</li>
411
797
  <li><code>GET /llms.txt</code> language reference for AI tools</li>
@@ -430,6 +816,19 @@ function handler(req, res) {
430
816
  if (cache && !errors.length) res.setHeader("cache-control", "public, max-age=31536000, immutable");
431
817
  res.end(r.svg);
432
818
  };
819
+ const sendView = (source) => {
820
+ const r = render$1(source, { theme });
821
+ const nonce = randomBytes(16).toString("base64");
822
+ res.setHeader("content-type", "text/html; charset=utf-8");
823
+ res.setHeader("content-security-policy", `default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'nonce-${nonce}'`);
824
+ res.setHeader("x-content-type-options", "nosniff");
825
+ res.setHeader("x-yuhwa-format", r.format);
826
+ res.end(viewerPage(r.svg, {
827
+ title: r.diagram.settings.title ?? "yuhwa diagram",
828
+ nonce,
829
+ background: r.layout.theme.background
830
+ }));
831
+ };
433
832
  const sendJson = (status, body) => {
434
833
  res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body, null, 2));
435
834
  };
@@ -447,6 +846,14 @@ function handler(req, res) {
447
846
  if (m) return sendSvg(decodeSource(m[1], false), true);
448
847
  m = path.match(/^\/yuhwa\/svg\/([\w-]+)$/);
449
848
  if (m) return sendSvg(decodeSource(m[1], true), true);
849
+ if (path === "/view") {
850
+ const src = url.searchParams.get("src");
851
+ return src === null ? fail(400, "missing ?src=") : sendView(src);
852
+ }
853
+ m = path.match(/^\/view\/([\w-]+)$/);
854
+ if (m) return sendView(decodeSource(m[1], false));
855
+ m = path.match(/^\/yuhwa\/view\/([\w-]+)$/);
856
+ if (m) return sendView(decodeSource(m[1], true));
450
857
  }
451
858
  if (req.method === "POST" && [
452
859
  "/svg",
@@ -463,7 +870,10 @@ function handler(req, res) {
463
870
  format: r.format,
464
871
  diagnostics: r.diagnostics
465
872
  });
466
- }, (e) => fail(e.status ?? 400, e.message));
873
+ }).catch((e) => {
874
+ if (!res.headersSent) fail(e.status ?? 400, e.message);
875
+ else res.end();
876
+ });
467
877
  return;
468
878
  }
469
879
  fail(404, `not found: ${req.method} ${path} (see GET /)`);
@@ -532,7 +942,8 @@ function saveEditorFiles(file, mainName, block, loaded, update) {
532
942
  * custom element:
533
943
  *
534
944
  * <yuhwa-diagram theme="midnight">a -> b -> c</yuhwa-diagram>
535
- * <yuhwa-diagram src="docs/arch.yuhwa"></yuhwa-diagram>
945
+ * <yuhwa-diagram src="docs/arch.yu"></yuhwa-diagram>
946
+ * <yuhwa-diagram src="big.yu" zoom="480px"></yuhwa-diagram> // pan and zoom
536
947
  * el.source = 'a -> b' // re-renders
537
948
  */
538
949
  const SELECTOR = "pre > code.language-yuhwa, pre > code.lang-yuhwa, pre.yuhwa, div.yuhwa:not([data-rendered])";
@@ -555,7 +966,7 @@ const IMPORT_RE = /^\s*import\s+(?:\{[^}]*\}\s*from\s+)?"([^"]+)"/gm;
555
966
  /**
556
967
  * Fetches every file that `source` imports, and what those import, so
557
968
  * `render` can resolve them synchronously. Paths join against `file` (a URL
558
- * path such as `/docs/arch.yuhwa`); a file that fails to load is left out and
969
+ * path such as `/docs/arch.yu`); a file that fails to load is left out and
559
970
  * shows up as a diagnostic on its import line.
560
971
  */
561
972
  async function fetchImports(source, file, load = fetchText) {
@@ -592,6 +1003,7 @@ function run(root = document, opts = {}) {
592
1003
  out.className = "yuhwa";
593
1004
  out.dataset.rendered = "true";
594
1005
  out.dataset.source = source;
1006
+ let ok = false;
595
1007
  try {
596
1008
  const r = render(source, {
597
1009
  theme: host.dataset.theme,
@@ -600,17 +1012,28 @@ function run(root = document, opts = {}) {
600
1012
  out.innerHTML = r.svg;
601
1013
  fit(out.querySelector("svg"));
602
1014
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
1015
+ ok = true;
603
1016
  } catch (e) {
604
1017
  out.textContent = `yuhwa error: ${e.message}`;
605
1018
  out.style.color = "crimson";
606
1019
  }
607
1020
  host.replaceWith(out);
1021
+ if (ok && host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
608
1022
  });
609
1023
  }
610
1024
  const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
611
- /** <yuhwa-diagram [theme] [src]>source</yuhwa-diagram>; fires `yuhwa:render` with the diagnostics */
1025
+ /**
1026
+ * <yuhwa-diagram [theme] [src] [zoom[=height]] [wheel]>source</yuhwa-diagram>;
1027
+ * fires `yuhwa:render` with the diagnostics. `zoom` makes it a pan and zoom
1028
+ * viewer, `wheel` lets the plain mouse wheel zoom it.
1029
+ */
612
1030
  var YuhwaDiagram = class extends Base {
613
- static observedAttributes = ["theme", "src"];
1031
+ static observedAttributes = [
1032
+ "theme",
1033
+ "src",
1034
+ "zoom",
1035
+ "wheel"
1036
+ ];
614
1037
  #source = null;
615
1038
  #fetched = null;
616
1039
  #request = 0;
@@ -660,9 +1083,15 @@ var YuhwaDiagram = class extends Base {
660
1083
  file: this.#file,
661
1084
  resolve: (p) => files[p]
662
1085
  });
1086
+ this.yuhwaZoom?.destroy();
663
1087
  this.innerHTML = r.svg;
664
1088
  fit(this.querySelector("svg"));
665
- this.setAttribute("role", "img");
1089
+ const zoom = this.getAttribute("zoom");
1090
+ this.setAttribute("role", zoom === null ? "img" : "group");
1091
+ if (zoom !== null) zoomable(this, {
1092
+ height: zoomHeight(zoom),
1093
+ wheel: this.hasAttribute("wheel")
1094
+ });
666
1095
  if (!this.hasAttribute("aria-label") || this.dataset.autoLabel) {
667
1096
  const t = r.diagram.settings.title;
668
1097
  if (t) this.setAttribute("aria-label", t), this.dataset.autoLabel = "1";
@@ -693,13 +1122,14 @@ if (typeof document !== "undefined") {
693
1122
  const HELP = `yuhwa — diagrams that look good and stay where you put them
694
1123
 
695
1124
  Usage
696
- yuhwa render <file|-> [-o out.svg] [--theme name]
697
- yuhwa check <file|-...> [--json]
698
- yuhwa convert <file.mmd|file.json|-> [-o out.yuhwa]
699
- yuhwa md <file.md...> [--out-dir diagrams] [--dark] [--keep-fences]
700
- yuhwa edit <file.yuhwa|file.md> [--block n] [--port 4747] [--no-open]
1125
+ yuhwa render <file|-> [-o out.svg|out.html] [--html] [--theme name] [--block n]
1126
+ yuhwa check <file|-...> [--json] [--lang yuhwa,yu]
1127
+ yuhwa lint <file...> [--fix] [--json] [--lang yuhwa,yu]
1128
+ yuhwa convert <file.mmd|file.json|-> [-o out.yu]
1129
+ yuhwa md <file.md...> [--out-dir diagrams] [--dark] [--keep-fences] [--view[=base]]
1130
+ yuhwa edit <file.yu|file.md> [--block n] [--port 4747] [--no-open]
701
1131
  yuhwa serve [--port 4749] [--host 127.0.0.1]
702
- yuhwa url <file|-> [--base http://localhost:4749]
1132
+ yuhwa url <file|-> [--base http://localhost:4749] [--view]
703
1133
  yuhwa <file> same as yuhwa render <file>
704
1134
  yuhwa guide language reference for AI tools (alias: llms)
705
1135
  yuhwa themes
@@ -708,15 +1138,27 @@ Usage
708
1138
 
709
1139
  Input can be yuhwa, a Mermaid flowchart or JSON; the format is detected.
710
1140
 
711
- render Render one diagram to SVG (stdout unless -o is given).
1141
+ render Render one diagram to SVG (stdout unless -o is given). From a
1142
+ Markdown file it renders block --block n (from 0, default 0).
1143
+ -o x.html or --html writes a page that pans and zooms instead.
712
1144
  check Validate without rendering. --json prints machine-readable diagnostics.
1145
+ A .md/.mdx/.markdown file is checked block by block: every
1146
+ \`\`\`yuhwa and \`\`\`yu fence (--lang picks others) and every
1147
+ <!--yuhwa --> comment, with line numbers in the Markdown file.
1148
+ lint Everything check reports, plus unused classes, variables and
1149
+ components, edges drawn twice and unformatted files. Fails on any
1150
+ finding, warnings included. --fix formats .yu files in place.
713
1151
  convert Turn a Mermaid flowchart or JSON diagram into yuhwa source.
714
1152
  md Render every yuhwa block in Markdown files, write the SVGs and
715
- insert or update the image reference below each block.
1153
+ insert or update the image reference below each block. --view
1154
+ links each image to a page that pans and zooms it (the hosted
1155
+ viewer, or --view=<base> for your own \`serve\`).
716
1156
  edit Open the visual editor in your browser. Drag boxes, bend edges,
717
1157
  move labels; saving writes the layout back into your file.
718
1158
  serve HTTP render service: <img src="http://host/svg?src=..."> anywhere.
719
1159
  url Print an embeddable image URL for a diagram (for \`serve\`).
1160
+ --view prints a link to a page that pans and zooms it instead:
1161
+ the hosted viewer, or your \`serve\` with --base.
720
1162
  guide Print the language reference (same as llms.txt). AI agents: read
721
1163
  this first, then write source and run \`check --json\` until it is clean.
722
1164
  `;
@@ -737,7 +1179,8 @@ function parseArgs(argv) {
737
1179
  "block",
738
1180
  "port",
739
1181
  "host",
740
- "base"
1182
+ "base",
1183
+ "lang"
741
1184
  ].includes(k)) a[k] = argv[++i];
742
1185
  else a[k] = true;
743
1186
  } else a._.push(s);
@@ -751,12 +1194,22 @@ function printDiagnostics(file, ds, prefix = "") {
751
1194
  function cmdRender(a) {
752
1195
  const file = a._[1];
753
1196
  if (!file) throw new Error("render: missing input file");
754
- const r = render$1(readInput(file), {
755
- theme: str(a.theme),
756
- ...fileOpts(file)
757
- });
758
- printDiagnostics(file, r.diagnostics);
759
- writeOut(str(a.out), r.svg + "\n");
1197
+ let source = readInput(file);
1198
+ let at = 0;
1199
+ if (isMarkdown(file)) {
1200
+ const blocks = blocksOf(a, file, source);
1201
+ const n = Number(str(a.block) ?? 0);
1202
+ const b = blocks[n];
1203
+ if (!b) throw new Error(blocks.length ? `${file} has no yuhwa block #${n} (it has ${blocks.length})` : `${file} has no yuhwa blocks`);
1204
+ ({source, line: at} = b);
1205
+ }
1206
+ const r = renderAs(a, file, source);
1207
+ printDiagnostics(file, shiftLines(r.diagnostics, at));
1208
+ const out = str(a.out);
1209
+ writeOut(out, !!a.html || /\.html?$/i.test(out ?? "") ? viewerPage(r.svg, {
1210
+ title: r.diagram.settings.title ?? basename(file),
1211
+ background: r.layout.theme.background
1212
+ }) : r.svg + "\n");
760
1213
  if (r.diagnostics.some((d) => d.severity === "error")) process.exitCode = 1;
761
1214
  }
762
1215
  const fileOpts = (file) => ({
@@ -770,14 +1223,74 @@ function writeOut(out, text) {
770
1223
  writeFileSync(out, text);
771
1224
  process.stderr.write(`wrote ${out}\n`);
772
1225
  }
773
- function cmdCheck(a) {
774
- const files = a._.slice(1);
775
- if (!files.length) throw new Error("check: missing input file");
776
- const reports = files.map((file) => {
777
- const r = render$1(readInput(file), {
778
- theme: str(a.theme),
779
- ...fileOpts(file)
1226
+ /** block diagnostics carry block lines; `at` is the opening fence's page line */
1227
+ const shiftLines = (ds, at) => at ? ds.map((d) => ({
1228
+ ...d,
1229
+ line: at + Math.max(d.line, 1)
1230
+ })) : ds;
1231
+ /** render with the command's `--theme` and the file's import resolver */
1232
+ const renderAs = (a, file, source) => render$1(source, {
1233
+ theme: str(a.theme),
1234
+ ...fileOpts(file)
1235
+ });
1236
+ /** the yuhwa blocks of a Markdown page, honouring `--lang` */
1237
+ const blocksOf = (a, file, source = readInput(file)) => pageBlocks(source, parseLanguages(a.lang));
1238
+ /** `check` on a Markdown page: one report for the page, one entry per block */
1239
+ function checkPage(file, a) {
1240
+ const blocks = blocksOf(a, file);
1241
+ const diagnostics = [];
1242
+ const counts = {
1243
+ nodes: 0,
1244
+ edges: 0,
1245
+ groups: 0
1246
+ };
1247
+ const entries = blocks.map((b) => {
1248
+ const r = renderAs(a, file, b.source);
1249
+ for (const d of shiftLines(r.diagnostics, b.line)) diagnostics.push({
1250
+ ...d,
1251
+ block: b.index
780
1252
  });
1253
+ const { nodes, edges, groups } = r.diagram;
1254
+ counts.nodes += nodes.size;
1255
+ counts.edges += edges.length;
1256
+ counts.groups += groups.size;
1257
+ const { source: _, ...where } = b;
1258
+ return {
1259
+ ...where,
1260
+ ok: !r.diagnostics.some((d) => d.severity === "error"),
1261
+ format: r.format,
1262
+ nodes: nodes.size,
1263
+ edges: edges.length,
1264
+ groups: groups.size
1265
+ };
1266
+ });
1267
+ const ok = entries.every((e) => e.ok);
1268
+ if (!ok) process.exitCode = 1;
1269
+ if (!a.json) {
1270
+ printDiagnostics(file, diagnostics);
1271
+ process.stderr.write(blocks.length ? `${file}: ${ok ? "ok" : "errors"} (markdown, ${blocks.length} block(s), ${diagnostics.length} diagnostic(s))\n` : `${file}: ok (markdown, no yuhwa blocks found)\n`);
1272
+ }
1273
+ return {
1274
+ file,
1275
+ ok,
1276
+ format: "markdown",
1277
+ ...counts,
1278
+ diagnostics,
1279
+ blocks: entries,
1280
+ ...blocks.length ? {} : { note: "no yuhwa blocks found" }
1281
+ };
1282
+ }
1283
+ /** run `one` per input file; `--json` prints one report, or an array for several files */
1284
+ function perFile(a, cmd, one) {
1285
+ const files = a._.slice(1);
1286
+ if (!files.length) throw new Error(`${cmd}: missing input file`);
1287
+ const reports = files.map(one);
1288
+ if (a.json) process.stdout.write(JSON.stringify(reports.length === 1 ? reports[0] : reports, null, 2) + "\n");
1289
+ }
1290
+ function cmdCheck(a) {
1291
+ perFile(a, "check", (file) => {
1292
+ if (isMarkdown(file)) return checkPage(file, a);
1293
+ const r = renderAs(a, file, readInput(file));
781
1294
  const ok = !r.diagnostics.some((d) => d.severity === "error");
782
1295
  if (!ok) process.exitCode = 1;
783
1296
  const { nodes, edges, groups } = r.diagram;
@@ -795,7 +1308,48 @@ function cmdCheck(a) {
795
1308
  diagnostics: r.diagnostics
796
1309
  };
797
1310
  });
798
- if (a.json) process.stdout.write(JSON.stringify(reports.length === 1 ? reports[0] : reports, null, 2) + "\n");
1311
+ }
1312
+ /** `check` plus hygiene and formatting; exit code 1 on any finding */
1313
+ function cmdLint(a) {
1314
+ const lintOne = (source, file, at = 0) => {
1315
+ const r = renderAs(a, file, source);
1316
+ return shiftLines([...r.diagnostics, ...r.format === "yuhwa" ? tidy(source, r.diagram) : []], at);
1317
+ };
1318
+ perFile(a, "lint", (file) => {
1319
+ let diagnostics;
1320
+ let fixed = false;
1321
+ if (isMarkdown(file)) diagnostics = blocksOf(a, file).flatMap((b) => lintOne(b.source, file, b.line).map((d) => ({
1322
+ ...d,
1323
+ block: b.index
1324
+ })));
1325
+ else {
1326
+ const source = readInput(file);
1327
+ diagnostics = lintOne(source, file);
1328
+ const formatted = format(source);
1329
+ if (formatted !== source) {
1330
+ if (a.fix && file !== "-") {
1331
+ writeFileSync(file, formatted);
1332
+ fixed = true;
1333
+ } else diagnostics.push({
1334
+ line: 1,
1335
+ message: "Not formatted: run yuhwa lint --fix",
1336
+ severity: "warning"
1337
+ });
1338
+ }
1339
+ }
1340
+ diagnostics.sort((x, y) => x.line - y.line);
1341
+ if (diagnostics.length) process.exitCode = 1;
1342
+ if (!a.json) {
1343
+ printDiagnostics(file, diagnostics);
1344
+ process.stderr.write(`${file}: ${diagnostics.length ? `${diagnostics.length} finding(s)` : "clean"}${fixed ? ", formatted" : ""}\n`);
1345
+ }
1346
+ return {
1347
+ file,
1348
+ ok: !diagnostics.length,
1349
+ ...fixed ? { fixed } : {},
1350
+ diagnostics
1351
+ };
1352
+ });
799
1353
  }
800
1354
  function cmdConvert(a) {
801
1355
  const file = a._[1];
@@ -808,8 +1362,10 @@ function cmdConvert(a) {
808
1362
  function cmdUrl(a) {
809
1363
  const file = a._[1];
810
1364
  if (!file) throw new Error("url: missing input file");
1365
+ const source = readInput(file);
1366
+ if (a.view) return void process.stdout.write(`${viewUrl(source, str(a.base))}\n`);
811
1367
  const base = (str(a.base) ?? "http://localhost:4749").replace(/\/$/, "");
812
- process.stdout.write(`${base}/yuhwa/svg/${encodeSource(readInput(file))}\n`);
1368
+ process.stdout.write(`${base}/yuhwa/svg/${encodeSource(source)}\n`);
813
1369
  }
814
1370
  function cmdMd(a) {
815
1371
  const files = a._.slice(1);
@@ -821,6 +1377,7 @@ function cmdMd(a) {
821
1377
  baseName: basename(file, extname(file)).toLowerCase(),
822
1378
  dark: !!a.dark,
823
1379
  keepFences: !!a["keep-fences"],
1380
+ view: a.view ? (src) => viewUrl(src, str(a.view)) : void 0,
824
1381
  ...fileOpts(file)
825
1382
  });
826
1383
  for (const d of res.diagnostics) process.stderr.write(`${file} [${d.block}]:${d.line}: ${d.severity}: ${d.message}\n`);
@@ -856,7 +1413,7 @@ function openBrowser(url) {
856
1413
  function cmdEdit(a) {
857
1414
  const file = a._[1];
858
1415
  if (!file) throw new Error("edit: missing file");
859
- const isMd = /\.(md|markdown|mdx)$/i.test(file);
1416
+ const isMd = isMarkdown(file);
860
1417
  if (!existsSync(file)) {
861
1418
  if (isMd) throw new Error(`${file} does not exist`);
862
1419
  writeFileSync(file, "direction: right\n\nhello \"Hello\" -> world \"World\"\n");
@@ -942,6 +1499,7 @@ function main() {
942
1499
  else if (cmd === "md") cmdMd(a);
943
1500
  else if (cmd === "edit") cmdEdit(a);
944
1501
  else if (cmd === "check") cmdCheck(a);
1502
+ else if (cmd === "lint") cmdLint(a);
945
1503
  else if (cmd === "convert") cmdConvert(a);
946
1504
  else if (cmd === "url") cmdUrl(a);
947
1505
  else if (cmd === "serve") serve(Number(str(a.port) ?? 4749), str(a.host) ?? "127.0.0.1");