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