yuhwa 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/astro.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as YuhwaDocsOptions } from "./figure-CCHRsOjO.js";
1
+ import { t as YuhwaDocsOptions } from "./figure-BZHIKnxv.js";
2
2
  interface SetupParams {
3
3
  updateConfig: (config: {
4
4
  markdown: {
package/dist/browser.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * <yuhwa-diagram src="docs/arch.yuhwa"></yuhwa-diagram>
9
9
  * el.source = 'a -> b' // re-renders
10
10
  */
11
- import { $ as ParseOptions, $t as PanelKind, A as MdBlock, An as registerTheme, At as LayoutOverrides, B as setProp, Bt as Point, C as NODE_PROPS, Cn as TONES, Ct as HeadKind, D as ConvertResult, Dn as getTheme, Dt as LaidNode, E as lint, En as createTheme, Et as LaidGroup, F as replaceBlockSource, Ft as PanelOverride, G as SHAPES, Gt as Side, H as writeLayout, Ht as ResolvedEdgeStyle, I as editPart, It as PanelPart, J as fromJSON, Jt as groupPath, K as DiagramJSON, Kt as SourceRef, L as formatLayout, Lt as PartAction, M as MdResult, Mn as approxMeasure, Mt as NodeOverride, N as findBlocks, Nn as canvasMeasure, Nt as PanelDecl, O as fromMermaid, On as isToneOrHex, Ot as LaidPanel, P as processMarkdown, Pt as PanelHandle, Q as PANELS, Qt as PanelCtx, R as setLabel, Rt as PartChange, S as GROUP_PROPS, Sn as THEME_NAMES, St as GroupDecl, T as PANEL_PROPS, Tn as ThemeInput, Tt as LaidEdge, U as dashFor, Ut as ResolvedNodeStyle, V as setSetting, Vt as Props, W as lineStyle, Wt as ShapeName, X as KNOWN_SETTINGS, Xt as Decoration, Y as renderSvg, Yt as layout, Z as LexedLine, Zt as FrameKind, _ as themes, _n as tspans, _t as Diagnostic, an as perPass, at as joinPath, b as EDGE_PROPS, bn as THEMES, bt as EdgeDecl, c as git, cn as use, ct as parse, d as sequence, dn as renderHead, dt as setLineProp, en as RowCtx, et as SETTING_VALUES, f as legend, fn as InkColors, ft as setTrailingProp, g as charts, gn as segsW, gt as Curve, h as tables, hn as renderSegs, ht as Component, i as hash, in as YuhwaPlugin, it as isYuhwaPath, j as MdOptions, jn as themeNames, jt as NodeDecl, k as isMermaid, kn as ramp, kt as Layout, l as chart, ln as MarkerKind, lt as parseProps, m as frames, mn as parseInline, mt as Box, n as Options, nn as RowPaint, nt as TokKind, o as toSource, on as recolor, ot as lex, p as footer, pn as Seg, pt as splitTrailingProps, q as JsonResult, qt as GRID, r as Result, rn as StatementKind, rt as blockBraces, s as builtins, sn as registry, st as onlyColor, t as InputFormat, tn as RowKind, tt as Tok, u as timeline, un as ShapeKind, ut as serializeProps, v as GUIDE, vn as LineStyle, vt as Diagram, w as NUMBERS, wn as Theme, wt as LabelRef, x as ENUMS, xn as THEME_KEYS, xt as EdgeOverride, y as BOOLS, yn as RAMPS, yt as Direction, z as setPartTone, zt as PartEdit } from "./index-vqADUsNi.js";
11
+ import { $ as PANELS, $t as PanelCtx, A as MdBlock, An as isSafeLink, At as Layout, B as setProp, Bt as PartEdit, C as NODE_PROPS, Cn as THEME_NAMES, Ct as GroupDecl, D as ConvertResult, Dn as createTheme, Dt as LaidGroup, E as lint, En as ThemeInput, Et as LaidEdge, F as replaceBlockSource, Fn as approxMeasure, Ft as PanelHandle, G as lineStyle, Gt as ShapeName, H as writeLayout, Ht as Props, I as editPart, In as canvasMeasure, It as PanelOverride, J as JsonResult, Jt as GRID, K as SHAPES, Kt as Side, L as formatLayout, Lt as PanelPart, M as MdResult, Mn as ramp, Mt as NodeDecl, N as findBlocks, Nn as registerTheme, Nt as NodeOverride, O as fromMermaid, On as getTheme, Ot as LaidNode, P as processMarkdown, Pn as themeNames, Pt as PanelDecl, Q as LexedLine, Qt as FrameKind, R as setLabel, Rt as PartAction, S as GROUP_PROPS, Sn as THEME_KEYS, St as EdgeOverride, T as PANEL_PROPS, Tn as Theme, Tt as LabelRef, U as writePanelDrag, Ut as ResolvedEdgeStyle, V as setSetting, Vt as Point, W as dashFor, Wt as ResolvedNodeStyle, X as renderSvg, Xt as layout, Y as fromJSON, Yt as groupPath, Z as KNOWN_SETTINGS, Zt as Decoration, _ as themes, _n as segsW, _t as Curve, an as YuhwaPlugin, at as isYuhwaPath, b as EDGE_PROPS, bn as RAMPS, bt as Direction, c as git, cn as registry, ct as onlyColor, d as sequence, dn as ShapeKind, dt as serializeProps, en as PanelKind, et as ParseOptions, f as legend, fn as renderHead, ft as setLineProp, g as charts, gn as renderSegs, gt as Component, h as tables, hn as parseInline, ht as Box, i as hash, in as StatementKind, it as blockBraces, j as MdOptions, jn as isToneOrHex, jt as LayoutOverrides, k as isMermaid, kn as isSafeCss, kt as LaidPanel, l as chart, ln as use, lt as parse, m as frames, mn as Seg, mt as splitTrailingProps, n as Options, nn as RowKind, nt as Tok, o as toSource, on as perPass, ot as joinPath, p as footer, pn as InkColors, pt as setTrailingProp, q as DiagramJSON, qt as SourceRef, r as Result, rn as RowPaint, rt as TokKind, s as builtins, sn as recolor, st as lex, t as InputFormat, tn as RowCtx, tt as SETTING_VALUES, u as timeline, un as MarkerKind, ut as parseProps, v as GUIDE, vn as tspans, vt as Diagnostic, w as NUMBERS, wn as TONES, wt as HeadKind, x as ENUMS, xn as THEMES, xt as EdgeDecl, y as BOOLS, yn as LineStyle, yt as Diagram, z as setPartTone, zt as PartChange } from "./index-Dl845tUQ.js";
12
12
  export declare function render(source: string, opts?: Options): Result;
13
13
  /**
14
14
  * Fetches every file that `source` imports, and what those import, so
@@ -28,4 +28,4 @@ export declare class YuhwaDiagram extends Base {
28
28
  connectedCallback(): void;
29
29
  attributeChangedCallback(): void;
30
30
  }
31
- export { BOOLS, type Box, type Component, type ConvertResult, type Curve, type Decoration, type Diagnostic, type Diagram, type DiagramJSON, type Direction, EDGE_PROPS, ENUMS, type EdgeDecl, type EdgeOverride, type FrameKind, GRID, GROUP_PROPS, GUIDE, type GroupDecl, type HeadKind, type InkColors, InputFormat, type JsonResult, KNOWN_SETTINGS, type LabelRef, type LaidEdge, type LaidGroup, type LaidNode, type LaidPanel, type Layout, type LayoutOverrides, type LexedLine, type LineStyle, type MarkerKind, type MdBlock, type MdOptions, type MdResult, NODE_PROPS, NUMBERS, type NodeDecl, type NodeOverride, Options, PANELS, PANEL_PROPS, type PanelCtx, type PanelDecl, type PanelHandle, type PanelKind, type PanelOverride, type PanelPart, type ParseOptions, type PartAction, type PartChange, type PartEdit, type Point, type Props, RAMPS, type ResolvedEdgeStyle, type ResolvedNodeStyle, Result, type RowCtx, type RowKind, type RowPaint, SETTING_VALUES, SHAPES, type Seg, type ShapeKind, type ShapeName, type Side, type SourceRef, type StatementKind, THEMES, THEME_KEYS, THEME_NAMES, TONES, type Theme, type ThemeInput, type Tok, type TokKind, type YuhwaPlugin, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, getTheme, git, groupPath, hash, isMermaid, isToneOrHex, isYuhwaPath, joinPath, layout, legend, lex, lineStyle, lint, onlyColor, parse, parseInline, parseProps, perPass, processMarkdown, ramp, recolor, registerTheme, registry, renderHead, renderSegs, renderSvg, replaceBlockSource, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, splitTrailingProps, tables, themeNames, themes, timeline, toSource, tspans, use, writeLayout };
31
+ export { BOOLS, type Box, type Component, type ConvertResult, type Curve, type Decoration, type Diagnostic, type Diagram, type DiagramJSON, type Direction, EDGE_PROPS, ENUMS, type EdgeDecl, type EdgeOverride, type FrameKind, GRID, GROUP_PROPS, GUIDE, type GroupDecl, type HeadKind, type InkColors, InputFormat, type JsonResult, KNOWN_SETTINGS, type LabelRef, type LaidEdge, type LaidGroup, type LaidNode, type LaidPanel, type Layout, type LayoutOverrides, type LexedLine, type LineStyle, type MarkerKind, type MdBlock, type MdOptions, type MdResult, NODE_PROPS, NUMBERS, type NodeDecl, type NodeOverride, Options, PANELS, PANEL_PROPS, type PanelCtx, type PanelDecl, type PanelHandle, type PanelKind, type PanelOverride, type PanelPart, type ParseOptions, type PartAction, type PartChange, type PartEdit, type Point, type Props, RAMPS, type ResolvedEdgeStyle, type ResolvedNodeStyle, Result, type RowCtx, type RowKind, type RowPaint, SETTING_VALUES, SHAPES, type Seg, type ShapeKind, type ShapeName, type Side, type SourceRef, type StatementKind, THEMES, THEME_KEYS, THEME_NAMES, TONES, type Theme, type ThemeInput, type Tok, type TokKind, type YuhwaPlugin, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, getTheme, git, groupPath, hash, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, layout, legend, lex, lineStyle, lint, onlyColor, parse, parseInline, parseProps, perPass, processMarkdown, ramp, recolor, registerTheme, registry, renderHead, renderSegs, renderSvg, replaceBlockSource, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, splitTrailingProps, tables, themeNames, themes, timeline, toSource, tspans, use, writeLayout, writePanelDrag };
package/dist/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as BOOLS, A as footer, B as PANELS, C as git, Ct as ramp, D as legend, E as sequence, F as perPass, G as lex, H as blockBraces, I as recolor, J as parseProps, K as onlyColor, L as registry, M as tables, N as charts, O as approxMeasure, P as themes, Q as splitTrailingProps, R as use, S as builtins, St as isToneOrHex, T as timeline, Tt as themeNames, U as isYuhwaPath, V as SETTING_VALUES, W as joinPath, X as setLineProp, Y as serializeProps, Z as setTrailingProp, _ as fromJSON, _t as THEME_KEYS, a as findBlocks, at as PANEL_PROPS, b as groupPath, bt as createTheme, c as editPart, ct as renderHead, d as setPartTone, dt as parseInline, et as EDGE_PROPS, f as setProp, ft as renderSegs, g as isMermaid, gt as THEMES, h as fromMermaid, ht as RAMPS, i as GUIDE, it as NUMBERS, j as frames, k as canvasMeasure, l as formatLayout, lt as dashFor, m as writeLayout, mt as tspans, n as render$1, nt as GROUP_PROPS, o as processMarkdown, ot as lint, p as setSetting, pt as segsW, q as parse, r as toSource, rt as NODE_PROPS, s as replaceBlockSource, st as SHAPES, t as hash, tt as ENUMS, u as setLabel, ut as lineStyle, v as renderSvg, vt as THEME_NAMES, w as chart, wt as registerTheme, x as layout, xt as getTheme, y as GRID, yt as TONES, z as KNOWN_SETTINGS } from "./src-CAxa6h4u.js";
1
+ import { $ as splitTrailingProps, A as canvasMeasure, B as KNOWN_SETTINGS, C as builtins, Ct as isSafeCss, D as sequence, Dt as registerTheme, E as timeline, Et as ramp, F as themes, G as joinPath, H as SETTING_VALUES, I as perPass, J as parse, K as lex, L as recolor, M as frames, N as tables, O as legend, Ot as themeNames, P as charts, Q as setTrailingProp, R as registry, S as layout, St as getTheme, T as chart, Tt as isToneOrHex, U as blockBraces, V as PANELS, W as isYuhwaPath, X as serializeProps, Y as parseProps, Z as setLineProp, _ as isMermaid, _t as THEMES, a as findBlocks, at as NUMBERS, b as GRID, bt as TONES, c as editPart, ct as SHAPES, d as setPartTone, dt as lineStyle, et as BOOLS, f as setProp, ft as parseInline, g as fromMermaid, gt as RAMPS, h as writePanelDrag, ht as tspans, i as GUIDE, it as NODE_PROPS, j as footer, k as approxMeasure, l as formatLayout, lt as renderHead, m as writeLayout, mt as segsW, n as render$1, nt as ENUMS, o as processMarkdown, ot as PANEL_PROPS, p as setSetting, pt as renderSegs, q as onlyColor, r as toSource, rt as GROUP_PROPS, s as replaceBlockSource, st as lint, t as hash, tt as EDGE_PROPS, u as setLabel, ut as dashFor, v as fromJSON, vt as THEME_KEYS, w as git, wt as isSafeLink, x as groupPath, xt as createTheme, y as renderSvg, yt as THEME_NAMES, z as use } from "./src-wk7tBpWs.js";
2
2
  // src/browser.ts
3
3
  /**
4
4
  * Drop-in browser runtime: <script src="yuhwa.js"><\/script>
@@ -87,13 +87,15 @@ const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
87
87
  var YuhwaDiagram = class extends Base {
88
88
  static observedAttributes = ["theme", "src"];
89
89
  #source = null;
90
- #fetched = "";
90
+ #fetched = null;
91
+ #request = 0;
91
92
  #file;
92
93
  #files = {};
93
94
  get source() {
94
95
  return this.#source ?? "";
95
96
  }
96
97
  set source(v) {
98
+ this.#request++;
97
99
  this.#source = v;
98
100
  this.#draw();
99
101
  }
@@ -107,15 +109,22 @@ var YuhwaDiagram = class extends Base {
107
109
  }
108
110
  #update() {
109
111
  const src = this.getAttribute("src");
110
- if (!src || src === this.#fetched) return this.#draw();
112
+ if (src === this.#fetched) return this.#draw();
113
+ const request = ++this.#request;
111
114
  this.#fetched = src;
115
+ if (!src) return this.#draw();
112
116
  const url = new URL(src, location.href);
113
117
  const file = url.origin === location.origin ? url.pathname : url.href;
114
118
  fetchText(url.href).then(async (t) => {
115
- this.#files = await fetchImports(t, file);
119
+ if (request !== this.#request) return;
120
+ const files = await fetchImports(t, file);
121
+ if (request !== this.#request) return;
122
+ this.#files = files;
116
123
  this.#file = file;
117
124
  this.source = t;
118
- }).catch((e) => this.#fail(e.message));
125
+ }).catch((e) => {
126
+ if (request === this.#request) this.#fail(e.message);
127
+ });
119
128
  }
120
129
  #draw() {
121
130
  if (this.#source === null) return;
@@ -155,4 +164,4 @@ if (typeof document !== "undefined") {
155
164
  else run();
156
165
  }
157
166
  }
158
- export { BOOLS, EDGE_PROPS, ENUMS, GRID, GROUP_PROPS, GUIDE, KNOWN_SETTINGS, NODE_PROPS, NUMBERS, PANELS, PANEL_PROPS, RAMPS, SETTING_VALUES, SHAPES, THEMES, THEME_KEYS, THEME_NAMES, TONES, YuhwaDiagram, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, fetchImports, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, getTheme, git, groupPath, hash, isMermaid, isToneOrHex, isYuhwaPath, joinPath, layout, legend, lex, lineStyle, lint, onlyColor, parse, parseInline, parseProps, perPass, processMarkdown, ramp, recolor, registerTheme, registry, render, renderHead, renderSegs, renderSvg, replaceBlockSource, run, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, splitTrailingProps, tables, themeNames, themes, timeline, toSource, tspans, use, writeLayout };
167
+ export { BOOLS, EDGE_PROPS, ENUMS, GRID, GROUP_PROPS, GUIDE, KNOWN_SETTINGS, NODE_PROPS, NUMBERS, PANELS, PANEL_PROPS, RAMPS, SETTING_VALUES, SHAPES, THEMES, THEME_KEYS, THEME_NAMES, TONES, YuhwaDiagram, approxMeasure, blockBraces, builtins, canvasMeasure, chart, charts, createTheme, dashFor, editPart, fetchImports, findBlocks, footer, formatLayout, frames, fromJSON, fromMermaid, getTheme, git, groupPath, hash, isMermaid, isSafeCss, isSafeLink, isToneOrHex, isYuhwaPath, joinPath, layout, legend, lex, lineStyle, lint, onlyColor, parse, parseInline, parseProps, perPass, processMarkdown, ramp, recolor, registerTheme, registry, render, renderHead, renderSegs, renderSvg, replaceBlockSource, run, segsW, sequence, serializeProps, setLabel, setLineProp, setPartTone, setProp, setSetting, setTrailingProp, splitTrailingProps, tables, themeNames, themes, timeline, toSource, tspans, use, writeLayout, writePanelDrag };
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
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-BHxDevlD.js";
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";
4
4
  import { createServer } from "node:http";
5
- import { basename, dirname, extname, join, resolve } from "node:path";
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 { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
@@ -23,8 +23,11 @@ import { deflateSync, inflateRawSync, inflateSync } from "node:zlib";
23
23
  */
24
24
  const COMMENT_OPEN = /^<!--\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
25
25
  const FENCE_OPEN = /^(```+|~~~+)\s*yuhwa(?:\s+([\w.-]+))?\s*$/;
26
- const IMAGE_LINE = /^(!\[[^\]]*\]\([^)]*\.svg\)|<picture>.*<\/picture>)\s*$/;
27
- function findBlocks(md, baseName = "diagram") {
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})`;
29
+ }
30
+ function findBlocks(md, baseName = "diagram", outDir = "diagrams") {
28
31
  const lines = md.split("\n");
29
32
  const blocks = [];
30
33
  const used = /* @__PURE__ */ new Set();
@@ -61,7 +64,9 @@ function findBlocks(md, baseName = "diagram") {
61
64
  };
62
65
  let k = j + 1;
63
66
  while (k < lines.length && lines[k].trim() === "" && k <= j + 1) k++;
64
- if (k < lines.length && IMAGE_LINE.test(lines[k].trim())) b.image = [k, k];
67
+ const candidate = lines[k]?.trim();
68
+ const path = joinPath(outDir, `${n}.svg`);
69
+ if (candidate === imageRef(n, path) || candidate === imageRef(n, path, joinPath(outDir, `${n}.dark.svg`))) b.image = [k, k];
65
70
  blocks.push(b);
66
71
  i = j;
67
72
  }
@@ -70,7 +75,7 @@ function findBlocks(md, baseName = "diagram") {
70
75
  const joinPath = (dir, file) => dir ? dir.replace(/\/+$/, "") + "/" + file : file;
71
76
  function processMarkdown(md, opts = {}) {
72
77
  const outDir = opts.outDir ?? "diagrams";
73
- const blocks = findBlocks(md, opts.baseName);
78
+ const blocks = findBlocks(md, opts.baseName, outDir);
74
79
  const lines = md.split("\n");
75
80
  const files = [];
76
81
  const diagnostics = [];
@@ -91,7 +96,7 @@ function processMarkdown(md, opts = {}) {
91
96
  path: lightPath,
92
97
  svg: light.svg + "\n"
93
98
  });
94
- let ref = `![${b.name}](${lightPath})`;
99
+ let ref = imageRef(b.name, lightPath);
95
100
  if (opts.dark) {
96
101
  const dark = render$1(b.source, {
97
102
  ...io,
@@ -102,7 +107,7 @@ function processMarkdown(md, opts = {}) {
102
107
  path: darkPath,
103
108
  svg: dark.svg + "\n"
104
109
  });
105
- ref = `<picture><source media="(prefers-color-scheme: dark)" srcset="${darkPath}"><img alt="${b.name}" src="${lightPath}"></picture>`;
110
+ ref = imageRef(b.name, lightPath, darkPath);
106
111
  }
107
112
  const replacement = [];
108
113
  if (b.kind === "fence" && !opts.keepFences) replacement.push(`<!--yuhwa ${b.name}`, ...b.source.split("\n"), "-->");
@@ -369,16 +374,15 @@ function decodeSource(encoded, compressed) {
369
374
  return inflateRawSync(buf).toString("utf8");
370
375
  }
371
376
  }
372
- function readBody(req) {
377
+ function readBody(req, max = MAX_BODY) {
373
378
  return new Promise((ok, fail) => {
374
379
  let size = 0;
375
380
  const chunks = [];
376
381
  req.on("data", (c) => {
377
382
  size += c.length;
378
- if (size > MAX_BODY) fail(Object.assign(/* @__PURE__ */ new Error("body too large"), { status: 413 }));
379
- else chunks.push(c);
383
+ if (size <= max) chunks.push(c);
380
384
  });
381
- req.on("end", () => ok(Buffer.concat(chunks).toString("utf8")));
385
+ req.on("end", () => size > max ? fail(Object.assign(/* @__PURE__ */ new Error("body too large"), { status: 413 })) : ok(Buffer.concat(chunks).toString("utf8")));
382
386
  req.on("error", fail);
383
387
  });
384
388
  }
@@ -419,6 +423,8 @@ function handler(req, res) {
419
423
  const r = render$1(source, { theme });
420
424
  const errors = r.diagnostics.filter((d) => d.severity === "error");
421
425
  res.setHeader("content-type", "image/svg+xml; charset=utf-8");
426
+ res.setHeader("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:");
427
+ res.setHeader("x-content-type-options", "nosniff");
422
428
  res.setHeader("x-yuhwa-format", r.format);
423
429
  if (errors.length) res.setHeader("x-yuhwa-errors", errors.map((d) => `${d.line}: ${d.message}`).join(" | ").slice(0, 2e3));
424
430
  if (cache && !errors.length) res.setHeader("cache-control", "public, max-age=31536000, immutable");
@@ -476,6 +482,48 @@ function serve(port, host) {
476
482
  });
477
483
  return server;
478
484
  }
485
+ // src/cli/save.ts
486
+ function saveEditorFiles(file, mainName, block, loaded, update) {
487
+ const base = dirname(resolve(file));
488
+ const entries = Object.entries(update.files ?? {});
489
+ for (const [name, text] of entries) {
490
+ if (name !== mainName && !loaded.has(name)) throw new Error(`${name} is not part of this diagram`);
491
+ if (typeof text !== "string") throw new Error(`invalid contents for ${name}`);
492
+ }
493
+ const written = [];
494
+ for (const [name, text] of entries) {
495
+ if (name === mainName) continue;
496
+ const path = join(base, name);
497
+ if (!existsSync(path) || readFileSync(path, "utf8") !== text) {
498
+ writeFileSync(path, text);
499
+ written.push(name);
500
+ }
501
+ }
502
+ const source = update.files?.[mainName] ?? update.source;
503
+ const previous = readFileSync(file, "utf8");
504
+ let next = previous;
505
+ if (block === void 0) next = source ?? previous;
506
+ else {
507
+ const md = source === void 0 ? previous : replaceBlockSource(previous, block, source);
508
+ if (md === previous && !written.length && update.source === void 0) return written;
509
+ const result = processMarkdown(md, {
510
+ baseName: basename(file, extname(file)).toLowerCase(),
511
+ resolve: diskResolve,
512
+ file
513
+ });
514
+ for (const asset of result.files) {
515
+ const path = join(base, asset.path);
516
+ mkdirSync(dirname(path), { recursive: true });
517
+ writeFileSync(path, asset.svg);
518
+ }
519
+ next = result.markdown;
520
+ }
521
+ if (next !== previous) {
522
+ writeFileSync(file, next);
523
+ written.push(mainName);
524
+ }
525
+ return written;
526
+ }
479
527
  // src/browser.ts
480
528
  /**
481
529
  * Drop-in browser runtime: <script src="yuhwa.js"><\/script>
@@ -564,13 +612,15 @@ const Base = typeof HTMLElement === "undefined" ? class {} : HTMLElement;
564
612
  var YuhwaDiagram = class extends Base {
565
613
  static observedAttributes = ["theme", "src"];
566
614
  #source = null;
567
- #fetched = "";
615
+ #fetched = null;
616
+ #request = 0;
568
617
  #file;
569
618
  #files = {};
570
619
  get source() {
571
620
  return this.#source ?? "";
572
621
  }
573
622
  set source(v) {
623
+ this.#request++;
574
624
  this.#source = v;
575
625
  this.#draw();
576
626
  }
@@ -584,15 +634,22 @@ var YuhwaDiagram = class extends Base {
584
634
  }
585
635
  #update() {
586
636
  const src = this.getAttribute("src");
587
- if (!src || src === this.#fetched) return this.#draw();
637
+ if (src === this.#fetched) return this.#draw();
638
+ const request = ++this.#request;
588
639
  this.#fetched = src;
640
+ if (!src) return this.#draw();
589
641
  const url = new URL(src, location.href);
590
642
  const file = url.origin === location.origin ? url.pathname : url.href;
591
643
  fetchText(url.href).then(async (t) => {
592
- this.#files = await fetchImports(t, file);
644
+ if (request !== this.#request) return;
645
+ const files = await fetchImports(t, file);
646
+ if (request !== this.#request) return;
647
+ this.#files = files;
593
648
  this.#file = file;
594
649
  this.source = t;
595
- }).catch((e) => this.#fail(e.message));
650
+ }).catch((e) => {
651
+ if (request === this.#request) this.#fail(e.message);
652
+ });
596
653
  }
597
654
  #draw() {
598
655
  if (this.#source === null) return;
@@ -813,15 +870,6 @@ function cmdEdit(a) {
813
870
  const text = readFileSync(file, "utf8");
814
871
  return isMd ? findBlocks(text)[blockIdx].source : text;
815
872
  };
816
- const writeSource = (src) => {
817
- if (!isMd) return writeFileSync(file, src);
818
- const res = processMarkdown(replaceBlockSource(readFileSync(file, "utf8"), blockIdx, src), { baseName: basename(file, extname(file)).toLowerCase() });
819
- for (const f of res.files) {
820
- mkdirSync(dirname(join(base, f.path)), { recursive: true });
821
- writeFileSync(join(base, f.path), f.svg);
822
- }
823
- writeFileSync(file, res.markdown);
824
- };
825
873
  const mainName = isMd ? `${basename(file)} #${blockIdx}` : basename(file);
826
874
  const loaded = /* @__PURE__ */ new Set();
827
875
  createServer((req, res) => {
@@ -834,7 +882,14 @@ function cmdEdit(a) {
834
882
  }
835
883
  if (url.pathname === "/api/source") {
836
884
  if (req.method === "GET") {
837
- const source = readSource();
885
+ let source;
886
+ try {
887
+ source = readSource();
888
+ } catch (e) {
889
+ res.statusCode = 500;
890
+ res.end(JSON.stringify({ error: String(e) }));
891
+ return;
892
+ }
838
893
  fetchImports(source, basename(file), async (p) => diskResolve(join(base, p)) ?? Promise.reject(/* @__PURE__ */ new Error(`cannot import ${p}`))).then((files) => {
839
894
  for (const p of Object.keys(files)) loaded.add(p);
840
895
  res.setHeader("content-type", "application/json");
@@ -848,37 +903,23 @@ function cmdEdit(a) {
848
903
  return;
849
904
  }
850
905
  if (req.method === "PUT") {
851
- let body = "";
852
- req.on("data", (c) => body += c);
853
- req.on("end", () => {
854
- try {
855
- const j = JSON.parse(body);
856
- if (typeof j.source === "string") writeSource(j.source);
857
- const written = [];
858
- for (const [name, text] of Object.entries(j.files ?? {})) {
859
- if (name === mainName) {
860
- if (text !== readSource()) writeSource(text), written.push(name);
861
- continue;
862
- }
863
- if (!loaded.has(name)) throw new Error(`${name} is not part of this diagram`);
864
- const p = join(base, name);
865
- if (!existsSync(p) || readFileSync(p, "utf8") !== text) writeFileSync(p, text), written.push(name);
866
- }
867
- res.end(JSON.stringify({
868
- ok: true,
869
- written
870
- }));
871
- } catch (e) {
872
- res.statusCode = 400;
873
- res.end(JSON.stringify({ error: String(e) }));
874
- }
906
+ readBody(req, 16 << 20).then((body) => {
907
+ const j = JSON.parse(body);
908
+ const written = saveEditorFiles(file, mainName, isMd ? blockIdx : void 0, loaded, j);
909
+ res.end(JSON.stringify({
910
+ ok: true,
911
+ written
912
+ }));
913
+ }).catch((e) => {
914
+ res.statusCode = e.status ?? 400;
915
+ res.end(JSON.stringify({ error: String(e) }));
875
916
  });
876
917
  return;
877
918
  }
878
919
  }
879
920
  const name = url.pathname === "/" ? "index.html" : url.pathname.slice(1);
880
921
  const p = join(dir, name);
881
- if (!p.startsWith(dir) || !existsSync(p) || statSync(p).isDirectory()) {
922
+ if (!p.startsWith(dir + sep) || !existsSync(p) || statSync(p).isDirectory()) {
882
923
  res.statusCode = 404;
883
924
  res.end("not found");
884
925
  return;