markemental 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,1034 +1,1596 @@
1
- 'use strict';
2
-
3
- // src/sources/line-source.ts
4
- function createLineSource() {
5
- let buffer = "";
6
- let closed = false;
7
- return {
8
- push(chunk) {
9
- if (closed) throw new Error("push after close");
10
- buffer += chunk;
11
- },
12
- readLines() {
13
- const lines = [];
14
- let at = buffer.indexOf("\n");
15
- while (at !== -1) {
16
- lines.push(buffer.slice(0, at).replace(/\r$/, ""));
17
- buffer = buffer.slice(at + 1);
18
- at = buffer.indexOf("\n");
19
- }
20
- return lines;
21
- },
22
- close() {
23
- closed = true;
24
- if (buffer === "") return [];
25
- const rest = buffer.replace(/\r$/, "");
26
- buffer = "";
27
- return [rest];
28
- }
29
- };
30
- }
31
-
32
- // src/core/pipelines/markdown-pipeline.ts
33
- function createMarkdownPipeline(renderer) {
34
- const source = createLineSource();
35
- function feed(lines) {
36
- for (const line of lines) renderer.writeLine(line);
37
- }
38
- return {
39
- async push(chunk) {
40
- source.push(await chunk);
41
- feed(source.readLines());
42
- },
43
- async flush() {
44
- feed(source.close());
45
- await renderer.flush();
46
- }
47
- };
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/streams/markdown-stream.ts
3
+ /**
4
+ * Create a streaming pipeline around any renderer and target.
5
+ *
6
+ * @remarks
7
+ * The pipeline chunks whatever strings are written into lines and feeds
8
+ * them to the renderer one at a time; the renderer owns its parse state
9
+ * and commits finished output to the target. Closing the stream renders
10
+ * the trailing remainder. Pass a built-in renderer (`GFMRenderer`,
11
+ * `CommonMarkRenderer`) or your own `MarkdownRenderer` implementation,
12
+ * and a DOM target from `createDOMTarget` or your own `HTMLTarget`.
13
+ *
14
+ * @param renderer - Line-consuming renderer holding its own parse state.
15
+ * @param target - Destination the renderer commits to.
16
+ * @returns A working pipeline.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const target = createDOMTarget(document, document.getElementById("out")!);
21
+ * const stream = createMarkdownStream(new GFMRenderer(target, {}), target);
22
+ * const writer = stream.getWriter();
23
+ * await writer.write("# Hello\n");
24
+ * await writer.close();
25
+ * writer.releaseLock();
26
+ * ```
27
+ *
28
+ * @public
29
+ */
30
+ function createMarkdownStream(renderer, target) {
31
+ renderer.setTarget(target);
32
+ let buffer = "";
33
+ const pipeline = new WritableStream({
34
+ write(chunk) {
35
+ if (typeof chunk !== "string") throw new TypeError(`MarkdownPipeline chunks must be strings, received ${typeof chunk}`);
36
+ buffer += chunk;
37
+ let at = buffer.indexOf("\n");
38
+ while (at !== -1) {
39
+ renderer.writeLine(buffer.slice(0, at).replace(/\r$/, ""));
40
+ buffer = buffer.slice(at + 1);
41
+ at = buffer.indexOf("\n");
42
+ }
43
+ },
44
+ close() {
45
+ if (buffer !== "") {
46
+ const rest = buffer.replace(/\r$/, "");
47
+ buffer = "";
48
+ renderer.writeLine(rest);
49
+ }
50
+ return renderer.flush();
51
+ }
52
+ });
53
+ pipeline.setTarget = (next) => {
54
+ renderer.setTarget(next);
55
+ };
56
+ pipeline.setConfig = (next) => {
57
+ renderer.setConfig(next);
58
+ };
59
+ return pipeline;
48
60
  }
49
-
61
+ // src/core/contracts/html-target.ts
62
+ /**
63
+ * A target call referenced an id the target never minted or already
64
+ * retired. Carries the offending id.
65
+ *
66
+ * @public
67
+ */
68
+ var UnknownNodeError = class extends Error {
69
+ /** The unknown id. */
70
+ nodeId;
71
+ /**
72
+ * @param nodeId - The unknown id.
73
+ */
74
+ constructor(nodeId) {
75
+ super(`Unknown node id: ${nodeId}`);
76
+ this.name = "UnknownNodeError";
77
+ this.nodeId = nodeId;
78
+ }
79
+ };
80
+ /**
81
+ * A replace targeted a node that was never attached. Carries the
82
+ * detached id.
83
+ *
84
+ * @public
85
+ */
86
+ var DetachedNodeError = class extends Error {
87
+ /** The detached id. */
88
+ nodeId;
89
+ /**
90
+ * @param nodeId - The detached id.
91
+ */
92
+ constructor(nodeId) {
93
+ super(`Cannot replace detached node: ${nodeId}`);
94
+ this.name = "DetachedNodeError";
95
+ this.nodeId = nodeId;
96
+ }
97
+ };
98
+ /**
99
+ * An attach would have built a cycle: the node is an ancestor of the
100
+ * parent. Carries both ids.
101
+ *
102
+ * @public
103
+ */
104
+ var HierarchyError = class extends Error {
105
+ /** The node being attached. */
106
+ nodeId;
107
+ /** The parent it was attached to. */
108
+ parentId;
109
+ /**
110
+ * @param nodeId - The node being attached.
111
+ * @param parentId - The parent it was attached to.
112
+ */
113
+ constructor(nodeId, parentId) {
114
+ super(`Cannot attach node ${nodeId} inside its own descendant ${parentId}`);
115
+ this.name = "HierarchyError";
116
+ this.nodeId = nodeId;
117
+ this.parentId = parentId;
118
+ }
119
+ };
50
120
  // src/renderers/parser/blocks.ts
51
- var HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
52
- var RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
53
- var FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
54
- var QUOTE_RE = /^>\s?(.*)$/;
55
- var BULLET_RE = /^\s*[-*+]\s+(.*)$/;
56
- var ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
57
- var TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
58
- var LEADING_WS_RE = /^\s*/;
121
+ const HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
122
+ const RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
123
+ const FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
124
+ const QUOTE_RE = /^>\s?(.*)$/;
125
+ const BULLET_RE = /^\s*[-*+]\s+(.*)$/;
126
+ const ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
127
+ const TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
128
+ const LEADING_WS_RE = /^\s*/;
129
+ /**
130
+ * Whether a line is blank (a pure block separator carrying no content).
131
+ *
132
+ * @param line - Source line to test.
133
+ * @returns True for empty or whitespace-only lines.
134
+ */
59
135
  function isBlankLine(line) {
60
- return line.trim() === "";
136
+ return line.trim() === "";
61
137
  }
138
+ /**
139
+ * Match a fence marker line.
140
+ *
141
+ * @param line - Source line to test.
142
+ * @returns The marker, or null when the line is not a fence marker.
143
+ */
62
144
  function matchFence(line) {
63
- const match = FENCE_RE.exec(line.trim());
64
- if (!match || !match[1]) return null;
65
- const run = match[1];
66
- return {
67
- marker: run[0],
68
- length: run.length,
69
- language: (match[2] ?? "").trim() || void 0
70
- };
145
+ const match = FENCE_RE.exec(line.trim());
146
+ if (!match || !match[1]) return null;
147
+ const run = match[1];
148
+ return {
149
+ marker: run[0],
150
+ length: run.length,
151
+ language: (match[2] ?? "").trim() || void 0
152
+ };
71
153
  }
154
+ /**
155
+ * Whether a line closes an open fence.
156
+ *
157
+ * @param open - Marker that opened the fence.
158
+ * @param line - Source line to test.
159
+ * @returns True for a same-character run at least as long.
160
+ */
72
161
  function fenceCloses(open, line) {
73
- const match = matchFence(line);
74
- return match !== null && match.marker === open.marker && match.length >= open.length;
162
+ const match = matchFence(line);
163
+ return match !== null && match.marker === open.marker && match.length >= open.length;
75
164
  }
165
+ /**
166
+ * Match an ATX heading line.
167
+ *
168
+ * @param line - Source line to test.
169
+ * @returns The heading, or null for non-heading lines.
170
+ */
76
171
  function matchHeading(line) {
77
- const match = HEADING_RE.exec(line);
78
- if (!match || !match[1]) return null;
79
- return {
80
- level: Math.min(6, match[1].length),
81
- text: (match[2] ?? "").replace(/\s+#+\s*$/, "").trim()
82
- };
172
+ const match = HEADING_RE.exec(line);
173
+ if (!match || !match[1]) return null;
174
+ return {
175
+ level: Math.min(6, match[1].length),
176
+ text: (match[2] ?? "").replace(/\s+#+\s*$/, "").trim()
177
+ };
83
178
  }
179
+ /**
180
+ * Whether a line is a thematic break.
181
+ *
182
+ * @param line - Source line to test.
183
+ * @returns True for `***`, `---`, `___` style lines.
184
+ */
84
185
  function isRuleLine(line) {
85
- return RULE_RE.test(line.trim());
186
+ return RULE_RE.test(line.trim());
86
187
  }
188
+ /**
189
+ * Match a quote line.
190
+ *
191
+ * @param line - Source line to test.
192
+ * @returns The content, or null for non-quote lines.
193
+ */
87
194
  function matchQuote(line) {
88
- const match = QUOTE_RE.exec(line);
89
- if (!match) return null;
90
- return { text: match[1] ?? "" };
195
+ const match = QUOTE_RE.exec(line);
196
+ if (!match) return null;
197
+ return { text: match[1] ?? "" };
91
198
  }
199
+ /**
200
+ * Match a bullet or ordered list item line.
201
+ *
202
+ * @param line - Source line to test.
203
+ * @returns The item, or null for non-item lines.
204
+ */
92
205
  function matchListItem(line) {
93
- const bullet = BULLET_RE.exec(line);
94
- const ordered = ORDERED_RE.exec(line);
95
- if (!bullet && !ordered) return null;
96
- return {
97
- ordered: !bullet,
98
- indent: LEADING_WS_RE.exec(line)?.[0].length ?? 0,
99
- text: bullet?.[1] ?? ordered?.[1] ?? ""
100
- };
206
+ const bullet = BULLET_RE.exec(line);
207
+ const ordered = ORDERED_RE.exec(line);
208
+ if (!bullet && !ordered) return null;
209
+ return {
210
+ ordered: !bullet,
211
+ indent: LEADING_WS_RE.exec(line)?.[0].length ?? 0,
212
+ text: bullet?.[1] ?? ordered?.[1] ?? ""
213
+ };
101
214
  }
215
+ /**
216
+ * Whether a line is a table delimiter row.
217
+ *
218
+ * @param line - Source line to test.
219
+ * @returns True for `|---|...` style rows.
220
+ */
102
221
  function isTableDelimiter(line) {
103
- if (!line.includes("|") && !line.includes("-")) return false;
104
- const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
105
- return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
222
+ if (!line.includes("|") && !line.includes("-")) return false;
223
+ const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
224
+ return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
106
225
  }
226
+ /**
227
+ * Whether `lines` ends inside an unclosed fenced code block.
228
+ *
229
+ * @param lines - Source lines to scan.
230
+ * @returns True when a fence opens without a matching close.
231
+ */
107
232
  function hasOpenFence(lines) {
108
- let open = null;
109
- for (const line of lines) {
110
- if (open === null) {
111
- open = matchFence(line);
112
- } else if (fenceCloses(open, line)) {
113
- open = null;
114
- }
115
- }
116
- return open !== null;
233
+ let open = null;
234
+ for (const line of lines) if (open === null) open = matchFence(line);
235
+ else if (fenceCloses(open, line)) open = null;
236
+ return open !== null;
117
237
  }
118
238
  function makeBlock(block, sourceLineCount) {
119
- return { ...block, sourceLineCount };
239
+ return {
240
+ ...block,
241
+ sourceLineCount
242
+ };
120
243
  }
244
+ /**
245
+ * Split leaf-block lines into blocks.
246
+ *
247
+ * @remarks
248
+ * Tables and lists never reach this function: the render state diverts them
249
+ * into streaming fragments, so only headings, paragraphs, fences, quotes,
250
+ * and rules are split here.
251
+ *
252
+ * @param lines - Source lines without line breaks.
253
+ * @returns Parsed blocks in document order.
254
+ */
121
255
  function splitBlocks(lines) {
122
- const blocks = [];
123
- let i = 0;
124
- while (i < lines.length) {
125
- const line = lines[i];
126
- if (isBlankLine(line)) {
127
- i++;
128
- continue;
129
- }
130
- const fence = matchFence(line);
131
- if (fence) {
132
- const content = [];
133
- let j2 = i + 1;
134
- while (j2 < lines.length && !fenceCloses(fence, lines[j2])) {
135
- content.push(lines[j2]);
136
- j2++;
137
- }
138
- const closed = j2 < lines.length;
139
- blocks.push(makeBlock({ kind: "fence", lines: content, language: fence.language }, j2 - i + (closed ? 1 : 0)));
140
- i = j2 + (closed ? 1 : 0);
141
- continue;
142
- }
143
- const heading = matchHeading(line);
144
- if (heading) {
145
- blocks.push(makeBlock({ kind: "heading", lines: [heading.text], level: heading.level }, 1));
146
- i++;
147
- continue;
148
- }
149
- if (isRuleLine(line)) {
150
- blocks.push(makeBlock({ kind: "rule", lines: [] }, 1));
151
- i++;
152
- continue;
153
- }
154
- const quote = matchQuote(line);
155
- if (quote) {
156
- const quoted = [quote.text];
157
- let j2 = i + 1;
158
- while (j2 < lines.length) {
159
- const next = matchQuote(lines[j2]);
160
- if (!next) break;
161
- quoted.push(next.text);
162
- j2++;
163
- }
164
- blocks.push(makeBlock({ kind: "quote", lines: quoted }, j2 - i));
165
- i = j2;
166
- continue;
167
- }
168
- const paragraph = [line];
169
- let j = i + 1;
170
- while (j < lines.length) {
171
- const next = lines[j];
172
- if (isBlankLine(next) || matchFence(next) !== null || matchHeading(next) !== null || isRuleLine(next) || matchQuote(next) !== null) {
173
- break;
174
- }
175
- paragraph.push(next);
176
- j++;
177
- }
178
- blocks.push(makeBlock({ kind: "paragraph", lines: paragraph }, j - i));
179
- i = j;
180
- }
181
- return blocks;
256
+ const blocks = [];
257
+ let i = 0;
258
+ while (i < lines.length) {
259
+ const line = lines[i];
260
+ if (isBlankLine(line)) {
261
+ i++;
262
+ continue;
263
+ }
264
+ const fence = matchFence(line);
265
+ if (fence) {
266
+ const content = [];
267
+ let j = i + 1;
268
+ while (j < lines.length && !fenceCloses(fence, lines[j])) {
269
+ content.push(lines[j]);
270
+ j++;
271
+ }
272
+ const closed = j < lines.length;
273
+ blocks.push(makeBlock({
274
+ kind: "fence",
275
+ lines: content,
276
+ language: fence.language
277
+ }, j - i + (closed ? 1 : 0)));
278
+ i = j + (closed ? 1 : 0);
279
+ continue;
280
+ }
281
+ const heading = matchHeading(line);
282
+ if (heading) {
283
+ blocks.push(makeBlock({
284
+ kind: "heading",
285
+ lines: [heading.text],
286
+ level: heading.level
287
+ }, 1));
288
+ i++;
289
+ continue;
290
+ }
291
+ if (isRuleLine(line)) {
292
+ blocks.push(makeBlock({
293
+ kind: "rule",
294
+ lines: []
295
+ }, 1));
296
+ i++;
297
+ continue;
298
+ }
299
+ const quote = matchQuote(line);
300
+ if (quote) {
301
+ const quoted = [quote.text];
302
+ let j = i + 1;
303
+ while (j < lines.length) {
304
+ const next = matchQuote(lines[j]);
305
+ if (!next) break;
306
+ quoted.push(next.text);
307
+ j++;
308
+ }
309
+ blocks.push(makeBlock({
310
+ kind: "quote",
311
+ lines: quoted
312
+ }, j - i));
313
+ i = j;
314
+ continue;
315
+ }
316
+ const paragraph = [line];
317
+ let j = i + 1;
318
+ while (j < lines.length) {
319
+ const next = lines[j];
320
+ if (isBlankLine(next) || matchFence(next) !== null || matchHeading(next) !== null || isRuleLine(next) || matchQuote(next) !== null) break;
321
+ paragraph.push(next);
322
+ j++;
323
+ }
324
+ blocks.push(makeBlock({
325
+ kind: "paragraph",
326
+ lines: paragraph
327
+ }, j - i));
328
+ i = j;
329
+ }
330
+ return blocks;
182
331
  }
332
+ /**
333
+ * Split a table row line into trimmed cells.
334
+ *
335
+ * @param line - Raw row line, with or without outer pipes.
336
+ * @returns Cells in order.
337
+ */
183
338
  function splitTableRow(line) {
184
- return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
339
+ return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
185
340
  }
341
+ /**
342
+ * Parse column alignment from a delimiter cell.
343
+ *
344
+ * @param cell - Raw delimiter cell (dashes with optional edge colons).
345
+ * @returns The alignment, or null for none.
346
+ */
186
347
  function parseTableAlignment(cell) {
187
- const left = cell.startsWith(":");
188
- const right = cell.endsWith(":");
189
- if (left && right) return "center";
190
- if (right) return "right";
191
- if (left) return "left";
192
- return null;
348
+ const left = cell.startsWith(":");
349
+ const right = cell.endsWith(":");
350
+ if (left && right) return "center";
351
+ if (right) return "right";
352
+ if (left) return "left";
353
+ return null;
193
354
  }
194
-
195
355
  // src/renderers/renderer-state.ts
356
+ /**
357
+ * Incremental line-driven parser for CommonMark structure.
358
+ *
359
+ * @remarks
360
+ * Internal helper owned by a renderer. Lines arrive one at a time: leaf
361
+ * blocks buffer until a new block starts or the stream flushes (preserving
362
+ * trailing holdback), and lists commit one fragment per item with an indent
363
+ * stack for nesting. Tables are not recognized here, so table-looking lines
364
+ * stay plain paragraph text; {@link GFMState} extends this class with table
365
+ * support and nothing else.
366
+ *
367
+ * @internal
368
+ */
196
369
  var CommonMarkState = class {
197
- /**
198
- * @param emit - Receives parse fragments in document order.
199
- */
200
- constructor(_emit) {
201
- this._emit = _emit;
202
- }
203
- _emit;
204
- _pending = [];
205
- _fence = null;
206
- _quote = null;
207
- _lists = [];
208
- /**
209
- * Feed one source line; completed fragments emit to the handler.
210
- *
211
- * @param line - Next source line, without its line break.
212
- */
213
- addLine(line) {
214
- if (this._consumeFence(line)) return;
215
- if (this._consumeLists(line)) return;
216
- if (this._consumeQuote(line)) return;
217
- this._classify(line);
218
- }
219
- /**
220
- * Close every open context and emit the trailing remainder.
221
- */
222
- flush() {
223
- this._closeLists();
224
- if (this._quote !== null) {
225
- this._pending.push(...this._quote);
226
- this._quote = null;
227
- }
228
- if (this._fence !== null) {
229
- this._pending.push(this._fence.openLine, ...this._fence.content);
230
- this._fence = null;
231
- }
232
- this._takeAll();
233
- }
234
- /**
235
- * Feed a line to the open fence, if any.
236
- *
237
- * @param line - Next source line.
238
- * @returns True when the line was consumed.
239
- */
240
- _consumeFence(line) {
241
- if (this._fence === null) return false;
242
- if (fenceCloses(this._fence, line)) {
243
- this._pending.push(this._fence.openLine, ...this._fence.content, line);
244
- this._fence = null;
245
- this._takeComplete();
246
- } else {
247
- this._fence.content.push(line);
248
- }
249
- return true;
250
- }
251
- /**
252
- * Feed a line to the open lists, if any, closing and reprocessing when
253
- * the line is not an item.
254
- *
255
- * @param line - Next source line.
256
- * @returns True when the line was consumed or reprocessed.
257
- */
258
- _consumeLists(line) {
259
- if (this._lists.length === 0) return false;
260
- const item = matchListItem(line);
261
- if (item !== null) {
262
- this._listItem(item);
263
- return true;
264
- }
265
- this._closeLists();
266
- this.addLine(line);
267
- return true;
268
- }
269
- /**
270
- * Feed a line to the open quote, if any, dumping it back to pending when
271
- * the line does not continue the quote.
272
- *
273
- * @param line - Next source line.
274
- * @returns True when the line was consumed.
275
- */
276
- _consumeQuote(line) {
277
- if (this._quote === null) return false;
278
- if (matchQuote(line) !== null) {
279
- this._quote.push(line);
280
- return true;
281
- }
282
- this._pending.push(...this._quote);
283
- this._quote = null;
284
- return false;
285
- }
286
- /**
287
- * Classify a line that continues no open context.
288
- *
289
- * @param line - Next source line.
290
- */
291
- _classify(line) {
292
- if (isBlankLine(line)) {
293
- this._pending.push(line);
294
- return;
295
- }
296
- const fence = matchFence(line);
297
- if (fence !== null) {
298
- this._takeAll();
299
- this._fence = { marker: fence.marker, length: fence.length, openLine: line, content: [] };
300
- return;
301
- }
302
- if (matchHeading(line) !== null || isRuleLine(line)) {
303
- this._takeAll();
304
- this._pending.push(line);
305
- return;
306
- }
307
- if (matchQuote(line) !== null) {
308
- this._takeAll();
309
- this._quote = [line];
310
- return;
311
- }
312
- const item = matchListItem(line);
313
- if (item !== null) {
314
- this._takeAll();
315
- this._listItem(item);
316
- return;
317
- }
318
- if (this._classifyPipe(line)) return;
319
- this._pending.push(line);
320
- this._takeComplete();
321
- }
322
- /**
323
- * Classify a line that matches no CommonMark opener. The base parser has
324
- * no pipe syntax, so this never consumes; {@link GFMState} overrides it
325
- * to start table candidates.
326
- *
327
- * @param _line - Next source line.
328
- * @returns Always false here.
329
- */
330
- _classifyPipe(_line) {
331
- return false;
332
- }
333
- _listItem(item) {
334
- while (this._lists.length > 0 && item.indent < this._lists[this._lists.length - 1].indent) {
335
- this._lists.pop();
336
- this._emit({ kind: "listEnd" });
337
- }
338
- const top = this._lists[this._lists.length - 1];
339
- if (top && top.indent === item.indent && top.ordered === item.ordered) {
340
- this._emit({ kind: "listItem", text: item.text });
341
- return;
342
- }
343
- if (top && top.indent === item.indent) {
344
- this._lists.pop();
345
- this._emit({ kind: "listEnd" });
346
- }
347
- this._emit({ kind: "listStart", ordered: item.ordered });
348
- this._lists.push({ ordered: item.ordered, indent: item.indent });
349
- this._emit({ kind: "listItem", text: item.text });
350
- }
351
- _closeLists() {
352
- while (this._lists.length > 0) {
353
- this._lists.pop();
354
- this._emit({ kind: "listEnd" });
355
- }
356
- }
357
- _takeComplete() {
358
- let start = 0;
359
- let end = this._pending.length;
360
- while (start < end && isBlankLine(this._pending[start])) start++;
361
- while (end > start && isBlankLine(this._pending[end - 1])) end--;
362
- const trimmed = this._pending.slice(start, end);
363
- if (trimmed.length === 0) {
364
- this._pending = [];
365
- return;
366
- }
367
- if (hasOpenFence(trimmed)) return;
368
- const blocks = splitBlocks(trimmed);
369
- const last = blocks[blocks.length - 1];
370
- if (last === void 0) {
371
- this._pending = [];
372
- return;
373
- }
374
- this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
375
- for (const block of blocks.slice(0, -1)) this._emit({ kind: "block", block });
376
- }
377
- _takeAll() {
378
- const blocks = splitBlocks(this._pending);
379
- this._pending = [];
380
- for (const block of blocks) this._emit({ kind: "block", block });
381
- }
370
+ _emit;
371
+ _pending = [];
372
+ _fence = null;
373
+ _quote = null;
374
+ _lists = [];
375
+ /**
376
+ * @param emit - Receives parse fragments in document order.
377
+ */
378
+ constructor(_emit) {
379
+ this._emit = _emit;
380
+ }
381
+ /**
382
+ * Feed one source line; completed fragments emit to the handler.
383
+ *
384
+ * @param line - Next source line, without its line break.
385
+ */
386
+ addLine(line) {
387
+ if (this._consumeFence(line)) return;
388
+ if (this._consumeLists(line)) return;
389
+ if (this._consumeQuote(line)) return;
390
+ this._classify(line);
391
+ }
392
+ /**
393
+ * Close every open context and emit the trailing remainder.
394
+ */
395
+ flush() {
396
+ this._closeLists();
397
+ if (this._quote !== null) {
398
+ this._pending.push(...this._quote);
399
+ this._quote = null;
400
+ }
401
+ if (this._fence !== null) {
402
+ this._pending.push(this._fence.openLine, ...this._fence.content);
403
+ this._fence = null;
404
+ }
405
+ this._takeAll();
406
+ }
407
+ /**
408
+ * Feed a line to the open fence, if any.
409
+ *
410
+ * @param line - Next source line.
411
+ * @returns True when the line was consumed.
412
+ */
413
+ _consumeFence(line) {
414
+ if (this._fence === null) return false;
415
+ if (fenceCloses(this._fence, line)) {
416
+ this._pending.push(this._fence.openLine, ...this._fence.content, line);
417
+ this._fence = null;
418
+ this._takeComplete();
419
+ } else this._fence.content.push(line);
420
+ return true;
421
+ }
422
+ /**
423
+ * Feed a line to the open lists, if any, closing and reprocessing when
424
+ * the line is not an item.
425
+ *
426
+ * @param line - Next source line.
427
+ * @returns True when the line was consumed or reprocessed.
428
+ */
429
+ _consumeLists(line) {
430
+ if (this._lists.length === 0) return false;
431
+ const item = matchListItem(line);
432
+ if (item !== null) {
433
+ this._listItem(item);
434
+ return true;
435
+ }
436
+ this._closeLists();
437
+ this.addLine(line);
438
+ return true;
439
+ }
440
+ /**
441
+ * Feed a line to the open quote, if any, dumping it back to pending when
442
+ * the line does not continue the quote.
443
+ *
444
+ * @param line - Next source line.
445
+ * @returns True when the line was consumed.
446
+ */
447
+ _consumeQuote(line) {
448
+ if (this._quote === null) return false;
449
+ if (matchQuote(line) !== null) {
450
+ this._quote.push(line);
451
+ return true;
452
+ }
453
+ this._pending.push(...this._quote);
454
+ this._quote = null;
455
+ return false;
456
+ }
457
+ /**
458
+ * Classify a line that continues no open context.
459
+ *
460
+ * @param line - Next source line.
461
+ */
462
+ _classify(line) {
463
+ if (isBlankLine(line)) {
464
+ this._pending.push(line);
465
+ return;
466
+ }
467
+ const fence = matchFence(line);
468
+ if (fence !== null) {
469
+ this._takeAll();
470
+ this._fence = {
471
+ marker: fence.marker,
472
+ length: fence.length,
473
+ openLine: line,
474
+ content: []
475
+ };
476
+ return;
477
+ }
478
+ if (matchHeading(line) !== null || isRuleLine(line)) {
479
+ this._takeAll();
480
+ this._pending.push(line);
481
+ return;
482
+ }
483
+ if (matchQuote(line) !== null) {
484
+ this._takeAll();
485
+ this._quote = [line];
486
+ return;
487
+ }
488
+ const item = matchListItem(line);
489
+ if (item !== null) {
490
+ this._takeAll();
491
+ this._listItem(item);
492
+ return;
493
+ }
494
+ if (this._classifyPipe(line)) return;
495
+ this._pending.push(line);
496
+ this._takeComplete();
497
+ }
498
+ /**
499
+ * Classify a line that matches no CommonMark opener. The base parser has
500
+ * no pipe syntax, so this never consumes; {@link GFMState} overrides it
501
+ * to start table candidates.
502
+ *
503
+ * @param _line - Next source line.
504
+ * @returns Always false here.
505
+ */
506
+ _classifyPipe(_line) {
507
+ return false;
508
+ }
509
+ _listItem(item) {
510
+ while (this._lists.length > 0 && item.indent < this._lists[this._lists.length - 1].indent) {
511
+ this._lists.pop();
512
+ this._emit({ kind: "listEnd" });
513
+ }
514
+ const top = this._lists[this._lists.length - 1];
515
+ if (top && top.indent === item.indent && top.ordered === item.ordered) {
516
+ this._emit({
517
+ kind: "listItem",
518
+ text: item.text
519
+ });
520
+ return;
521
+ }
522
+ if (top && top.indent === item.indent) {
523
+ this._lists.pop();
524
+ this._emit({ kind: "listEnd" });
525
+ }
526
+ this._emit({
527
+ kind: "listStart",
528
+ ordered: item.ordered
529
+ });
530
+ this._lists.push({
531
+ ordered: item.ordered,
532
+ indent: item.indent
533
+ });
534
+ this._emit({
535
+ kind: "listItem",
536
+ text: item.text
537
+ });
538
+ }
539
+ _closeLists() {
540
+ while (this._lists.length > 0) {
541
+ this._lists.pop();
542
+ this._emit({ kind: "listEnd" });
543
+ }
544
+ }
545
+ _takeComplete() {
546
+ let start = 0;
547
+ let end = this._pending.length;
548
+ while (start < end && isBlankLine(this._pending[start])) start++;
549
+ while (end > start && isBlankLine(this._pending[end - 1])) end--;
550
+ const trimmed = this._pending.slice(start, end);
551
+ if (trimmed.length === 0) {
552
+ this._pending = [];
553
+ return;
554
+ }
555
+ if (hasOpenFence(trimmed)) return;
556
+ const blocks = splitBlocks(trimmed);
557
+ const last = blocks[blocks.length - 1];
558
+ if (last === void 0) {
559
+ this._pending = [];
560
+ return;
561
+ }
562
+ this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
563
+ for (const block of blocks.slice(0, -1)) this._emit({
564
+ kind: "block",
565
+ block
566
+ });
567
+ }
568
+ _takeAll() {
569
+ const blocks = splitBlocks(this._pending);
570
+ this._pending = [];
571
+ for (const block of blocks) this._emit({
572
+ kind: "block",
573
+ block
574
+ });
575
+ }
382
576
  };
577
+ /**
578
+ * Incremental line-driven parser for GFM structure.
579
+ *
580
+ * @remarks
581
+ * Extends {@link CommonMarkState} with tables and nothing else: a table
582
+ * commits at the delimiter row and streams one fragment per row. All leaf
583
+ * and list parsing is inherited unchanged.
584
+ *
585
+ * @internal
586
+ */
383
587
  var GFMState = class extends CommonMarkState {
384
- _tableOpen = false;
385
- _candidate = null;
386
- /**
387
- * Feed one source line; completed fragments emit to the handler.
388
- *
389
- * @param line - Next source line, without its line break.
390
- */
391
- addLine(line) {
392
- if (this._consumeFence(line)) return;
393
- if (this._consumeTable(line)) return;
394
- if (this._consumeLists(line)) return;
395
- if (this._consumeQuote(line)) return;
396
- if (this._consumeCandidate(line)) return;
397
- this._classify(line);
398
- }
399
- /**
400
- * Close every open context and emit the trailing remainder.
401
- */
402
- flush() {
403
- if (this._candidate !== null) {
404
- this._pending.push(this._candidate);
405
- this._candidate = null;
406
- }
407
- if (this._tableOpen) {
408
- this._emit({ kind: "tableEnd" });
409
- this._tableOpen = false;
410
- }
411
- super.flush();
412
- }
413
- /**
414
- * Feed a line to the open table, if any, closing and reprocessing when
415
- * the line is not a row.
416
- *
417
- * @param line - Next source line.
418
- * @returns True when the line was consumed or reprocessed.
419
- */
420
- _consumeTable(line) {
421
- if (!this._tableOpen) return false;
422
- if (!isBlankLine(line) && line.includes("|")) {
423
- this._emit({ kind: "tableRow", line });
424
- return true;
425
- }
426
- this._emit({ kind: "tableEnd" });
427
- this._tableOpen = false;
428
- this.addLine(line);
429
- return true;
430
- }
431
- /**
432
- * Resolve a pending table header candidate against the next line.
433
- *
434
- * @param line - Next source line.
435
- * @returns True when a table opened.
436
- */
437
- _consumeCandidate(line) {
438
- if (this._candidate === null) return false;
439
- if (isTableDelimiter(line)) {
440
- this._emit({ kind: "tableHead", headLine: this._candidate, delimLine: line });
441
- this._candidate = null;
442
- this._tableOpen = true;
443
- return true;
444
- }
445
- this._pending.push(this._candidate);
446
- this._candidate = null;
447
- return false;
448
- }
449
- /**
450
- * Start a table header candidate on pipe lines.
451
- *
452
- * @param line - Next source line.
453
- * @returns True when the line starts a candidate.
454
- */
455
- _classifyPipe(line) {
456
- if (!line.includes("|")) return false;
457
- this._takeAll();
458
- this._candidate = line;
459
- return true;
460
- }
588
+ _tableOpen = false;
589
+ _candidate = null;
590
+ /**
591
+ * Feed one source line; completed fragments emit to the handler.
592
+ *
593
+ * @param line - Next source line, without its line break.
594
+ */
595
+ addLine(line) {
596
+ if (this._consumeFence(line)) return;
597
+ if (this._consumeTable(line)) return;
598
+ if (this._consumeLists(line)) return;
599
+ if (this._consumeQuote(line)) return;
600
+ if (this._consumeCandidate(line)) return;
601
+ this._classify(line);
602
+ }
603
+ /**
604
+ * Close every open context and emit the trailing remainder.
605
+ */
606
+ flush() {
607
+ if (this._candidate !== null) {
608
+ this._pending.push(this._candidate);
609
+ this._candidate = null;
610
+ }
611
+ if (this._tableOpen) {
612
+ this._emit({ kind: "tableEnd" });
613
+ this._tableOpen = false;
614
+ }
615
+ super.flush();
616
+ }
617
+ /**
618
+ * Feed a line to the open table, if any, closing and reprocessing when
619
+ * the line is not a row.
620
+ *
621
+ * @param line - Next source line.
622
+ * @returns True when the line was consumed or reprocessed.
623
+ */
624
+ _consumeTable(line) {
625
+ if (!this._tableOpen) return false;
626
+ if (!isBlankLine(line) && line.includes("|")) {
627
+ this._emit({
628
+ kind: "tableRow",
629
+ line
630
+ });
631
+ return true;
632
+ }
633
+ this._emit({ kind: "tableEnd" });
634
+ this._tableOpen = false;
635
+ this.addLine(line);
636
+ return true;
637
+ }
638
+ /**
639
+ * Resolve a pending table header candidate against the next line.
640
+ *
641
+ * @param line - Next source line.
642
+ * @returns True when a table opened.
643
+ */
644
+ _consumeCandidate(line) {
645
+ if (this._candidate === null) return false;
646
+ if (isTableDelimiter(line)) {
647
+ this._emit({
648
+ kind: "tableHead",
649
+ headLine: this._candidate,
650
+ delimLine: line
651
+ });
652
+ this._candidate = null;
653
+ this._tableOpen = true;
654
+ return true;
655
+ }
656
+ this._pending.push(this._candidate);
657
+ this._candidate = null;
658
+ return false;
659
+ }
660
+ /**
661
+ * Start a table header candidate on pipe lines.
662
+ *
663
+ * @param line - Next source line.
664
+ * @returns True when the line starts a candidate.
665
+ */
666
+ _classifyPipe(line) {
667
+ if (!line.includes("|")) return false;
668
+ this._takeAll();
669
+ this._candidate = line;
670
+ return true;
671
+ }
461
672
  };
462
-
463
673
  // src/renderers/parser/inline.ts
464
- var ESCAPABLE_RE = /^[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]$/;
465
- var AUTOLINK_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]*$/;
466
- var ALNUM_RE = /[A-Za-z0-9]/;
674
+ const ESCAPABLE_RE = /^[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]$/;
675
+ const AUTOLINK_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]*$/;
676
+ const ALNUM_RE = /[A-Za-z0-9]/;
677
+ /** Parse `[label](href)` at `text[start]` (which must be `[`). */
467
678
  function tryParseLink(text, start) {
468
- const labelEnd = text.indexOf("]", start + 1);
469
- if (labelEnd === -1 || text[labelEnd + 1] !== "(") return null;
470
- const label = text.slice(start + 1, labelEnd);
471
- if (label.includes("[") || label.includes("\n")) return null;
472
- const hrefEnd = text.indexOf(")", labelEnd + 2);
473
- if (hrefEnd === -1) return null;
474
- const inside = text.slice(labelEnd + 2, hrefEnd).trim();
475
- if (inside === "") return null;
476
- if (/\s/.test(inside) && !/^<?\S+>?\s+"[^"]*"$/.test(inside)) return null;
477
- const href = inside.replace(/^<(.*)>$/, "$1").split(/\s+/)[0];
478
- return { label, href, end: hrefEnd + 1 };
679
+ const labelEnd = text.indexOf("]", start + 1);
680
+ if (labelEnd === -1 || text[labelEnd + 1] !== "(") return null;
681
+ const label = text.slice(start + 1, labelEnd);
682
+ if (label.includes("[") || label.includes("\n")) return null;
683
+ const hrefEnd = text.indexOf(")", labelEnd + 2);
684
+ if (hrefEnd === -1) return null;
685
+ const inside = text.slice(labelEnd + 2, hrefEnd).trim();
686
+ if (inside === "") return null;
687
+ if (/\s/.test(inside) && !/^<?\S+>?\s+"[^"]*"$/.test(inside)) return null;
688
+ return {
689
+ label,
690
+ href: inside.replace(/^<(.*)>$/, "$1").split(/\s+/)[0],
691
+ end: hrefEnd + 1
692
+ };
479
693
  }
694
+ /** Match an emphasis opener at position `i`, if any. */
480
695
  function matchEmphasis(text, i, gfm) {
481
- if (gfm && text.startsWith("~~", i)) return { marker: "~~", tag: "del", underscore: false };
482
- if (text.startsWith("**", i)) return { marker: "**", tag: "strong", underscore: false };
483
- if (text.startsWith("__", i)) return { marker: "__", tag: "strong", underscore: true };
484
- if (text[i] === "*") return { marker: "*", tag: "em", underscore: false };
485
- if (text[i] === "_") {
486
- if (i > 0 && ALNUM_RE.test(text[i - 1])) return null;
487
- return { marker: "_", tag: "em", underscore: true };
488
- }
489
- return null;
696
+ if (gfm && text.startsWith("~~", i)) return {
697
+ marker: "~~",
698
+ tag: "del",
699
+ underscore: false
700
+ };
701
+ if (text.startsWith("**", i)) return {
702
+ marker: "**",
703
+ tag: "strong",
704
+ underscore: false
705
+ };
706
+ if (text.startsWith("__", i)) return {
707
+ marker: "__",
708
+ tag: "strong",
709
+ underscore: true
710
+ };
711
+ if (text[i] === "*") return {
712
+ marker: "*",
713
+ tag: "em",
714
+ underscore: false
715
+ };
716
+ if (text[i] === "_") {
717
+ if (i > 0 && ALNUM_RE.test(text[i - 1])) return null;
718
+ return {
719
+ marker: "_",
720
+ tag: "em",
721
+ underscore: true
722
+ };
723
+ }
724
+ return null;
490
725
  }
726
+ /** Find the closing marker, skipping `_` closers inside words. */
491
727
  function findEmphasisClose(text, from, token) {
492
- let at = text.indexOf(token.marker, from);
493
- while (at !== -1 && token.underscore) {
494
- const next = text[at + token.marker.length];
495
- if (next === void 0 || !ALNUM_RE.test(next)) return at;
496
- at = text.indexOf(token.marker, at + 1);
497
- }
498
- return at;
728
+ let at = text.indexOf(token.marker, from);
729
+ while (at !== -1 && token.underscore) {
730
+ const next = text[at + token.marker.length];
731
+ if (next === void 0 || !ALNUM_RE.test(next)) return at;
732
+ at = text.indexOf(token.marker, at + 1);
733
+ }
734
+ return at;
499
735
  }
500
- function appendInline(parent, text, doc, gfm) {
501
- let i = 0;
502
- let literal = "";
503
- const flushLiteral = () => {
504
- if (literal !== "") {
505
- parent.appendChild(doc.createTextNode(literal));
506
- literal = "";
507
- }
508
- };
509
- while (i < text.length) {
510
- const ch = text[i];
511
- if (ch === "\\" && i + 1 < text.length && ESCAPABLE_RE.test(text[i + 1])) {
512
- literal += text[i + 1];
513
- i += 2;
514
- continue;
515
- }
516
- if (ch === "`") {
517
- const run = /^`+/.exec(text.slice(i));
518
- const close = text.indexOf(run[0], i + run[0].length);
519
- if (close !== -1) {
520
- flushLiteral();
521
- const code = doc.createElement("code");
522
- code.appendChild(doc.createTextNode(text.slice(i + run[0].length, close)));
523
- parent.appendChild(code);
524
- i = close + run[0].length;
525
- continue;
526
- }
527
- literal += ch;
528
- i++;
529
- continue;
530
- }
531
- if (ch === "!" && text[i + 1] === "[") {
532
- const link = tryParseLink(text, i + 1);
533
- if (link && link.href !== "") {
534
- flushLiteral();
535
- const img = doc.createElement("img");
536
- img.setAttribute?.("src", link.href);
537
- img.setAttribute?.("alt", link.label);
538
- parent.appendChild(img);
539
- i = link.end;
540
- continue;
541
- }
542
- }
543
- if (ch === "[") {
544
- const link = tryParseLink(text, i);
545
- if (link) {
546
- flushLiteral();
547
- const anchor = doc.createElement("a");
548
- anchor.setAttribute?.("href", link.href);
549
- appendInline(anchor, link.label, doc, gfm);
550
- parent.appendChild(anchor);
551
- i = link.end;
552
- continue;
553
- }
554
- literal += ch;
555
- i++;
556
- continue;
557
- }
558
- if (ch === "<") {
559
- const end = text.indexOf(">", i + 1);
560
- if (end !== -1 && AUTOLINK_RE.test(text.slice(i + 1, end))) {
561
- flushLiteral();
562
- const href = text.slice(i + 1, end);
563
- const anchor = doc.createElement("a");
564
- anchor.setAttribute?.("href", href);
565
- anchor.appendChild(doc.createTextNode(href));
566
- parent.appendChild(anchor);
567
- i = end + 1;
568
- continue;
569
- }
570
- literal += ch;
571
- i++;
572
- continue;
573
- }
574
- const token = matchEmphasis(text, i, gfm);
575
- if (token) {
576
- const close = findEmphasisClose(text, i + token.marker.length, token);
577
- if (close !== -1 && close > i + token.marker.length) {
578
- flushLiteral();
579
- const el = doc.createElement(token.tag);
580
- appendInline(el, text.slice(i + token.marker.length, close), doc, gfm);
581
- parent.appendChild(el);
582
- i = close + token.marker.length;
583
- continue;
584
- }
585
- literal += token.marker;
586
- i += token.marker.length;
587
- continue;
588
- }
589
- literal += ch;
590
- i++;
591
- }
592
- flushLiteral();
736
+ /** Append a text node to the parent unless the run is empty. */
737
+ function appendText(target, parentId, text) {
738
+ if (text !== "") target.appendChild(parentId, target.createTextNode(text));
593
739
  }
740
+ /**
741
+ * Parse one line of inline markdown (code spans, emphasis, links, images,
742
+ * autolinks, and GFM strikethrough when `gfm` is set) into the target.
743
+ *
744
+ * @param target - Target receiving the parsed nodes.
745
+ * @param parentId - Node the inlines append to.
746
+ * @param text - Source text for one line.
747
+ * @param gfm - Enable GFM-only inlines (strikethrough).
748
+ */
749
+ function appendInline(target, parentId, text, gfm) {
750
+ let i = 0;
751
+ let literal = "";
752
+ const flushLiteral = () => {
753
+ appendText(target, parentId, literal);
754
+ literal = "";
755
+ };
756
+ while (i < text.length) {
757
+ const ch = text[i];
758
+ if (ch === "\\" && i + 1 < text.length && ESCAPABLE_RE.test(text[i + 1])) {
759
+ literal += text[i + 1];
760
+ i += 2;
761
+ continue;
762
+ }
763
+ if (ch === "`") {
764
+ const run = /^`+/.exec(text.slice(i));
765
+ const close = text.indexOf(run[0], i + run[0].length);
766
+ if (close !== -1) {
767
+ flushLiteral();
768
+ const code = target.createElement("code");
769
+ appendText(target, code, text.slice(i + run[0].length, close));
770
+ target.appendChild(parentId, code);
771
+ i = close + run[0].length;
772
+ continue;
773
+ }
774
+ literal += ch;
775
+ i++;
776
+ continue;
777
+ }
778
+ if (ch === "!" && text[i + 1] === "[") {
779
+ const link = tryParseLink(text, i + 1);
780
+ if (link && link.href !== "") {
781
+ flushLiteral();
782
+ const img = target.createElement("img", {
783
+ src: link.href,
784
+ alt: link.label
785
+ });
786
+ target.appendChild(parentId, img);
787
+ i = link.end;
788
+ continue;
789
+ }
790
+ }
791
+ if (ch === "[") {
792
+ const link = tryParseLink(text, i);
793
+ if (link) {
794
+ flushLiteral();
795
+ const anchor = target.createElement("a", { href: link.href });
796
+ appendInline(target, anchor, link.label, gfm);
797
+ target.appendChild(parentId, anchor);
798
+ i = link.end;
799
+ continue;
800
+ }
801
+ literal += ch;
802
+ i++;
803
+ continue;
804
+ }
805
+ if (ch === "<") {
806
+ const end = text.indexOf(">", i + 1);
807
+ if (end !== -1 && AUTOLINK_RE.test(text.slice(i + 1, end))) {
808
+ flushLiteral();
809
+ const href = text.slice(i + 1, end);
810
+ const anchor = target.createElement("a", { href });
811
+ appendText(target, anchor, href);
812
+ target.appendChild(parentId, anchor);
813
+ i = end + 1;
814
+ continue;
815
+ }
816
+ literal += ch;
817
+ i++;
818
+ continue;
819
+ }
820
+ const token = matchEmphasis(text, i, gfm);
821
+ if (token) {
822
+ const close = findEmphasisClose(text, i + token.marker.length, token);
823
+ if (close !== -1 && close > i + token.marker.length) {
824
+ flushLiteral();
825
+ const el = target.createElement(token.tag);
826
+ appendInline(target, el, text.slice(i + token.marker.length, close), gfm);
827
+ target.appendChild(parentId, el);
828
+ i = close + token.marker.length;
829
+ continue;
830
+ }
831
+ literal += token.marker;
832
+ i += token.marker.length;
833
+ continue;
834
+ }
835
+ literal += ch;
836
+ i++;
837
+ }
838
+ flushLiteral();
839
+ }
840
+ /**
841
+ * Split a paragraph line into text plus a trailing hard break marker.
842
+ *
843
+ * @param line - Raw paragraph line.
844
+ * @returns Text without the break marker, and whether one was present.
845
+ */
594
846
  function splitHardBreak(line) {
595
- const hardBreak = / {2,}$/.test(line);
596
- return { text: hardBreak ? line.replace(/ {2,}$/, "") : line, hardBreak };
847
+ const hardBreak = / {2,}$/.test(line);
848
+ return {
849
+ text: hardBreak ? line.replace(/ {2,}$/, "") : line,
850
+ hardBreak
851
+ };
597
852
  }
598
-
599
853
  // src/renderers/commonmark.ts
854
+ /**
855
+ * Renderer for CommonMark.
856
+ *
857
+ * @remarks
858
+ * Constructed with its target and config. Feed it lines with
859
+ * {@link CommonMarkRenderer.writeLine}; it holds its own parse state and
860
+ * writes finished blocks to the target as they complete. Open lists are
861
+ * tracked on a stack so items — including nested ones — append to the
862
+ * right container as they arrive.
863
+ *
864
+ * The renderer never touches the DOM: it builds everything through the
865
+ * write-only target, so the same renderer drives live pages, simulated
866
+ * DOMs, and fully custom targets.
867
+ *
868
+ * @public
869
+ */
600
870
  var CommonMarkRenderer = class {
601
- /** Rendering options. */
602
- options;
603
- _target;
604
- _doc;
605
- _state;
606
- _open = [];
607
- /**
608
- * @param target - Destination for rendered output, from
609
- * `createRenderTarget`. Pass `requestAnimationFrame` there to batch
610
- * writes on animation frames, or nothing for synchronous writes.
611
- * @param doc - Document used to create nodes.
612
- * @param opts - CommonMark rendering options.
613
- */
614
- constructor(target, doc, opts) {
615
- this._target = target;
616
- this._doc = doc;
617
- this.options = opts;
618
- this._state = this._createState((fragment) => this._applyFragment(fragment));
619
- }
620
- /**
621
- * Create the parser state. Overridden by `GFMRenderer` to parse
622
- * tables.
623
- *
624
- * @param emit - Receives parse fragments in document order.
625
- * @returns The state for this renderer.
626
- */
627
- _createState(emit) {
628
- return new CommonMarkState(emit);
629
- }
630
- /**
631
- * Feed one source line; completed output is written to the target.
632
- *
633
- * @param line - Next source line, without its line break.
634
- */
635
- writeLine(line) {
636
- this._state.addLine(line);
637
- }
638
- /**
639
- * Render the buffered remainder and settle the target.
640
- *
641
- * @returns A promise that resolves once all output has landed in the target.
642
- */
643
- async flush() {
644
- this._state.flush();
645
- await this._target.flush();
646
- }
647
- _applyFragment(fragment) {
648
- switch (fragment.kind) {
649
- case "block": {
650
- const node = this.renderBlock(fragment.block, this._doc);
651
- if (node !== null) this._commit(node, null);
652
- break;
653
- }
654
- case "listStart": {
655
- const top = this._open[this._open.length - 1];
656
- const list = this._doc.createElement(fragment.ordered ? "ol" : "ul");
657
- this._commit(list, top?.currentItem ?? null);
658
- this._open.push({ node: list, currentItem: null });
659
- break;
660
- }
661
- case "listItem": {
662
- const top = this._open[this._open.length - 1];
663
- const item = this._doc.createElement("li");
664
- appendInline(item, fragment.text, this._doc, this.inlineGfm());
665
- this._commit(item, top.node);
666
- top.currentItem = item;
667
- break;
668
- }
669
- case "listEnd":
670
- this._open.pop();
671
- break;
672
- }
673
- }
674
- /**
675
- * Append a node to the target (top level) or to its parent container,
676
- * running the sanitizer first when one is set.
677
- *
678
- * @param node - Node to commit.
679
- * @param parent - Parent container, or null to commit to the target.
680
- */
681
- _commit(node, parent) {
682
- const sanitizer = this.options.sanitizer;
683
- const out = sanitizer === void 0 ? node : sanitizer(node);
684
- if (parent === null) this._target.append(out);
685
- else parent.appendChild(out);
686
- }
687
- /**
688
- * Whether GFM-only inlines are enabled. Always false here; overridden by
689
- * `GFMRenderer`.
690
- *
691
- * @returns False.
692
- */
693
- inlineGfm() {
694
- return false;
695
- }
696
- /**
697
- * Render one block to a DOM-like node.
698
- *
699
- * @param block - Parsed block to render.
700
- * @param doc - Document used to create nodes.
701
- * @returns The rendered node, or `null` to emit nothing.
702
- */
703
- renderBlock(block, doc) {
704
- switch (block.kind) {
705
- case "heading": {
706
- const heading = doc.createElement(`h${block.level ?? 1}`);
707
- this.appendLinesInline(heading, block.lines, doc, " ");
708
- return heading;
709
- }
710
- case "paragraph":
711
- return this.renderParagraph(block.lines, doc);
712
- case "fence": {
713
- const pre = doc.createElement("pre");
714
- const code = doc.createElement("code");
715
- if (block.language !== void 0) code.setAttribute?.("class", `language-${block.language}`);
716
- const text = block.lines.join("\n");
717
- code.appendChild(doc.createTextNode(text === "" ? "" : `${text}
718
- `));
719
- pre.appendChild(code);
720
- return pre;
721
- }
722
- case "quote": {
723
- const quote = doc.createElement("blockquote");
724
- const body = doc.createElement("p");
725
- this.appendLinesInline(body, block.lines, doc, " ");
726
- quote.appendChild(body);
727
- return quote;
728
- }
729
- case "rule":
730
- return doc.createElement("hr");
731
- }
732
- }
733
- /**
734
- * Render paragraph lines, honoring two-space hard breaks.
735
- *
736
- * @param lines - Raw paragraph lines.
737
- * @param doc - Document used to create nodes.
738
- * @returns The paragraph element.
739
- */
740
- renderParagraph(lines, doc) {
741
- const paragraph = doc.createElement("p");
742
- lines.forEach((line, at) => {
743
- const { text, hardBreak } = splitHardBreak(line);
744
- appendInline(paragraph, text, doc, this.inlineGfm());
745
- if (at < lines.length - 1) {
746
- if (hardBreak) paragraph.appendChild(doc.createElement("br"));
747
- else paragraph.appendChild(doc.createTextNode(" "));
748
- }
749
- });
750
- return paragraph;
751
- }
752
- appendLinesInline(parent, lines, doc, join) {
753
- lines.forEach((line, at) => {
754
- if (at > 0) parent.appendChild(doc.createTextNode(join));
755
- appendInline(parent, line, doc, this.inlineGfm());
756
- });
757
- }
871
+ _target;
872
+ _config;
873
+ _state;
874
+ _open = [];
875
+ /**
876
+ * @param target - Destination for rendered output, from `createDOMTarget`
877
+ * or a custom `HTMLTarget` implementation.
878
+ * @param config - CommonMark rendering config.
879
+ */
880
+ constructor(target, config) {
881
+ this._target = target;
882
+ this._config = config;
883
+ this._state = this._createState((fragment) => this._applyFragment(fragment));
884
+ }
885
+ /**
886
+ * Feed one source line; completed output is written to the target.
887
+ *
888
+ * @param line - Next source line, without its line break.
889
+ */
890
+ writeLine(line) {
891
+ this._state.addLine(line);
892
+ }
893
+ /**
894
+ * Write the buffered remainder and settle the target.
895
+ *
896
+ * @returns A promise that resolves once all output has landed in the target.
897
+ */
898
+ async flush() {
899
+ this._state.flush();
900
+ await this._target.flush();
901
+ }
902
+ /**
903
+ * Point the renderer at another target; subsequent writes go there.
904
+ *
905
+ * @param target - Target receiving future output.
906
+ */
907
+ setTarget(target) {
908
+ this._target = target;
909
+ }
910
+ /**
911
+ * Replace the renderer config; applies to subsequent writes.
912
+ *
913
+ * @param config - Next config.
914
+ */
915
+ setConfig(config) {
916
+ this._config = config;
917
+ }
918
+ /**
919
+ * Create the parser state. Overridden by `GFMRenderer` to parse
920
+ * tables.
921
+ *
922
+ * @param emit - Receives parse fragments in document order.
923
+ * @returns The state for this renderer.
924
+ */
925
+ _createState(emit) {
926
+ return new CommonMarkState(emit);
927
+ }
928
+ _applyFragment(fragment) {
929
+ switch (fragment.kind) {
930
+ case "block":
931
+ this.renderBlock(fragment.block);
932
+ break;
933
+ case "listStart": {
934
+ const parent = this._open[this._open.length - 1]?.currentItem ?? null;
935
+ const list = this._target.createElement(fragment.ordered ? "ol" : "ul");
936
+ this._target.appendChild(parent, list);
937
+ this._open.push({
938
+ id: list,
939
+ currentItem: null
940
+ });
941
+ break;
942
+ }
943
+ case "listItem": {
944
+ const top = this._open[this._open.length - 1];
945
+ const item = this._target.createElement("li");
946
+ appendInline(this._target, item, fragment.text, this.inlineGfm());
947
+ this._target.appendChild(top.id, item);
948
+ top.currentItem = item;
949
+ break;
950
+ }
951
+ case "listEnd": this._open.pop();
952
+ }
953
+ }
954
+ /**
955
+ * Whether GFM-only inlines are enabled. Always false here; overridden by
956
+ * `GFMRenderer`.
957
+ *
958
+ * @returns False.
959
+ */
960
+ inlineGfm() {
961
+ return false;
962
+ }
963
+ /**
964
+ * Write one parsed block to the target.
965
+ *
966
+ * @param block - Parsed block to write.
967
+ */
968
+ renderBlock(block) {
969
+ switch (block.kind) {
970
+ case "heading": {
971
+ const heading = this._target.createElement(`h${block.level ?? 1}`);
972
+ this.appendJoinedLines(heading, block.lines);
973
+ this._target.appendChild(null, heading);
974
+ break;
975
+ }
976
+ case "paragraph": {
977
+ const paragraph = this._target.createElement("p");
978
+ this.appendParagraphLines(paragraph, block.lines);
979
+ this._target.appendChild(null, paragraph);
980
+ break;
981
+ }
982
+ case "fence": {
983
+ const pre = this._target.createElement("pre");
984
+ const code = this._target.createElement("code", block.language === void 0 ? {} : { class: `language-${block.language}` });
985
+ const text = block.lines.join("\n");
986
+ this._target.appendChild(code, this._target.createTextNode(text === "" ? "" : `${text}\n`));
987
+ this._target.appendChild(pre, code);
988
+ this._target.appendChild(null, pre);
989
+ break;
990
+ }
991
+ case "quote": {
992
+ const quote = this._target.createElement("blockquote");
993
+ const body = this._target.createElement("p");
994
+ this.appendJoinedLines(body, block.lines);
995
+ this._target.appendChild(quote, body);
996
+ this._target.appendChild(null, quote);
997
+ break;
998
+ }
999
+ case "rule": this._target.appendChild(null, this._target.createElement("hr"));
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Write paragraph lines into a parent, honoring two-space hard breaks.
1004
+ *
1005
+ * @param parentId - Node the lines append to.
1006
+ * @param lines - Raw paragraph lines.
1007
+ */
1008
+ appendParagraphLines(parentId, lines) {
1009
+ lines.forEach((line, at) => {
1010
+ const { text, hardBreak } = splitHardBreak(line);
1011
+ appendInline(this._target, parentId, text, this.inlineGfm());
1012
+ if (at < lines.length - 1) {
1013
+ if (hardBreak) this._target.appendChild(parentId, this._target.createElement("br"));
1014
+ else this._target.appendChild(parentId, this._target.createTextNode(" "));
1015
+ }
1016
+ });
1017
+ }
1018
+ appendJoinedLines(parentId, lines) {
1019
+ lines.forEach((line, at) => {
1020
+ if (at > 0) this._target.appendChild(parentId, this._target.createTextNode(" "));
1021
+ appendInline(this._target, parentId, line, this.inlineGfm());
1022
+ });
1023
+ }
758
1024
  };
759
-
760
1025
  // src/renderers/gfm.ts
1026
+ /**
1027
+ * Renderer for GitHub Flavored Markdown.
1028
+ *
1029
+ * @remarks
1030
+ * Supports CommonMark blocks and inlines plus GFM tables and strikethrough.
1031
+ * Tables commit at the delimiter row and stream one row at a time; column
1032
+ * widths come from the header row, short rows are padded, and extra cells
1033
+ * on wide rows are kept as unaligned cells.
1034
+ *
1035
+ * @public
1036
+ */
761
1037
  var GFMRenderer = class extends CommonMarkRenderer {
762
- /** Rendering options. */
763
- options;
764
- _table = null;
765
- /**
766
- * @param target - Destination for rendered output, from
767
- * `createRenderTarget`. Pass `requestAnimationFrame` there to batch
768
- * writes on animation frames, or nothing for synchronous writes.
769
- * @param doc - Document used to create nodes.
770
- * @param opts - GFM rendering options.
771
- */
772
- constructor(target, doc, opts) {
773
- super(target, doc, opts);
774
- this.options = opts;
775
- }
776
- /**
777
- * GFM-only inlines are enabled.
778
- *
779
- * @returns True.
780
- */
781
- inlineGfm() {
782
- return true;
783
- }
784
- /**
785
- * Create the GFM parser state.
786
- *
787
- * @param emit - Receives parse fragments in document order.
788
- * @returns The state for this renderer.
789
- */
790
- _createState(emit) {
791
- return new GFMState(emit);
792
- }
793
- /**
794
- * Apply a fragment, handling tables here and delegating the rest.
795
- *
796
- * @param fragment - Fragment to apply.
797
- */
798
- _applyFragment(fragment) {
799
- switch (fragment.kind) {
800
- case "tableHead":
801
- this._applyTableHead(fragment.headLine, fragment.delimLine);
802
- break;
803
- case "tableRow":
804
- this._applyTableRow(fragment.line);
805
- break;
806
- case "tableEnd":
807
- this._applyTableEnd();
808
- break;
809
- default:
810
- super._applyFragment(fragment);
811
- break;
812
- }
813
- }
814
- /**
815
- * Commit the table with its header; body rows stream in afterwards.
816
- *
817
- * @param headLine - Raw header row line.
818
- * @param delimLine - Delimiter row line carrying column alignment.
819
- */
820
- _applyTableHead(headLine, delimLine) {
821
- const header = splitTableRow(headLine);
822
- const aligns = splitTableRow(delimLine).map(parseTableAlignment);
823
- const width = header.length;
824
- const table = this._doc.createElement("table");
825
- const head = this._doc.createElement("thead");
826
- const headRow = this._doc.createElement("tr");
827
- for (let col = 0; col < width; col++) {
828
- const cell = this._doc.createElement("th");
829
- const align = aligns[col] ?? null;
830
- if (align !== null) cell.setAttribute?.("align", align);
831
- appendInline(cell, header[col] ?? "", this._doc, true);
832
- headRow.appendChild(cell);
833
- }
834
- head.appendChild(headRow);
835
- table.appendChild(head);
836
- const body = this._doc.createElement("tbody");
837
- table.appendChild(body);
838
- this._commit(table, null);
839
- this._table = { body, aligns, width };
840
- }
841
- /**
842
- * Append one body row to the open table.
843
- *
844
- * @param line - Raw body row line.
845
- */
846
- _applyTableRow(line) {
847
- const table = this._table;
848
- if (table === null) return;
849
- const cells = splitTableRow(line);
850
- const row = this._doc.createElement("tr");
851
- for (let col = 0; col < table.width; col++) {
852
- const cell = this._doc.createElement("td");
853
- const align = table.aligns[col] ?? null;
854
- if (align !== null) cell.setAttribute?.("align", align);
855
- appendInline(cell, cells[col] ?? "", this._doc, true);
856
- row.appendChild(cell);
857
- }
858
- for (let col = table.width; col < cells.length; col++) {
859
- const cell = this._doc.createElement("td");
860
- appendInline(cell, cells[col], this._doc, true);
861
- row.appendChild(cell);
862
- }
863
- this._commit(row, table.body);
864
- }
865
- /**
866
- * Close the open table.
867
- */
868
- _applyTableEnd() {
869
- this._table = null;
870
- }
1038
+ _table = null;
1039
+ /**
1040
+ * @param target - Destination for rendered output, from `createDOMTarget`
1041
+ * or a custom `HTMLTarget` implementation.
1042
+ * @param config - GFM rendering config.
1043
+ */
1044
+ constructor(target, config) {
1045
+ super(target, config);
1046
+ }
1047
+ /**
1048
+ * GFM-only inlines are enabled.
1049
+ *
1050
+ * @returns True.
1051
+ */
1052
+ inlineGfm() {
1053
+ return true;
1054
+ }
1055
+ /**
1056
+ * Create the GFM parser state.
1057
+ *
1058
+ * @param emit - Receives parse fragments in document order.
1059
+ * @returns The state for this renderer.
1060
+ */
1061
+ _createState(emit) {
1062
+ return new GFMState(emit);
1063
+ }
1064
+ /**
1065
+ * Apply a fragment, handling tables here and delegating the rest.
1066
+ *
1067
+ * @param fragment - Fragment to apply.
1068
+ */
1069
+ _applyFragment(fragment) {
1070
+ switch (fragment.kind) {
1071
+ case "tableHead":
1072
+ this._applyTableHead(fragment.headLine, fragment.delimLine);
1073
+ break;
1074
+ case "tableRow":
1075
+ this._applyTableRow(fragment.line);
1076
+ break;
1077
+ case "tableEnd":
1078
+ this._applyTableEnd();
1079
+ break;
1080
+ default: super._applyFragment(fragment);
1081
+ }
1082
+ }
1083
+ /**
1084
+ * Commit the table with its header; body rows stream in afterwards.
1085
+ *
1086
+ * @param headLine - Raw header row line.
1087
+ * @param delimLine - Delimiter row line carrying column alignment.
1088
+ */
1089
+ _applyTableHead(headLine, delimLine) {
1090
+ const header = splitTableRow(headLine);
1091
+ const aligns = splitTableRow(delimLine).map(parseTableAlignment);
1092
+ const width = header.length;
1093
+ const table = this._target.createElement("table");
1094
+ const head = this._target.createElement("thead");
1095
+ const headRow = this._target.createElement("tr");
1096
+ for (let col = 0; col < width; col++) {
1097
+ const align = aligns[col] ?? null;
1098
+ const cell = this._target.createElement("th", align === null ? {} : { align });
1099
+ appendInline(this._target, cell, header[col] ?? "", true);
1100
+ this._target.appendChild(headRow, cell);
1101
+ }
1102
+ this._target.appendChild(head, headRow);
1103
+ this._target.appendChild(table, head);
1104
+ const body = this._target.createElement("tbody");
1105
+ this._target.appendChild(table, body);
1106
+ this._target.appendChild(null, table);
1107
+ this._table = {
1108
+ body,
1109
+ aligns,
1110
+ width
1111
+ };
1112
+ }
1113
+ /**
1114
+ * Append one body row to the open table.
1115
+ *
1116
+ * @param line - Raw body row line.
1117
+ */
1118
+ _applyTableRow(line) {
1119
+ const table = this._table;
1120
+ if (table === null) return;
1121
+ const cells = splitTableRow(line);
1122
+ const row = this._target.createElement("tr");
1123
+ for (let col = 0; col < table.width; col++) {
1124
+ const align = table.aligns[col] ?? null;
1125
+ const cell = this._target.createElement("td", align === null ? {} : { align });
1126
+ appendInline(this._target, cell, cells[col] ?? "", true);
1127
+ this._target.appendChild(row, cell);
1128
+ }
1129
+ for (let col = table.width; col < cells.length; col++) {
1130
+ const cell = this._target.createElement("td");
1131
+ appendInline(this._target, cell, cells[col], true);
1132
+ this._target.appendChild(row, cell);
1133
+ }
1134
+ this._target.appendChild(table.body, row);
1135
+ }
1136
+ /**
1137
+ * Close the open table.
1138
+ */
1139
+ _applyTableEnd() {
1140
+ this._table = null;
1141
+ }
871
1142
  };
872
-
873
1143
  // src/targets/animated-dom-target.ts
1144
+ /**
1145
+ * Throw when attributes were requested but the DOM cannot set them.
1146
+ *
1147
+ * @param node - Freshly created node.
1148
+ * @param attrs - Requested attributes.
1149
+ */
1150
+ function assertAttributesSupported$1(node, attrs) {
1151
+ if (Object.keys(attrs).length > 0 && typeof node.setAttribute !== "function") throw new Error("Cannot set attributes: this DOM does not implement setAttribute");
1152
+ }
1153
+ /**
1154
+ * Target that batches node updates on animation frames.
1155
+ *
1156
+ * @remarks
1157
+ * Wraps an externally provided container node from a real DOM. Uses the
1158
+ * injected frame scheduler so streamed output lands once per frame instead
1159
+ * of once per write. Ids are minted synchronously and unknown ids throw
1160
+ * synchronously; updates apply in call order when the frame runs.
1161
+ *
1162
+ * Internal implementation behind `createDOMTarget`.
1163
+ *
1164
+ * @internal
1165
+ */
874
1166
  var AnimatedDOMTarget = class {
875
- _targetNode;
876
- _raf;
877
- _queue = [];
878
- _scheduled = false;
879
- _flushResolvers = [];
880
- /**
881
- * @param targetNode - Container node receiving rendered output.
882
- * @param raf - Frame scheduler used to batch writes.
883
- */
884
- constructor(targetNode, raf) {
885
- this._targetNode = targetNode;
886
- this._raf = raf;
887
- }
888
- /**
889
- * Queue a rendered node for the next frame.
890
- *
891
- * @param node - Node to attach.
892
- */
893
- append(node) {
894
- this._queue.push(node);
895
- if (!this._scheduled) {
896
- this._scheduled = true;
897
- this._raf(() => {
898
- this._scheduled = false;
899
- const batch = this._queue;
900
- this._queue = [];
901
- for (const queued of batch) this._targetNode.appendChild(queued);
902
- const resolvers = this._flushResolvers;
903
- this._flushResolvers = [];
904
- for (const resolve of resolvers) resolve();
905
- });
906
- }
907
- }
908
- /**
909
- * Wait until every queued node has been attached.
910
- *
911
- * @returns A promise that resolves after the next frame carrying nodes.
912
- */
913
- flush() {
914
- if (!this._scheduled && this._queue.length === 0) return Promise.resolve();
915
- return new Promise((resolve) => {
916
- this._flushResolvers.push(resolve);
917
- });
918
- }
1167
+ _container;
1168
+ _doc;
1169
+ _raf;
1170
+ _graph = /* @__PURE__ */ new Map();
1171
+ _nodes = /* @__PURE__ */ new Map();
1172
+ _nextId = 0;
1173
+ _queue = [];
1174
+ _scheduled = false;
1175
+ _flushResolvers = [];
1176
+ /**
1177
+ * @param targetNode - Container node receiving rendered output.
1178
+ * @param document - Document used to create nodes.
1179
+ * @param raf - Frame scheduler used to batch writes.
1180
+ */
1181
+ constructor(targetNode, document, raf) {
1182
+ this._container = targetNode;
1183
+ this._doc = document;
1184
+ this._raf = raf;
1185
+ }
1186
+ /**
1187
+ * Queue an element creation for the next frame.
1188
+ *
1189
+ * @param tag - Lowercase tag name.
1190
+ * @param attrs - Attributes to set.
1191
+ * @returns Id addressing the new node.
1192
+ */
1193
+ createElement(tag, attrs = {}) {
1194
+ const id = this._mint();
1195
+ const snap = { ...attrs };
1196
+ this._enqueue(() => {
1197
+ const node = this._doc.createElement(tag);
1198
+ assertAttributesSupported$1(node, snap);
1199
+ for (const [name, value] of Object.entries(snap)) node.setAttribute?.(name, value);
1200
+ this._nodes.set(id, node);
1201
+ });
1202
+ return id;
1203
+ }
1204
+ /**
1205
+ * Queue a text node creation for the next frame.
1206
+ *
1207
+ * @param text - Text content.
1208
+ * @returns Id addressing the new node.
1209
+ */
1210
+ createTextNode(text) {
1211
+ const id = this._mint();
1212
+ this._enqueue(() => {
1213
+ this._nodes.set(id, this._doc.createTextNode(text));
1214
+ });
1215
+ return id;
1216
+ }
1217
+ /**
1218
+ * Queue an append for the next frame.
1219
+ *
1220
+ * @param parent - Receiving node, or `null` for the top level.
1221
+ * @param child - Node to append.
1222
+ */
1223
+ appendChild(parent, child) {
1224
+ if (parent !== null) this._mustGraph(parent);
1225
+ this._mustGraph(child);
1226
+ this._assertAcyclic(child, parent);
1227
+ this._reparentGraph(child, parent);
1228
+ this._enqueue(() => {
1229
+ (parent === null ? this._container : this._mustNode(parent)).appendChild(this._mustNode(child));
1230
+ });
1231
+ }
1232
+ /**
1233
+ * Queue a replacement for the next frame, retiring the old id.
1234
+ *
1235
+ * @param oldId - Attached node to replace.
1236
+ * @param newId - Replacement node.
1237
+ */
1238
+ replaceNode(oldId, newId) {
1239
+ const old = this._mustGraph(oldId);
1240
+ this._mustGraph(newId);
1241
+ if (old.parent === void 0) throw new DetachedNodeError(oldId);
1242
+ if (oldId === newId) return;
1243
+ this._assertAcyclic(newId, old.parent);
1244
+ const parent = old.parent;
1245
+ this._reparentGraph(newId, parent);
1246
+ const doomed = this._retireGraph(oldId);
1247
+ this._enqueue(() => {
1248
+ (parent === null ? this._container : this._mustNode(parent)).replaceChild(this._mustNode(newId), this._mustNode(oldId));
1249
+ for (const id of doomed) this._nodes.delete(id);
1250
+ });
1251
+ }
1252
+ /**
1253
+ * Queue a removal for the next frame, retiring the id.
1254
+ *
1255
+ * @param id - Node to remove.
1256
+ */
1257
+ remove(id) {
1258
+ const parent = this._mustGraph(id).parent;
1259
+ const doomed = this._retireGraph(id);
1260
+ this._enqueue(() => {
1261
+ if (parent !== void 0) (parent === null ? this._container : this._mustNode(parent)).removeChild(this._mustNode(id));
1262
+ for (const stale of doomed) this._nodes.delete(stale);
1263
+ });
1264
+ }
1265
+ /**
1266
+ * Queue a text replacement for the next frame.
1267
+ *
1268
+ * @param node - Node to update.
1269
+ * @param text - Replacement text.
1270
+ */
1271
+ setTextContent(node, text) {
1272
+ const entry = this._mustGraph(node);
1273
+ const doomed = [];
1274
+ for (const child of [...entry.children]) doomed.push(...this._retireGraph(child));
1275
+ this._enqueue(() => {
1276
+ this._mustNode(node).textContent = text;
1277
+ for (const stale of doomed) this._nodes.delete(stale);
1278
+ });
1279
+ }
1280
+ /**
1281
+ * Wait until every queued update has been applied.
1282
+ *
1283
+ * @returns A promise that resolves after the next frame carrying updates.
1284
+ */
1285
+ flush() {
1286
+ if (!this._scheduled && this._queue.length === 0) return Promise.resolve();
1287
+ return new Promise((resolve) => {
1288
+ this._flushResolvers.push(resolve);
1289
+ });
1290
+ }
1291
+ _enqueue(apply) {
1292
+ this._queue.push(apply);
1293
+ if (!this._scheduled) {
1294
+ this._scheduled = true;
1295
+ this._raf(() => {
1296
+ this._scheduled = false;
1297
+ const batch = this._queue;
1298
+ this._queue = [];
1299
+ for (const queued of batch) queued();
1300
+ const resolvers = this._flushResolvers;
1301
+ this._flushResolvers = [];
1302
+ for (const resolve of resolvers) resolve();
1303
+ });
1304
+ }
1305
+ }
1306
+ _mint() {
1307
+ this._nextId += 1;
1308
+ const id = `n${this._nextId}`;
1309
+ this._graph.set(id, {
1310
+ parent: void 0,
1311
+ children: /* @__PURE__ */ new Set()
1312
+ });
1313
+ return id;
1314
+ }
1315
+ _mustGraph(id) {
1316
+ const entry = this._graph.get(id);
1317
+ if (entry === void 0) throw new UnknownNodeError(id);
1318
+ return entry;
1319
+ }
1320
+ _assertAcyclic(child, parent) {
1321
+ if (parent === null) return;
1322
+ let at = parent;
1323
+ while (at !== null && at !== void 0) {
1324
+ if (at === child) throw new HierarchyError(child, parent);
1325
+ at = this._graph.get(at)?.parent;
1326
+ }
1327
+ }
1328
+ _mustNode(id) {
1329
+ const node = this._nodes.get(id);
1330
+ if (node === void 0) throw new UnknownNodeError(id);
1331
+ return node;
1332
+ }
1333
+ _reparentGraph(child, parent) {
1334
+ const entry = this._graph.get(child);
1335
+ if (entry.parent !== void 0 && entry.parent !== null) this._graph.get(entry.parent)?.children.delete(child);
1336
+ entry.parent = parent;
1337
+ if (parent !== null) this._graph.get(parent)?.children.add(child);
1338
+ }
1339
+ _retireGraph(id) {
1340
+ const entry = this._graph.get(id);
1341
+ if (entry !== void 0 && entry.parent !== void 0 && entry.parent !== null) this._graph.get(entry.parent)?.children.delete(id);
1342
+ const doomed = [];
1343
+ const visit = (at) => {
1344
+ const next = this._graph.get(at);
1345
+ if (next === void 0) return;
1346
+ doomed.push(at);
1347
+ for (const child of [...next.children]) visit(child);
1348
+ this._graph.delete(at);
1349
+ };
1350
+ visit(id);
1351
+ return doomed;
1352
+ }
919
1353
  };
920
-
921
1354
  // src/targets/dom-target.ts
1355
+ /**
1356
+ * Throw when attributes were requested but the DOM cannot set them.
1357
+ *
1358
+ * @param node - Freshly created node.
1359
+ * @param attrs - Requested attributes.
1360
+ */
1361
+ function assertAttributesSupported(node, attrs) {
1362
+ if (Object.keys(attrs).length > 0 && typeof node.setAttribute !== "function") throw new Error("Cannot set attributes: this DOM does not implement setAttribute");
1363
+ }
1364
+ /**
1365
+ * Target that applies node updates to a DOM container synchronously.
1366
+ *
1367
+ * @remarks
1368
+ * Internal implementation behind `createDOMTarget`. Wraps an externally
1369
+ * provided container node from a real or simulated DOM, and tracks ids
1370
+ * to nodes in memory.
1371
+ *
1372
+ * @internal
1373
+ */
922
1374
  var DOMTarget = class {
923
- _targetNode;
924
- /**
925
- * @param targetNode - Container node receiving rendered output.
926
- */
927
- constructor(targetNode) {
928
- this._targetNode = targetNode;
929
- }
930
- /**
931
- * Append a rendered node immediately.
932
- *
933
- * @param node - Node to attach.
934
- */
935
- append(node) {
936
- this._targetNode.appendChild(node);
937
- }
938
- /**
939
- * Resolve immediately: synchronous targets hold every node already.
940
- *
941
- * @returns A resolved promise.
942
- */
943
- flush() {
944
- return Promise.resolve();
945
- }
1375
+ _container;
1376
+ _doc;
1377
+ _entries = /* @__PURE__ */ new Map();
1378
+ _nextId = 0;
1379
+ /**
1380
+ * @param targetNode - Container node receiving rendered output.
1381
+ * @param document - Document used to create nodes.
1382
+ */
1383
+ constructor(targetNode, document) {
1384
+ this._container = targetNode;
1385
+ this._doc = document;
1386
+ }
1387
+ /**
1388
+ * Create a detached element node with attributes.
1389
+ *
1390
+ * @param tag - Lowercase tag name.
1391
+ * @param attrs - Attributes to set.
1392
+ * @returns Id addressing the new node.
1393
+ */
1394
+ createElement(tag, attrs = {}) {
1395
+ const node = this._doc.createElement(tag);
1396
+ assertAttributesSupported(node, attrs);
1397
+ for (const [name, value] of Object.entries(attrs)) node.setAttribute?.(name, value);
1398
+ return this._store(node, void 0);
1399
+ }
1400
+ /**
1401
+ * Create a detached text node.
1402
+ *
1403
+ * @param text - Text content.
1404
+ * @returns Id addressing the new node.
1405
+ */
1406
+ createTextNode(text) {
1407
+ return this._store(this._doc.createTextNode(text), void 0);
1408
+ }
1409
+ /**
1410
+ * Append a child to a parent, or to the top level for a `null` parent.
1411
+ *
1412
+ * @param parent - Receiving node, or `null` for the top level.
1413
+ * @param child - Node to append.
1414
+ */
1415
+ appendChild(parent, child) {
1416
+ const entry = this._must(child);
1417
+ const attachTo = parent === null ? this._container : this._must(parent).node;
1418
+ this._assertAcyclic(child, parent);
1419
+ attachTo.appendChild(entry.node);
1420
+ this._reparent(child, parent);
1421
+ }
1422
+ /**
1423
+ * Replace an attached node with another node, retiring the old id.
1424
+ *
1425
+ * @param oldId - Attached node to replace.
1426
+ * @param newId - Replacement node.
1427
+ */
1428
+ replaceNode(oldId, newId) {
1429
+ const old = this._must(oldId);
1430
+ const fresh = this._must(newId);
1431
+ if (old.parent === void 0) throw new DetachedNodeError(oldId);
1432
+ if (oldId === newId) return;
1433
+ this._assertAcyclic(newId, old.parent);
1434
+ (old.parent === null ? this._container : this._must(old.parent).node).replaceChild(fresh.node, old.node);
1435
+ this._reparent(newId, old.parent);
1436
+ this._retire(oldId);
1437
+ }
1438
+ /**
1439
+ * Detach a node and retire its id.
1440
+ *
1441
+ * @param id - Node to remove.
1442
+ */
1443
+ remove(id) {
1444
+ const entry = this._must(id);
1445
+ if (entry.parent !== void 0) (entry.parent === null ? this._container : this._must(entry.parent).node).removeChild(entry.node);
1446
+ this._retire(id);
1447
+ }
1448
+ /**
1449
+ * Replace a node's children with a single text run.
1450
+ *
1451
+ * @param node - Node to update.
1452
+ * @param text - Replacement text.
1453
+ */
1454
+ setTextContent(node, text) {
1455
+ const entry = this._must(node);
1456
+ entry.node.textContent = text;
1457
+ for (const child of [...entry.children]) this._retire(child);
1458
+ entry.children.clear();
1459
+ }
1460
+ /**
1461
+ * Nothing to wait for: synchronous targets hold every update already.
1462
+ */
1463
+ flush() {}
1464
+ _must(id) {
1465
+ const entry = this._entries.get(id);
1466
+ if (entry === void 0) throw new UnknownNodeError(id);
1467
+ return entry;
1468
+ }
1469
+ _assertAcyclic(child, parent) {
1470
+ if (parent === null) return;
1471
+ let at = parent;
1472
+ while (at !== null && at !== void 0) {
1473
+ if (at === child) throw new HierarchyError(child, parent);
1474
+ at = this._entries.get(at)?.parent;
1475
+ }
1476
+ }
1477
+ _store(node, parent) {
1478
+ this._nextId += 1;
1479
+ const id = `n${this._nextId}`;
1480
+ this._entries.set(id, {
1481
+ node,
1482
+ parent,
1483
+ children: /* @__PURE__ */ new Set()
1484
+ });
1485
+ return id;
1486
+ }
1487
+ _reparent(child, parent) {
1488
+ const entry = this._entries.get(child);
1489
+ if (entry.parent !== void 0 && entry.parent !== null) this._entries.get(entry.parent)?.children.delete(child);
1490
+ entry.parent = parent;
1491
+ if (parent !== null) this._entries.get(parent)?.children.add(child);
1492
+ }
1493
+ _retire(id) {
1494
+ const entry = this._entries.get(id);
1495
+ if (entry === void 0) return;
1496
+ for (const child of [...entry.children]) this._retire(child);
1497
+ if (entry.parent !== void 0 && entry.parent !== null) this._entries.get(entry.parent)?.children.delete(id);
1498
+ this._entries.delete(id);
1499
+ }
946
1500
  };
947
-
948
- // src/targets/render-target.ts
949
- function createRenderTarget(targetNode, raf) {
950
- return raf === void 0 ? new DOMTarget(targetNode) : new AnimatedDOMTarget(targetNode, raf);
1501
+ // src/targets/create-dom-target.ts
1502
+ /**
1503
+ * Create a target rendering into a DOM container.
1504
+ *
1505
+ * @param document - Document used to create nodes: a real browser document
1506
+ * for live pages, or a simulated one such as linkedom for server-side
1507
+ * rendering.
1508
+ * @param targetNode - Container node receiving rendered output.
1509
+ * @param options - Frame scheduler.
1510
+ * @returns The target to hand to a renderer.
1511
+ *
1512
+ * @public
1513
+ */
1514
+ function createDOMTarget(document, targetNode, options = {}) {
1515
+ const { raf } = options;
1516
+ return raf === void 0 ? new DOMTarget(targetNode, document) : new AnimatedDOMTarget(targetNode, document, raf);
951
1517
  }
952
-
953
- // src/core/pipelines/gfm-pipeline.ts
954
- function createGFMPipeline(target, dom, opts, raf) {
955
- return new GFMPipeline(target, dom, opts, raf);
1518
+ // src/streams/gfm-stream.ts
1519
+ /**
1520
+ * Create a GFM stream rendering into the given container.
1521
+ *
1522
+ * @remarks
1523
+ * The environment is implicit: pass a real browser document for live pages
1524
+ * or a simulated one such as linkedom for server-side rendering. Pass
1525
+ * target options to batch DOM writes on animation frames.
1526
+ *
1527
+ * @param target - Container node receiving rendered output.
1528
+ * @param dom - Document used to create nodes.
1529
+ * @param config - GFM rendering config.
1530
+ * @param targetOptions - Frame scheduler for the DOM target.
1531
+ * @returns The configured pipeline.
1532
+ *
1533
+ * @example
1534
+ * ```ts
1535
+ * const stream = createGFMStream(
1536
+ * document.getElementById("out")!,
1537
+ * document,
1538
+ * {},
1539
+ * { raf: requestAnimationFrame },
1540
+ * );
1541
+ * const writer = stream.getWriter();
1542
+ * await writer.write("# Hello\n");
1543
+ * await writer.close();
1544
+ * ```
1545
+ *
1546
+ * @public
1547
+ */
1548
+ function createGFMStream(target, dom, config, targetOptions) {
1549
+ const domTarget = createDOMTarget(dom, target, targetOptions);
1550
+ return createMarkdownStream(new GFMRenderer(domTarget, config), domTarget);
956
1551
  }
957
- var GFMPipeline = class {
958
- _engine;
959
- /**
960
- * @param target - Container node receiving rendered output.
961
- * @param dom - Document used to create nodes.
962
- * @param opts - GFM rendering options.
963
- * @param raf - Optional frame scheduler for batched DOM writes.
964
- */
965
- constructor(target, dom, opts, raf) {
966
- this._engine = createMarkdownPipeline(
967
- new GFMRenderer(createRenderTarget(target, raf), dom, opts)
968
- );
969
- }
970
- /**
971
- * Push a chunk of markdown into the pipeline.
972
- *
973
- * @param chunk - Markdown text, or a promise resolving to markdown text.
974
- * @returns A promise that resolves once the chunk has been consumed.
975
- */
976
- push(chunk) {
977
- return this._engine.push(chunk);
978
- }
979
- /**
980
- * Render any buffered remainder.
981
- *
982
- * @returns A promise that resolves once all output has been flushed.
983
- */
984
- flush() {
985
- return this._engine.flush();
986
- }
987
- };
988
-
989
- // src/core/pipelines/commonmark-pipeline.ts
990
- function createCommonMarkPipeline(target, dom, opts, raf) {
991
- return new CommonMarkPipeline(target, dom, opts, raf);
1552
+ // src/streams/commonmark-stream.ts
1553
+ /**
1554
+ * Create a CommonMark stream rendering into the given container.
1555
+ *
1556
+ * @remarks
1557
+ * The environment is implicit: pass a real browser document for live pages
1558
+ * or a simulated one such as linkedom for server-side rendering. Pass
1559
+ * target options to batch DOM writes on animation frames.
1560
+ *
1561
+ * @param target - Container node receiving rendered output.
1562
+ * @param dom - Document used to create nodes.
1563
+ * @param config - CommonMark rendering config.
1564
+ * @param targetOptions - Frame scheduler for the DOM target.
1565
+ * @returns The configured pipeline.
1566
+ *
1567
+ * @example
1568
+ * ```ts
1569
+ * const stream = createCommonMarkStream(
1570
+ * document.getElementById("out")!,
1571
+ * document,
1572
+ * {},
1573
+ * { raf: requestAnimationFrame },
1574
+ * );
1575
+ * const writer = stream.getWriter();
1576
+ * await writer.write("# Hello\n");
1577
+ * await writer.close();
1578
+ * ```
1579
+ *
1580
+ * @public
1581
+ */
1582
+ function createCommonMarkStream(target, dom, config, targetOptions) {
1583
+ const domTarget = createDOMTarget(dom, target, targetOptions);
1584
+ return createMarkdownStream(new CommonMarkRenderer(domTarget, config), domTarget);
992
1585
  }
993
- var CommonMarkPipeline = class {
994
- _engine;
995
- /**
996
- * @param target - Container node receiving rendered output.
997
- * @param dom - Document used to create nodes.
998
- * @param opts - CommonMark rendering options.
999
- * @param raf - Optional frame scheduler for batched DOM writes.
1000
- */
1001
- constructor(target, dom, opts, raf) {
1002
- this._engine = createMarkdownPipeline(
1003
- new CommonMarkRenderer(createRenderTarget(target, raf), dom, opts)
1004
- );
1005
- }
1006
- /**
1007
- * Push a chunk of markdown into the pipeline.
1008
- *
1009
- * @param chunk - Markdown text, or a promise resolving to markdown text.
1010
- * @returns A promise that resolves once the chunk has been consumed.
1011
- */
1012
- push(chunk) {
1013
- return this._engine.push(chunk);
1014
- }
1015
- /**
1016
- * Render any buffered remainder.
1017
- *
1018
- * @returns A promise that resolves once all output has been flushed.
1019
- */
1020
- flush() {
1021
- return this._engine.flush();
1022
- }
1023
- };
1024
-
1025
- exports.CommonMarkPipeline = CommonMarkPipeline;
1026
1586
  exports.CommonMarkRenderer = CommonMarkRenderer;
1027
- exports.GFMPipeline = GFMPipeline;
1587
+ exports.DetachedNodeError = DetachedNodeError;
1028
1588
  exports.GFMRenderer = GFMRenderer;
1029
- exports.createCommonMarkPipeline = createCommonMarkPipeline;
1030
- exports.createGFMPipeline = createGFMPipeline;
1031
- exports.createMarkdownPipeline = createMarkdownPipeline;
1032
- exports.createRenderTarget = createRenderTarget;
1033
- //# sourceMappingURL=index.cjs.map
1589
+ exports.HierarchyError = HierarchyError;
1590
+ exports.UnknownNodeError = UnknownNodeError;
1591
+ exports.createCommonMarkStream = createCommonMarkStream;
1592
+ exports.createDOMTarget = createDOMTarget;
1593
+ exports.createGFMStream = createGFMStream;
1594
+ exports.createMarkdownStream = createMarkdownStream;
1595
+
1034
1596
  //# sourceMappingURL=index.cjs.map