yuhwa 1.3.0 → 1.4.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 (57) hide show
  1. package/README.md +5 -3
  2. package/dist/astro.d.ts +1 -1
  3. package/dist/astro.js +4 -3
  4. package/dist/browser.d.ts +10 -4
  5. package/dist/browser.js +85 -22
  6. package/dist/canvas.d.ts +2 -0
  7. package/dist/canvas.js +40 -0
  8. package/dist/cli.js +485 -236
  9. package/dist/editor/assets/index-DWm3xV_v.js +689 -0
  10. package/dist/editor/assets/{lsp.worker-CMSpDTsX.js → lsp.worker-N6A9m364.js} +23 -17
  11. package/dist/editor/index.html +4 -1
  12. package/dist/{figure-QAwSU1Ry.d.ts → figure-BLHfxz_e.d.ts} +28 -5
  13. package/dist/{index-6ZPJGThY.d.ts → index-xVW43gqW.d.ts} +48 -3
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.js +5 -3
  16. package/dist/ironmark.d.ts +1 -1
  17. package/dist/ironmark.js +1 -1
  18. package/dist/lsp-browser.d.ts +2 -2
  19. package/dist/lsp-browser.js +2 -1
  20. package/dist/lsp-node.js +46 -26
  21. package/dist/lsp-server.d.ts +5 -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 +1 -1
  26. package/dist/markdown-it.js +5 -3
  27. package/dist/{node-CLu2Pp_2.js → node-CkrQnPFb.js} +90 -13
  28. package/dist/{plugin-Bs4eiAuz.js → parse--ljBMU60.js} +25 -307
  29. package/dist/plugin-CitzbblK.js +301 -0
  30. package/dist/{plugin-NSkNyoUj.d.ts → plugin-NMP_uf1a.d.ts} +15 -1
  31. package/dist/plugin.d.ts +1 -1
  32. package/dist/plugin.js +3 -1
  33. package/dist/raster-iqi6XRPU.js +299 -0
  34. package/dist/remark.d.ts +1 -1
  35. package/dist/remark.js +1 -1
  36. package/dist/rolldown-runtime-CEjnN5Q1.js +37 -0
  37. package/dist/{server-D6BSNC1P.js → server-BTYtmr6B.js} +41 -63
  38. package/dist/{server--jHjJjOS.d.ts → server-DMAOtqqK.d.ts} +1 -1
  39. package/dist/{service-D7DNWBAU.js → service-C60VdeKS.js} +34 -3
  40. package/dist/{service-Brvpt7Do.d.ts → service-DimTFsE3.d.ts} +2 -0
  41. package/dist/{shared-6aCU_HaV.js → shared-h8tkFLY4.js} +231 -21
  42. package/dist/{src-BjOhvTAB.js → src-NCXCTK_4.js} +81 -45
  43. package/dist/svg-uri-Dx8SGV-n.js +7 -0
  44. package/dist/vite.d.ts +1 -1
  45. package/dist/vite.js +3 -3
  46. package/dist/vuepress.d.ts +3 -2
  47. package/dist/vuepress.js +4 -2
  48. package/dist/watch-2VeW5DUN.js +35 -0
  49. package/dist/yuhwa.iife.js +55 -54
  50. package/dist/zoom-script-CaJ5MNUw.js +29 -0
  51. package/dist/{zoom-QeqB6QlH.js → zoom-yxhxX16c.js} +1 -1
  52. package/dist/zoom.d.ts +16 -7
  53. package/dist/zoom.js +2 -2
  54. package/package.json +19 -2
  55. package/skills/yuhwa/SKILL.md +12 -0
  56. package/dist/editor/assets/index-DAk6b1UB.js +0 -689
  57. package/dist/zoom-script-CVdAzMhX.js +0 -51
package/dist/cli.js CHANGED
@@ -1,154 +1,317 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
- import { C as COLORS, D as NODE_PROPS, E as GROUP_PROPS, I as THEME_KEYS, L as THEME_NAMES, N as esc, R as TONES, T as ENUMS, _ as isYuhwaPath, c as render$1, d as optionKind, f as registry, h as SETTING_VALUES, i as format, j as SHAPES, k as PANEL_PROPS, l as toSource, o as tidy, p as KNOWN_SETTINGS, s as diskResolve, t as VERSION, u as canvasMeasure, v as joinPath$1, w as EDGE_PROPS, z as isSafeCss } from "./shared-6aCU_HaV.js";
3
+ import { F as NODE_PROPS, G as THEME_NAMES, K as TONES, L as PANEL_PROPS, M as EDGE_PROPS, N as ENUMS, P as GROUP_PROPS, S as SETTING_VALUES, T as joinPath, V as esc, W as THEME_KEYS, _ as canvasMeasure, a as formatPage, b as KNOWN_SETTINGS, c as diskResolve, d as MD_LANGUAGES, f as findBlocks, g as replaceBlockSource, h as processMarkdown, i as format, j as COLORS, k as unquote, l as render$1, m as pageBlocks, p as isMarkdown, q as isSafeCss, s as tidy, t as VERSION, u as toSource, v as optionKind, w as isYuhwaPath, y as registry, z as SHAPES } from "./shared-h8tkFLY4.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
8
  import { randomBytes } from "node:crypto";
9
9
  import { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
10
- // src/markdown.ts
10
+ // src/raster.ts
11
11
  /**
12
- * Markdown integration.
12
+ * Drawing a rendered SVG into a canvas. No side effects on import, so the
13
+ * editor and other apps can take it from `yuhwa` without the browser runtime.
13
14
  *
14
- * Diagrams live in Markdown as HTML comments, so the source stays next to the
15
- * docs but is invisible when rendered:
16
- *
17
- * <!--yuhwa checkout
18
- * a -> b
19
- * -->
20
- * ![checkout](diagrams/checkout.svg)
21
- *
22
- * Fenced ```yuhwa blocks are converted to that form on the first run.
23
- * The image line right after a block is inserted or kept up to date.
15
+ * A browser loads an SVG image in isolation: it cannot use the page's web
16
+ * fonts. `svgToCanvas` therefore embeds the fonts the diagram names, as
17
+ * `data:` URLs in an `@font-face` rule inside the SVG, before drawing it.
24
18
  */
25
- const COMMENT_OPEN = /^<!--\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
26
- const FENCE_OPEN = /^(```+|~~~+)\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
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;
19
+ /** natural size of a rendered SVG: its width and height, else its viewBox */
20
+ function svgSize(svg) {
21
+ const root = svg.match(/<svg\b[^>]*>/)?.[0] ?? "";
22
+ const attr = (name) => Number(root.match(new RegExp(`\\s${name}="([\\d.]+)"`))?.[1]);
23
+ const box = root.match(/\sviewBox="([^"]+)"/)?.[1].trim().split(/[\s,]+/).map(Number) ?? [];
24
+ const width = attr("width") || box[2] || 300;
25
+ return {
26
+ width,
27
+ height: attr("height") || (box[2] && box[3] ? width * box[3] / box[2] : 150)
28
+ };
29
+ }
30
+ const decode = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([\da-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))).replace(/&amp;/g, "&");
31
+ /** the values of a presentation attribute or CSS property across the SVG, decoded and trimmed */
32
+ function svgProp(svg, name) {
33
+ return [...svg.matchAll(new RegExp(`${name}(?:="([^"]*)"|\\s*:\\s*([^;"}]+))`, "g"))].map((m) => decode(m[1] ?? m[2]).trim());
34
+ }
35
+ /** lower-cased family names the SVG asks for, from font-family attributes and styles */
36
+ function svgFamilies(svg) {
37
+ const out = /* @__PURE__ */ new Set();
38
+ for (const v of svgProp(svg, "font-family")) for (const f of v.split(",")) out.add(unquote(f).toLowerCase());
39
+ return out;
40
+ }
41
+ const WEIGHT_WORDS = {
42
+ normal: 400,
43
+ bold: 700
44
+ };
45
+ function fontUsage(svg) {
46
+ const chars = /* @__PURE__ */ new Set();
47
+ const text = svg.replace(/<style\b[^>]*>[\s\S]*?<\/style>/g, "").match(/>[^<]+</g) ?? [];
48
+ for (const t of text) for (const ch of decode(t.slice(1, -1))) chars.add(ch.codePointAt(0));
49
+ const weights = /* @__PURE__ */ new Set([400]);
50
+ for (const v of svgProp(svg, "font-weight")) {
51
+ const w = WEIGHT_WORDS[v] ?? Number(v);
52
+ if (w > 0) weights.add(w);
31
53
  }
32
- return href ? `[![${name}](${lightPath})](${href})` : `![${name}](${lightPath})`;
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;
36
- function findBlocks(md, baseName = "diagram", outDir = "diagrams") {
37
- const lines = md.split("\n");
38
- const blocks = [];
39
- const used = /* @__PURE__ */ new Set();
40
- for (let i = 0; i < lines.length; i++) {
41
- const line = lines[i];
42
- let m = line.match(COMMENT_OPEN);
43
- let kind;
44
- let closer;
45
- let name;
46
- if (m) {
47
- kind = "comment";
48
- name = m[1];
49
- closer = (l) => l.trim() === "-->";
50
- } else if (m = line.match(FENCE_OPEN)) {
51
- kind = "fence";
52
- name = m[2];
53
- const fence = m[1];
54
- closer = (l) => l.trim() === fence;
55
- } else continue;
56
- let j = i + 1;
57
- while (j < lines.length && !closer(lines[j])) j++;
58
- if (j >= lines.length) break;
59
- const index = blocks.length;
60
- let n = name ?? `${baseName}-${index + 1}`;
61
- while (used.has(n)) n += "-" + (index + 1);
62
- used.add(n);
63
- const b = {
64
- index,
65
- name: n,
66
- source: lines.slice(i + 1, j).join("\n"),
67
- kind,
68
- start: i,
69
- end: j
70
- };
71
- let k = j + 1;
72
- while (k < lines.length && lines[k].trim() === "" && k <= j + 1) k++;
73
- const candidate = unlinked(lines[k]?.trim() ?? "");
74
- const path = joinPath(outDir, `${n}.svg`);
75
- if (candidate === imageRef(n, path) || candidate === imageRef(n, path, joinPath(outDir, `${n}.dark.svg`))) b.image = [k, k];
76
- blocks.push(b);
77
- i = j;
54
+ const italic = svgProp(svg, "font-style").some((v) => /^(?:italic|oblique)/.test(v));
55
+ return {
56
+ families: svgFamilies(svg),
57
+ chars,
58
+ weights,
59
+ italic
60
+ };
61
+ }
62
+ /** a face's weight range: `400`, `100 900` (variable font) or `bold` */
63
+ function weightRange(weight) {
64
+ const [lo, hi = lo] = (weight ?? "normal").trim().split(/\s+/).map((v) => WEIGHT_WORDS[v] ?? (Number(v) || 400));
65
+ return [lo, hi];
66
+ }
67
+ /** how badly a face's weight range serves weight `w`, in the order CSS font matching tries faces; 0 is exact */
68
+ function weightMiss(w, [lo, hi]) {
69
+ if (w >= lo && w <= hi) return 0;
70
+ const v = w < lo ? lo : hi;
71
+ const d = Math.abs(v - w);
72
+ if (w >= 400 && w <= 500) return (v > w && v <= 500 ? 1e3 : v < w ? 2e3 : 3e3) + d;
73
+ return ((w < 400 ? v < w : v > w) ? 1e3 : 2e3) + d;
74
+ }
75
+ /**
76
+ * The faces a browser would pick for the SVG's weights and styles, per family
77
+ * and unicode-range. A family offered in nine weights embeds only the ones used.
78
+ */
79
+ function pickFaces(faces, { weights, italic }) {
80
+ const groups = /* @__PURE__ */ new Map();
81
+ for (const f of faces) {
82
+ const key = `${f.family.toLowerCase()}|${f.unicodeRange ?? ""}`;
83
+ groups.set(key, [...groups.get(key) ?? [], f]);
78
84
  }
79
- return blocks;
80
- }
81
- const joinPath = (dir, file) => dir ? dir.replace(/\/+$/, "") + "/" + file : file;
82
- function processMarkdown(md, opts = {}) {
83
- const outDir = opts.outDir ?? "diagrams";
84
- const blocks = findBlocks(md, opts.baseName, outDir);
85
- const lines = md.split("\n");
86
- const files = [];
87
- const diagnostics = [];
88
- for (const b of [...blocks].reverse()) {
89
- const io = {
90
- resolve: opts.resolve,
91
- file: opts.file
92
- };
93
- const light = render$1(b.source, io);
94
- for (const dg of light.diagnostics) diagnostics.push({
95
- block: b.name,
96
- line: dg.line,
97
- message: dg.message,
98
- severity: dg.severity
99
- });
100
- const lightPath = joinPath(outDir, `${b.name}.svg`);
101
- files.push({
102
- path: lightPath,
103
- svg: light.svg + "\n"
104
- });
105
- const href = light.diagram.imports?.length ? void 0 : opts.view?.(b.source);
106
- let ref = imageRef(b.name, lightPath, void 0, href);
107
- if (opts.dark) {
108
- const dark = render$1(b.source, {
109
- ...io,
110
- theme: "midnight"
111
- });
112
- const darkPath = joinPath(outDir, `${b.name}.dark.svg`);
113
- files.push({
114
- path: darkPath,
115
- svg: dark.svg + "\n"
116
- });
117
- ref = imageRef(b.name, lightPath, darkPath, href);
85
+ const out = /* @__PURE__ */ new Set();
86
+ const isItalic = (f) => /italic|oblique/i.test(f.style ?? "");
87
+ for (const group of groups.values()) for (const wantItalic of italic ? [false, true] : [false]) {
88
+ const styled = group.filter((f) => isItalic(f) === wantItalic);
89
+ const pool = styled.length ? styled : group;
90
+ for (const w of weights) {
91
+ let best = pool[0];
92
+ for (const f of pool) if (weightMiss(w, weightRange(f.weight)) < weightMiss(w, weightRange(best.weight))) best = f;
93
+ out.add(best);
118
94
  }
119
- const replacement = [];
120
- if (b.kind === "fence" && !opts.keepFences) replacement.push(`<!--yuhwa ${b.name}`, ...b.source.split("\n"), "-->");
121
- else replacement.push(...lines.slice(b.start, b.end + 1));
122
- replacement.push(ref);
123
- const end = b.image ? b.image[1] : b.end;
124
- lines.splice(b.start, end - b.start + 1, ...replacement);
125
95
  }
126
- files.reverse();
96
+ return faces.filter((f) => out.has(f));
97
+ }
98
+ /** does a CSS unicode-range (`U+0000-00FF, U+0131, U+02??`) cover any of `chars`? */
99
+ function inUnicodeRange(range, chars) {
100
+ if (!range?.trim()) return true;
101
+ const spans = range.split(",").map((part) => {
102
+ const [a, b] = part.trim().replace(/^u\+/i, "").split("-");
103
+ if (b !== void 0) return [parseInt(a, 16), parseInt(b.replace(/^u\+/i, ""), 16)];
104
+ return [parseInt(a.replace(/\?/g, "0"), 16), parseInt(a.replace(/\?/g, "f"), 16)];
105
+ });
106
+ for (const c of chars) if (spans.some(([lo, hi]) => c >= lo && c <= hi)) return true;
107
+ return false;
108
+ }
109
+ /** first downloadable `url(...)` in an @font-face src, resolved against `base` */
110
+ function srcUrl(src, base) {
111
+ const m = src.match(/url\(\s*(['"]?)(.*?)\1\s*\)/);
112
+ if (!m) return void 0;
113
+ try {
114
+ return new URL(m[2], base).href;
115
+ } catch {
116
+ return;
117
+ }
118
+ }
119
+ function faceFrom(get, base) {
120
+ const url = srcUrl(get("src"), base);
121
+ const family = unquote(get("font-family"));
122
+ if (!url || !family) return void 0;
127
123
  return {
128
- markdown: lines.join("\n"),
129
- files,
130
- blocks,
131
- diagnostics
124
+ family,
125
+ url,
126
+ weight: get("font-weight").trim() || void 0,
127
+ style: get("font-style").trim() || void 0,
128
+ unicodeRange: get("unicode-range").trim() || void 0
129
+ };
130
+ }
131
+ /** @font-face rules in CSS text, for stylesheets the page may not read (cross-origin) */
132
+ function parseFontFaces(css, base) {
133
+ const out = [];
134
+ for (const m of css.matchAll(/@font-face\s*\{([^}]*)\}/g)) {
135
+ const body = m[1];
136
+ const get = (prop) => body.match(new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`, "i"))?.[1] ?? "";
137
+ const face = faceFrom(get, base);
138
+ if (face) out.push(face);
139
+ }
140
+ return out;
141
+ }
142
+ /** cache entries kept per map; the oldest goes first, so base64 fonts do not pile up */
143
+ const CACHE_SIZE = 32;
144
+ /** one promise per key, so a stylesheet or font file is fetched once per page */
145
+ function cached(map, key, load) {
146
+ let p = map.get(key);
147
+ if (p) return p;
148
+ map.set(key, p = load());
149
+ if (map.size > CACHE_SIZE) map.delete(map.keys().next().value);
150
+ return p;
151
+ }
152
+ const cssCache = /* @__PURE__ */ new Map();
153
+ let walking;
154
+ /** every @font-face the page declares; diagrams drawn together share one walk of the stylesheets */
155
+ function pageFonts() {
156
+ return walking ??= walkSheets().finally(() => walking = void 0);
157
+ }
158
+ /** readable sheets directly, cross-origin ones fetched */
159
+ async function walkSheets() {
160
+ if (typeof document === "undefined") return [];
161
+ const out = [];
162
+ const pending = [];
163
+ const walk = (rules, base) => {
164
+ for (const rule of Array.from(rules)) if (rule instanceof CSSFontFaceRule) {
165
+ const face = faceFrom((p) => rule.style.getPropertyValue(p), base);
166
+ if (face) out.push(face);
167
+ } else if (rule instanceof CSSImportRule) {
168
+ if (rule.styleSheet) sheet(rule.styleSheet);
169
+ } else if ("cssRules" in rule) walk(rule.cssRules, base);
170
+ };
171
+ const sheet = (s) => {
172
+ const base = s.href ?? location.href;
173
+ try {
174
+ walk(s.cssRules, base);
175
+ } catch {
176
+ const href = s.href;
177
+ if (!href) return;
178
+ pending.push(cached(cssCache, href, () => fetch(href).then((r) => r.ok ? r.text() : "").then((css) => parseFontFaces(css, href)).catch(() => [])));
179
+ }
132
180
  };
181
+ for (const s of Array.from(document.styleSheets)) sheet(s);
182
+ for (const faces of await Promise.all(pending)) out.push(...faces);
183
+ return out;
184
+ }
185
+ function base64(bytes) {
186
+ const native = bytes.toBase64;
187
+ if (native) return native.call(bytes);
188
+ let bin = "";
189
+ for (let i = 0; i < bytes.length; i += 32768) bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
190
+ return btoa(bin);
133
191
  }
134
- /** Replace the source of block `index` in a markdown document. */
135
- function replaceBlockSource(md, index, source) {
136
- const b = findBlocks(md)[index];
137
- if (!b) throw new Error(`No yuhwa block #${index}`);
138
- const lines = md.split("\n");
139
- lines.splice(b.start + 1, b.end - b.start - 1, ...source.split("\n"));
140
- return lines.join("\n");
192
+ const fileCache = /* @__PURE__ */ new Map();
193
+ /** a font file as a data: URL, typed by its extension; undefined when it cannot be fetched (CORS, 404) */
194
+ function fontData(url) {
195
+ if (url.startsWith("data:")) return Promise.resolve(url);
196
+ return cached(fileCache, url, () => fetch(url).then((r) => r.ok ? r.arrayBuffer() : Promise.reject(new Error(String(r.status)))).then((buf) => {
197
+ return `data:font/${url.match(/\.(woff2?|ttf|otf)(?:[?#]|$)/i)?.[1].toLowerCase() ?? "woff2"};base64,${base64(new Uint8Array(buf))}`;
198
+ }).catch(() => void 0));
199
+ }
200
+ const cssString = (s) => `"${s.replace(/["\\<>]/g, "")}"`;
201
+ const cssValue = (s) => s.replace(/[;{}<>"\\]/g, "");
202
+ /**
203
+ * Embeds the fonts the SVG names as an `@font-face` `<style>` inside it.
204
+ * Fonts it cannot fetch are skipped: the image then falls back to system fonts.
205
+ */
206
+ async function embedFonts(svg, fonts = "page") {
207
+ const usage = fontUsage(svg);
208
+ const wanted = pickFaces((fonts === "page" ? await pageFonts() : fonts).filter((f) => usage.families.has(f.family.toLowerCase()) && inUnicodeRange(f.unicodeRange, usage.chars)), usage);
209
+ const byUrl = /* @__PURE__ */ new Map();
210
+ for (const f of wanted) {
211
+ const prev = byUrl.get(f.url);
212
+ if (!prev) byUrl.set(f.url, f);
213
+ else {
214
+ const [a, b] = [weightRange(prev.weight), weightRange(f.weight)];
215
+ byUrl.set(f.url, {
216
+ ...prev,
217
+ weight: `${Math.min(a[0], b[0])} ${Math.max(a[1], b[1])}`
218
+ });
219
+ }
220
+ }
221
+ const css = (await Promise.all([...byUrl.values()].map(async (f) => {
222
+ const data = await fontData(f.url);
223
+ if (!data) return "";
224
+ return `@font-face{font-family:${cssString(f.family)};src:url(${data});` + (f.weight ? `font-weight:${cssValue(f.weight)};` : "") + (f.style ? `font-style:${cssValue(f.style)};` : "") + (f.unicodeRange ? `unicode-range:${cssValue(f.unicodeRange)};` : "") + "}";
225
+ }))).join("");
226
+ if (!css) return svg;
227
+ return svg.replace(/<svg\b[^>]*>/, (open) => `${open}<style>${css}</style>`);
228
+ }
229
+ /**
230
+ * Loads the page's web fonts that the SVG names, in the weights and styles
231
+ * it uses. Text is measured when the diagram renders, and a font that has
232
+ * not loaded yet is measured with its fallback. Resolves true when a font
233
+ * finished loading that was not ready before: render again for exact boxes.
234
+ */
235
+ async function loadFonts(svg) {
236
+ const fonts = typeof document === "undefined" ? void 0 : document.fonts;
237
+ if (!fonts) return false;
238
+ const { families, chars, weights, italic } = fontUsage(svg);
239
+ const text = String.fromCodePoint(...chars) || "a";
240
+ const specs = [];
241
+ for (const family of families) for (const w of weights) for (const style of italic ? ["normal", "italic"] : ["normal"]) specs.push(`${style} ${w} 16px ${cssString(family)}`);
242
+ const missing = specs.filter((s) => {
243
+ try {
244
+ return !fonts.check(s, text);
245
+ } catch {
246
+ return false;
247
+ }
248
+ });
249
+ if (!missing.length) return false;
250
+ return (await Promise.all(missing.map((s) => fonts.load(s, text).catch(() => [])))).some((faces) => faces.length > 0);
251
+ }
252
+ /**
253
+ * Draws an SVG string, such as `render(...).svg`, into a canvas. The page's
254
+ * web fonts that the diagram names are embedded first (see `fonts`).
255
+ */
256
+ async function svgToCanvas(svg, opts = {}) {
257
+ const { width, height } = svgSize(svg);
258
+ const scale = opts.scale ?? (typeof devicePixelRatio === "number" && devicePixelRatio > 0 ? devicePixelRatio : 1);
259
+ const fonts = opts.fonts ?? "page";
260
+ const source = fonts === false ? svg : await embedFonts(svg, fonts);
261
+ const url = URL.createObjectURL(new Blob([source], { type: "image/svg+xml" }));
262
+ const img = new Image();
263
+ img.src = url;
264
+ try {
265
+ await img.decode();
266
+ } finally {
267
+ URL.revokeObjectURL(url);
268
+ }
269
+ const canvas = opts.canvas ?? document.createElement("canvas");
270
+ canvas.width = Math.max(1, Math.round(width * scale));
271
+ canvas.height = Math.max(1, Math.round(height * scale));
272
+ const ctx = canvas.getContext("2d");
273
+ if (!ctx) throw new Error("yuhwa: no 2d canvas context");
274
+ if (opts.background) {
275
+ ctx.fillStyle = opts.background;
276
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
277
+ }
278
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
279
+ return canvas;
280
+ }
281
+ /**
282
+ * Draws `svg` and swaps the drawing in for `node`: a `<canvas>`, or for
283
+ * `png` an `<img>` of its PNG (a `blob:` URL; revoke it when the image goes),
284
+ * sized to the diagram. Nothing is swapped when `node` left the page or
285
+ * `current()` says a newer draw came.
286
+ */
287
+ async function swapForRaster(node, svg, mode, label, current = () => true) {
288
+ const canvas = await svgToCanvas(svg);
289
+ const stale = () => !current() || !node.isConnected;
290
+ if (stale()) return;
291
+ let out = canvas;
292
+ if (mode === "png") {
293
+ const blob = await new Promise((done) => canvas.toBlob(done, "image/png"));
294
+ if (!blob) throw new Error("the canvas gave no PNG");
295
+ if (stale()) return;
296
+ const img = new Image();
297
+ img.src = URL.createObjectURL(blob);
298
+ img.alt = label;
299
+ out = img;
300
+ } else canvas.setAttribute("role", "img"), canvas.setAttribute("aria-label", label);
301
+ out.style.width = `${svgSize(svg).width}px`;
302
+ node.replaceWith(out);
303
+ return out;
141
304
  }
142
305
  // src/core/guide.ts
143
- const list = (xs) => [...xs].join(", ");
144
- const code = (xs) => list([...xs].map((x) => "`" + x + "`"));
306
+ const list$1 = (xs) => [...xs].join(", ");
307
+ const code = (xs) => list$1([...xs].map((x) => "`" + x + "`"));
145
308
  const panels = [...registry.panels.values()];
146
309
  const PLACEHOLDER = {
147
310
  color: "<colour>",
148
311
  number: "N",
149
312
  text: "…"
150
313
  };
151
- const settings = list([...KNOWN_SETTINGS].map((k) => SETTING_VALUES[k] ? `${k} (${SETTING_VALUES[k].join("|")})` : k));
314
+ const settings = list$1([...KNOWN_SETTINGS].map((k) => SETTING_VALUES[k] ? `${k} (${SETTING_VALUES[k].join("|")})` : k));
152
315
  const panelLines = panels.map((p) => {
153
316
  const header = Object.entries(p.options ?? {}).map(([k, v]) => {
154
317
  const o = optionKind(v);
@@ -231,19 +394,19 @@ orders --> queue "Events" [shape: hexagon]: publish [flow: true]
231
394
  ## Values
232
395
 
233
396
  - \`color\` sets fill, border and text in one: \`[blue]\` or \`[color: blue]\`.
234
- Palette: ${list(TONES)}; shades like blue-600; any CSS colour. The colour
235
- props (${list(COLORS)}) take the same values and colour one part.
236
- - Shapes: ${list(SHAPES)}.
237
- - Line styles: ${list(ENUMS.style)}. Heads: ${list(ENUMS.head)}. Sides (\`exit\`, \`enter\`): ${list(ENUMS.exit)}.
238
- - Themes: ${list(THEME_NAMES)}. Define one with \`theme brand [base: midnight, accent: orange]\`
397
+ Palette: ${list$1(TONES)}; shades like blue-600; any CSS colour. The colour
398
+ props (${list$1(COLORS)}) take the same values and colour one part.
399
+ - Shapes: ${list$1(SHAPES)}.
400
+ - Line styles: ${list$1(ENUMS.style)}. Heads: ${list$1(ENUMS.head)}. Sides (\`exit\`, \`enter\`): ${list$1(ENUMS.exit)}.
401
+ - Themes: ${list$1(THEME_NAMES)}. Define one with \`theme brand [base: midnight, accent: orange]\`
239
402
  or \`theme brand {\` and one \`key: value\` per line, then \`theme: brand\`.
240
- Keys: ${list(Object.keys(THEME_KEYS))}.
403
+ Keys: ${list$1(Object.keys(THEME_KEYS))}.
241
404
 
242
405
  ## Props
243
406
 
244
- - Node: ${list(NODE_PROPS)}.
245
- - Edge: ${list(EDGE_PROPS)}.
246
- - Group: ${list(GROUP_PROPS)}.
407
+ - Node: ${list$1(NODE_PROPS)}.
408
+ - Edge: ${list$1(EDGE_PROPS)}.
409
+ - Group: ${list$1(GROUP_PROPS)}.
247
410
 
248
411
  \`sub\` is a second, smaller line; \`icon\` an emoji before the label; \`link\`
249
412
  makes a node clickable; \`flow: true\` animates an edge; \`constraint: false\`
@@ -251,7 +414,7 @@ keeps an edge out of the layout; \`shape: text\` is an annotation without a box.
251
414
  \`below: <id>\`, \`above\`, \`right-of\`, \`left-of\` and \`rank\` place a node next to another
252
415
  node without drawing an edge; do not use invisible edges for that. The \`max-width: <px>\` setting
253
416
  wraps the ranks of a right or left diagram into rows that fit that width.
254
- \`frame: <kind> <text>\` draws window chrome: ${list(registry.frames.keys())}.
417
+ \`frame: <kind> <text>\` draws window chrome: ${list$1(registry.frames.keys())}.
255
418
 
256
419
  ## Card bodies
257
420
 
@@ -389,7 +552,7 @@ function zoomable(host, opts = {}) {
389
552
  .yuhwa-zoom-stage{transform-origin:0 0}
390
553
  .yuhwa-zoom-stage.yuhwa-zoom-anim{transition:transform .18s ease-out}
391
554
  .yuhwa-zoom-fixed .yuhwa-zoom-stage,.yuhwa-zoom:fullscreen .yuhwa-zoom-stage{height:100%;display:flex;align-items:center;justify-content:center}
392
- .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}
555
+ .yuhwa-zoom-fixed .yuhwa-zoom-stage :is(svg,img,canvas),.yuhwa-zoom:fullscreen .yuhwa-zoom-stage :is(svg,img,canvas){max-width:100%;max-height:100%;width:auto;height:auto}
393
556
  .yuhwa-zoom:fullscreen{background:var(--yuhwa-zoom-bg,Canvas)}
394
557
  .yuhwa-zoom-stage img{-webkit-user-drag:none}
395
558
  .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}
@@ -646,54 +809,58 @@ function zoomHeight(value) {
646
809
  if (!v || v === "true") return void 0;
647
810
  return /^\d+(\.\d+)?$/.test(v) ? `${v}px` : v;
648
811
  }
649
- // src/cli/blocks.ts
650
- /**
651
- * Finds the diagrams in a Markdown page for `yuhwa check` and `yuhwa render`:
652
- * fenced blocks in one of `languages` and the `<!--yuhwa name … -->` comments
653
- * that `yuhwa md` writes. Fences in other languages are skipped whole, so a
654
- * ```markdown fence that shows a yuhwa block is not checked.
655
- */
656
- /** fence languages read by default; `--lang` overrides them */
657
- const MD_LANGUAGES = ["yuhwa", "yu"];
658
- const isMarkdown = (file) => /\.(md|mdx|markdown)$/i.test(file);
659
- const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)(.*)$/;
660
- function pageBlocks(md, languages = MD_LANGUAGES) {
661
- const lines = md.split("\n");
662
- const blocks = [];
663
- for (let i = 0; i < lines.length; i++) {
664
- const line = lines[i].replace(/\r$/, "");
665
- let close;
666
- let lang;
667
- let meta = "";
668
- let m = line.match(FENCE);
669
- if (m) {
670
- const fence = m[1];
671
- const closer = new RegExp(`^ {0,3}${fence[0]}{${fence.length},}\\s*$`);
672
- close = (l) => closer.test(l);
673
- lang = m[2];
674
- meta = m[3].trim();
675
- } else if (m = line.match(COMMENT_OPEN)) {
676
- close = (l) => l.trim() === "-->";
677
- lang = "comment";
678
- meta = m[1] ?? "";
679
- } else continue;
680
- let j = i + 1;
681
- while (j < lines.length && !close(lines[j].replace(/\r$/, ""))) j++;
682
- if (j >= lines.length) break;
683
- if (lang === "comment" || languages.includes(lang) && !/(^|\s)no-render(\s|$)/.test(meta)) {
684
- const name = meta.split(/\s+/).find((w) => w && w !== "no-code");
685
- blocks.push({
686
- index: blocks.length,
687
- lang,
688
- ...name ? { name } : {},
689
- line: i + 1,
690
- source: lines.slice(i + 1, j).join("\n")
691
- });
812
+ // src/integrations/png.ts
813
+ let resvg;
814
+ function builtin(id) {
815
+ const get = globalThis.process?.getBuiltinModule;
816
+ if (!get) throw new Error("PNG output needs Node 22.3 or later");
817
+ return get(id);
818
+ }
819
+ const pathCache = /* @__PURE__ */ new Map();
820
+ /** `fonts` checked and sorted into files and folders, once per list: a site build draws many diagrams */
821
+ function fontPaths(fonts) {
822
+ const key = fonts.join("\0");
823
+ const hit = pathCache.get(key);
824
+ if (hit) return hit;
825
+ const { existsSync, statSync } = builtin("node:fs");
826
+ const { resolve } = builtin("node:path");
827
+ const paths = {
828
+ fontFiles: [],
829
+ fontDirs: []
830
+ };
831
+ for (const f of fonts) {
832
+ if (!existsSync(f)) throw new Error(`no such font file or folder: ${f}`);
833
+ if (/\.woff2?$/i.test(f)) throw new Error(`PNG output reads ttf, otf and ttc fonts, not woff: ${f}`);
834
+ (statSync(f).isDirectory() ? paths.fontDirs : paths.fontFiles).push(resolve(f));
835
+ }
836
+ pathCache.set(key, paths);
837
+ return paths;
838
+ }
839
+ function svgToPng(svg, { scale = 2, fonts = [], systemFonts = true } = {}) {
840
+ if (!(scale > 0)) throw new Error("the PNG scale must be a number above 0");
841
+ if (!resvg) {
842
+ const { createRequire } = builtin("node:module");
843
+ try {
844
+ resvg = createRequire(import.meta.url)("@resvg/resvg-js").Resvg;
845
+ } catch {
846
+ throw new Error("PNG output needs @resvg/resvg-js: npm install -D @resvg/resvg-js, or pnpm add -D @resvg/resvg-js");
692
847
  }
693
- i = j;
694
848
  }
695
- return blocks;
849
+ const { fontFiles, fontDirs } = fontPaths(fonts);
850
+ return new resvg(svg, {
851
+ fitTo: {
852
+ mode: "zoom",
853
+ value: scale
854
+ },
855
+ font: {
856
+ loadSystemFonts: systemFonts,
857
+ fontFiles,
858
+ fontDirs
859
+ }
860
+ }).render().asPng();
696
861
  }
862
+ // src/cli/blocks.ts
863
+ /** `--lang` for the commands that read Markdown pages */
697
864
  /** parses `--lang yuhwa,yu` */
698
865
  function parseLanguages(v) {
699
866
  if (typeof v !== "string") return MD_LANGUAGES;
@@ -942,16 +1109,22 @@ function saveEditorFiles(file, mainName, block, loaded, update) {
942
1109
  // src/browser.ts
943
1110
  /**
944
1111
  * Drop-in browser runtime: <script src="yuhwa.js"><\/script>
945
- * Renders every `pre > code.language-yuhwa` (or `.lang-yuhwa`), `pre.yuhwa` and
1112
+ * Renders every `pre > code.language-yuhwa` (or `.lang-yuhwa`, `.language-yu`,
1113
+ * `.lang-yu`), `pre.yuhwa` and
946
1114
  * `div.yuhwa` element on the page, and defines the <yuhwa-diagram>
947
1115
  * custom element:
948
1116
  *
949
1117
  * <yuhwa-diagram theme="midnight">a -> b -> c</yuhwa-diagram>
950
1118
  * <yuhwa-diagram src="docs/arch.yu"></yuhwa-diagram>
951
1119
  * <yuhwa-diagram src="big.yu" zoom="480px"></yuhwa-diagram> // pan and zoom
1120
+ * <yuhwa-diagram render="canvas">a -> b</yuhwa-diagram> // or png; default svg
952
1121
  * el.source = 'a -> b' // re-renders
953
1122
  */
954
- const SELECTOR = "pre > code.language-yuhwa, pre > code.lang-yuhwa, pre.yuhwa, div.yuhwa:not([data-rendered])";
1123
+ const SELECTOR = [
1124
+ ...MD_LANGUAGES.flatMap((l) => [`pre > code.language-${l}`, `pre > code.lang-${l}`]),
1125
+ "pre.yuhwa",
1126
+ "div.yuhwa:not([data-rendered])"
1127
+ ].join(", ");
955
1128
  function prefersDark() {
956
1129
  return typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
957
1130
  }
@@ -979,7 +1152,7 @@ async function fetchImports(source, file, load = fetchText) {
979
1152
  const queue = [[source, file]];
980
1153
  while (queue.length) {
981
1154
  const [text, from] = queue.shift();
982
- const paths = [...text.matchAll(IMPORT_RE)].map((m) => joinPath$1(from, m[1])).filter((p) => isYuhwaPath(p) && !(p in files));
1155
+ const paths = [...text.matchAll(IMPORT_RE)].map((m) => joinPath(from, m[1])).filter((p) => isYuhwaPath(p) && !(p in files));
983
1156
  await Promise.all(paths.map(async (p) => {
984
1157
  files[p] = "";
985
1158
  try {
@@ -993,12 +1166,49 @@ async function fetchImports(source, file, load = fetchText) {
993
1166
  return files;
994
1167
  }
995
1168
  const fetchText = (url) => fetch(url).then((r) => r.ok ? r.text() : Promise.reject(/* @__PURE__ */ new Error(`${url}: HTTP ${r.status}`)));
996
- function fit(svg) {
997
- if (!svg) return;
998
- svg.removeAttribute("height");
999
- svg.style.maxWidth = "100%";
1000
- svg.style.height = "auto";
1001
- svg.style.display = "block";
1169
+ function fit(el) {
1170
+ if (!el) return;
1171
+ el.removeAttribute("height");
1172
+ el.style.maxWidth = "100%";
1173
+ el.style.height = "auto";
1174
+ el.style.display = "block";
1175
+ }
1176
+ /** diagrams to redraw when one of their web fonts loads: the families each names, and its redraw */
1177
+ const waiting = /* @__PURE__ */ new Map();
1178
+ let listening = false;
1179
+ /**
1180
+ * Redraws `node` once a web font it names (in `svg`) finishes loading, so
1181
+ * boxes fit the real text. Text is measured when the diagram renders, and a
1182
+ * font still loading is measured with its fallback. One `loadingdone`
1183
+ * listener serves every diagram; a node that left the page drops out.
1184
+ */
1185
+ function redrawOnFonts(node, svg, redraw) {
1186
+ const fonts = typeof document === "undefined" ? void 0 : document.fonts;
1187
+ if (!fonts) return;
1188
+ waiting.set(node, {
1189
+ families: svgFamilies(svg),
1190
+ redraw
1191
+ });
1192
+ if (listening) return;
1193
+ listening = true;
1194
+ fonts.addEventListener("loadingdone", (e) => {
1195
+ const loaded = new Set(e.fontfaces.map((f) => unquote(f.family).toLowerCase()));
1196
+ for (const [el, { families, redraw }] of waiting) if (!el.isConnected) waiting.delete(el);
1197
+ else if ([...families].some((f) => loaded.has(f))) redraw();
1198
+ });
1199
+ }
1200
+ /**
1201
+ * Puts the SVG into `host`. `render="png"` or `"canvas"` then draws it and
1202
+ * swaps the drawing in for the SVG, unless `current()` says a newer draw came.
1203
+ */
1204
+ function show(host, svg, mode, label, current) {
1205
+ host.querySelectorAll("img[src^=\"blob:\"]").forEach((img) => URL.revokeObjectURL(img.src));
1206
+ host.innerHTML = svg;
1207
+ const node = host.querySelector("svg");
1208
+ fit(node);
1209
+ const fonts = loadFonts(svg);
1210
+ if (!node || mode !== "png" && mode !== "canvas") return;
1211
+ fonts.then((changed) => changed ? void 0 : swapForRaster(node, svg, mode, label, current)).then(fit, (e) => console.warn(`yuhwa: ${mode} drawing failed: ${e.message}`));
1002
1212
  }
1003
1213
  function run(root = document, opts = {}) {
1004
1214
  root.querySelectorAll(SELECTOR).forEach((el) => {
@@ -1008,22 +1218,27 @@ function run(root = document, opts = {}) {
1008
1218
  out.className = "yuhwa";
1009
1219
  out.dataset.rendered = "true";
1010
1220
  out.dataset.source = source;
1011
- let ok = false;
1012
- try {
1221
+ let draws = 0;
1222
+ const paint = () => {
1013
1223
  const r = render(source, {
1014
1224
  theme: host.dataset.theme,
1015
1225
  ...opts
1016
1226
  });
1017
- out.innerHTML = r.svg;
1018
- fit(out.querySelector("svg"));
1227
+ out.yuhwaZoom?.destroy();
1228
+ const draw = ++draws;
1229
+ show(out, r.svg, host.dataset.render, r.diagram.settings.title ?? "diagram", () => draw === draws);
1230
+ if (host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
1231
+ redrawOnFonts(out, r.svg, paint);
1232
+ return r;
1233
+ };
1234
+ host.replaceWith(out);
1235
+ try {
1236
+ const r = paint();
1019
1237
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
1020
- ok = true;
1021
1238
  } catch (e) {
1022
1239
  out.textContent = `yuhwa error: ${e.message}`;
1023
1240
  out.style.color = "crimson";
1024
1241
  }
1025
- host.replaceWith(out);
1026
- if (ok && host.dataset.zoom !== void 0) zoomable(out, { height: zoomHeight(host.dataset.zoom) });
1027
1242
  });
1028
1243
  }
1029
1244
  const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
@@ -1037,13 +1252,15 @@ var YuhwaDiagram = class extends Base {
1037
1252
  "theme",
1038
1253
  "src",
1039
1254
  "zoom",
1040
- "wheel"
1255
+ "wheel",
1256
+ "render"
1041
1257
  ];
1042
1258
  #source = null;
1043
1259
  #fetched = null;
1044
1260
  #request = 0;
1045
1261
  #file;
1046
1262
  #files = {};
1263
+ #draws = 0;
1047
1264
  get source() {
1048
1265
  return this.#source ?? "";
1049
1266
  }
@@ -1089,8 +1306,9 @@ var YuhwaDiagram = class extends Base {
1089
1306
  resolve: (p) => files[p]
1090
1307
  });
1091
1308
  this.yuhwaZoom?.destroy();
1092
- this.innerHTML = r.svg;
1093
- fit(this.querySelector("svg"));
1309
+ const draw = ++this.#draws;
1310
+ const label = this.getAttribute("aria-label") ?? r.diagram.settings.title ?? "diagram";
1311
+ show(this, r.svg, this.getAttribute("render") ?? void 0, label, () => draw === this.#draws);
1094
1312
  const zoom = this.getAttribute("zoom");
1095
1313
  this.setAttribute("role", zoom === null ? "img" : "group");
1096
1314
  if (zoom !== null) zoomable(this, {
@@ -1103,6 +1321,7 @@ var YuhwaDiagram = class extends Base {
1103
1321
  else if (this.dataset.autoLabel) this.removeAttribute("aria-label"), delete this.dataset.autoLabel;
1104
1322
  }
1105
1323
  for (const d of r.diagnostics) console.warn(`yuhwa:${d.line}: ${d.message}`);
1324
+ redrawOnFonts(this, r.svg, () => this.#draw());
1106
1325
  this.dispatchEvent(new CustomEvent("yuhwa:render", { detail: {
1107
1326
  diagnostics: r.diagnostics,
1108
1327
  format: r.format
@@ -1127,7 +1346,7 @@ if (typeof document !== "undefined") {
1127
1346
  const HELP = `yuhwa — diagrams that look good and stay where you put them
1128
1347
 
1129
1348
  Usage
1130
- yuhwa render <file|-> [-o out.svg|out.html] [--html] [--theme name] [--block n]
1349
+ yuhwa render <file|-> [-o out.svg|out.html|out.png] [--html] [--png] [--scale 2] [--font f] [--no-system-fonts] [--theme name] [--block n]
1131
1350
  yuhwa check <file|-...> [--json] [--lang yuhwa,yu]
1132
1351
  yuhwa lint <file...> [--fix] [--json] [--lang yuhwa,yu]
1133
1352
  yuhwa convert <file.mmd|file.json|-> [-o out.yu]
@@ -1146,13 +1365,18 @@ Input can be yuhwa, a Mermaid flowchart or JSON; the format is detected.
1146
1365
  render Render one diagram to SVG (stdout unless -o is given). From a
1147
1366
  Markdown file it renders block --block n (from 0, default 0).
1148
1367
  -o x.html or --html writes a page that pans and zooms instead.
1368
+ -o x.png or --png writes a PNG, --scale times the natural size
1369
+ (default 2). PNG needs the optional @resvg/resvg-js package and
1370
+ uses system fonts; --font adds a font file or folder (repeatable),
1371
+ --no-system-fonts uses only those, the same on every machine.
1149
1372
  check Validate without rendering. --json prints machine-readable diagnostics.
1150
1373
  A .md/.mdx/.markdown file is checked block by block: every
1151
1374
  \`\`\`yuhwa and \`\`\`yu fence (--lang picks others) and every
1152
1375
  <!--yuhwa --> comment, with line numbers in the Markdown file.
1153
1376
  lint Everything check reports, plus unused classes, variables and
1154
- components, edges drawn twice and unformatted files. Fails on any
1155
- finding, warnings included. --fix formats .yu files in place.
1377
+ components, edges drawn twice and unformatted files or Markdown
1378
+ blocks. Fails on any finding, warnings included. --fix formats
1379
+ .yu files and the blocks of Markdown files in place.
1156
1380
  convert Turn a Mermaid flowchart or JSON diagram into yuhwa source.
1157
1381
  md Render every yuhwa block in Markdown files, write the SVGs and
1158
1382
  insert or update the image reference below each block. --view
@@ -1167,6 +1391,20 @@ url Print an embeddable image URL for a diagram (for \`serve\`).
1167
1391
  guide Print the language reference (same as llms.txt). AI agents: read
1168
1392
  this first, then write source and run \`check --json\` until it is clean.
1169
1393
  `;
1394
+ /** flags that take a value; repeatable ones collect every value in a list */
1395
+ const VALUE_FLAGS = /* @__PURE__ */ new Set([
1396
+ "theme",
1397
+ "out",
1398
+ "out-dir",
1399
+ "block",
1400
+ "port",
1401
+ "host",
1402
+ "base",
1403
+ "lang",
1404
+ "scale",
1405
+ "font"
1406
+ ]);
1407
+ const REPEATABLE = /* @__PURE__ */ new Set(["font"]);
1170
1408
  function parseArgs(argv) {
1171
1409
  const a = { _: [] };
1172
1410
  for (let i = 0; i < argv.length; i++) {
@@ -1176,23 +1414,15 @@ function parseArgs(argv) {
1176
1414
  else if (s === "-v") a.version = true;
1177
1415
  else if (s.startsWith("--")) {
1178
1416
  const [k, v] = s.slice(2).split("=", 2);
1179
- if (v !== void 0) a[k] = v;
1180
- else if (argv[i + 1] && !argv[i + 1].startsWith("-") && [
1181
- "theme",
1182
- "out",
1183
- "out-dir",
1184
- "block",
1185
- "port",
1186
- "host",
1187
- "base",
1188
- "lang"
1189
- ].includes(k)) a[k] = argv[++i];
1190
- else a[k] = true;
1417
+ const value = v ?? (argv[i + 1] && !argv[i + 1].startsWith("-") && VALUE_FLAGS.has(k) ? argv[++i] : true);
1418
+ if (REPEATABLE.has(k) && typeof value === "string") a[k] = [...list(a[k]), value];
1419
+ else a[k] = value;
1191
1420
  } else a._.push(s);
1192
1421
  }
1193
1422
  return a;
1194
1423
  }
1195
1424
  const str = (v) => typeof v === "string" ? v : void 0;
1425
+ const list = (v) => Array.isArray(v) ? v : [];
1196
1426
  function printDiagnostics(file, ds, prefix = "") {
1197
1427
  for (const d of ds) process.stderr.write(`${file}:${d.line}: ${d.severity}: ${prefix}${d.message}\n`);
1198
1428
  }
@@ -1211,10 +1441,19 @@ function cmdRender(a) {
1211
1441
  const r = renderAs(a, file, source);
1212
1442
  printDiagnostics(file, shiftLines(r.diagnostics, at));
1213
1443
  const out = str(a.out);
1214
- writeOut(out, !!a.html || /\.html?$/i.test(out ?? "") ? viewerPage(r.svg, {
1215
- title: r.diagram.settings.title ?? basename(file),
1216
- background: r.layout.theme.background
1217
- }) : r.svg + "\n");
1444
+ const kind = a.html || /\.html?$/i.test(out ?? "") ? "html" : a.png || /\.png$/i.test(out ?? "") ? "png" : "svg";
1445
+ if (kind === "png") writeOut(out, svgToPng(r.svg, {
1446
+ scale: Number(str(a.scale) ?? 2),
1447
+ fonts: list(a.font),
1448
+ systemFonts: !a["no-system-fonts"]
1449
+ }));
1450
+ else if (kind === "html") {
1451
+ const title = r.diagram.settings.title ?? basename(file);
1452
+ writeOut(out, viewerPage(r.svg, {
1453
+ title,
1454
+ background: r.layout.theme.background
1455
+ }));
1456
+ } else writeOut(out, r.svg + "\n");
1218
1457
  if (r.diagnostics.some((d) => d.severity === "error")) process.exitCode = 1;
1219
1458
  }
1220
1459
  const fileOpts = (file) => ({
@@ -1323,24 +1562,34 @@ function cmdLint(a) {
1323
1562
  perFile(a, "lint", (file) => {
1324
1563
  let diagnostics;
1325
1564
  let fixed = false;
1326
- if (isMarkdown(file)) diagnostics = blocksOf(a, file).flatMap((b) => lintOne(b.source, file, b.line).map((d) => ({
1327
- ...d,
1328
- block: b.index
1329
- })));
1330
- else {
1331
- const source = readInput(file);
1565
+ const source = readInput(file);
1566
+ let unformatted;
1567
+ let formatted;
1568
+ if (isMarkdown(file)) {
1569
+ diagnostics = blocksOf(a, file, source).flatMap((b) => lintOne(b.source, file, b.line).map((d) => ({
1570
+ ...d,
1571
+ block: b.index
1572
+ })));
1573
+ const page = formatPage(source, parseLanguages(a.lang));
1574
+ formatted = page.text;
1575
+ unformatted = page.changed.map((b) => ({
1576
+ line: b.line,
1577
+ block: b.index
1578
+ }));
1579
+ } else {
1332
1580
  diagnostics = lintOne(source, file);
1333
- const formatted = format(source);
1334
- if (formatted !== source) {
1335
- if (a.fix && file !== "-") {
1336
- writeFileSync(file, formatted);
1337
- fixed = true;
1338
- } else diagnostics.push({
1339
- line: 1,
1340
- message: "Not formatted: run yuhwa lint --fix",
1341
- severity: "warning"
1342
- });
1343
- }
1581
+ formatted = format(source);
1582
+ unformatted = [{ line: 1 }];
1583
+ }
1584
+ if (formatted !== source) {
1585
+ if (a.fix && file !== "-") {
1586
+ writeFileSync(file, formatted);
1587
+ fixed = true;
1588
+ } else for (const at of unformatted) diagnostics.push({
1589
+ ...at,
1590
+ message: "Not formatted: run yuhwa lint --fix",
1591
+ severity: "warning"
1592
+ });
1344
1593
  }
1345
1594
  diagnostics.sort((x, y) => x.line - y.line);
1346
1595
  if (diagnostics.length) process.exitCode = 1;