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