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