markemental 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,6 +1,466 @@
1
1
  'use strict';
2
2
 
3
- // src/renderers/util/inline.ts
3
+ // src/sources/line-source.ts
4
+ function createLineSource() {
5
+ let buffer = "";
6
+ let closed = false;
7
+ return {
8
+ push(chunk) {
9
+ if (closed) throw new Error("push after close");
10
+ buffer += chunk;
11
+ },
12
+ readLines() {
13
+ const lines = [];
14
+ let at = buffer.indexOf("\n");
15
+ while (at !== -1) {
16
+ lines.push(buffer.slice(0, at).replace(/\r$/, ""));
17
+ buffer = buffer.slice(at + 1);
18
+ at = buffer.indexOf("\n");
19
+ }
20
+ return lines;
21
+ },
22
+ close() {
23
+ closed = true;
24
+ if (buffer === "") return [];
25
+ const rest = buffer.replace(/\r$/, "");
26
+ buffer = "";
27
+ return [rest];
28
+ }
29
+ };
30
+ }
31
+
32
+ // src/core/pipelines/markdown-pipeline.ts
33
+ function createMarkdownPipeline(renderer) {
34
+ const source = createLineSource();
35
+ function feed(lines) {
36
+ for (const line of lines) renderer.writeLine(line);
37
+ }
38
+ return {
39
+ async push(chunk) {
40
+ source.push(await chunk);
41
+ feed(source.readLines());
42
+ },
43
+ async flush() {
44
+ feed(source.close());
45
+ await renderer.flush();
46
+ }
47
+ };
48
+ }
49
+
50
+ // src/renderers/parser/blocks.ts
51
+ var HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
52
+ var RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
53
+ var FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
54
+ var QUOTE_RE = /^>\s?(.*)$/;
55
+ var BULLET_RE = /^\s*[-*+]\s+(.*)$/;
56
+ var ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
57
+ var TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
58
+ var LEADING_WS_RE = /^\s*/;
59
+ function isBlankLine(line) {
60
+ return line.trim() === "";
61
+ }
62
+ function matchFence(line) {
63
+ const match = FENCE_RE.exec(line.trim());
64
+ if (!match || !match[1]) return null;
65
+ const run = match[1];
66
+ return {
67
+ marker: run[0],
68
+ length: run.length,
69
+ language: (match[2] ?? "").trim() || void 0
70
+ };
71
+ }
72
+ function fenceCloses(open, line) {
73
+ const match = matchFence(line);
74
+ return match !== null && match.marker === open.marker && match.length >= open.length;
75
+ }
76
+ function matchHeading(line) {
77
+ const match = HEADING_RE.exec(line);
78
+ if (!match || !match[1]) return null;
79
+ return {
80
+ level: Math.min(6, match[1].length),
81
+ text: (match[2] ?? "").replace(/\s+#+\s*$/, "").trim()
82
+ };
83
+ }
84
+ function isRuleLine(line) {
85
+ return RULE_RE.test(line.trim());
86
+ }
87
+ function matchQuote(line) {
88
+ const match = QUOTE_RE.exec(line);
89
+ if (!match) return null;
90
+ return { text: match[1] ?? "" };
91
+ }
92
+ function matchListItem(line) {
93
+ const bullet = BULLET_RE.exec(line);
94
+ const ordered = ORDERED_RE.exec(line);
95
+ if (!bullet && !ordered) return null;
96
+ return {
97
+ ordered: !bullet,
98
+ indent: LEADING_WS_RE.exec(line)?.[0].length ?? 0,
99
+ text: bullet?.[1] ?? ordered?.[1] ?? ""
100
+ };
101
+ }
102
+ function isTableDelimiter(line) {
103
+ if (!line.includes("|") && !line.includes("-")) return false;
104
+ const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
105
+ return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
106
+ }
107
+ function hasOpenFence(lines) {
108
+ let open = null;
109
+ for (const line of lines) {
110
+ if (open === null) {
111
+ open = matchFence(line);
112
+ } else if (fenceCloses(open, line)) {
113
+ open = null;
114
+ }
115
+ }
116
+ return open !== null;
117
+ }
118
+ function makeBlock(block, sourceLineCount) {
119
+ return { ...block, sourceLineCount };
120
+ }
121
+ function splitBlocks(lines) {
122
+ const blocks = [];
123
+ let i = 0;
124
+ while (i < lines.length) {
125
+ const line = lines[i];
126
+ if (isBlankLine(line)) {
127
+ i++;
128
+ continue;
129
+ }
130
+ const fence = matchFence(line);
131
+ if (fence) {
132
+ const content = [];
133
+ let j2 = i + 1;
134
+ while (j2 < lines.length && !fenceCloses(fence, lines[j2])) {
135
+ content.push(lines[j2]);
136
+ j2++;
137
+ }
138
+ const closed = j2 < lines.length;
139
+ blocks.push(makeBlock({ kind: "fence", lines: content, language: fence.language }, j2 - i + (closed ? 1 : 0)));
140
+ i = j2 + (closed ? 1 : 0);
141
+ continue;
142
+ }
143
+ const heading = matchHeading(line);
144
+ if (heading) {
145
+ blocks.push(makeBlock({ kind: "heading", lines: [heading.text], level: heading.level }, 1));
146
+ i++;
147
+ continue;
148
+ }
149
+ if (isRuleLine(line)) {
150
+ blocks.push(makeBlock({ kind: "rule", lines: [] }, 1));
151
+ i++;
152
+ continue;
153
+ }
154
+ const quote = matchQuote(line);
155
+ if (quote) {
156
+ const quoted = [quote.text];
157
+ let j2 = i + 1;
158
+ while (j2 < lines.length) {
159
+ const next = matchQuote(lines[j2]);
160
+ if (!next) break;
161
+ quoted.push(next.text);
162
+ j2++;
163
+ }
164
+ blocks.push(makeBlock({ kind: "quote", lines: quoted }, j2 - i));
165
+ i = j2;
166
+ continue;
167
+ }
168
+ const paragraph = [line];
169
+ let j = i + 1;
170
+ while (j < lines.length) {
171
+ const next = lines[j];
172
+ if (isBlankLine(next) || matchFence(next) !== null || matchHeading(next) !== null || isRuleLine(next) || matchQuote(next) !== null) {
173
+ break;
174
+ }
175
+ paragraph.push(next);
176
+ j++;
177
+ }
178
+ blocks.push(makeBlock({ kind: "paragraph", lines: paragraph }, j - i));
179
+ i = j;
180
+ }
181
+ return blocks;
182
+ }
183
+ function splitTableRow(line) {
184
+ return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
185
+ }
186
+ function parseTableAlignment(cell) {
187
+ const left = cell.startsWith(":");
188
+ const right = cell.endsWith(":");
189
+ if (left && right) return "center";
190
+ if (right) return "right";
191
+ if (left) return "left";
192
+ return null;
193
+ }
194
+
195
+ // src/renderers/renderer-state.ts
196
+ var CommonMarkState = class {
197
+ /**
198
+ * @param emit - Receives parse fragments in document order.
199
+ */
200
+ constructor(_emit) {
201
+ this._emit = _emit;
202
+ }
203
+ _emit;
204
+ _pending = [];
205
+ _fence = null;
206
+ _quote = null;
207
+ _lists = [];
208
+ /**
209
+ * Feed one source line; completed fragments emit to the handler.
210
+ *
211
+ * @param line - Next source line, without its line break.
212
+ */
213
+ addLine(line) {
214
+ if (this._consumeFence(line)) return;
215
+ if (this._consumeLists(line)) return;
216
+ if (this._consumeQuote(line)) return;
217
+ this._classify(line);
218
+ }
219
+ /**
220
+ * Close every open context and emit the trailing remainder.
221
+ */
222
+ flush() {
223
+ this._closeLists();
224
+ if (this._quote !== null) {
225
+ this._pending.push(...this._quote);
226
+ this._quote = null;
227
+ }
228
+ if (this._fence !== null) {
229
+ this._pending.push(this._fence.openLine, ...this._fence.content);
230
+ this._fence = null;
231
+ }
232
+ this._takeAll();
233
+ }
234
+ /**
235
+ * Feed a line to the open fence, if any.
236
+ *
237
+ * @param line - Next source line.
238
+ * @returns True when the line was consumed.
239
+ */
240
+ _consumeFence(line) {
241
+ if (this._fence === null) return false;
242
+ if (fenceCloses(this._fence, line)) {
243
+ this._pending.push(this._fence.openLine, ...this._fence.content, line);
244
+ this._fence = null;
245
+ this._takeComplete();
246
+ } else {
247
+ this._fence.content.push(line);
248
+ }
249
+ return true;
250
+ }
251
+ /**
252
+ * Feed a line to the open lists, if any, closing and reprocessing when
253
+ * the line is not an item.
254
+ *
255
+ * @param line - Next source line.
256
+ * @returns True when the line was consumed or reprocessed.
257
+ */
258
+ _consumeLists(line) {
259
+ if (this._lists.length === 0) return false;
260
+ const item = matchListItem(line);
261
+ if (item !== null) {
262
+ this._listItem(item);
263
+ return true;
264
+ }
265
+ this._closeLists();
266
+ this.addLine(line);
267
+ return true;
268
+ }
269
+ /**
270
+ * Feed a line to the open quote, if any, dumping it back to pending when
271
+ * the line does not continue the quote.
272
+ *
273
+ * @param line - Next source line.
274
+ * @returns True when the line was consumed.
275
+ */
276
+ _consumeQuote(line) {
277
+ if (this._quote === null) return false;
278
+ if (matchQuote(line) !== null) {
279
+ this._quote.push(line);
280
+ return true;
281
+ }
282
+ this._pending.push(...this._quote);
283
+ this._quote = null;
284
+ return false;
285
+ }
286
+ /**
287
+ * Classify a line that continues no open context.
288
+ *
289
+ * @param line - Next source line.
290
+ */
291
+ _classify(line) {
292
+ if (isBlankLine(line)) {
293
+ this._pending.push(line);
294
+ return;
295
+ }
296
+ const fence = matchFence(line);
297
+ if (fence !== null) {
298
+ this._takeAll();
299
+ this._fence = { marker: fence.marker, length: fence.length, openLine: line, content: [] };
300
+ return;
301
+ }
302
+ if (matchHeading(line) !== null || isRuleLine(line)) {
303
+ this._takeAll();
304
+ this._pending.push(line);
305
+ return;
306
+ }
307
+ if (matchQuote(line) !== null) {
308
+ this._takeAll();
309
+ this._quote = [line];
310
+ return;
311
+ }
312
+ const item = matchListItem(line);
313
+ if (item !== null) {
314
+ this._takeAll();
315
+ this._listItem(item);
316
+ return;
317
+ }
318
+ if (this._classifyPipe(line)) return;
319
+ this._pending.push(line);
320
+ this._takeComplete();
321
+ }
322
+ /**
323
+ * Classify a line that matches no CommonMark opener. The base parser has
324
+ * no pipe syntax, so this never consumes; {@link GFMState} overrides it
325
+ * to start table candidates.
326
+ *
327
+ * @param _line - Next source line.
328
+ * @returns Always false here.
329
+ */
330
+ _classifyPipe(_line) {
331
+ return false;
332
+ }
333
+ _listItem(item) {
334
+ while (this._lists.length > 0 && item.indent < this._lists[this._lists.length - 1].indent) {
335
+ this._lists.pop();
336
+ this._emit({ kind: "listEnd" });
337
+ }
338
+ const top = this._lists[this._lists.length - 1];
339
+ if (top && top.indent === item.indent && top.ordered === item.ordered) {
340
+ this._emit({ kind: "listItem", text: item.text });
341
+ return;
342
+ }
343
+ if (top && top.indent === item.indent) {
344
+ this._lists.pop();
345
+ this._emit({ kind: "listEnd" });
346
+ }
347
+ this._emit({ kind: "listStart", ordered: item.ordered });
348
+ this._lists.push({ ordered: item.ordered, indent: item.indent });
349
+ this._emit({ kind: "listItem", text: item.text });
350
+ }
351
+ _closeLists() {
352
+ while (this._lists.length > 0) {
353
+ this._lists.pop();
354
+ this._emit({ kind: "listEnd" });
355
+ }
356
+ }
357
+ _takeComplete() {
358
+ let start = 0;
359
+ let end = this._pending.length;
360
+ while (start < end && isBlankLine(this._pending[start])) start++;
361
+ while (end > start && isBlankLine(this._pending[end - 1])) end--;
362
+ const trimmed = this._pending.slice(start, end);
363
+ if (trimmed.length === 0) {
364
+ this._pending = [];
365
+ return;
366
+ }
367
+ if (hasOpenFence(trimmed)) return;
368
+ const blocks = splitBlocks(trimmed);
369
+ const last = blocks[blocks.length - 1];
370
+ if (last === void 0) {
371
+ this._pending = [];
372
+ return;
373
+ }
374
+ this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
375
+ for (const block of blocks.slice(0, -1)) this._emit({ kind: "block", block });
376
+ }
377
+ _takeAll() {
378
+ const blocks = splitBlocks(this._pending);
379
+ this._pending = [];
380
+ for (const block of blocks) this._emit({ kind: "block", block });
381
+ }
382
+ };
383
+ var GFMState = class extends CommonMarkState {
384
+ _tableOpen = false;
385
+ _candidate = null;
386
+ /**
387
+ * Feed one source line; completed fragments emit to the handler.
388
+ *
389
+ * @param line - Next source line, without its line break.
390
+ */
391
+ addLine(line) {
392
+ if (this._consumeFence(line)) return;
393
+ if (this._consumeTable(line)) return;
394
+ if (this._consumeLists(line)) return;
395
+ if (this._consumeQuote(line)) return;
396
+ if (this._consumeCandidate(line)) return;
397
+ this._classify(line);
398
+ }
399
+ /**
400
+ * Close every open context and emit the trailing remainder.
401
+ */
402
+ flush() {
403
+ if (this._candidate !== null) {
404
+ this._pending.push(this._candidate);
405
+ this._candidate = null;
406
+ }
407
+ if (this._tableOpen) {
408
+ this._emit({ kind: "tableEnd" });
409
+ this._tableOpen = false;
410
+ }
411
+ super.flush();
412
+ }
413
+ /**
414
+ * Feed a line to the open table, if any, closing and reprocessing when
415
+ * the line is not a row.
416
+ *
417
+ * @param line - Next source line.
418
+ * @returns True when the line was consumed or reprocessed.
419
+ */
420
+ _consumeTable(line) {
421
+ if (!this._tableOpen) return false;
422
+ if (!isBlankLine(line) && line.includes("|")) {
423
+ this._emit({ kind: "tableRow", line });
424
+ return true;
425
+ }
426
+ this._emit({ kind: "tableEnd" });
427
+ this._tableOpen = false;
428
+ this.addLine(line);
429
+ return true;
430
+ }
431
+ /**
432
+ * Resolve a pending table header candidate against the next line.
433
+ *
434
+ * @param line - Next source line.
435
+ * @returns True when a table opened.
436
+ */
437
+ _consumeCandidate(line) {
438
+ if (this._candidate === null) return false;
439
+ if (isTableDelimiter(line)) {
440
+ this._emit({ kind: "tableHead", headLine: this._candidate, delimLine: line });
441
+ this._candidate = null;
442
+ this._tableOpen = true;
443
+ return true;
444
+ }
445
+ this._pending.push(this._candidate);
446
+ this._candidate = null;
447
+ return false;
448
+ }
449
+ /**
450
+ * Start a table header candidate on pipe lines.
451
+ *
452
+ * @param line - Next source line.
453
+ * @returns True when the line starts a candidate.
454
+ */
455
+ _classifyPipe(line) {
456
+ if (!line.includes("|")) return false;
457
+ this._takeAll();
458
+ this._candidate = line;
459
+ return true;
460
+ }
461
+ };
462
+
463
+ // src/renderers/parser/inline.ts
4
464
  var ESCAPABLE_RE = /^[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]$/;
5
465
  var AUTOLINK_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]*$/;
6
466
  var ALNUM_RE = /[A-Za-z0-9]/;
@@ -131,20 +591,102 @@ function appendInline(parent, text, doc, gfm) {
131
591
  }
132
592
  flushLiteral();
133
593
  }
594
+ function splitHardBreak(line) {
595
+ const hardBreak = / {2,}$/.test(line);
596
+ return { text: hardBreak ? line.replace(/ {2,}$/, "") : line, hardBreak };
597
+ }
134
598
 
135
599
  // src/renderers/commonmark.ts
136
600
  var CommonMarkRenderer = class {
137
601
  /** Rendering options. */
138
602
  options;
603
+ _target;
604
+ _doc;
605
+ _state;
606
+ _open = [];
139
607
  /**
608
+ * @param target - Destination for rendered output, from
609
+ * `createRenderTarget`. Pass `requestAnimationFrame` there to batch
610
+ * writes on animation frames, or nothing for synchronous writes.
611
+ * @param doc - Document used to create nodes.
140
612
  * @param opts - CommonMark rendering options.
141
613
  */
142
- constructor(opts) {
614
+ constructor(target, doc, opts) {
615
+ this._target = target;
616
+ this._doc = doc;
143
617
  this.options = opts;
618
+ this._state = this._createState((fragment) => this._applyFragment(fragment));
619
+ }
620
+ /**
621
+ * Create the parser state. Overridden by `GFMRenderer` to parse
622
+ * tables.
623
+ *
624
+ * @param emit - Receives parse fragments in document order.
625
+ * @returns The state for this renderer.
626
+ */
627
+ _createState(emit) {
628
+ return new CommonMarkState(emit);
629
+ }
630
+ /**
631
+ * Feed one source line; completed output is written to the target.
632
+ *
633
+ * @param line - Next source line, without its line break.
634
+ */
635
+ writeLine(line) {
636
+ this._state.addLine(line);
637
+ }
638
+ /**
639
+ * Render the buffered remainder and settle the target.
640
+ *
641
+ * @returns A promise that resolves once all output has landed in the target.
642
+ */
643
+ async flush() {
644
+ this._state.flush();
645
+ await this._target.flush();
646
+ }
647
+ _applyFragment(fragment) {
648
+ switch (fragment.kind) {
649
+ case "block": {
650
+ const node = this.renderBlock(fragment.block, this._doc);
651
+ if (node !== null) this._commit(node, null);
652
+ break;
653
+ }
654
+ case "listStart": {
655
+ const top = this._open[this._open.length - 1];
656
+ const list = this._doc.createElement(fragment.ordered ? "ol" : "ul");
657
+ this._commit(list, top?.currentItem ?? null);
658
+ this._open.push({ node: list, currentItem: null });
659
+ break;
660
+ }
661
+ case "listItem": {
662
+ const top = this._open[this._open.length - 1];
663
+ const item = this._doc.createElement("li");
664
+ appendInline(item, fragment.text, this._doc, this.inlineGfm());
665
+ this._commit(item, top.node);
666
+ top.currentItem = item;
667
+ break;
668
+ }
669
+ case "listEnd":
670
+ this._open.pop();
671
+ break;
672
+ }
673
+ }
674
+ /**
675
+ * Append a node to the target (top level) or to its parent container,
676
+ * running the sanitizer first when one is set.
677
+ *
678
+ * @param node - Node to commit.
679
+ * @param parent - Parent container, or null to commit to the target.
680
+ */
681
+ _commit(node, parent) {
682
+ const sanitizer = this.options.sanitizer;
683
+ const out = sanitizer === void 0 ? node : sanitizer(node);
684
+ if (parent === null) this._target.append(out);
685
+ else parent.appendChild(out);
144
686
  }
145
687
  /**
146
688
  * Whether GFM-only inlines are enabled. Always false here; overridden by
147
- * {@link GFMRenderer}.
689
+ * `GFMRenderer`.
148
690
  *
149
691
  * @returns False.
150
692
  */
@@ -177,15 +719,6 @@ var CommonMarkRenderer = class {
177
719
  pre.appendChild(code);
178
720
  return pre;
179
721
  }
180
- case "list": {
181
- const list = doc.createElement(block.ordered ? "ol" : "ul");
182
- for (const item of block.lines) {
183
- const li = doc.createElement("li");
184
- appendInline(li, item, doc, this.inlineGfm());
185
- list.appendChild(li);
186
- }
187
- return list;
188
- }
189
722
  case "quote": {
190
723
  const quote = doc.createElement("blockquote");
191
724
  const body = doc.createElement("p");
@@ -195,8 +728,6 @@ var CommonMarkRenderer = class {
195
728
  }
196
729
  case "rule":
197
730
  return doc.createElement("hr");
198
- case "table":
199
- return this.renderParagraph(block.lines.filter((_, at) => at !== 1), doc);
200
731
  }
201
732
  }
202
733
  /**
@@ -209,8 +740,8 @@ var CommonMarkRenderer = class {
209
740
  renderParagraph(lines, doc) {
210
741
  const paragraph = doc.createElement("p");
211
742
  lines.forEach((line, at) => {
212
- const hardBreak = / {2,}$/.test(line);
213
- appendInline(paragraph, hardBreak ? line.replace(/ {2,}$/, "") : line, doc, this.inlineGfm());
743
+ const { text, hardBreak } = splitHardBreak(line);
744
+ appendInline(paragraph, text, doc, this.inlineGfm());
214
745
  if (at < lines.length - 1) {
215
746
  if (hardBreak) paragraph.appendChild(doc.createElement("br"));
216
747
  else paragraph.appendChild(doc.createTextNode(" "));
@@ -227,25 +758,19 @@ var CommonMarkRenderer = class {
227
758
  };
228
759
 
229
760
  // src/renderers/gfm.ts
230
- function splitRow(line) {
231
- return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
232
- }
233
- function parseAlignment(cell) {
234
- const left = cell.startsWith(":");
235
- const right = cell.endsWith(":");
236
- if (left && right) return "center";
237
- if (right) return "right";
238
- if (left) return "left";
239
- return null;
240
- }
241
761
  var GFMRenderer = class extends CommonMarkRenderer {
242
762
  /** Rendering options. */
243
763
  options;
764
+ _table = null;
244
765
  /**
766
+ * @param target - Destination for rendered output, from
767
+ * `createRenderTarget`. Pass `requestAnimationFrame` there to batch
768
+ * writes on animation frames, or nothing for synchronous writes.
769
+ * @param doc - Document used to create nodes.
245
770
  * @param opts - GFM rendering options.
246
771
  */
247
- constructor(opts) {
248
- super({});
772
+ constructor(target, doc, opts) {
773
+ super(target, doc, opts);
249
774
  this.options = opts;
250
775
  }
251
776
  /**
@@ -257,44 +782,91 @@ var GFMRenderer = class extends CommonMarkRenderer {
257
782
  return true;
258
783
  }
259
784
  /**
260
- * Render one block to a DOM-like node, handling GFM tables.
785
+ * Create the GFM parser state.
261
786
  *
262
- * @param block - Parsed block to render.
263
- * @param doc - Document used to create nodes.
264
- * @returns The rendered node, or `null` to emit nothing.
787
+ * @param emit - Receives parse fragments in document order.
788
+ * @returns The state for this renderer.
265
789
  */
266
- renderBlock(block, doc) {
267
- if (block.kind !== "table") return super.renderBlock(block, doc);
268
- const rows = block.lines.map(splitRow);
269
- const header = rows[0] ?? [];
270
- const alignments = (rows[1] ?? []).map(parseAlignment);
271
- const width = Math.max(header.length, ...rows.map((row) => row.length));
272
- const table = doc.createElement("table");
273
- const head = doc.createElement("thead");
274
- const headRow = doc.createElement("tr");
790
+ _createState(emit) {
791
+ return new GFMState(emit);
792
+ }
793
+ /**
794
+ * Apply a fragment, handling tables here and delegating the rest.
795
+ *
796
+ * @param fragment - Fragment to apply.
797
+ */
798
+ _applyFragment(fragment) {
799
+ switch (fragment.kind) {
800
+ case "tableHead":
801
+ this._applyTableHead(fragment.headLine, fragment.delimLine);
802
+ break;
803
+ case "tableRow":
804
+ this._applyTableRow(fragment.line);
805
+ break;
806
+ case "tableEnd":
807
+ this._applyTableEnd();
808
+ break;
809
+ default:
810
+ super._applyFragment(fragment);
811
+ break;
812
+ }
813
+ }
814
+ /**
815
+ * Commit the table with its header; body rows stream in afterwards.
816
+ *
817
+ * @param headLine - Raw header row line.
818
+ * @param delimLine - Delimiter row line carrying column alignment.
819
+ */
820
+ _applyTableHead(headLine, delimLine) {
821
+ const header = splitTableRow(headLine);
822
+ const aligns = splitTableRow(delimLine).map(parseTableAlignment);
823
+ const width = header.length;
824
+ const table = this._doc.createElement("table");
825
+ const head = this._doc.createElement("thead");
826
+ const headRow = this._doc.createElement("tr");
275
827
  for (let col = 0; col < width; col++) {
276
- const cell = doc.createElement("th");
277
- const align = alignments[col] ?? null;
828
+ const cell = this._doc.createElement("th");
829
+ const align = aligns[col] ?? null;
278
830
  if (align !== null) cell.setAttribute?.("align", align);
279
- appendInline(cell, header[col] ?? "", doc, true);
831
+ appendInline(cell, header[col] ?? "", this._doc, true);
280
832
  headRow.appendChild(cell);
281
833
  }
282
834
  head.appendChild(headRow);
283
835
  table.appendChild(head);
284
- const body = doc.createElement("tbody");
285
- for (const row of rows.slice(2)) {
286
- const bodyRow = doc.createElement("tr");
287
- for (let col = 0; col < width; col++) {
288
- const cell = doc.createElement("td");
289
- const align = alignments[col] ?? null;
290
- if (align !== null) cell.setAttribute?.("align", align);
291
- appendInline(cell, row[col] ?? "", doc, true);
292
- bodyRow.appendChild(cell);
293
- }
294
- body.appendChild(bodyRow);
295
- }
836
+ const body = this._doc.createElement("tbody");
296
837
  table.appendChild(body);
297
- return table;
838
+ this._commit(table, null);
839
+ this._table = { body, aligns, width };
840
+ }
841
+ /**
842
+ * Append one body row to the open table.
843
+ *
844
+ * @param line - Raw body row line.
845
+ */
846
+ _applyTableRow(line) {
847
+ const table = this._table;
848
+ if (table === null) return;
849
+ const cells = splitTableRow(line);
850
+ const row = this._doc.createElement("tr");
851
+ for (let col = 0; col < table.width; col++) {
852
+ const cell = this._doc.createElement("td");
853
+ const align = table.aligns[col] ?? null;
854
+ if (align !== null) cell.setAttribute?.("align", align);
855
+ appendInline(cell, cells[col] ?? "", this._doc, true);
856
+ row.appendChild(cell);
857
+ }
858
+ for (let col = table.width; col < cells.length; col++) {
859
+ const cell = this._doc.createElement("td");
860
+ appendInline(cell, cells[col], this._doc, true);
861
+ row.appendChild(cell);
862
+ }
863
+ this._commit(row, table.body);
864
+ }
865
+ /**
866
+ * Close the open table.
867
+ */
868
+ _applyTableEnd() {
869
+ this._table = null;
298
870
  }
299
871
  };
300
872
 
@@ -373,265 +945,26 @@ var DOMTarget = class {
373
945
  }
374
946
  };
375
947
 
376
- // src/core/util/blocks.ts
377
- var HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
378
- var RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
379
- var FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
380
- var QUOTE_RE = /^>\s?(.*)$/;
381
- var BULLET_RE = /^\s*[-*+]\s+(.*)$/;
382
- var ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
383
- var TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
384
- function isBlankLine(line) {
385
- return line.trim() === "";
386
- }
387
- function isBlank(line) {
388
- return isBlankLine(line);
389
- }
390
- function isTableDelimiter(line) {
391
- if (!line.includes("|") && !line.includes("-")) return false;
392
- const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
393
- return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
394
- }
395
- function hasOpenFence(lines) {
396
- let openChar = "";
397
- let openLen = 0;
398
- for (const line of lines) {
399
- const match = FENCE_RE.exec(line.trim());
400
- if (!match || !match[1]) continue;
401
- const run = match[1];
402
- if (openChar === "") {
403
- openChar = run[0];
404
- openLen = run.length;
405
- } else if (run[0] === openChar && run.length >= openLen) {
406
- openChar = "";
407
- openLen = 0;
408
- }
409
- }
410
- return openChar !== "";
411
- }
412
- function makeBlock(block, sourceLineCount) {
413
- return { ...block, sourceLineCount };
414
- }
415
- function splitBlocks(lines) {
416
- const blocks = [];
417
- let i = 0;
418
- while (i < lines.length) {
419
- const line = lines[i];
420
- if (isBlank(line)) {
421
- i++;
422
- continue;
423
- }
424
- const fence = FENCE_RE.exec(line.trim());
425
- if (fence && fence[1]) {
426
- const run = fence[1];
427
- const language = (fence[2] ?? "").trim() || void 0;
428
- const content = [];
429
- let j2 = i + 1;
430
- while (j2 < lines.length) {
431
- const inner = lines[j2];
432
- const close = FENCE_RE.exec(inner.trim());
433
- if (close && close[1] && close[1][0] === run[0] && close[1].length >= run.length) break;
434
- content.push(inner);
435
- j2++;
436
- }
437
- const closed = j2 < lines.length;
438
- blocks.push(makeBlock({ kind: "fence", lines: content, language }, j2 - i + (closed ? 1 : 0)));
439
- i = j2 + (closed ? 1 : 0);
440
- continue;
441
- }
442
- const heading = HEADING_RE.exec(line);
443
- if (heading && heading[1]) {
444
- const text = (heading[2] ?? "").replace(/\s+#+\s*$/, "").trim();
445
- blocks.push(makeBlock({ kind: "heading", lines: [text], level: Math.min(6, heading[1].length) }, 1));
446
- i++;
447
- continue;
448
- }
449
- if (RULE_RE.test(line.trim())) {
450
- blocks.push(makeBlock({ kind: "rule", lines: [] }, 1));
451
- i++;
452
- continue;
453
- }
454
- if (line.includes("|") && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) {
455
- const rows = [line, lines[i + 1]];
456
- let j2 = i + 2;
457
- while (j2 < lines.length && !isBlank(lines[j2]) && lines[j2].includes("|")) {
458
- rows.push(lines[j2]);
459
- j2++;
460
- }
461
- blocks.push(makeBlock({ kind: "table", lines: rows }, j2 - i));
462
- i = j2;
463
- continue;
464
- }
465
- const quote = QUOTE_RE.exec(line);
466
- if (quote) {
467
- const quoted = [quote[1] ?? ""];
468
- let j2 = i + 1;
469
- while (j2 < lines.length) {
470
- const next = QUOTE_RE.exec(lines[j2]);
471
- if (!next) break;
472
- quoted.push(next[1] ?? "");
473
- j2++;
474
- }
475
- blocks.push(makeBlock({ kind: "quote", lines: quoted }, j2 - i));
476
- i = j2;
477
- continue;
478
- }
479
- const bullet = BULLET_RE.exec(line);
480
- const ordered = ORDERED_RE.exec(line);
481
- if (bullet || ordered) {
482
- const isOrdered = !bullet;
483
- const items = [bullet?.[1] ?? ordered?.[1] ?? ""];
484
- let j2 = i + 1;
485
- while (j2 < lines.length) {
486
- const nextBullet = BULLET_RE.exec(lines[j2]);
487
- const nextOrdered = ORDERED_RE.exec(lines[j2]);
488
- if (isOrdered && nextOrdered) items.push(nextOrdered[1] ?? "");
489
- else if (!isOrdered && nextBullet && !ORDERED_RE.test(lines[j2])) items.push(nextBullet[1] ?? "");
490
- else break;
491
- j2++;
492
- }
493
- blocks.push(makeBlock({ kind: "list", lines: items, ordered: isOrdered }, j2 - i));
494
- i = j2;
495
- continue;
496
- }
497
- const paragraph = [line];
498
- let j = i + 1;
499
- while (j < lines.length) {
500
- const next = lines[j];
501
- 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])) {
502
- break;
503
- }
504
- paragraph.push(next);
505
- j++;
506
- }
507
- blocks.push(makeBlock({ kind: "paragraph", lines: paragraph }, j - i));
508
- i = j;
509
- }
510
- return blocks;
948
+ // src/targets/render-target.ts
949
+ function createRenderTarget(targetNode, raf) {
950
+ return raf === void 0 ? new DOMTarget(targetNode) : new AnimatedDOMTarget(targetNode, raf);
511
951
  }
512
952
 
513
- // src/renderers/renderer-state.ts
514
- var RendererState = class {
515
- _pending = [];
516
- /**
517
- * Buffer newly arrived lines.
518
- *
519
- * @param lines - Complete source lines to buffer.
520
- */
521
- addLines(lines) {
522
- for (const line of lines) this._pending.push(line);
523
- }
524
- /**
525
- * Parse buffered lines, returning every block except a trailing partial one.
526
- *
527
- * @remarks
528
- * The last block is held back because more input may still extend it.
529
- * Nothing is returned while the buffer ends inside an unclosed fence.
530
- *
531
- * @returns Complete blocks ready to render.
532
- */
533
- takeCompleteBlocks() {
534
- let start = 0;
535
- let end = this._pending.length;
536
- while (start < end && isBlankLine(this._pending[start])) start++;
537
- while (end > start && isBlankLine(this._pending[end - 1])) end--;
538
- const trimmed = this._pending.slice(start, end);
539
- if (trimmed.length === 0) {
540
- this._pending = [];
541
- return [];
542
- }
543
- if (hasOpenFence(trimmed)) return [];
544
- const blocks = splitBlocks(trimmed);
545
- const last = blocks[blocks.length - 1];
546
- if (last === void 0) {
547
- this._pending = [];
548
- return [];
549
- }
550
- this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
551
- return blocks.slice(0, -1);
552
- }
553
- /**
554
- * Parse and drain all buffered lines, including a trailing partial block.
555
- *
556
- * @returns Every remaining block.
557
- */
558
- takeAllBlocks() {
559
- const blocks = splitBlocks(this._pending);
560
- this._pending = [];
561
- return blocks;
562
- }
563
- };
564
-
565
- // src/sources/line-source.ts
566
- function createLineSource() {
567
- let buffer = "";
568
- let closed = false;
569
- return {
570
- push(chunk) {
571
- if (closed) throw new Error("push after close");
572
- buffer += chunk;
573
- },
574
- readLines() {
575
- const lines = [];
576
- let at = buffer.indexOf("\n");
577
- while (at !== -1) {
578
- lines.push(buffer.slice(0, at).replace(/\r$/, ""));
579
- buffer = buffer.slice(at + 1);
580
- at = buffer.indexOf("\n");
581
- }
582
- return lines;
583
- },
584
- close() {
585
- closed = true;
586
- if (buffer === "") return [];
587
- const rest = buffer.replace(/\r$/, "");
588
- buffer = "";
589
- return [rest];
590
- }
591
- };
592
- }
593
-
594
- // src/core/pipelines/pipeline-engine.ts
595
- function createPipelineEngine(renderer, target, dom) {
596
- const source = createLineSource();
597
- const state = new RendererState();
598
- function render(blocks) {
599
- for (const block of blocks) {
600
- const node = renderer.renderBlock(block, dom);
601
- if (node !== null) target.append(node);
602
- }
603
- }
604
- return {
605
- async push(chunk) {
606
- source.push(await chunk);
607
- state.addLines(source.readLines());
608
- render(state.takeCompleteBlocks());
609
- },
610
- async flush() {
611
- state.addLines(source.close());
612
- render(state.takeAllBlocks());
613
- await target.flush();
614
- }
615
- };
616
- }
617
-
618
- // src/core/pipelines/frontend-gfm-pipeline.ts
619
- function createFrontendGFMPipeline(target, dom, opts, raf) {
620
- return new FrontendGFMPipeline(target, dom, opts, raf);
953
+ // src/core/pipelines/gfm-pipeline.ts
954
+ function createGFMPipeline(target, dom, opts, raf) {
955
+ return new GFMPipeline(target, dom, opts, raf);
621
956
  }
622
- var FrontendGFMPipeline = class {
957
+ var GFMPipeline = class {
623
958
  _engine;
624
959
  /**
625
- * @param target - Container node receiving rendered blocks.
960
+ * @param target - Container node receiving rendered output.
626
961
  * @param dom - Document used to create nodes.
627
962
  * @param opts - GFM rendering options.
628
963
  * @param raf - Optional frame scheduler for batched DOM writes.
629
964
  */
630
965
  constructor(target, dom, opts, raf) {
631
- this._engine = createPipelineEngine(
632
- new GFMRenderer(opts),
633
- raf === void 0 ? new DOMTarget(target) : new AnimatedDOMTarget(target, raf),
634
- dom
966
+ this._engine = createMarkdownPipeline(
967
+ new GFMRenderer(createRenderTarget(target, raf), dom, opts)
635
968
  );
636
969
  }
637
970
  /**
@@ -653,23 +986,21 @@ var FrontendGFMPipeline = class {
653
986
  }
654
987
  };
655
988
 
656
- // src/core/pipelines/frontend-commonmark-pipeline.ts
657
- function createFrontendCommonMarkPipeline(target, dom, opts, raf) {
658
- return new FrontendCommonMarkPipeline(target, dom, opts, raf);
989
+ // src/core/pipelines/commonmark-pipeline.ts
990
+ function createCommonMarkPipeline(target, dom, opts, raf) {
991
+ return new CommonMarkPipeline(target, dom, opts, raf);
659
992
  }
660
- var FrontendCommonMarkPipeline = class {
993
+ var CommonMarkPipeline = class {
661
994
  _engine;
662
995
  /**
663
- * @param target - Container node receiving rendered blocks.
996
+ * @param target - Container node receiving rendered output.
664
997
  * @param dom - Document used to create nodes.
665
998
  * @param opts - CommonMark rendering options.
666
999
  * @param raf - Optional frame scheduler for batched DOM writes.
667
1000
  */
668
1001
  constructor(target, dom, opts, raf) {
669
- this._engine = createPipelineEngine(
670
- new CommonMarkRenderer(opts),
671
- raf === void 0 ? new DOMTarget(target) : new AnimatedDOMTarget(target, raf),
672
- dom
1002
+ this._engine = createMarkdownPipeline(
1003
+ new CommonMarkRenderer(createRenderTarget(target, raf), dom, opts)
673
1004
  );
674
1005
  }
675
1006
  /**
@@ -691,85 +1022,13 @@ var FrontendCommonMarkPipeline = class {
691
1022
  }
692
1023
  };
693
1024
 
694
- // src/core/pipelines/backend-gfm-pipeline.ts
695
- function createBackendGFMPipeline(target, dom, opts) {
696
- return new BackendGFMPipeline(target, dom, opts);
697
- }
698
- var BackendGFMPipeline = class {
699
- _engine;
700
- /**
701
- * @param target - Container node receiving rendered blocks.
702
- * @param dom - Document used to create nodes.
703
- * @param opts - GFM rendering options.
704
- */
705
- constructor(target, dom, opts) {
706
- this._engine = createPipelineEngine(new GFMRenderer(opts), new DOMTarget(target), dom);
707
- }
708
- /**
709
- * Push a chunk of markdown into the pipeline.
710
- *
711
- * @param chunk - Markdown text, or a promise resolving to markdown text.
712
- * @returns A promise that resolves once the chunk has been consumed.
713
- */
714
- push(chunk) {
715
- return this._engine.push(chunk);
716
- }
717
- /**
718
- * Render any buffered remainder.
719
- *
720
- * @returns A promise that resolves once all output has been flushed.
721
- */
722
- flush() {
723
- return this._engine.flush();
724
- }
725
- };
726
-
727
- // src/core/pipelines/backend-commonmark-pipeline.ts
728
- function createBackendCommonMarkPipeline(target, dom, opts) {
729
- return new BackendCommonMarkPipeline(target, dom, opts);
730
- }
731
- var BackendCommonMarkPipeline = class {
732
- _engine;
733
- /**
734
- * @param target - Container node receiving rendered blocks.
735
- * @param dom - Document used to create nodes.
736
- * @param opts - CommonMark rendering options.
737
- */
738
- constructor(target, dom, opts) {
739
- this._engine = createPipelineEngine(new CommonMarkRenderer(opts), new DOMTarget(target), dom);
740
- }
741
- /**
742
- * Push a chunk of markdown into the pipeline.
743
- *
744
- * @param chunk - Markdown text, or a promise resolving to markdown text.
745
- * @returns A promise that resolves once the chunk has been consumed.
746
- */
747
- push(chunk) {
748
- return this._engine.push(chunk);
749
- }
750
- /**
751
- * Render any buffered remainder.
752
- *
753
- * @returns A promise that resolves once all output has been flushed.
754
- */
755
- flush() {
756
- return this._engine.flush();
757
- }
758
- };
759
-
760
- exports.AnimatedDOMTarget = AnimatedDOMTarget;
761
- exports.BackendCommonMarkPipeline = BackendCommonMarkPipeline;
762
- exports.BackendGFMPipeline = BackendGFMPipeline;
1025
+ exports.CommonMarkPipeline = CommonMarkPipeline;
763
1026
  exports.CommonMarkRenderer = CommonMarkRenderer;
764
- exports.DOMTarget = DOMTarget;
765
- exports.FrontendCommonMarkPipeline = FrontendCommonMarkPipeline;
766
- exports.FrontendGFMPipeline = FrontendGFMPipeline;
1027
+ exports.GFMPipeline = GFMPipeline;
767
1028
  exports.GFMRenderer = GFMRenderer;
768
- exports.RendererState = RendererState;
769
- exports.createBackendCommonMarkPipeline = createBackendCommonMarkPipeline;
770
- exports.createBackendGFMPipeline = createBackendGFMPipeline;
771
- exports.createFrontendCommonMarkPipeline = createFrontendCommonMarkPipeline;
772
- exports.createFrontendGFMPipeline = createFrontendGFMPipeline;
773
- exports.createLineSource = createLineSource;
1029
+ exports.createCommonMarkPipeline = createCommonMarkPipeline;
1030
+ exports.createGFMPipeline = createGFMPipeline;
1031
+ exports.createMarkdownPipeline = createMarkdownPipeline;
1032
+ exports.createRenderTarget = createRenderTarget;
774
1033
  //# sourceMappingURL=index.cjs.map
775
1034
  //# sourceMappingURL=index.cjs.map