vantage-md 0.5.4 → 0.5.6

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/index.js CHANGED
@@ -1,1025 +1,1458 @@
1
- import { unified } from 'unified';
2
- import remarkParse from 'remark-parse';
3
- import remarkRehype from 'remark-rehype';
4
- import rehypeStringify from 'rehype-stringify';
5
- import remarkGfm from 'remark-gfm';
6
- import remarkMath from 'remark-math';
7
- import rehypeRaw from 'rehype-raw';
8
- import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
9
- import rehypeHighlight from 'rehype-highlight';
10
- import rehypeKatex from 'rehype-katex';
11
- import rehypeSlug from 'rehype-slug';
12
- import YAML from 'yaml';
13
- import { parse } from 'smol-toml';
14
-
15
- // src/renderMarkdown.ts
16
-
17
- // src/rehypeSourceLines.ts
18
- var BLOCK_TAGS = /* @__PURE__ */ new Set([
19
- "p",
20
- "h1",
21
- "h2",
22
- "h3",
23
- "h4",
24
- "h5",
25
- "h6",
26
- "li",
27
- "blockquote",
28
- "pre",
29
- "table",
30
- "tr",
31
- "ul",
32
- "ol",
33
- "hr",
34
- "div"
1
+ import { unified } from "unified";
2
+ import remarkParse from "remark-parse";
3
+ import remarkRehype from "remark-rehype";
4
+ import rehypeStringify from "rehype-stringify";
5
+ import remarkGfm from "remark-gfm";
6
+ import remarkMath from "remark-math";
7
+ import rehypeRaw from "rehype-raw";
8
+ import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
9
+ import rehypeHighlight from "rehype-highlight";
10
+ import rehypeKatex from "rehype-katex";
11
+ import rehypeSlug from "rehype-slug";
12
+ import YAML from "yaml";
13
+ import { parse } from "smol-toml";
14
+ //#region src/rehypeSourceLines.ts
15
+ const BLOCK_TAGS = /* @__PURE__ */ new Set([
16
+ "p",
17
+ "h1",
18
+ "h2",
19
+ "h3",
20
+ "h4",
21
+ "h5",
22
+ "h6",
23
+ "li",
24
+ "blockquote",
25
+ "pre",
26
+ "table",
27
+ "tr",
28
+ "ul",
29
+ "ol",
30
+ "hr",
31
+ "div"
35
32
  ]);
36
33
  function visit(node, offset) {
37
- if ("children" in node) {
38
- for (const child of node.children) {
39
- if (child.type === "element") {
40
- if (BLOCK_TAGS.has(child.tagName) && child.position?.start?.line) {
41
- child.properties = child.properties || {};
42
- child.properties["dataSourceLine"] = child.position.start.line + offset;
43
- }
44
- visit(child, offset);
45
- }
46
- }
47
- }
34
+ if ("children" in node) {
35
+ for (const child of node.children) if (child.type === "element") {
36
+ if (BLOCK_TAGS.has(child.tagName) && child.position?.start?.line) {
37
+ child.properties = child.properties || {};
38
+ child.properties["dataSourceLine"] = child.position.start.line + offset;
39
+ }
40
+ visit(child, offset);
41
+ }
42
+ }
48
43
  }
49
- var rehypeSourceLines = (options) => {
50
- const offset = options?.offset ?? 0;
51
- return (tree) => {
52
- visit(tree, offset);
53
- };
44
+ const rehypeSourceLines = (options) => {
45
+ const offset = options?.offset ?? 0;
46
+ return (tree) => {
47
+ visit(tree, offset);
48
+ };
54
49
  };
55
- var rehypeSourceLines_default = rehypeSourceLines;
56
-
57
- // src/vantageDirectives.ts
58
- var VANTAGE_SENTINEL = "vantage:";
59
- var DIRECTIVE_NAMES = ["section", "block", "oq"];
60
- var VANTAGE_TONES = [
61
- "note",
62
- "tip",
63
- "important",
64
- "warning",
65
- "caution",
66
- "muted"
50
+ //#endregion
51
+ //#region src/vantageDirectives.ts
52
+ /**
53
+ * The directive grammar and the closed vocabulary — one parser, no renderer.
54
+ *
55
+ * A Vantage directive is an ordinary HTML comment carrying a `vantage:`
56
+ * sentinel: `<!-- vantage: section tone=warning -->`. GitHub drops it, every
57
+ * other Markdown renderer drops it, and Vantage compiles it into
58
+ * `data-vantage-*` attributes on the block that follows
59
+ * (`rehypeVantageDirectives`). See `docs/reference/inline-markup.md`, "The carrier and the grammar".
60
+ *
61
+ * This module is deliberately **zero-dependency — not even a type import**, and
62
+ * it knows nothing about hast. Two callers need it and only one of them has a
63
+ * tree: the rehype plugin stamps attributes, and the `vantage-check` CLI
64
+ * validates directives with no rendering at all, importing this file by
65
+ * relative path. A checker with its own copy of the grammar is a checker that
66
+ * disagrees with the renderer, which is the failure D5 names.
67
+ *
68
+ * Everything here is a pure function of a string. Nothing throws, nothing logs
69
+ * (P3): a comment that is not a directive is `null`, and a comment that carries
70
+ * the sentinel but does not parse is `malformed` with a reason only the checker
71
+ * reads.
72
+ */
73
+ /**
74
+ * The mandatory sentinel — the full word, never a terser `v:`.
75
+ *
76
+ * It is what keeps an ordinary `<!-- TODO: rewrite this -->` from being parsed
77
+ * as markup, and it makes the common case a prefix test rather than a grammar
78
+ * attempt (Ledger OQ-1).
79
+ */
80
+ const VANTAGE_SENTINEL = "vantage:";
81
+ /**
82
+ * The closed name set. An unknown name drops the **whole** directive: there is
83
+ * no target semantics without a name. An unknown key or value drops only that
84
+ * pair (D2 is per-key).
85
+ *
86
+ * Position picks the target; the name picks the extent. `section` before a
87
+ * heading reaches the heading's whole section, `block` reaches one block, and
88
+ * `oq` marks one answerable question. The name cannot disagree with position —
89
+ * it only says how far the stamp reaches — so §4.2's refusal of a `scope=` key
90
+ * stands.
91
+ */
92
+ const DIRECTIVE_NAMES = [
93
+ "section",
94
+ "block",
95
+ "oq"
96
+ ];
97
+ /**
98
+ * The `tone` vocabulary: GitHub's alert words plus `muted`.
99
+ *
100
+ * Semantic, never chromatic (P2, Ledger OQ-3). A document says what a section
101
+ * *is*; the theme decides what that looks like, which is what lets one document
102
+ * render correctly in light, in dark, and in themes that do not exist yet.
103
+ */
104
+ const VANTAGE_TONES = [
105
+ "note",
106
+ "tip",
107
+ "important",
108
+ "warning",
109
+ "caution",
110
+ "muted"
111
+ ];
112
+ /** How much the block should pull the eye — separate from `tone` on purpose. */
113
+ const VANTAGE_EMPHASIS = [
114
+ "strong",
115
+ "normal",
116
+ "quiet"
67
117
  ];
68
- var VANTAGE_EMPHASIS = ["strong", "normal", "quiet"];
69
- var VANTAGE_BADGES = [
70
- "draft",
71
- "stale",
72
- "blocked",
73
- "done",
74
- "wip"
118
+ /** A small chip beside the heading. */
119
+ const VANTAGE_BADGES = [
120
+ "draft",
121
+ "stale",
122
+ "blocked",
123
+ "done",
124
+ "wip"
75
125
  ];
76
- var VANTAGE_COLLAPSED = ["true", "false"];
77
- var VANTAGE_RUNS = ["start", "middle", "end", "only"];
78
- var VANTAGE_STYLE_TARGETS = [
79
- "p",
80
- "h1",
81
- "h2",
82
- "h3",
83
- "h4",
84
- "h5",
85
- "h6",
86
- "li",
87
- "blockquote",
88
- "pre",
89
- "table",
90
- "tr",
91
- "ul",
92
- "ol",
93
- "hr",
94
- "div"
126
+ /**
127
+ * `collapsed` is a token, not a flag: `false` is the default written down.
128
+ *
129
+ * It stamps nothing on its own. Its one real effect is overriding a
130
+ * `collapsed=true` earlier in the same merged directive run — last key wins — so
131
+ * it is in the vocabulary rather than being an unknown value that drops. It
132
+ * cannot cancel an *enclosing* collapsed section: a nested heading is a hidden
133
+ * member of the outer group by design (A3), and the outer run is stamped before
134
+ * any inner directive has been resolved.
135
+ */
136
+ const VANTAGE_COLLAPSED = ["true", "false"];
137
+ /**
138
+ * Where a block sits in a stamped run, so section-wide CSS can join its members
139
+ * without an adjacent-sibling combinator.
140
+ *
141
+ * Not cosmetic. Review mode inserts comment cards as siblings *inside* a
142
+ * stamped run (`useReviewHighlights`), so `[tone] + [tone]` severs at every
143
+ * commented paragraph and bleeds across the boundary between two adjacent runs
144
+ * of different tone. An attribute survives both.
145
+ */
146
+ const VANTAGE_RUNS = [
147
+ "start",
148
+ "middle",
149
+ "end",
150
+ "only"
95
151
  ];
96
- var VANTAGE_ANCHOR_TARGETS = [
97
- "p",
98
- "h1",
99
- "h2",
100
- "h3",
101
- "h4",
102
- "h5",
103
- "h6",
104
- "li",
105
- "blockquote",
106
- "pre",
107
- "table"
152
+ /**
153
+ * The tags a `section`/`block` directive may stamp.
154
+ *
155
+ * Deliberately `rehypeSourceLines`'s `BLOCK_TAGS`: a stamped block should also
156
+ * be a block with a `data-source-line`, so the styling surface and the anchor
157
+ * surface coincide. It also keeps an inline directive from stamping the `<em>`
158
+ * that happens to follow it inside a paragraph.
159
+ *
160
+ * It lives here rather than in the plugin because the CLI checker has to answer
161
+ * "will this directive stamp anything?" from an mdast tree with no hast in
162
+ * sight. A checker with its own copy of this list is a checker that calls a
163
+ * working directive an orphan, or stays silent about a dead one (D5).
164
+ */
165
+ const VANTAGE_STYLE_TARGETS = [
166
+ "p",
167
+ "h1",
168
+ "h2",
169
+ "h3",
170
+ "h4",
171
+ "h5",
172
+ "h6",
173
+ "li",
174
+ "blockquote",
175
+ "pre",
176
+ "table",
177
+ "tr",
178
+ "ul",
179
+ "ol",
180
+ "hr",
181
+ "div"
108
182
  ];
109
- var VANTAGE_OQ_HOST_TARGETS = VANTAGE_ANCHOR_TARGETS.filter(
110
- (tag) => tag !== "pre" && tag !== "table"
111
- );
112
- var STYLE_KEYS = {
113
- tone: VANTAGE_TONES,
114
- emphasis: VANTAGE_EMPHASIS,
115
- badge: VANTAGE_BADGES,
116
- collapsed: VANTAGE_COLLAPSED
183
+ /**
184
+ * The tags an `oq` directive may stamp — strictly the tags the review system
185
+ * can resolve an anchor on (`ANCHOR_TAGS` in the app's `MarkdownViewer`, and the
186
+ * block map in `useReviewHighlights`). `ul`, `ol`, `tr`, `hr` and `div` are in
187
+ * neither, so a button on one of them would build an anchor no review pass can
188
+ * find — the "mis-wired button" D6 forbids.
189
+ *
190
+ * The gap between this list and `VANTAGE_STYLE_TARGETS` is why an `oq`
191
+ * directive at column 0 above a list silently does nothing: the target is the
192
+ * `<ul>`, not the `<li>`. The checker says so.
193
+ */
194
+ const VANTAGE_ANCHOR_TARGETS = [
195
+ "p",
196
+ "h1",
197
+ "h2",
198
+ "h3",
199
+ "h4",
200
+ "h5",
201
+ "h6",
202
+ "li",
203
+ "blockquote",
204
+ "pre",
205
+ "table"
206
+ ];
207
+ /**
208
+ * The tags a `<!-- vantage: oq … -->` directive actually yields a *button* on —
209
+ * `VANTAGE_ANCHOR_TARGETS` minus `pre` and `table`, written as an explicit
210
+ * subtraction so the narrowing stays visible.
211
+ *
212
+ * Anchorable and button-hosting are different questions, and this is the second
213
+ * one. A comment *can* be anchored on a `<pre>` or a `<table>` — both are in
214
+ * `ANCHOR_TAGS` — but neither can hold the affordance: inside a `<pre>` the
215
+ * button renders as part of the code, and a `<button>` child of `<table>` is not
216
+ * valid HTML at all, so the parser hoists it out.
217
+ *
218
+ * Both consumers read it from here: `OQ_HOST_TAGS` in the app's
219
+ * `useOpenQuestionButtons`, and the `oq` branch of the checker's
220
+ * `vantage/orphan`. They were two hand-written lists that disagreed — the
221
+ * checker called an `oq` above a fence fine while the app rendered no button
222
+ * and said nothing, which is the D5 break this module exists to prevent.
223
+ */
224
+ const VANTAGE_OQ_HOST_TARGETS = VANTAGE_ANCHOR_TARGETS.filter((tag) => tag !== "pre" && tag !== "table");
225
+ const STYLE_KEYS = {
226
+ tone: VANTAGE_TONES,
227
+ emphasis: VANTAGE_EMPHASIS,
228
+ badge: VANTAGE_BADGES,
229
+ collapsed: VANTAGE_COLLAPSED
117
230
  };
118
- var DIRECTIVE_VOCABULARY = {
119
- section: STYLE_KEYS,
120
- block: STYLE_KEYS,
121
- oq: { id: null, leaning: null }
231
+ /**
232
+ * Name → key → the closed value set for that key.
233
+ *
234
+ * `section` and `block` share their keys: they differ in *extent*, not in what
235
+ * they can say. `oq`'s two keys are the design's only values with no closed set
236
+ * — `id` is a token an author chose and `leaning` is a sentence (§8.3) — so
237
+ * neither can be value-allowlisted, which is recorded here as `null` rather
238
+ * than left to a caller to guess.
239
+ */
240
+ const DIRECTIVE_VOCABULARY = {
241
+ section: STYLE_KEYS,
242
+ block: STYLE_KEYS,
243
+ oq: {
244
+ id: null,
245
+ leaning: null
246
+ }
122
247
  };
123
- var WS = /[ \t\r\n]*/y;
124
- var SENTINEL_PREFIX = /^[ \t\r\n]*vantage:/;
125
- var NAME = /[a-z][a-z0-9-]*/y;
126
- var UNQUOTED = /[A-Za-z0-9_.:#-]+/y;
127
- var QUOTED = /"[^"]*"/y;
248
+ /**
249
+ * `ws` is `[ \t\r\n]` — the design's grammar leaves it undefined, and `\n` has
250
+ * to be in the set because a directive may legally wrap: a multi-line comment
251
+ * is one node whose value contains the newlines.
252
+ */
253
+ const WS = /[ \t\r\n]*/y;
254
+ const SENTINEL_PREFIX = /^[ \t\r\n]*vantage:/;
255
+ const NAME = /[a-z][a-z0-9-]*/y;
256
+ const UNQUOTED = /[A-Za-z0-9_.:#-]+/y;
257
+ /**
258
+ * A quoted value holds anything but a `"`, `--` included: measured through the
259
+ * real chain, `leaning="a--b"` reaches the tree intact, because HTML5 closes a
260
+ * comment on `-->` or `--!>` and on nothing else. There is deliberately **no**
261
+ * `--` restriction here. What a quoted value cannot hold is a terminator: a
262
+ * `-->` inside one ends the comment early and spills the tail into the document
263
+ * as literal text, which is a finding for the checker rather than a rule here —
264
+ * by the time this function runs, the truncation has already happened.
265
+ */
266
+ const QUOTED = /"[^"]*"/y;
267
+ /**
268
+ * The cheap prefix test. Runs first on every comment in every document, so an
269
+ * ordinary editorial comment never reaches the tokenizer.
270
+ *
271
+ * Note `<!--- vantage: x -->` is *not* a directive: its inner text begins with
272
+ * the extra `-`, and the sentinel must be the first thing in the comment.
273
+ */
128
274
  function hasVantageSentinel(comment) {
129
- return SENTINEL_PREFIX.test(comment);
275
+ return SENTINEL_PREFIX.test(comment);
130
276
  }
277
+ /** The whole non-whitespace run at `offset`, capped, for a quotable message. */
131
278
  function token(comment, offset) {
132
- const rest = comment.slice(offset);
133
- const end = rest.search(/[ \t\r\n]/);
134
- const word = end === -1 ? rest : rest.slice(0, end);
135
- return word.length > 24 ? `${word.slice(0, 24)}\u2026` : word;
279
+ const rest = comment.slice(offset);
280
+ const end = rest.search(/[ \t\r\n]/);
281
+ const word = end === -1 ? rest : rest.slice(0, end);
282
+ return word.length > 24 ? `${word.slice(0, 24)}…` : word;
136
283
  }
284
+ /** The sticky match at `offset`, or `null` if the pattern does not apply. */
137
285
  function matchAt(pattern, comment, offset) {
138
- pattern.lastIndex = offset;
139
- const match = pattern.exec(comment);
140
- return match === null ? null : match[0];
286
+ pattern.lastIndex = offset;
287
+ const match = pattern.exec(comment);
288
+ return match === null ? null : match[0];
141
289
  }
290
+ /** How much whitespace sits at `offset`. `WS` matches everywhere, empty. */
142
291
  function skipWhitespace(comment, offset) {
143
- return matchAt(WS, comment, offset)?.length ?? 0;
292
+ return matchAt(WS, comment, offset)?.length ?? 0;
144
293
  }
145
294
  function malformed(reason, offset) {
146
- return { kind: "malformed", reason, offset };
295
+ return {
296
+ kind: "malformed",
297
+ reason,
298
+ offset
299
+ };
147
300
  }
301
+ /**
302
+ * Parse one comment's **inner** text — the value of a hast `comment` node, with
303
+ * `<!--` and `-->` already stripped. `null` means "no sentinel, not ours".
304
+ *
305
+ * Hand-rolled rather than one regular expression, because a repeated capture
306
+ * group keeps only its last match and the checker needs an offset per token to
307
+ * point at the character that broke.
308
+ */
148
309
  function parseVantageDirective(comment) {
149
- const sentinel = SENTINEL_PREFIX.exec(comment);
150
- if (sentinel === null) return null;
151
- let at = sentinel[0].length;
152
- at += skipWhitespace(comment, at);
153
- const nameOffset = at;
154
- const name = matchAt(NAME, comment, at);
155
- if (name === null) {
156
- return malformed("no directive name after `vantage:`", at);
157
- }
158
- at += name.length;
159
- const pairs = [];
160
- while (at < comment.length) {
161
- const gap = skipWhitespace(comment, at);
162
- at += gap;
163
- if (at >= comment.length) break;
164
- if (gap === 0) {
165
- return malformed(`\`${token(comment, at)}\` needs a space before it`, at);
166
- }
167
- const keyOffset = at;
168
- const key = matchAt(NAME, comment, at);
169
- if (key === null) {
170
- return malformed(
171
- `\`${token(comment, at)}\` is not a \`key=value\` pair`,
172
- at
173
- );
174
- }
175
- at += key.length;
176
- if (comment[at] !== "=") {
177
- return malformed(`\`${key}\` is not followed by \`=value\``, at);
178
- }
179
- at += 1;
180
- const valueOffset = at;
181
- const quoted = matchAt(QUOTED, comment, at);
182
- if (quoted !== null) {
183
- at += quoted.length;
184
- pairs.push({
185
- key,
186
- value: quoted.slice(1, -1),
187
- keyOffset,
188
- valueOffset,
189
- quoted: true
190
- });
191
- continue;
192
- }
193
- const unquoted = matchAt(UNQUOTED, comment, at);
194
- if (unquoted === null) {
195
- const found = token(comment, at);
196
- return malformed(
197
- found === "" ? `\`${key}=\` has no value` : `\`${found}\` is not a valid value for \`${key}\``,
198
- at
199
- );
200
- }
201
- at += unquoted.length;
202
- pairs.push({ key, value: unquoted, keyOffset, valueOffset, quoted: false });
203
- }
204
- return { kind: "directive", name, nameOffset, pairs };
310
+ const sentinel = SENTINEL_PREFIX.exec(comment);
311
+ if (sentinel === null) return null;
312
+ let at = sentinel[0].length;
313
+ at += skipWhitespace(comment, at);
314
+ const nameOffset = at;
315
+ const name = matchAt(NAME, comment, at);
316
+ if (name === null) return malformed("no directive name after `vantage:`", at);
317
+ at += name.length;
318
+ const pairs = [];
319
+ while (at < comment.length) {
320
+ const gap = skipWhitespace(comment, at);
321
+ at += gap;
322
+ if (at >= comment.length) break;
323
+ if (gap === 0) return malformed(`\`${token(comment, at)}\` needs a space before it`, at);
324
+ const keyOffset = at;
325
+ const key = matchAt(NAME, comment, at);
326
+ if (key === null) return malformed(`\`${token(comment, at)}\` is not a \`key=value\` pair`, at);
327
+ at += key.length;
328
+ if (comment[at] !== "=") return malformed(`\`${key}\` is not followed by \`=value\``, at);
329
+ at += 1;
330
+ const valueOffset = at;
331
+ const quoted = matchAt(QUOTED, comment, at);
332
+ if (quoted !== null) {
333
+ at += quoted.length;
334
+ pairs.push({
335
+ key,
336
+ value: quoted.slice(1, -1),
337
+ keyOffset,
338
+ valueOffset,
339
+ quoted: true
340
+ });
341
+ continue;
342
+ }
343
+ const unquoted = matchAt(UNQUOTED, comment, at);
344
+ if (unquoted === null) {
345
+ const found = token(comment, at);
346
+ return malformed(found === "" ? `\`${key}=\` has no value` : `\`${found}\` is not a valid value for \`${key}\``, at);
347
+ }
348
+ at += unquoted.length;
349
+ pairs.push({
350
+ key,
351
+ value: unquoted,
352
+ keyOffset,
353
+ valueOffset,
354
+ quoted: false
355
+ });
356
+ }
357
+ return {
358
+ kind: "directive",
359
+ name,
360
+ nameOffset,
361
+ pairs
362
+ };
205
363
  }
206
-
207
- // src/rehypeVantageDirectives.ts
208
- var STYLE_TARGET_TAGS = new Set(VANTAGE_STYLE_TARGETS);
209
- var ANCHOR_TARGET_TAGS = new Set(VANTAGE_ANCHOR_TARGETS);
210
- var HEADING_DEPTHS = /* @__PURE__ */ new Map([
211
- ["h1", 1],
212
- ["h2", 2],
213
- ["h3", 3],
214
- ["h4", 4],
215
- ["h5", 5],
216
- ["h6", 6]
217
- ]);
218
- var RANGE_PROPERTIES = /* @__PURE__ */ new Map([
219
- ["tone", "dataVantageTone"],
220
- ["emphasis", "dataVantageEmphasis"]
364
+ //#endregion
365
+ //#region src/rehypeVantageDirectives.ts
366
+ /**
367
+ * What a `section`/`block` and an `oq` directive may stamp.
368
+ *
369
+ * Both lists live in `vantageDirectives.ts`, with the reasoning for each tag,
370
+ * because the CLI checker resolves the same question over mdast and must reach
371
+ * the same answer (D5).
372
+ */
373
+ const STYLE_TARGET_TAGS = new Set(VANTAGE_STYLE_TARGETS);
374
+ const ANCHOR_TARGET_TAGS = new Set(VANTAGE_ANCHOR_TARGETS);
375
+ const HEADING_DEPTHS = /* @__PURE__ */ new Map([
376
+ ["h1", 1],
377
+ ["h2", 2],
378
+ ["h3", 3],
379
+ ["h4", 4],
380
+ ["h5", 5],
381
+ ["h6", 6]
221
382
  ]);
222
- var POINT_PROPERTIES = /* @__PURE__ */ new Map([["badge", "dataVantageBadge"]]);
223
- var RUN_PROPERTY = "dataVantageRun";
224
- var OQ_PROPERTY = "dataVantageOq";
225
- var LEANING_PROPERTY = "dataVantageLeaning";
226
- var COLLAPSED_PROPERTY = "dataVantageCollapsed";
227
- var COLLAPSE_GROUP_PROPERTY = "dataVantageCollapseGroup";
228
- var COLLAPSE_TOGGLE_PROPERTY = "dataVantageCollapseToggle";
229
- var MAX_LEANING = 500;
383
+ /**
384
+ * Key → hast property, for the keys that treat a whole run.
385
+ *
386
+ * A camelCase hast property serialises to the kebab-case attribute, so
387
+ * `dataVantageTone` is `data-vantage-tone` in every renderer.
388
+ *
389
+ * `tone` and `emphasis` describe what a section *is* and how loud it is, so
390
+ * every block in the range wears them: the tone rule is a slice of one
391
+ * continuous line down the section, and the weight applies to all of its prose.
392
+ *
393
+ * `collapsed` is not here because it is not one property on one block: it puts a
394
+ * toggle on the heading and a collapsed flag plus a group id on every block the
395
+ * heading hides, which `stampStyle` does with the three properties below.
396
+ */
397
+ const RANGE_PROPERTIES = /* @__PURE__ */ new Map([["tone", "dataVantageTone"], ["emphasis", "dataVantageEmphasis"]]);
398
+ /**
399
+ * Key → hast property, for the keys that mark one block: the directive's target.
400
+ *
401
+ * `badge` is the asymmetry in the vocabulary and the reason this second map
402
+ * exists. It is not a treatment of a run but a single chip — "a small chip after
403
+ * the heading text" (§4.3), drawn as `[data-vantage-badge]::after` — so a
404
+ * section-wide stamp paints the word once per paragraph, list, table and fence
405
+ * under the heading instead of once beside it.
406
+ *
407
+ * The chip is fixed here rather than in the stylesheet, because narrowing the
408
+ * CSS to `:is(h1, …, h6)` would silently draw nothing for the two placements
409
+ * that legitimately badge a non-heading — `block badge=…` on a paragraph, and a
410
+ * `section` that degraded onto one (A1) — and would leave an attribute stamped
411
+ * on every block that says something untrue about it.
412
+ */
413
+ const POINT_PROPERTIES = /* @__PURE__ */ new Map([["badge", "dataVantageBadge"]]);
414
+ const RUN_PROPERTY = "dataVantageRun";
415
+ const OQ_PROPERTY = "dataVantageOq";
416
+ const LEANING_PROPERTY = "dataVantageLeaning";
417
+ /**
418
+ * The three properties `collapsed=true` stamps across a section.
419
+ *
420
+ * The heading takes a *different* attribute from the blocks it hides, and that
421
+ * asymmetry is the whole design (A3): a nested `###` inside a collapsed `##` is
422
+ * both a hidden member of the outer group and the toggle for its own, so one
423
+ * shared attribute would make it permanently invisible and unreachable by
424
+ * either toggle. There is no `<details>` and no wrapper — the run stays a flat
425
+ * list of siblings, which is what keeps review comment cards, the typography
426
+ * plugin's `h2 + *` margin resets and the anchor surface working.
427
+ *
428
+ * Hiding is CSS, and that CSS is gated on two markers the toggle JS sets — the
429
+ * prose container's readiness, and an armed marker on each block whose group it
430
+ * gave a caret (`docs/reference/inline-markup.md`, "Collapse without a wrapper"). A renderer without the JS
431
+ * — the CLI checker's HTML, an external consumer of this package — shows every
432
+ * block, and so does any block that ended up with no control.
433
+ */
434
+ const COLLAPSED_PROPERTY = "dataVantageCollapsed";
435
+ const COLLAPSE_GROUP_PROPERTY = "dataVantageCollapseGroup";
436
+ const COLLAPSE_TOGGLE_PROPERTY = "dataVantageCollapseToggle";
437
+ /** A review-comment body, not prose. Bounds the attribute; 500 is generous. */
438
+ const MAX_LEANING = 500;
439
+ /**
440
+ * Nodes that may sit between a directive and its target.
441
+ *
442
+ * A whitespace-only `text` node always does — measured, with or without a blank
443
+ * line in the source. Comments do too, and an unrelated `<!-- TODO -->` must not
444
+ * break the chain: it is invisible in every renderer and deleted by the
445
+ * sanitiser, so letting it change a directive's meaning would make behaviour
446
+ * depend on something no reader can see.
447
+ */
230
448
  function isSkippable(node) {
231
- if (node.type === "comment" || node.type === "doctype") return true;
232
- if (node.type === "text") return node.value.trim() === "";
233
- return false;
449
+ if (node.type === "comment" || node.type === "doctype") return true;
450
+ if (node.type === "text") return node.value.trim() === "";
451
+ return false;
234
452
  }
235
453
  function headingDepth(node) {
236
- if (node.type !== "element") return void 0;
237
- return HEADING_DEPTHS.get(node.tagName);
454
+ if (node.type !== "element") return void 0;
455
+ return HEADING_DEPTHS.get(node.tagName);
238
456
  }
239
457
  function setProperty(element, property, value) {
240
- element.properties = element.properties ?? {};
241
- element.properties[property] = value;
458
+ element.properties = element.properties ?? {};
459
+ element.properties[property] = value;
242
460
  }
461
+ /**
462
+ * Where a member sits in a stamped run: `only` for a lone block, otherwise
463
+ * `start`, `middle`, `end`. See `VANTAGE_RUNS`.
464
+ */
243
465
  function runValue(index, length) {
244
- if (length === 1) return "only";
245
- if (index === 0) return "start";
246
- return index === length - 1 ? "end" : "middle";
466
+ if (length === 1) return "only";
467
+ if (index === 0) return "start";
468
+ return index === length - 1 ? "end" : "middle";
247
469
  }
470
+ /** The closed value set for one key, or `undefined` when the key is unknown. */
248
471
  function vocabularyOf(name, key) {
249
- return DIRECTIVE_VOCABULARY[name]?.[key];
472
+ return DIRECTIVE_VOCABULARY[name]?.[key];
250
473
  }
251
474
  function accepts(name, key, value) {
252
- const values = vocabularyOf(name, key);
253
- if (values === void 0) return false;
254
- return values === null || values.includes(value);
475
+ const values = vocabularyOf(name, key);
476
+ if (values === void 0) return false;
477
+ return values === null || values.includes(value);
255
478
  }
479
+ /**
480
+ * The nodes one style directive reaches, as indexes into its own parent's
481
+ * children — never outside that array, so a directive inside a blockquote or a
482
+ * list item cannot stamp past it.
483
+ *
484
+ * Position picks the target (the next sibling element); the name picks how far
485
+ * the stamp goes. `section` before a heading takes the heading and every
486
+ * following sibling until the first heading of the same or shallower depth;
487
+ * `section` before anything else degrades to that one block, and `block` is
488
+ * always that one block. A heading nested inside a stamped `blockquote` or
489
+ * `li` does not end the section: the walk never descends.
490
+ */
256
491
  function styleRange(children, targetIndex, name) {
257
- const range = [targetIndex];
258
- const depth = name === "section" ? headingDepth(children[targetIndex]) : void 0;
259
- if (depth === void 0) return range;
260
- for (let i = targetIndex + 1; i < children.length; i++) {
261
- const node = children[i];
262
- const nodeDepth = headingDepth(node);
263
- if (nodeDepth !== void 0 && nodeDepth <= depth) break;
264
- if (node.type === "element" && STYLE_TARGET_TAGS.has(node.tagName)) {
265
- range.push(i);
266
- }
267
- }
268
- return range;
492
+ const range = [targetIndex];
493
+ const depth = name === "section" ? headingDepth(children[targetIndex]) : void 0;
494
+ if (depth === void 0) return range;
495
+ for (let i = targetIndex + 1; i < children.length; i++) {
496
+ const node = children[i];
497
+ const nodeDepth = headingDepth(node);
498
+ if (nodeDepth !== void 0 && nodeDepth <= depth) break;
499
+ if (node.type === "element" && STYLE_TARGET_TAGS.has(node.tagName)) range.push(i);
500
+ }
501
+ return range;
269
502
  }
503
+ /**
504
+ * Whether this directive collapses its section — three ways to say no.
505
+ *
506
+ * `collapsed=false` stamps nothing: it is the default written down, and "not
507
+ * collapsed" is not a thing an attribute can usefully say. Its only effect is
508
+ * upstream of here — `stampRun` merges a run of comments last-key-wins, so a
509
+ * `false` cancels a `true` in the *same* run. It does not cancel an *enclosing*
510
+ * section: `styleRange` walks the outer heading's whole sibling span before any
511
+ * inner directive is resolved, and a nested heading being a hidden member of the
512
+ * outer group is the design (A3), not an oversight.
513
+ *
514
+ * A `block` scope is **dropped**, and so is a `section` that degraded onto
515
+ * a non-heading, because both would hide a lone paragraph with nothing left
516
+ * behind to reveal it — content that is simply gone, which is the P1/D8 failure
517
+ * the readiness gate exists to prevent. Only a heading can be a summary.
518
+ */
270
519
  function collapsesSection(name, pairs, target) {
271
- if (name !== "section") return false;
272
- if (pairs.get("collapsed") !== "true") return false;
273
- return headingDepth(target) !== void 0;
520
+ if (name !== "section") return false;
521
+ if (pairs.get("collapsed") !== "true") return false;
522
+ return headingDepth(target) !== void 0;
274
523
  }
275
524
  function stampStyle(children, targetIndex, name, pairs, state) {
276
- const target = children[targetIndex];
277
- if (!STYLE_TARGET_TAGS.has(target.tagName)) return;
278
- const rangeStamps = [];
279
- const targetStamps = [];
280
- for (const [key, value] of pairs) {
281
- if (!accepts(name, key, value)) continue;
282
- const rangeProperty = RANGE_PROPERTIES.get(key);
283
- if (rangeProperty !== void 0) {
284
- rangeStamps.push([rangeProperty, value]);
285
- continue;
286
- }
287
- const pointProperty = POINT_PROPERTIES.get(key);
288
- if (pointProperty !== void 0) targetStamps.push([pointProperty, value]);
289
- }
290
- const collapses = collapsesSection(name, pairs, target);
291
- if (rangeStamps.length === 0 && targetStamps.length === 0 && !collapses) {
292
- return;
293
- }
294
- const range = styleRange(children, targetIndex, name);
295
- const group = collapses && range.length > 1 ? String(state.nextGroup++) : void 0;
296
- for (let i = 0; i < range.length; i++) {
297
- const element = children[range[i]];
298
- for (const [property, value] of rangeStamps) {
299
- setProperty(element, property, value);
300
- }
301
- if (i === 0) {
302
- for (const [property, value] of targetStamps) {
303
- setProperty(element, property, value);
304
- }
305
- }
306
- if (rangeStamps.length > 0) {
307
- setProperty(element, RUN_PROPERTY, runValue(i, range.length));
308
- }
309
- if (group === void 0) continue;
310
- if (i === 0) {
311
- setProperty(element, COLLAPSE_TOGGLE_PROPERTY, group);
312
- } else {
313
- setProperty(element, COLLAPSED_PROPERTY, "true");
314
- setProperty(element, COLLAPSE_GROUP_PROPERTY, group);
315
- }
316
- }
525
+ const target = children[targetIndex];
526
+ if (!STYLE_TARGET_TAGS.has(target.tagName)) return;
527
+ const rangeStamps = [];
528
+ const targetStamps = [];
529
+ for (const [key, value] of pairs) {
530
+ if (!accepts(name, key, value)) continue;
531
+ const rangeProperty = RANGE_PROPERTIES.get(key);
532
+ if (rangeProperty !== void 0) {
533
+ rangeStamps.push([rangeProperty, value]);
534
+ continue;
535
+ }
536
+ const pointProperty = POINT_PROPERTIES.get(key);
537
+ if (pointProperty !== void 0) targetStamps.push([pointProperty, value]);
538
+ }
539
+ const collapses = collapsesSection(name, pairs, target);
540
+ if (rangeStamps.length === 0 && targetStamps.length === 0 && !collapses) return;
541
+ const range = styleRange(children, targetIndex, name);
542
+ const group = collapses && range.length > 1 ? String(state.nextGroup++) : void 0;
543
+ for (let i = 0; i < range.length; i++) {
544
+ const element = children[range[i]];
545
+ for (const [property, value] of rangeStamps) setProperty(element, property, value);
546
+ if (i === 0) for (const [property, value] of targetStamps) setProperty(element, property, value);
547
+ if (rangeStamps.length > 0) setProperty(element, RUN_PROPERTY, runValue(i, range.length));
548
+ if (group === void 0) continue;
549
+ if (i === 0) setProperty(element, COLLAPSE_TOGGLE_PROPERTY, group);
550
+ else {
551
+ setProperty(element, COLLAPSED_PROPERTY, "true");
552
+ setProperty(element, COLLAPSE_GROUP_PROPERTY, group);
553
+ }
554
+ }
317
555
  }
318
556
  function stampOq(target, pairs) {
319
- setProperty(target, OQ_PROPERTY, "true");
320
- const leaning = pairs.get("leaning");
321
- if (leaning === void 0) return;
322
- const text = leaning.replace(/\s+/g, " ").trim().slice(0, MAX_LEANING);
323
- if (text !== "") setProperty(target, LEANING_PROPERTY, text);
557
+ setProperty(target, OQ_PROPERTY, "true");
558
+ const leaning = pairs.get("leaning");
559
+ if (leaning === void 0) return;
560
+ const text = leaning.replace(/\s+/g, " ").trim().slice(0, MAX_LEANING);
561
+ if (text !== "") setProperty(target, LEANING_PROPERTY, text);
324
562
  }
563
+ /**
564
+ * Merge one run of directives onto one target, then stamp.
565
+ *
566
+ * Merging is defined on the tree, not on the source: every directive comment up
567
+ * to the target merges, last-key-wins, whether or not blank lines separate
568
+ * them. Measured — adjacent comments and comments separated by a blank line
569
+ * produce byte-identical trees, so a rule that told them apart would have to
570
+ * re-read line numbers to do it.
571
+ */
325
572
  function stampRun(children, targetIndex, run, state) {
326
- const target = children[targetIndex];
327
- const style = /* @__PURE__ */ new Map();
328
- const oq = /* @__PURE__ */ new Map();
329
- let styleName;
330
- let hasOq = false;
331
- for (const directive of run) {
332
- if (directive.name === "section" || directive.name === "block") {
333
- styleName = directive.name;
334
- for (const pair of directive.pairs) style.set(pair.key, pair.value);
335
- } else if (directive.name === "oq") {
336
- hasOq = true;
337
- for (const pair of directive.pairs) oq.set(pair.key, pair.value);
338
- }
339
- }
340
- if (styleName !== void 0) {
341
- stampStyle(children, targetIndex, styleName, style, state);
342
- }
343
- if (hasOq && ANCHOR_TARGET_TAGS.has(target.tagName)) {
344
- stampOq(target, oq);
345
- }
573
+ const target = children[targetIndex];
574
+ const style = /* @__PURE__ */ new Map();
575
+ const oq = /* @__PURE__ */ new Map();
576
+ let styleName;
577
+ let hasOq = false;
578
+ for (const directive of run) if (directive.name === "section" || directive.name === "block") {
579
+ styleName = directive.name;
580
+ for (const pair of directive.pairs) style.set(pair.key, pair.value);
581
+ } else if (directive.name === "oq") {
582
+ hasOq = true;
583
+ for (const pair of directive.pairs) oq.set(pair.key, pair.value);
584
+ }
585
+ if (styleName !== void 0) stampStyle(children, targetIndex, styleName, style, state);
586
+ if (hasOq && ANCHOR_TARGET_TAGS.has(target.tagName)) stampOq(target, oq);
346
587
  }
588
+ /** A directive comment, or `undefined` for anything else — malformed included. */
347
589
  function directiveOf(node) {
348
- if (node.type !== "comment") return void 0;
349
- const parsed = parseVantageDirective(node.value);
350
- return parsed !== null && parsed.kind === "directive" ? parsed : void 0;
590
+ if (node.type !== "comment") return void 0;
591
+ const parsed = parseVantageDirective(node.value);
592
+ return parsed !== null && parsed.kind === "directive" ? parsed : void 0;
351
593
  }
594
+ /**
595
+ * One left-to-right pass over a parent's children, recursing into elements.
596
+ *
597
+ * The whole tree, not just the root: `rehype-raw` leaves comment nodes inside
598
+ * `blockquote`, inside `li`, inside `td` and inline inside `p`, and the real
599
+ * Open Questions layout puts the `oq` directive inside a list item — so a
600
+ * root-only walk finds none of them.
601
+ *
602
+ * Pass order is also what resolves a nested section: an inner heading's
603
+ * directive necessarily sits at a higher child index than the outer directive
604
+ * that ranged over it, so each property is simply last-write-wins.
605
+ */
352
606
  function processChildren(parent, state) {
353
- const children = parent.children;
354
- let i = 0;
355
- while (i < children.length) {
356
- const node = children[i];
357
- if (node.type === "element") {
358
- processChildren(node, state);
359
- i++;
360
- continue;
361
- }
362
- const first = directiveOf(node);
363
- if (first === void 0) {
364
- i++;
365
- continue;
366
- }
367
- const run = [first];
368
- let j = i + 1;
369
- let targetIndex = -1;
370
- for (; j < children.length; j++) {
371
- const next = children[j];
372
- if (next.type === "element") {
373
- targetIndex = j;
374
- break;
375
- }
376
- if (!isSkippable(next)) break;
377
- const directive = directiveOf(next);
378
- if (directive !== void 0) run.push(directive);
379
- }
380
- if (targetIndex >= 0) stampRun(children, targetIndex, run, state);
381
- i = j;
382
- }
607
+ const children = parent.children;
608
+ let i = 0;
609
+ while (i < children.length) {
610
+ const node = children[i];
611
+ if (node.type === "element") {
612
+ processChildren(node, state);
613
+ i++;
614
+ continue;
615
+ }
616
+ const first = directiveOf(node);
617
+ if (first === void 0) {
618
+ i++;
619
+ continue;
620
+ }
621
+ const run = [first];
622
+ let j = i + 1;
623
+ let targetIndex = -1;
624
+ for (; j < children.length; j++) {
625
+ const next = children[j];
626
+ if (next.type === "element") {
627
+ targetIndex = j;
628
+ break;
629
+ }
630
+ if (!isSkippable(next)) break;
631
+ const directive = directiveOf(next);
632
+ if (directive !== void 0) run.push(directive);
633
+ }
634
+ if (targetIndex >= 0) stampRun(children, targetIndex, run, state);
635
+ i = j;
636
+ }
383
637
  }
384
- var rehypeVantageDirectives = () => {
385
- return (tree) => {
386
- processChildren(tree, { nextGroup: 1 });
387
- };
638
+ const rehypeVantageDirectives = () => {
639
+ return (tree) => {
640
+ processChildren(tree, { nextGroup: 1 });
641
+ };
388
642
  };
389
- var rehypeVantageDirectives_default = rehypeVantageDirectives;
390
-
391
- // src/rehypeVantageMathStamps.ts
392
- var CARRIED_KEY = "vantageDisplayMathStamps";
643
+ //#endregion
644
+ //#region src/rehypeVantageMathStamps.ts
645
+ /**
646
+ * Where the snapshot lives between the two halves.
647
+ *
648
+ * `file.data` rather than a closure or a module-level map: `buildPipeline` is
649
+ * allowed to be built once and run over many documents, and per-file state is
650
+ * the only kind that cannot leak from one of those to the next.
651
+ */
652
+ const CARRIED_KEY = "vantageDisplayMathStamps";
393
653
  function classNames(node) {
394
- const value = node.properties?.className;
395
- return Array.isArray(value) ? value.map(String) : [];
654
+ const value = node.properties?.className;
655
+ return Array.isArray(value) ? value.map(String) : [];
396
656
  }
657
+ /**
658
+ * A `<pre>` `rehype-katex` will replace — its own condition, restated.
659
+ *
660
+ * `language-math` is the only class to test: `rehype-katex` keys the
661
+ * pre-as-scope branch on it, and the sanitiser strips the `math-display` that
662
+ * `remark-math` also emits (measured — a stamped fence arrives here with
663
+ * `className: ["language-math"]` alone).
664
+ */
397
665
  function isDisplayMath(node) {
398
- if (node.type !== "element" || node.tagName !== "pre") return false;
399
- return node.children.some(
400
- (child) => child.type === "element" && child.tagName === "code" && classNames(child).includes("language-math")
401
- );
666
+ if (node.type !== "element" || node.tagName !== "pre") return false;
667
+ return node.children.some((child) => child.type === "element" && child.tagName === "code" && classNames(child).includes("language-math"));
402
668
  }
669
+ /**
670
+ * What is worth carrying: everything this pipeline stamped itself.
671
+ *
672
+ * Deliberately not the whole property bag. `className`, `style` and `id` belong
673
+ * to the element KaTeX is about to build, and copying a `<pre>`'s onto a
674
+ * `<span class="katex-display">` would fight it.
675
+ */
403
676
  function carriedProperties(properties) {
404
- const carried = {};
405
- for (const [key, value] of Object.entries(properties ?? {})) {
406
- if (key === "dataSourceLine" || key.startsWith("dataVantage")) {
407
- carried[key] = value;
408
- }
409
- }
410
- return carried;
677
+ const carried = {};
678
+ for (const [key, value] of Object.entries(properties ?? {})) if (key === "dataSourceLine" || key.startsWith("dataVantage")) carried[key] = value;
679
+ return carried;
411
680
  }
412
681
  function collect(parent, out) {
413
- const children = parent.children;
414
- for (let i = 0; i < children.length; i++) {
415
- const node = children[i];
416
- if (node.type !== "element") continue;
417
- if (isDisplayMath(node)) {
418
- const properties = carriedProperties(node.properties);
419
- if (Object.keys(properties).length > 0) {
420
- out.push({
421
- parent,
422
- anchor: i === 0 ? void 0 : children[i - 1],
423
- properties
424
- });
425
- }
426
- continue;
427
- }
428
- collect(node, out);
429
- }
682
+ const children = parent.children;
683
+ for (let i = 0; i < children.length; i++) {
684
+ const node = children[i];
685
+ if (node.type !== "element") continue;
686
+ if (isDisplayMath(node)) {
687
+ const properties = carriedProperties(node.properties);
688
+ if (Object.keys(properties).length > 0) out.push({
689
+ parent,
690
+ anchor: i === 0 ? void 0 : children[i - 1],
691
+ properties
692
+ });
693
+ continue;
694
+ }
695
+ collect(node, out);
696
+ }
430
697
  }
431
698
  function reapply(carried) {
432
- for (const { parent, anchor, properties } of carried) {
433
- const siblings = parent.children;
434
- let index = 0;
435
- if (anchor !== void 0) {
436
- const at = siblings.indexOf(anchor);
437
- if (at === -1) continue;
438
- index = at + 1;
439
- }
440
- const replacement = siblings[index];
441
- if (replacement === void 0 || replacement.type !== "element") continue;
442
- if (!classNames(replacement).some((name) => name.startsWith("katex"))) {
443
- continue;
444
- }
445
- replacement.properties ??= {};
446
- for (const [key, value] of Object.entries(properties)) {
447
- replacement.properties[key] ??= value;
448
- }
449
- }
699
+ for (const { parent, anchor, properties } of carried) {
700
+ const siblings = parent.children;
701
+ let index = 0;
702
+ if (anchor !== void 0) {
703
+ const at = siblings.indexOf(anchor);
704
+ if (at === -1) continue;
705
+ index = at + 1;
706
+ }
707
+ const replacement = siblings[index];
708
+ if (replacement === void 0 || replacement.type !== "element") continue;
709
+ if (!classNames(replacement).some((name) => name.startsWith("katex"))) continue;
710
+ replacement.properties ??= {};
711
+ for (const [key, value] of Object.entries(properties)) replacement.properties[key] ??= value;
712
+ }
450
713
  }
451
- var rehypeCaptureMathStamps = () => {
452
- return (tree, file) => {
453
- const carried = [];
454
- collect(tree, carried);
455
- file.data[CARRIED_KEY] = carried;
456
- };
714
+ /** Snapshot every stamped display-math block. Register before `rehypeKatex`. */
715
+ const rehypeCaptureMathStamps = () => {
716
+ return (tree, file) => {
717
+ const carried = [];
718
+ collect(tree, carried);
719
+ file.data[CARRIED_KEY] = carried;
720
+ };
457
721
  };
458
- var rehypeRestoreMathStamps = () => {
459
- return (_tree, file) => {
460
- const carried = file.data[CARRIED_KEY];
461
- delete file.data[CARRIED_KEY];
462
- if (Array.isArray(carried)) reapply(carried);
463
- };
722
+ /** Re-apply the snapshot. Register immediately after `rehypeKatex`. */
723
+ const rehypeRestoreMathStamps = () => {
724
+ return (_tree, file) => {
725
+ const carried = file.data[CARRIED_KEY];
726
+ delete file.data[CARRIED_KEY];
727
+ if (Array.isArray(carried)) reapply(carried);
728
+ };
464
729
  };
465
- var SAFE_STYLE_PROPERTIES = [
466
- // Box metrics. `top`/`right`/`bottom`/`left` are inert now that `position` is
467
- // banned, and they stay only because dropping them would fail the whole
468
- // attribute for a document that writes one — the all-or-nothing rule below
469
- // makes every removal a behaviour change. They buy an attacker nothing that
470
- // negative `margin` does not already buy.
471
- "height",
472
- "min-height",
473
- "max-height",
474
- "width",
475
- "min-width",
476
- "max-width",
477
- "top",
478
- "bottom",
479
- "left",
480
- "right",
481
- "margin",
482
- "margin-top",
483
- "margin-right",
484
- "margin-bottom",
485
- "margin-left",
486
- "padding",
487
- "padding-top",
488
- "padding-right",
489
- "padding-bottom",
490
- "padding-left",
491
- // Rules and boxes.
492
- "border",
493
- "border-style",
494
- "border-color",
495
- "border-width",
496
- "border-top-width",
497
- "border-right-width",
498
- "border-bottom-width",
499
- "border-left-width",
500
- "border-top-style",
501
- "border-right-style",
502
- "border-bottom-style",
503
- "border-left-style",
504
- "border-top-color",
505
- "border-right-color",
506
- "border-bottom-color",
507
- "border-left-color",
508
- "border-radius",
509
- // Typography.
510
- "color",
511
- "background-color",
512
- "font",
513
- "font-size",
514
- "font-style",
515
- "font-weight",
516
- "font-family",
517
- "font-variant",
518
- "line-height",
519
- "letter-spacing",
520
- "word-spacing",
521
- "text-align",
522
- "text-decoration",
523
- "text-indent",
524
- "white-space",
525
- "vertical-align",
526
- "list-style-type",
527
- // Flow.
528
- "display",
529
- "float",
530
- "clear",
531
- "opacity",
532
- "overflow"
533
- ];
534
- var VALUE = `[^;:()"'\\\\]*`;
535
- var DECLARATION = `(?:(?:${SAFE_STYLE_PROPERTIES.join("|")})\\s*:${VALUE})`;
536
- var SAFE_STYLE = new RegExp(
537
- `^\\s*(?:${DECLARATION};\\s*)*${DECLARATION}?$`,
538
- "i"
539
- );
540
- var COLLAPSE_GROUP_ID = /^[0-9]+$/;
541
- var sanitizeSchema = {
542
- ...defaultSchema,
543
- tagNames: [
544
- ...defaultSchema.tagNames || [],
545
- // KaTeX MathML elements
546
- "math",
547
- "semantics",
548
- "mrow",
549
- "mi",
550
- "mo",
551
- "mn",
552
- "msup",
553
- "msub",
554
- "mfrac",
555
- "mover",
556
- "munder",
557
- "msqrt",
558
- "mroot",
559
- "mtable",
560
- "mtr",
561
- "mtd",
562
- "mtext",
563
- "mspace",
564
- "annotation",
565
- // Other
566
- "figure",
567
- "figcaption",
568
- "summary",
569
- "details"
570
- ],
571
- attributes: {
572
- ...defaultSchema.attributes,
573
- "*": [
574
- ...defaultSchema.attributes?.["*"] || [],
575
- "className",
576
- ["style", SAFE_STYLE],
577
- "dataSourceLine",
578
- // What `rehypeVantageDirectives` compiles a `<!-- vantage: … -->` comment
579
- // into, named individually — never by a `data-vantage-*` wildcard, which
580
- // would readmit whatever a future bug emits and whatever a document
581
- // hand-writes as raw HTML.
582
- //
583
- // The value lists are the belt to the plugin's braces: the vocabulary is
584
- // closed in the plugin *and* here, imported from the one module that
585
- // defines it, so even if a refactor let an unvalidated value reach the
586
- // tree the sanitiser still refuses it.
587
- ["dataVantageTone", ...VANTAGE_TONES],
588
- ["dataVantageEmphasis", ...VANTAGE_EMPHASIS],
589
- ["dataVantageBadge", ...VANTAGE_BADGES],
590
- ["dataVantageCollapsed", ...VANTAGE_COLLAPSED],
591
- // The other half of `collapsed`: which group a hidden block belongs to,
592
- // and which group a heading toggles. Both are plugin-minted counters with
593
- // no vocabulary to allowlist, so they take a pattern instead —
594
- // `hast-util-sanitize` accepts a `RegExp` in place of a literal value.
595
- // A pattern rather than a bare name because the JS interpolates the value
596
- // into a selector: anything but digits has no business reaching it.
597
- ["dataVantageCollapseGroup", COLLAPSE_GROUP_ID],
598
- ["dataVantageCollapseToggle", COLLAPSE_GROUP_ID],
599
- ["dataVantageRun", ...VANTAGE_RUNS],
600
- ["dataVantageOq", "true"],
601
- // The design's one genuinely free-text value: the body of a review
602
- // comment, so it cannot be value-allowlisted and this entry is name-only.
603
- // Two defences remain rather than three — `hast` escapes the value on
604
- // serialisation and React sets it through the DOM property path, so it
605
- // cannot break out of the attribute — and the honest record of that is in
606
- // the design doc rather than a third layer implied here.
607
- "dataVantageLeaning"
608
- ],
609
- code: [...defaultSchema.attributes?.code || [], "className"],
610
- span: [
611
- ...defaultSchema.attributes?.span || [],
612
- "className",
613
- ["style", SAFE_STYLE]
614
- ],
615
- div: [
616
- ...defaultSchema.attributes?.div || [],
617
- "className",
618
- ["style", SAFE_STYLE]
619
- ],
620
- a: [...defaultSchema.attributes?.a || [], "id", "className"],
621
- math: ["xmlns"],
622
- annotation: ["encoding"],
623
- img: [...defaultSchema.attributes?.img || [], "loading"],
624
- td: [...defaultSchema.attributes?.td || [], ["style", SAFE_STYLE]],
625
- th: [...defaultSchema.attributes?.th || [], ["style", SAFE_STYLE]]
626
- }
730
+ //#endregion
731
+ //#region src/sanitize.ts
732
+ /**
733
+ * Sanitization schema for the rendering pipeline.
734
+ * Allows GFM, KaTeX MathML, syntax highlighting classes, and
735
+ * data-source-line attributes while blocking XSS vectors.
736
+ */
737
+ const DECLARATION = `(?:(?:${[
738
+ "height",
739
+ "min-height",
740
+ "max-height",
741
+ "width",
742
+ "min-width",
743
+ "max-width",
744
+ "top",
745
+ "bottom",
746
+ "left",
747
+ "right",
748
+ "margin",
749
+ "margin-top",
750
+ "margin-right",
751
+ "margin-bottom",
752
+ "margin-left",
753
+ "padding",
754
+ "padding-top",
755
+ "padding-right",
756
+ "padding-bottom",
757
+ "padding-left",
758
+ "border",
759
+ "border-style",
760
+ "border-color",
761
+ "border-width",
762
+ "border-top-width",
763
+ "border-right-width",
764
+ "border-bottom-width",
765
+ "border-left-width",
766
+ "border-top-style",
767
+ "border-right-style",
768
+ "border-bottom-style",
769
+ "border-left-style",
770
+ "border-top-color",
771
+ "border-right-color",
772
+ "border-bottom-color",
773
+ "border-left-color",
774
+ "border-radius",
775
+ "color",
776
+ "background-color",
777
+ "font",
778
+ "font-size",
779
+ "font-style",
780
+ "font-weight",
781
+ "font-family",
782
+ "font-variant",
783
+ "line-height",
784
+ "letter-spacing",
785
+ "word-spacing",
786
+ "text-align",
787
+ "text-decoration",
788
+ "text-indent",
789
+ "white-space",
790
+ "vertical-align",
791
+ "list-style-type",
792
+ "display",
793
+ "float",
794
+ "clear",
795
+ "opacity",
796
+ "overflow"
797
+ ].join("|")})\\s*:[^;:()"'\\\\]*)`;
798
+ const SAFE_STYLE = new RegExp(`^\\s*(?:${DECLARATION};\\s*)*${DECLARATION}?$`, "i");
799
+ /**
800
+ * A collapse group id: one or more digits, anchored.
801
+ *
802
+ * The plugin mints these as a per-document counter, so there is no vocabulary to
803
+ * list. Keeping the shape narrow matters anyway — the toggle JS builds a
804
+ * `[data-vantage-collapse-group="…"]` selector out of the value, and a document
805
+ * that hand-wrote raw HTML is the only way a non-numeric one could ever appear.
806
+ */
807
+ const COLLAPSE_GROUP_ID = /^[0-9]+$/;
808
+ /**
809
+ * Never set `allowComments` here.
810
+ *
811
+ * `hast-util-sanitize` drops comment nodes because that boolean defaults to
812
+ * `false` — comments are not elements, so `tagNames` has nothing to do with it.
813
+ * `rehypeVantageDirectives` relies on that deletion: it consumes a
814
+ * `<!-- vantage: … -->` comment into attributes and deliberately leaves the node
815
+ * for the sanitiser. Turning the switch on readmits every directive comment —
816
+ * valid and malformed alike — into the rendered HTML, which breaks the carrier's
817
+ * whole premise. `vantageDirectives.test.ts` ("leaves no comment in the rendered
818
+ * markup") is the guard.
819
+ */
820
+ const sanitizeSchema = {
821
+ ...defaultSchema,
822
+ tagNames: [
823
+ ...defaultSchema.tagNames || [],
824
+ "math",
825
+ "semantics",
826
+ "mrow",
827
+ "mi",
828
+ "mo",
829
+ "mn",
830
+ "msup",
831
+ "msub",
832
+ "mfrac",
833
+ "mover",
834
+ "munder",
835
+ "msqrt",
836
+ "mroot",
837
+ "mtable",
838
+ "mtr",
839
+ "mtd",
840
+ "mtext",
841
+ "mspace",
842
+ "annotation",
843
+ "figure",
844
+ "figcaption",
845
+ "summary",
846
+ "details"
847
+ ],
848
+ attributes: {
849
+ ...defaultSchema.attributes,
850
+ "*": [
851
+ ...defaultSchema.attributes?.["*"] || [],
852
+ "className",
853
+ ["style", SAFE_STYLE],
854
+ "dataSourceLine",
855
+ ["dataVantageTone", ...VANTAGE_TONES],
856
+ ["dataVantageEmphasis", ...VANTAGE_EMPHASIS],
857
+ ["dataVantageBadge", ...VANTAGE_BADGES],
858
+ ["dataVantageCollapsed", ...VANTAGE_COLLAPSED],
859
+ ["dataVantageCollapseGroup", COLLAPSE_GROUP_ID],
860
+ ["dataVantageCollapseToggle", COLLAPSE_GROUP_ID],
861
+ ["dataVantageRun", ...VANTAGE_RUNS],
862
+ ["dataVantageOq", "true"],
863
+ "dataVantageLeaning"
864
+ ],
865
+ code: [...defaultSchema.attributes?.code || [], "className"],
866
+ span: [
867
+ ...defaultSchema.attributes?.span || [],
868
+ "className",
869
+ ["style", SAFE_STYLE]
870
+ ],
871
+ div: [
872
+ ...defaultSchema.attributes?.div || [],
873
+ "className",
874
+ ["style", SAFE_STYLE]
875
+ ],
876
+ a: [
877
+ ...defaultSchema.attributes?.a || [],
878
+ "id",
879
+ "className"
880
+ ],
881
+ math: ["xmlns"],
882
+ annotation: ["encoding"],
883
+ img: [...defaultSchema.attributes?.img || [], "loading"],
884
+ td: [...defaultSchema.attributes?.td || [], ["style", SAFE_STYLE]],
885
+ th: [...defaultSchema.attributes?.th || [], ["style", SAFE_STYLE]]
886
+ }
627
887
  };
628
-
629
- // src/pipeline.ts
888
+ //#endregion
889
+ //#region src/pipeline.ts
890
+ /**
891
+ * The mdast half of the chain. Exported on its own because there is a real
892
+ * mdast-only consumer: the CLI checker parses documents without ever running
893
+ * rehype (`packages/vantage-check/src/core/document.ts`), and it has to parse
894
+ * them exactly the way the viewer does.
895
+ */
630
896
  function buildRemarkPlugins(options = {}) {
631
- const { gfm = true, math = true } = options;
632
- const plugins = [];
633
- if (gfm) plugins.push([remarkGfm, { singleTilde: false }]);
634
- if (math) plugins.push([remarkMath, { singleDollarTextMath: false }]);
635
- return plugins;
897
+ const { gfm = true, math = true } = options;
898
+ const plugins = [];
899
+ if (gfm) plugins.push([remarkGfm, { singleTilde: false }]);
900
+ if (math) plugins.push([remarkMath, { singleDollarTextMath: false }]);
901
+ return plugins;
636
902
  }
903
+ /** The hast half. Deliberately not exported: see `buildPipeline`. */
637
904
  function buildRehypePlugins(options = {}) {
638
- const {
639
- math = true,
640
- highlight = true,
641
- sourceLines = true,
642
- sanitize = true,
643
- bodyLineOffset = 0
644
- } = options;
645
- const plugins = [rehypeRaw];
646
- if (sourceLines) {
647
- plugins.push([rehypeSourceLines_default, { offset: bodyLineOffset }]);
648
- }
649
- plugins.push(rehypeVantageDirectives_default);
650
- if (sanitize) plugins.push([rehypeSanitize, sanitizeSchema]);
651
- plugins.push(rehypeSlug);
652
- if (highlight) plugins.push(rehypeHighlight);
653
- if (math) {
654
- plugins.push(rehypeCaptureMathStamps, rehypeKatex, rehypeRestoreMathStamps);
655
- }
656
- return plugins;
905
+ const { math = true, highlight = true, sourceLines = true, sanitize = true, bodyLineOffset = 0 } = options;
906
+ const plugins = [rehypeRaw];
907
+ if (sourceLines) plugins.push([rehypeSourceLines, { offset: bodyLineOffset }]);
908
+ plugins.push(rehypeVantageDirectives);
909
+ if (sanitize) plugins.push([rehypeSanitize, sanitizeSchema]);
910
+ plugins.push(rehypeSlug);
911
+ if (highlight) plugins.push(rehypeHighlight);
912
+ if (math) plugins.push(rehypeCaptureMathStamps, rehypeKatex, rehypeRestoreMathStamps);
913
+ return plugins;
657
914
  }
915
+ /**
916
+ * Both halves from one options object.
917
+ *
918
+ * This is what every renderer calls. It takes one object rather than exposing
919
+ * the two builders because `math` spans both halves — `remark-math` parses the
920
+ * delimiters, `rehype-katex` renders the result — and two calls are two places
921
+ * to forget the second one.
922
+ *
923
+ * Returns fresh arrays on every call and reads no module-level state; keep it
924
+ * that way, so a plugin in the chain cannot become a function of how many times
925
+ * the chain has been built.
926
+ */
658
927
  function buildPipeline(options = {}) {
659
- return {
660
- remarkPlugins: buildRemarkPlugins(options),
661
- rehypePlugins: buildRehypePlugins(options)
662
- };
928
+ return {
929
+ remarkPlugins: buildRemarkPlugins(options),
930
+ rehypePlugins: buildRehypePlugins(options)
931
+ };
663
932
  }
933
+ //#endregion
934
+ //#region src/frontmatter.ts
935
+ /**
936
+ * Frontmatter parser for YAML (---) and TOML (+++) delimited content.
937
+ * Works in both browser and server environments.
938
+ */
939
+ /**
940
+ * Parse frontmatter from markdown content.
941
+ * Supports YAML (delimited by ---) and TOML (delimited by +++).
942
+ */
664
943
  function parseFrontmatter(content) {
665
- if (content.startsWith("+++")) {
666
- return parseFrontmatterWithDelimiter(content, "+++", "toml");
667
- }
668
- if (content.startsWith("---")) {
669
- return parseFrontmatterWithDelimiter(content, "---", "yaml");
670
- }
671
- return withOffset(content, {
672
- frontmatter: {},
673
- body: content,
674
- format: "none"
675
- });
944
+ if (content.startsWith("+++")) return parseFrontmatterWithDelimiter(content, "+++", "toml");
945
+ if (content.startsWith("---")) return parseFrontmatterWithDelimiter(content, "---", "yaml");
946
+ return withOffset(content, {
947
+ frontmatter: {},
948
+ body: content,
949
+ format: "none"
950
+ });
676
951
  }
952
+ /**
953
+ * Fill in `bodyLineOffset`. `body` is always a suffix of `content`, so the
954
+ * newlines in the prefix that was stripped are exactly the shift — which also
955
+ * accounts for the blank line consumed after the closing delimiter.
956
+ */
677
957
  function withOffset(content, parsed) {
678
- const stripped = content.slice(0, content.length - parsed.body.length);
679
- let bodyLineOffset = 0;
680
- for (const ch of stripped) {
681
- if (ch === "\n") bodyLineOffset++;
682
- }
683
- return { ...parsed, bodyLineOffset };
958
+ const stripped = content.slice(0, content.length - parsed.body.length);
959
+ let bodyLineOffset = 0;
960
+ for (const ch of stripped) if (ch === "\n") bodyLineOffset++;
961
+ return {
962
+ ...parsed,
963
+ bodyLineOffset
964
+ };
684
965
  }
685
966
  function parseFrontmatterWithDelimiter(content, delimiter, format) {
686
- const searchStart = delimiter.length;
687
- const endIndex = content.indexOf(`
688
- ${delimiter}`, searchStart);
689
- if (endIndex === -1) {
690
- return withOffset(content, {
691
- frontmatter: {},
692
- body: content,
693
- format: "none",
694
- problem: { kind: "unterminated", delimiter }
695
- });
696
- }
697
- const raw = content.slice(searchStart + 1, endIndex).trim();
698
- const bodyStart = endIndex + 1 + delimiter.length;
699
- const body = content.slice(bodyStart).replace(/^\n/, "");
700
- try {
701
- const parsed = format === "toml" ? parse(raw) : YAML.parse(raw);
702
- return withOffset(content, {
703
- frontmatter: parsed || {},
704
- body,
705
- format,
706
- ...isMapping(parsed) ? {} : { problem: { kind: "not-a-mapping", delimiter } }
707
- });
708
- } catch (error) {
709
- return withOffset(content, {
710
- frontmatter: {},
711
- body: content,
712
- format: "none",
713
- problem: { kind: "invalid", delimiter, ...errorPosition(error) }
714
- });
715
- }
967
+ const searchStart = delimiter.length;
968
+ const endIndex = content.indexOf(`\n${delimiter}`, searchStart);
969
+ if (endIndex === -1) return withOffset(content, {
970
+ frontmatter: {},
971
+ body: content,
972
+ format: "none",
973
+ problem: {
974
+ kind: "unterminated",
975
+ delimiter
976
+ }
977
+ });
978
+ const raw = content.slice(searchStart + 1, endIndex).trim();
979
+ const bodyStart = endIndex + 1 + delimiter.length;
980
+ const body = content.slice(bodyStart).replace(/^\n/, "");
981
+ try {
982
+ const parsed = format === "toml" ? parse(raw) : YAML.parse(raw);
983
+ return withOffset(content, {
984
+ frontmatter: parsed || {},
985
+ body,
986
+ format,
987
+ ...isMapping(parsed) ? {} : { problem: {
988
+ kind: "not-a-mapping",
989
+ delimiter
990
+ } }
991
+ });
992
+ } catch (error) {
993
+ return withOffset(content, {
994
+ frontmatter: {},
995
+ body: content,
996
+ format: "none",
997
+ problem: {
998
+ kind: "invalid",
999
+ delimiter,
1000
+ ...errorPosition(error)
1001
+ }
1002
+ });
1003
+ }
716
1004
  }
1005
+ /** Empty frontmatter is fine; a scalar or a list where a table belongs is not. */
717
1006
  function isMapping(value) {
718
- return value === null || value === void 0 || typeof value === "object" && !Array.isArray(value);
1007
+ return value === null || value === void 0 || typeof value === "object" && !Array.isArray(value);
719
1008
  }
1009
+ /**
1010
+ * Pull the parser's message and, where it gave one, the position inside the
1011
+ * frontmatter block. `yaml` reports `linePos`; `smol-toml` reports `line` and
1012
+ * `column`. Both are optional and both are read defensively — a missing
1013
+ * position costs a less precise report, a wrong assumption costs a crash.
1014
+ */
720
1015
  function errorPosition(error) {
721
- const message = error instanceof Error ? error.message : String(error);
722
- const source = error;
723
- const yamlPosition = source?.linePos?.[0];
724
- if (typeof yamlPosition?.line === "number") {
725
- return {
726
- message,
727
- line: yamlPosition.line,
728
- ...typeof yamlPosition.col === "number" ? { column: yamlPosition.col } : {}
729
- };
730
- }
731
- if (typeof source?.line === "number") {
732
- return {
733
- message,
734
- line: source.line,
735
- ...typeof source.column === "number" ? { column: source.column } : {}
736
- };
737
- }
738
- return { message };
1016
+ const message = error instanceof Error ? error.message : String(error);
1017
+ const source = error;
1018
+ const yamlPosition = source?.linePos?.[0];
1019
+ if (typeof yamlPosition?.line === "number") return {
1020
+ message,
1021
+ line: yamlPosition.line,
1022
+ ...typeof yamlPosition.col === "number" ? { column: yamlPosition.col } : {}
1023
+ };
1024
+ if (typeof source?.line === "number") return {
1025
+ message,
1026
+ line: source.line,
1027
+ ...typeof source.column === "number" ? { column: source.column } : {}
1028
+ };
1029
+ return { message };
739
1030
  }
740
-
741
- // src/renderMarkdown.ts
1031
+ //#endregion
1032
+ //#region src/renderMarkdown.ts
1033
+ /**
1034
+ * Framework-agnostic markdown -> HTML rendering pipeline.
1035
+ * Uses the same remark/rehype chain as the Vantage viewer.
1036
+ */
1037
+ /**
1038
+ * Render a markdown string to HTML using the full Vantage pipeline.
1039
+ *
1040
+ * Features (all enabled by default):
1041
+ * - GitHub Flavored Markdown (tables, strikethrough, task lists)
1042
+ * - KaTeX math rendering, inline and block ($$...$$ only; single $ is not a delimiter)
1043
+ * - Syntax highlighting via highlight.js
1044
+ * - `data-source-line` attributes for line anchors
1045
+ * - XSS sanitization
1046
+ * - Heading slugs/anchors
1047
+ * - YAML/TOML frontmatter parsing
1048
+ *
1049
+ * Mermaid diagrams are NOT rendered server-side (they require a browser).
1050
+ * Mermaid code blocks are preserved as `<pre><code class="language-mermaid">`.
1051
+ * Use the React `<MarkdownViewer>` component for client-side mermaid rendering.
1052
+ */
742
1053
  async function renderMarkdown(content, options = {}) {
743
- const {
744
- gfm = true,
745
- math = true,
746
- highlight = true,
747
- sourceLines = true,
748
- sanitize = true,
749
- frontmatter: parseFm = true
750
- } = options;
751
- let parsed;
752
- if (parseFm) {
753
- parsed = parseFrontmatter(content);
754
- } else {
755
- parsed = {
756
- frontmatter: {},
757
- body: content,
758
- format: "none",
759
- bodyLineOffset: 0
760
- };
761
- }
762
- const { remarkPlugins, rehypePlugins } = buildPipeline({
763
- gfm,
764
- math,
765
- highlight,
766
- sourceLines,
767
- sanitize,
768
- bodyLineOffset: parsed.bodyLineOffset
769
- });
770
- const processor = unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, { allowDangerousHtml: true }).use(rehypePlugins).use(rehypeStringify);
771
- const result = await processor.process(parsed.body);
772
- return {
773
- html: String(result),
774
- frontmatter: parsed.frontmatter,
775
- body: parsed.body
776
- };
1054
+ const { gfm = true, math = true, highlight = true, sourceLines = true, sanitize = true, frontmatter: parseFm = true } = options;
1055
+ let parsed;
1056
+ if (parseFm) parsed = parseFrontmatter(content);
1057
+ else parsed = {
1058
+ frontmatter: {},
1059
+ body: content,
1060
+ format: "none",
1061
+ bodyLineOffset: 0
1062
+ };
1063
+ const { remarkPlugins, rehypePlugins } = buildPipeline({
1064
+ gfm,
1065
+ math,
1066
+ highlight,
1067
+ sourceLines,
1068
+ sanitize,
1069
+ bodyLineOffset: parsed.bodyLineOffset
1070
+ });
1071
+ const result = await unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, { allowDangerousHtml: true }).use(rehypePlugins).use(rehypeStringify).process(parsed.body);
1072
+ return {
1073
+ html: String(result),
1074
+ frontmatter: parsed.frontmatter,
1075
+ body: parsed.body
1076
+ };
777
1077
  }
778
-
779
- // src/lineAnchor.ts
1078
+ //#endregion
1079
+ //#region src/lineAnchor.ts
1080
+ /**
1081
+ * Parsing for GitHub-style line anchors, with no DOM in sight.
1082
+ *
1083
+ * Split out from scrollToLineAnchor.ts so that non-browser consumers — the
1084
+ * `vantage-check` CLI, which validates `#L42` links against the file on disk —
1085
+ * can share the *same* syntax the viewer honours instead of reimplementing it
1086
+ * and drifting.
1087
+ */
1088
+ /**
1089
+ * Parse a GitHub-style line anchor hash.
1090
+ * Supports: #L42, #L42-L50, #L42-50
1091
+ * Returns null if the hash is not a line anchor.
1092
+ */
780
1093
  function parseLineAnchor(hash) {
781
- if (!hash) return null;
782
- const frag = hash.startsWith("#") ? hash.slice(1) : hash;
783
- const match = frag.match(/^L(\d+)(?:-L?(\d+))?$/);
784
- if (!match) return null;
785
- const start = parseInt(match[1], 10);
786
- const end = match[2] ? parseInt(match[2], 10) : start;
787
- return { start: Math.min(start, end), end: Math.max(start, end) };
1094
+ if (!hash) return null;
1095
+ const match = (hash.startsWith("#") ? hash.slice(1) : hash).match(/^L(\d+)(?:-L?(\d+))?$/);
1096
+ if (!match) return null;
1097
+ const start = parseInt(match[1], 10);
1098
+ const end = match[2] ? parseInt(match[2], 10) : start;
1099
+ return {
1100
+ start: Math.min(start, end),
1101
+ end: Math.max(start, end)
1102
+ };
788
1103
  }
789
-
790
- // src/scrollToLineAnchor.ts
791
- var HIGHLIGHT_CLASS = "line-anchor-highlight";
1104
+ //#endregion
1105
+ //#region src/scrollToLineAnchor.ts
1106
+ /**
1107
+ * Framework-agnostic line anchor utilities.
1108
+ * Scroll to and highlight the elements a GitHub-style line anchor
1109
+ * (#L42, #L42-L50) names. The parsing half lives in lineAnchor.ts, which has
1110
+ * no DOM dependency.
1111
+ */
1112
+ const HIGHLIGHT_CLASS = "line-anchor-highlight";
1113
+ /**
1114
+ * Clear all line anchor highlights from a container.
1115
+ */
792
1116
  function clearLineAnchorHighlights(container) {
793
- container.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach((node) => {
794
- node.classList.remove(HIGHLIGHT_CLASS);
795
- });
1117
+ container.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach((node) => {
1118
+ node.classList.remove(HIGHLIGHT_CLASS);
1119
+ });
796
1120
  }
1121
+ /**
1122
+ * Scroll to and highlight line-anchored elements in a container.
1123
+ *
1124
+ * @param container - The DOM element containing rendered markdown
1125
+ * @param hash - The URL hash (e.g. "#L42" or "#L42-L50")
1126
+ * @returns A cleanup function that removes the highlights
1127
+ */
797
1128
  function scrollToLineAnchor(container, hash) {
798
- clearLineAnchorHighlights(container);
799
- const range = parseLineAnchor(hash);
800
- if (!range) return null;
801
- const blocks = container.querySelectorAll("[data-source-line]");
802
- let firstMatch = null;
803
- for (const block of blocks) {
804
- const line = parseInt(block.dataset.sourceLine || "0", 10);
805
- if (line >= range.start && line <= range.end) {
806
- block.classList.add(HIGHLIGHT_CLASS);
807
- if (!firstMatch) firstMatch = block;
808
- }
809
- }
810
- if (!firstMatch) {
811
- let closest = null;
812
- let closestLine = 0;
813
- for (const block of blocks) {
814
- const line = parseInt(
815
- block.dataset.sourceLine || "0",
816
- 10
817
- );
818
- if (line <= range.start && line > closestLine) {
819
- closestLine = line;
820
- closest = block;
821
- }
822
- }
823
- if (closest) {
824
- closest.classList.add(HIGHLIGHT_CLASS);
825
- firstMatch = closest;
826
- }
827
- }
828
- if (firstMatch) {
829
- requestAnimationFrame(() => {
830
- const scrollParent = findScrollParent(container);
831
- if (scrollParent) {
832
- const offset = firstMatch.getBoundingClientRect().top - scrollParent.getBoundingClientRect().top + scrollParent.scrollTop;
833
- scrollParent.scrollTo({ top: offset - 32, behavior: "smooth" });
834
- } else {
835
- firstMatch.scrollIntoView({ behavior: "smooth", block: "start" });
836
- }
837
- });
838
- }
839
- return () => clearLineAnchorHighlights(container);
1129
+ clearLineAnchorHighlights(container);
1130
+ const range = parseLineAnchor(hash);
1131
+ if (!range) return null;
1132
+ const blocks = container.querySelectorAll("[data-source-line]");
1133
+ let firstMatch = null;
1134
+ for (const block of blocks) {
1135
+ const line = parseInt(block.dataset.sourceLine || "0", 10);
1136
+ if (line >= range.start && line <= range.end) {
1137
+ block.classList.add(HIGHLIGHT_CLASS);
1138
+ if (!firstMatch) firstMatch = block;
1139
+ }
1140
+ }
1141
+ if (!firstMatch) {
1142
+ let closest = null;
1143
+ let closestLine = 0;
1144
+ for (const block of blocks) {
1145
+ const line = parseInt(block.dataset.sourceLine || "0", 10);
1146
+ if (line <= range.start && line > closestLine) {
1147
+ closestLine = line;
1148
+ closest = block;
1149
+ }
1150
+ }
1151
+ if (closest) {
1152
+ closest.classList.add(HIGHLIGHT_CLASS);
1153
+ firstMatch = closest;
1154
+ }
1155
+ }
1156
+ if (firstMatch) requestAnimationFrame(() => {
1157
+ const scrollParent = findScrollParent(container);
1158
+ if (scrollParent) {
1159
+ const offset = firstMatch.getBoundingClientRect().top - scrollParent.getBoundingClientRect().top + scrollParent.scrollTop;
1160
+ scrollParent.scrollTo({
1161
+ top: offset - 32,
1162
+ behavior: "smooth"
1163
+ });
1164
+ } else firstMatch.scrollIntoView({
1165
+ behavior: "smooth",
1166
+ block: "start"
1167
+ });
1168
+ });
1169
+ return () => clearLineAnchorHighlights(container);
840
1170
  }
841
1171
  function findScrollParent(el) {
842
- let node = el;
843
- while (node) {
844
- const overflow = getComputedStyle(node).overflowY;
845
- if (overflow === "auto" || overflow === "scroll") return node;
846
- node = node.parentElement;
847
- }
848
- return null;
1172
+ let node = el;
1173
+ while (node) {
1174
+ const overflow = getComputedStyle(node).overflowY;
1175
+ if (overflow === "auto" || overflow === "scroll") return node;
1176
+ node = node.parentElement;
1177
+ }
1178
+ return null;
849
1179
  }
850
-
851
- // src/vantageFrontmatter.ts
852
- var DOC_STATUSES = [
853
- "draft",
854
- "in-review",
855
- "accepted",
856
- "deprecated"
1180
+ //#endregion
1181
+ //#region src/vantageFrontmatter.ts
1182
+ /**
1183
+ * The document lifecycle vocabulary. Closed; extending it is a code change.
1184
+ *
1185
+ * This is the repo's own existing set, not a new one — `styleGuide.ts` tells
1186
+ * every agent to write `status: in-review # draft | in-review | accepted |
1187
+ * deprecated`, and every document under `docs/` follows it. It is deliberately
1188
+ * *not* the `badge` set (`draft stale blocked done wip`): `badge` is
1189
+ * section-scoped workflow state, `status` is document lifecycle state, and
1190
+ * `in-review` — the value the design doc's own only example renders — is not a
1191
+ * badge word at all. Only `draft` is a member of both, and a token set is per key.
1192
+ */
1193
+ const DOC_STATUSES = [
1194
+ "draft",
1195
+ "in-review",
1196
+ "accepted",
1197
+ "deprecated"
857
1198
  ];
858
- var VANTAGE_FRONTMATTER_KEYS = ["status-chip"];
859
- var DOC_STATUS_TONES = {
860
- draft: "muted",
861
- "in-review": "warning",
862
- accepted: "tip",
863
- deprecated: "caution"
1199
+ /** Every key this build knows under `vantage:`. Closed. */
1200
+ const VANTAGE_FRONTMATTER_KEYS = ["status-chip"];
1201
+ /**
1202
+ * Which tone each status borrows its colours from.
1203
+ *
1204
+ * The chip has no palette of its own: it reuses the tone chips
1205
+ * (`.vantage-chip--<tone>` in `styles/directives.css`), which is also what makes
1206
+ * a `draft` chip and a `badge=draft` chip the same visual object. A map rather
1207
+ * than a computed class name, so the whole status→tone relation is one readable
1208
+ * table and a test can assert it covers the vocabulary.
1209
+ */
1210
+ const DOC_STATUS_TONES = {
1211
+ draft: "muted",
1212
+ "in-review": "warning",
1213
+ accepted: "tip",
1214
+ deprecated: "caution"
864
1215
  };
865
- var STATUS_CHIP_VALUES = [
866
- ...DOC_STATUSES,
867
- "true",
868
- "false"
1216
+ /** The legal `status-chip` values, in the order a message should list them. */
1217
+ const STATUS_CHIP_VALUES = [
1218
+ ...DOC_STATUSES,
1219
+ "true",
1220
+ "false"
869
1221
  ];
1222
+ /** Narrowing helper the chip and the checker both use. */
870
1223
  function isDocStatus(value) {
871
- return typeof value === "string" && DOC_STATUSES.includes(value);
1224
+ return typeof value === "string" && DOC_STATUSES.includes(value);
872
1225
  }
873
1226
  function isTable(value) {
874
- return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
1227
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
875
1228
  }
1229
+ /**
1230
+ * Read the `vantage:` key out of parsed frontmatter.
1231
+ *
1232
+ * Pure: no module state, no mutation of the input, no logging. The same object
1233
+ * in twice gives equal results out.
1234
+ */
876
1235
  function readVantageFrontmatter(frontmatter) {
877
- const issues = [];
878
- if (!Object.hasOwn(frontmatter, "vantage")) return { issues };
879
- const value = frontmatter["vantage"];
880
- if (!isTable(value)) {
881
- issues.push({ kind: "not-a-table", value });
882
- return { issues };
883
- }
884
- let statusChip;
885
- for (const key of Object.keys(value)) {
886
- if (!VANTAGE_FRONTMATTER_KEYS.includes(key)) {
887
- issues.push({ kind: "unknown-key", key });
888
- continue;
889
- }
890
- if (key === "status-chip") {
891
- statusChip = readStatusChip(frontmatter, value[key], issues);
892
- }
893
- }
894
- return { ...statusChip === void 0 ? {} : { statusChip }, issues };
1236
+ const issues = [];
1237
+ if (!Object.hasOwn(frontmatter, "vantage")) return { issues };
1238
+ const value = frontmatter["vantage"];
1239
+ if (!isTable(value)) {
1240
+ issues.push({
1241
+ kind: "not-a-table",
1242
+ value
1243
+ });
1244
+ return { issues };
1245
+ }
1246
+ let statusChip;
1247
+ for (const key of Object.keys(value)) {
1248
+ if (!VANTAGE_FRONTMATTER_KEYS.includes(key)) {
1249
+ issues.push({
1250
+ kind: "unknown-key",
1251
+ key
1252
+ });
1253
+ continue;
1254
+ }
1255
+ if (key === "status-chip") statusChip = readStatusChip(frontmatter, value[key], issues);
1256
+ }
1257
+ return {
1258
+ ...statusChip === void 0 ? {} : { statusChip },
1259
+ issues
1260
+ };
895
1261
  }
1262
+ /**
1263
+ * `status-chip` takes two shapes, and the boolean one is the recommended shape.
1264
+ *
1265
+ * `true` **inherits** the document's own top-level `status:`, so the chip cannot
1266
+ * disagree with it — which is the entire point of §5.3 ("makes `status: draft`
1267
+ * visible rather than only buried in a metadata card"; the row stays, the chip
1268
+ * promotes the value rather than moving it). A literal token is kept
1269
+ * because the design doc's first draft of that example used one, and the
1270
+ * disagreement it makes possible is turned into a checker finding rather than
1271
+ * banned.
1272
+ *
1273
+ * Discrimination is on `typeof`, never truthiness: `true` is a YAML boolean and
1274
+ * `2026-08-31` is a `Date`, and both would sail through a truthy test.
1275
+ */
896
1276
  function readStatusChip(frontmatter, raw, issues) {
897
- const status = frontmatter["status"];
898
- if (raw === false) return void 0;
899
- if (raw === true) {
900
- if (isDocStatus(status)) return status;
901
- issues.push({ kind: "status-chip-orphan", status });
902
- return void 0;
903
- }
904
- if (isDocStatus(raw)) {
905
- if (isDocStatus(status) && status !== raw) {
906
- issues.push({ kind: "status-chip-disagrees", chip: raw, status });
907
- }
908
- return raw;
909
- }
910
- issues.push({
911
- kind: "bad-value",
912
- key: "status-chip",
913
- value: raw,
914
- legal: STATUS_CHIP_VALUES
915
- });
916
- return void 0;
1277
+ const status = frontmatter["status"];
1278
+ if (raw === false) return void 0;
1279
+ if (raw === true) {
1280
+ if (isDocStatus(status)) return status;
1281
+ issues.push({
1282
+ kind: "status-chip-orphan",
1283
+ status
1284
+ });
1285
+ return;
1286
+ }
1287
+ if (isDocStatus(raw)) {
1288
+ if (isDocStatus(status) && status !== raw) issues.push({
1289
+ kind: "status-chip-disagrees",
1290
+ chip: raw,
1291
+ status
1292
+ });
1293
+ return raw;
1294
+ }
1295
+ issues.push({
1296
+ kind: "bad-value",
1297
+ key: "status-chip",
1298
+ value: raw,
1299
+ legal: STATUS_CHIP_VALUES
1300
+ });
917
1301
  }
918
-
919
- // src/mermaidCache.ts
920
- var svgCache = /* @__PURE__ */ new Map();
921
-
922
- // src/mermaidLoader.ts
923
- var mermaidInstance = null;
924
- var mermaidLoading = null;
925
- var isDark = () => typeof document !== "undefined" && document.documentElement.classList.contains("dark");
1302
+ //#endregion
1303
+ //#region src/mermaidCache.ts
1304
+ const svgCache = /* @__PURE__ */ new Map();
1305
+ //#endregion
1306
+ //#region src/mermaidLoader.ts
1307
+ let mermaidInstance = null;
1308
+ let mermaidLoading = null;
1309
+ const isDark = () => typeof document !== "undefined" && document.documentElement.classList.contains("dark");
926
1310
  async function getMermaid() {
927
- if (mermaidInstance) return mermaidInstance;
928
- if (!mermaidLoading) {
929
- mermaidLoading = import('mermaid').then((mod) => {
930
- const m = mod.default;
931
- m.initialize({
932
- startOnLoad: false,
933
- theme: isDark() ? "dark" : "default",
934
- securityLevel: "strict",
935
- suppressErrorRendering: true
936
- });
937
- mermaidInstance = m;
938
- return m;
939
- });
940
- }
941
- return mermaidLoading;
1311
+ if (mermaidInstance) return mermaidInstance;
1312
+ if (!mermaidLoading) mermaidLoading = import("mermaid").then((mod) => {
1313
+ const m = mod.default;
1314
+ m.initialize({
1315
+ startOnLoad: false,
1316
+ theme: isDark() ? "dark" : "default",
1317
+ securityLevel: "strict",
1318
+ suppressErrorRendering: true
1319
+ });
1320
+ mermaidInstance = m;
1321
+ return m;
1322
+ });
1323
+ return mermaidLoading;
942
1324
  }
943
-
944
- // src/renderMermaidBlocks.ts
1325
+ //#endregion
1326
+ //#region src/renderMermaidBlocks.ts
1327
+ /**
1328
+ * Client-side utility to find and render mermaid code blocks in a container.
1329
+ *
1330
+ * After calling `renderMarkdown()`, mermaid blocks come through as
1331
+ * `<pre><code class="language-mermaid">...</code></pre>`. This function
1332
+ * finds those blocks and replaces them with rendered SVG diagrams.
1333
+ *
1334
+ * Framework-agnostic — works in any browser environment.
1335
+ */
1336
+ /**
1337
+ * Find all `<pre><code class="language-mermaid">` blocks in a container
1338
+ * and replace them with rendered SVG diagrams.
1339
+ *
1340
+ * @param container - DOM element containing rendered markdown HTML
1341
+ * @param options - Optional configuration
1342
+ * @returns Promise that resolves when all diagrams are rendered
1343
+ *
1344
+ * @example
1345
+ * ```ts
1346
+ * import { renderMarkdown, renderMermaidBlocks } from "vantage-md";
1347
+ *
1348
+ * const { html } = await renderMarkdown(content);
1349
+ * container.innerHTML = html;
1350
+ * await renderMermaidBlocks(container);
1351
+ * ```
1352
+ */
945
1353
  async function renderMermaidBlocks(container, options = {}) {
946
- const { className = "mermaid", onError } = options;
947
- const codeBlocks = container.querySelectorAll(
948
- 'pre > code.language-mermaid, pre > code[class*="language-mermaid"]'
949
- );
950
- if (codeBlocks.length === 0) return;
951
- const mermaid = await getMermaid();
952
- const renderPromises = Array.from(codeBlocks).map(async (codeEl) => {
953
- const preEl = codeEl.parentElement;
954
- if (!preEl) return;
955
- const code = codeEl.textContent || "";
956
- if (!code.trim()) return;
957
- const cached = svgCache.get(code);
958
- if (cached) {
959
- replaceWithSvg(preEl, cached, className);
960
- return;
961
- }
962
- try {
963
- let hash = 0;
964
- for (let i = 0; i < code.length; i++) {
965
- hash = (hash << 5) - hash + code.charCodeAt(i);
966
- hash = hash & hash;
967
- }
968
- const id = `mermaid-${Math.abs(hash).toString(36)}-${Date.now()}`;
969
- const { svg } = await mermaid.render(id, code);
970
- svgCache.set(code, svg);
971
- replaceWithSvg(preEl, svg, className);
972
- } catch (err) {
973
- if (onError) {
974
- onError(code, err instanceof Error ? err : new Error(String(err)));
975
- }
976
- }
977
- });
978
- await Promise.all(renderPromises);
1354
+ const { className = "mermaid", onError } = options;
1355
+ const codeBlocks = container.querySelectorAll("pre > code.language-mermaid, pre > code[class*=\"language-mermaid\"]");
1356
+ if (codeBlocks.length === 0) return;
1357
+ const mermaid = await getMermaid();
1358
+ const renderPromises = Array.from(codeBlocks).map(async (codeEl) => {
1359
+ const preEl = codeEl.parentElement;
1360
+ if (!preEl) return;
1361
+ const code = codeEl.textContent || "";
1362
+ if (!code.trim()) return;
1363
+ const cached = svgCache.get(code);
1364
+ if (cached) {
1365
+ replaceWithSvg(preEl, cached, className);
1366
+ return;
1367
+ }
1368
+ try {
1369
+ let hash = 0;
1370
+ for (let i = 0; i < code.length; i++) {
1371
+ hash = (hash << 5) - hash + code.charCodeAt(i);
1372
+ hash = hash & hash;
1373
+ }
1374
+ const id = `mermaid-${Math.abs(hash).toString(36)}-${Date.now()}`;
1375
+ const { svg } = await mermaid.render(id, code);
1376
+ svgCache.set(code, svg);
1377
+ replaceWithSvg(preEl, svg, className);
1378
+ } catch (err) {
1379
+ if (onError) onError(code, err instanceof Error ? err : new Error(String(err)));
1380
+ }
1381
+ });
1382
+ await Promise.all(renderPromises);
979
1383
  }
980
1384
  function replaceWithSvg(preEl, svg, className) {
981
- const wrapper = document.createElement("div");
982
- wrapper.className = className;
983
- wrapper.innerHTML = svg;
984
- preEl.replaceWith(wrapper);
1385
+ const wrapper = document.createElement("div");
1386
+ wrapper.className = className;
1387
+ wrapper.innerHTML = svg;
1388
+ preEl.replaceWith(wrapper);
985
1389
  }
986
-
987
- // src/resolveLinks.ts
1390
+ //#endregion
1391
+ //#region src/resolveLinks.ts
1392
+ /**
1393
+ * Rewrite relative links in rendered HTML.
1394
+ *
1395
+ * Processes all `href="..."` attributes, skipping:
1396
+ * - Absolute URLs (http://, https://, mailto:, etc.)
1397
+ * - Anchor-only links (#section)
1398
+ * - Already-absolute paths (/path/to/file)
1399
+ *
1400
+ * @example
1401
+ * ```ts
1402
+ * import { renderMarkdown, resolveLinks } from "vantage-md";
1403
+ *
1404
+ * const { html } = await renderMarkdown(content);
1405
+ *
1406
+ * // Simple: prepend a base path
1407
+ * const resolved = resolveLinks(html, { basePath: "/docs/", currentPath: "guides/setup.md" });
1408
+ *
1409
+ * // Custom: full control over link rewriting
1410
+ * const resolved = resolveLinks(html, {
1411
+ * currentPath: "guides/setup.md",
1412
+ * rewriter: (href, currentPath) => `/kb/${currentPath}/../${href}`,
1413
+ * });
1414
+ * ```
1415
+ */
988
1416
  function resolveLinks(html, options = {}) {
989
- const { basePath = "/", rewriter, currentPath = "" } = options;
990
- const parts = currentPath.split("/");
991
- parts.pop();
992
- const currentDir = parts.join("/");
993
- return html.replace(
994
- /href="([^"]*?)"/g,
995
- (_match, href) => {
996
- if (href.startsWith("http://") || href.startsWith("https://") || href.startsWith("mailto:") || href.startsWith("data:") || href.startsWith("#") || href.startsWith("/")) {
997
- return `href="${href}"`;
998
- }
999
- if (rewriter) {
1000
- const result = rewriter(href, currentPath);
1001
- if (result !== null) {
1002
- return `href="${result}"`;
1003
- }
1004
- return `href="${href}"`;
1005
- }
1006
- const [pathPart, hashPart] = href.split("#");
1007
- const cleanHref = pathPart.replace(/^\.\//, "");
1008
- const resolvedPath = currentDir ? `${currentDir}/${cleanHref}` : cleanHref;
1009
- const base = basePath.endsWith("/") ? basePath : `${basePath}/`;
1010
- const finalHref = `${base}${resolvedPath}${hashPart ? `#${hashPart}` : ""}`;
1011
- return `href="${finalHref}"`;
1012
- }
1013
- );
1417
+ const { basePath = "/", rewriter, currentPath = "" } = options;
1418
+ const parts = currentPath.split("/");
1419
+ parts.pop();
1420
+ const currentDir = parts.join("/");
1421
+ return html.replace(/href="([^"]*?)"/g, (_match, href) => {
1422
+ if (href.startsWith("http://") || href.startsWith("https://") || href.startsWith("mailto:") || href.startsWith("data:") || href.startsWith("#") || href.startsWith("/")) return `href="${href}"`;
1423
+ if (rewriter) {
1424
+ const result = rewriter(href, currentPath);
1425
+ if (result !== null) return `href="${result}"`;
1426
+ return `href="${href}"`;
1427
+ }
1428
+ const [pathPart, hashPart] = href.split("#");
1429
+ const cleanHref = pathPart.replace(/^\.\//, "");
1430
+ const resolvedPath = currentDir ? `${currentDir}/${cleanHref}` : cleanHref;
1431
+ return `href="${`${basePath.endsWith("/") ? basePath : `${basePath}/`}${resolvedPath}${hashPart ? `#${hashPart}` : ""}`}"`;
1432
+ });
1014
1433
  }
1015
-
1016
- // src/styleGuide.ts
1017
- var STYLE_GUIDE = `## Markdown style guide (for Vantage viewer)
1434
+ //#endregion
1435
+ //#region src/styleGuide.ts
1436
+ /**
1437
+ * The canonical Vantage Markdown style guide.
1438
+ *
1439
+ * This string is the single source of truth for the conventions Vantage's
1440
+ * renderer expects. Two consumers read it:
1441
+ *
1442
+ * - the in-app "Style Guide for Agents" modal, which shows it with a copy
1443
+ * button, and
1444
+ * - the `vantage-check style-guide` command, which prints it so an agent can
1445
+ * fetch it without a human in the loop.
1446
+ *
1447
+ * Every rule stated here should be one a checker can enforce or a renderer
1448
+ * actually cares about — if a line is neither, it does not belong.
1449
+ */
1450
+ const STYLE_GUIDE = `## Markdown style guide (for Vantage viewer)
1018
1451
 
1019
1452
  When writing or updating markdown documents that will be viewed in Vantage, follow these conventions:
1020
1453
 
1021
1454
  ### Structure
1022
- - Use headings (## and ###) to organize content \u2014 they become navigable outline anchors.
1455
+ - Use headings (## and ###) to organize content — they become navigable outline anchors.
1023
1456
  - Keep paragraphs focused and concise. Break up dense text with subheadings, lists, or tables.
1024
1457
 
1025
1458
  ### Links and cross-references
@@ -1028,11 +1461,11 @@ When writing or updating markdown documents that will be viewed in Vantage, foll
1028
1461
  - Subdirectory: \`[Design Doc](./design/auth.md)\`
1029
1462
  - Parent / sibling folder: \`[Overview](../overview.md)\` or \`[Spec](../specs/api.md)\`
1030
1463
  - **Never use leading slashes**:
1031
- - \u274C \`[Doc](/docs/guide.md)\` (breaks web routing and multi-repo scoping)
1032
- - \u2705 \`[Doc](../docs/guide.md)\` or \`[Doc](./guide.md)\`
1464
+ - ❌ \`[Doc](/docs/guide.md)\` (breaks web routing and multi-repo scoping)
1465
+ - ✅ \`[Doc](../docs/guide.md)\` or \`[Doc](./guide.md)\`
1033
1466
  - **Never use absolute filesystem paths or URI schemes**:
1034
- - \u274C \`file:///workspace/docs/guide.md\`, \`/workspace/docs/guide.md\`, \`C:\\...\`
1035
- - \u2705 \`[Doc](./guide.md)\` or \`[Doc](../guide.md)\`
1467
+ - ❌ \`file:///workspace/docs/guide.md\`, \`/workspace/docs/guide.md\`, \`C:\\...\`
1468
+ - ✅ \`[Doc](./guide.md)\` or \`[Doc](../guide.md)\`
1036
1469
  - **Always include the file extension**: Use \`.md\`, \`.ts\`, \`.go\`, etc. (e.g. \`[Model](model.go)\`).
1037
1470
  - **Line anchors and ranges**:
1038
1471
  - Link to specific lines: \`[Handler](../server/api.go#L42)\` or \`[Range](../server/api.go#L42-L58)\`
@@ -1043,8 +1476,8 @@ When writing or updating markdown documents that will be viewed in Vantage, foll
1043
1476
  - Cross-doc: \`[Architecture](../overview.md#system-architecture)\`
1044
1477
  - Anchor slugs are lowercase, hyphenated, and punctuation-stripped.
1045
1478
  - **Backticks in links**: Place backticks inside the link label, not around the markdown link syntax:
1046
- - \u2705 \`[\`config.json\`](./config.json)\` or \`[config.json](./config.json)\`
1047
- - \u274C \`\`[config.json](./config.json)\`\`
1479
+ - ✅ \`[\`config.json\`](./config.json)\` or \`[config.json](./config.json)\`
1480
+ - ❌ \`\`[config.json](./config.json)\`\`
1048
1481
 
1049
1482
  ### Frontmatter (Metadata)
1050
1483
  - Include structured metadata at the very top of docs delimited by \`---\` (YAML) or \`+++\` (TOML). Vantage renders this as a metadata card:
@@ -1060,9 +1493,9 @@ vantage:
1060
1493
  status-chip: true # show \`status\` as a chip above the metadata card
1061
1494
  ---
1062
1495
  \`\`\`
1063
- - **Nothing may sit above the opening delimiter** \u2014 not a blank line, not an editorial comment, not a \`<!-- vantage: \u2026 -->\` directive. Frontmatter is recognised only at the very first byte of the file (in Vantage, on GitHub, and in every other reader), so one line above it turns the whole block into body text: a horizontal rule followed by a heading made of the raw keys, with every field lost. \`vantage-check\` reports it as \`frontmatter/not-at-top\`.
1496
+ - **Nothing may sit above the opening delimiter** — not a blank line, not an editorial comment, not a \`<!-- vantage: … -->\` directive. Frontmatter is recognised only at the very first byte of the file (in Vantage, on GitHub, and in every other reader), so one line above it turns the whole block into body text: a horizontal rule followed by a heading made of the raw keys, with every field lost. \`vantage-check\` reports it as \`frontmatter/not-at-top\`.
1064
1497
  - **\`vantage:\` is Vantage's own reserved key.** It holds chrome that belongs to the file rather than to a section, it never shows up in the metadata card, and every other renderer ignores it. One key today: \`status-chip\`.
1065
- - **Prefer \`status-chip: true\`**, which shows the document's own \`status:\` and therefore cannot disagree with it. A literal \`status-chip: accepted\` is accepted too, but it is a second value that goes stale on its own \u2014 \`vantage-check\` reports the disagreement.
1498
+ - **Prefer \`status-chip: true\`**, which shows the document's own \`status:\` and therefore cannot disagree with it. A literal \`status-chip: accepted\` is accepted too, but it is a second value that goes stale on its own — \`vantage-check\` reports the disagreement.
1066
1499
  - The chip's vocabulary is \`status\`'s, exactly: \`draft | in-review | accepted | deprecated\`, lowercase. \`Draft\` renders no chip at all, silently.
1067
1500
 
1068
1501
  ### Mermaid diagrams
@@ -1101,7 +1534,7 @@ flowchart TD
1101
1534
 
1102
1535
  ### Vantage directives (optional, and Vantage-only)
1103
1536
 
1104
- Vantage reads a few styling hints from ordinary HTML comments. Every other renderer \u2014 GitHub included \u2014 drops them, so a document has to read exactly the same without them: directives decorate, they never carry meaning. One goes on a line of its own, with a blank line after it, and applies to the block that follows:
1537
+ Vantage reads a few styling hints from ordinary HTML comments. Every other renderer — GitHub included — drops them, so a document has to read exactly the same without them: directives decorate, they never carry meaning. One goes on a line of its own, with a blank line after it, and applies to the block that follows:
1105
1538
 
1106
1539
  \`\`\`markdown
1107
1540
  <!-- vantage: section tone=warning badge=stale -->
@@ -1112,17 +1545,17 @@ The steps below predate the rewrite.
1112
1545
  \`\`\`
1113
1546
 
1114
1547
  - **Three names**: \`section\` (the heading and everything under it), \`block\` (the one block after it), \`oq\` (one answerable Open Question).
1115
- - **The keys and values are a closed set**: \`tone\` = \`note | tip | important | warning | caution | muted\`; \`emphasis\` = \`strong | normal | quiet\`; \`badge\` = \`draft | stale | blocked | done | wip\`; \`collapsed\` = \`true | false\`. Name a *tone*, never a colour \u2014 the theme decides what a warning looks like, in light mode, in dark mode, and in print.
1548
+ - **The keys and values are a closed set**: \`tone\` = \`note | tip | important | warning | caution | muted\`; \`emphasis\` = \`strong | normal | quiet\`; \`badge\` = \`draft | stale | blocked | done | wip\`; \`collapsed\` = \`true | false\`. Name a *tone*, never a colour — the theme decides what a warning looks like, in light mode, in dark mode, and in print.
1116
1549
  - **Use them sparingly.** One or two per document, on the sections that genuinely differ. A document where everything is toned says nothing, and a rainbow one is harder to read than a plain one.
1117
- - **Anything outside those sets is silently ignored** \u2014 nothing breaks, and nothing styles either. Run \`vantage-check\` on the document: the \`vantage/*\` rules are the only thing that will ever tell you a directive did nothing.
1118
- - **Always close the comment with \`-->\`.** Never \`--!>\`, and never leave it open: Markdown reads every line below an unclosed \`<!--\` as part of the comment, and the whole rest of the document vanishes from the page. For the same reason \`-->\` cannot appear *inside* a value \u2014 it ends the comment early and spills the remainder into the page as literal text.
1119
- - **In a list, indent the directive inside the item**, with blank lines around it (below). At the start of a line between two items it ends the list and starts a second one, which changes the numbering and the spacing in every renderer \u2014 the one thing a directive must never do.
1120
- - **A \`leaning\` restates the leaning; it is never "yes".** The one-click button in review mode files that text as a review comment, and the comment is all the agent reading it has \u2014 nobody remembers which button was clicked. \`leaning="Yes"\` beside a two-branch question is a support ticket.
1550
+ - **Anything outside those sets is silently ignored** — nothing breaks, and nothing styles either. Run \`vantage-check\` on the document: the \`vantage/*\` rules are the only thing that will ever tell you a directive did nothing.
1551
+ - **Always close the comment with \`-->\`.** Never \`--!>\`, and never leave it open: Markdown reads every line below an unclosed \`<!--\` as part of the comment, and the whole rest of the document vanishes from the page. For the same reason \`-->\` cannot appear *inside* a value — it ends the comment early and spills the remainder into the page as literal text.
1552
+ - **In a list, indent the directive inside the item**, with blank lines around it (below). At the start of a line between two items it ends the list and starts a second one, which changes the numbering and the spacing in every renderer — the one thing a directive must never do.
1553
+ - **A \`leaning\` restates the leaning; it is never "yes".** The one-click button in review mode files that text as a review comment, and the comment is all the agent reading it has — nobody remembers which button was clicked. \`leaning="Yes"\` beside a two-branch question is a support ticket.
1121
1554
 
1122
1555
  \`\`\`markdown
1123
1556
  1. **OQ-9: Queue position on re-entry.**
1124
1557
 
1125
- <!-- vantage: oq id=OQ-9 leaning="Back of the queue \u2014 the fix might interact with what merged while it was out." -->
1558
+ <!-- vantage: oq id=OQ-9 leaning="Back of the queue — the fix might interact with what merged while it was out." -->
1126
1559
 
1127
1560
  _Leaning:_ Back of the queue.
1128
1561
  \`\`\`
@@ -1130,10 +1563,10 @@ The steps below predate the rewrite.
1130
1563
  ### Tables, task lists, and math
1131
1564
  - **Tables**: Use standard markdown tables for structured comparisons and schemas.
1132
1565
  - **Task lists**: Use \`- [ ]\` and \`- [x]\` for actionable checklists and status tracking.
1133
- - **LaTeX Math**: Use \`$$...$$\` for *all* KaTeX math \u2014 display blocks (\`$$\` alone on its own lines) and inline alike (\`$$E = mc^2$$\` mid-sentence).
1566
+ - **LaTeX Math**: Use \`$$...$$\` for *all* KaTeX math — display blocks (\`$$\` alone on its own lines) and inline alike (\`$$E = mc^2$$\` mid-sentence).
1134
1567
  - Single dollars are **not** math delimiters: \`$HOME\` and \`$100\` stay literal, so prose and shell snippets are safe to write as-is.
1135
1568
  `;
1569
+ //#endregion
1570
+ export { DIRECTIVE_NAMES, DIRECTIVE_VOCABULARY, DOC_STATUSES, DOC_STATUS_TONES, SAFE_STYLE, STYLE_GUIDE, VANTAGE_BADGES, VANTAGE_COLLAPSED, VANTAGE_EMPHASIS, VANTAGE_FRONTMATTER_KEYS, VANTAGE_OQ_HOST_TARGETS, VANTAGE_RUNS, VANTAGE_SENTINEL, VANTAGE_TONES, buildPipeline, buildRemarkPlugins, clearLineAnchorHighlights, hasVantageSentinel, isDocStatus, parseFrontmatter, parseLineAnchor, parseVantageDirective, readVantageFrontmatter, rehypeSourceLines, rehypeVantageDirectives, renderMarkdown, renderMermaidBlocks, resolveLinks, sanitizeSchema, scrollToLineAnchor };
1136
1571
 
1137
- export { DIRECTIVE_NAMES, DIRECTIVE_VOCABULARY, DOC_STATUSES, DOC_STATUS_TONES, SAFE_STYLE, STYLE_GUIDE, VANTAGE_BADGES, VANTAGE_COLLAPSED, VANTAGE_EMPHASIS, VANTAGE_FRONTMATTER_KEYS, VANTAGE_OQ_HOST_TARGETS, VANTAGE_RUNS, VANTAGE_SENTINEL, VANTAGE_TONES, buildPipeline, buildRemarkPlugins, clearLineAnchorHighlights, hasVantageSentinel, isDocStatus, parseFrontmatter, parseLineAnchor, parseVantageDirective, readVantageFrontmatter, rehypeSourceLines_default as rehypeSourceLines, rehypeVantageDirectives_default as rehypeVantageDirectives, renderMarkdown, renderMermaidBlocks, resolveLinks, sanitizeSchema, scrollToLineAnchor };
1138
- //# sourceMappingURL=index.js.map
1139
1572
  //# sourceMappingURL=index.js.map