@mdream/js 1.7.1 → 2.0.0-beta.1

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.
@@ -1,13 +1,420 @@
1
1
  import { DEFAULT_BLOCK_SPACING, NO_SPACING, TagIdMap, isInsideRawHtmlBlock } from "./const.mjs";
2
- import { blockOpenPrefix, breakHandler, continuationPrefix, finalizeParse, getLanguageFromClass, isCharacterReferenceTail, isInsideHeading, isInsideTableCell, isSafeHtmlUrl, listMarkerLineStart, orderedItemNumber, parseHtmlStream, parseUnsignedInteger, renderBreak, resolveUrl } from "./parse.mjs";
2
+ import { blockOpenPrefix, breakHandler, continuationPrefix, escapeHtml, figcaptionOwnsBlockSpacing, finalizeParse, getLanguageFromClass, isCharacterReferenceTail, isDataUrl, isEmptyLinkHref, isInsideHeading, isInsideTableCell, isSafeHtmlUrl, lastOutputChar, listMarkerLineStart, markRenderedChildContent, orderedItemNumber, parseHtmlStream, parseUnsignedInteger, renderBreak, resolveUrl, safeAnchorOutput } from "./parse.mjs";
3
+ function resolveClean(clean) {
4
+ if (clean === true) return {
5
+ urls: true,
6
+ fragments: true,
7
+ emptyLinks: true,
8
+ redundantLinks: true,
9
+ selfLinkHeadings: true,
10
+ emptyImages: true,
11
+ emptyLinkText: true
12
+ };
13
+ if (clean === false) return {};
14
+ return clean;
15
+ }
16
+ function parseLink(md, start) {
17
+ const len = md.length;
18
+ let j = start + 1;
19
+ let depth = 1;
20
+ while (j < len && depth > 0) {
21
+ const c = md.charCodeAt(j);
22
+ if (c === 91) depth++;
23
+ else if (c === 93) depth--;
24
+ j++;
25
+ }
26
+ if (depth !== 0) return null;
27
+ const textEnd = j - 1;
28
+ if (j >= len || md.charCodeAt(j) !== 40) return null;
29
+ j++;
30
+ const urlStart = j;
31
+ let parenDepth = 1;
32
+ while (j < len && parenDepth > 0) {
33
+ const c = md.charCodeAt(j);
34
+ if (c === 40) parenDepth++;
35
+ else if (c === 41) parenDepth--;
36
+ j++;
37
+ }
38
+ if (parenDepth !== 0) return null;
39
+ const urlEnd = j - 1;
40
+ return {
41
+ text: md.slice(start + 1, textEnd),
42
+ url: md.slice(urlStart, urlEnd),
43
+ end: j
44
+ };
45
+ }
46
+ function isEscaped(md, index) {
47
+ const end = index;
48
+ while (index > 0 && md.charCodeAt(index - 1) === 92) index--;
49
+ return (end - index) % 2 !== 0;
50
+ }
51
+ function htmlTagEnd(md, start, lastGt) {
52
+ if (start >= lastGt || isEscaped(md, start)) return -1;
53
+ let i = start + 1;
54
+ if (md.charCodeAt(i) === 47) i++;
55
+ let code = md.charCodeAt(i);
56
+ if (!(code >= 65 && code <= 90 || code >= 97 && code <= 122)) return -1;
57
+ do {
58
+ i++;
59
+ code = md.charCodeAt(i);
60
+ } while (code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45);
61
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13 && code !== 47 && code !== 62) return -1;
62
+ let quote = 0;
63
+ while (i < md.length) {
64
+ code = md.charCodeAt(i);
65
+ if (quote) {
66
+ if (code === quote) quote = 0;
67
+ } else if (code === 34 || code === 39) quote = code;
68
+ else if (code === 62) return i + 1;
69
+ else if (code === 60) return -1;
70
+ i++;
71
+ }
72
+ return -1;
73
+ }
74
+ function slugify(text) {
75
+ let slug = "";
76
+ let lastWasDash = false;
77
+ for (let i = 0; i < text.length; i++) {
78
+ const c = text.charCodeAt(i);
79
+ if (c >= 97 && c <= 122) {
80
+ slug += text[i];
81
+ lastWasDash = false;
82
+ } else if (c >= 65 && c <= 90) {
83
+ slug += String.fromCharCode(c + 32);
84
+ lastWasDash = false;
85
+ } else if (c >= 48 && c <= 57) {
86
+ slug += text[i];
87
+ lastWasDash = false;
88
+ } else if (c === 95) {
89
+ slug += "_";
90
+ lastWasDash = false;
91
+ } else if (c === 32 || c === 9 || c === 45) {
92
+ if (!lastWasDash && slug.length > 0) {
93
+ slug += "-";
94
+ lastWasDash = true;
95
+ }
96
+ }
97
+ }
98
+ if (lastWasDash) slug = slug.slice(0, -1);
99
+ return slug;
100
+ }
101
+ function stripHeadingFormatting(text) {
102
+ let result = "";
103
+ const len = text.length;
104
+ const lastGt = text.lastIndexOf(">");
105
+ let firstTickLength = 0;
106
+ let firstTickLast = 0;
107
+ let otherTickLasts;
108
+ if (text.includes("`")) {
109
+ let scan = 0;
110
+ while (scan < len) {
111
+ let code = text.charCodeAt(scan);
112
+ if (code === 96) {
113
+ const start = scan;
114
+ do {
115
+ scan++;
116
+ code = text.charCodeAt(scan);
117
+ } while (code === 96);
118
+ const ticks = scan - start;
119
+ if (firstTickLength === 0) {
120
+ firstTickLength = ticks;
121
+ firstTickLast = start;
122
+ } else if (ticks === firstTickLength) firstTickLast = start;
123
+ else {
124
+ otherTickLasts ||= /* @__PURE__ */ new Map();
125
+ otherTickLasts.set(ticks, start);
126
+ }
127
+ } else if (code === 60) {
128
+ const tagEnd = htmlTagEnd(text, scan, lastGt);
129
+ scan = tagEnd === -1 ? scan + 1 : tagEnd;
130
+ } else scan++;
131
+ }
132
+ }
133
+ let i = 0;
134
+ let codeTicks = 0;
135
+ while (i < len) {
136
+ const c = text.charCodeAt(i);
137
+ if (c === 96) {
138
+ let end = i + 1;
139
+ while (text.charCodeAt(end) === 96) end++;
140
+ const ticks = end - i;
141
+ if (codeTicks === 0) {
142
+ if ((ticks === firstTickLength ? firstTickLast : otherTickLasts?.get(ticks) ?? i) > i) codeTicks = ticks;
143
+ } else if (codeTicks === ticks) codeTicks = 0;
144
+ i = end;
145
+ continue;
146
+ }
147
+ if (codeTicks !== 0) {
148
+ result += text[i];
149
+ i++;
150
+ continue;
151
+ }
152
+ if (c === 92 && i + 1 < len) {
153
+ result += text[i + 1];
154
+ i += 2;
155
+ continue;
156
+ }
157
+ const tagEnd = c === 60 ? htmlTagEnd(text, i, lastGt) : -1;
158
+ if (tagEnd !== -1) {
159
+ i = tagEnd;
160
+ continue;
161
+ }
162
+ if (c === 91) {
163
+ const link = parseLink(text, i);
164
+ if (link) {
165
+ result += link.text;
166
+ i = link.end;
167
+ continue;
168
+ }
169
+ }
170
+ if (c === 42 || c === 95 || c === 126) {
171
+ i++;
172
+ continue;
173
+ }
174
+ result += text[i];
175
+ i++;
176
+ }
177
+ return result.trim();
178
+ }
179
+ function collectHeadingSlugs(md) {
180
+ const slugs = /* @__PURE__ */ new Set();
181
+ const len = md.length;
182
+ let i = 0;
183
+ while (i < len) {
184
+ if (i === 0 || md.charCodeAt(i - 1) === 10) {
185
+ let hashes = 0;
186
+ let j = i;
187
+ while (j < len && md.charCodeAt(j) === 35) {
188
+ hashes++;
189
+ j++;
190
+ }
191
+ if (hashes >= 1 && hashes <= 6 && j < len && md.charCodeAt(j) === 32) {
192
+ j++;
193
+ const lineEnd = md.indexOf("\n", j);
194
+ const cleaned = stripHeadingFormatting(lineEnd === -1 ? md.slice(j) : md.slice(j, lineEnd));
195
+ if (cleaned) slugs.add(slugify(cleaned));
196
+ }
197
+ }
198
+ const nl = md.indexOf("\n", i);
199
+ if (nl === -1) break;
200
+ i = nl + 1;
201
+ }
202
+ return slugs;
203
+ }
204
+ function cleanFragments(md) {
205
+ const slugs = collectHeadingSlugs(md);
206
+ const len = md.length;
207
+ const lastGt = md.lastIndexOf(">");
208
+ let result = "";
209
+ let i = 0;
210
+ while (i < len) {
211
+ const tagEnd = md.charCodeAt(i) === 60 ? htmlTagEnd(md, i, lastGt) : -1;
212
+ if (tagEnd !== -1) {
213
+ result += md.slice(i, tagEnd);
214
+ i = tagEnd;
215
+ continue;
216
+ }
217
+ if (md.charCodeAt(i) === 91) {
218
+ const link = parseLink(md, i);
219
+ if (link && link.url.charCodeAt(0) === 35 && link.url.length > 1) {
220
+ const fragment = link.url.slice(1).split(" ")[0];
221
+ if (slugs.size > 0 ? !slugs.has(fragment) : true) {
222
+ result += link.text;
223
+ i = link.end;
224
+ continue;
225
+ }
226
+ }
227
+ }
228
+ result += md[i];
229
+ i++;
230
+ }
231
+ return result;
232
+ }
233
+ function cleanEmptyLinks(md) {
234
+ const len = md.length;
235
+ const lastGt = md.lastIndexOf(">");
236
+ let result = "";
237
+ let i = 0;
238
+ while (i < len) {
239
+ const tagEnd = md.charCodeAt(i) === 60 ? htmlTagEnd(md, i, lastGt) : -1;
240
+ if (tagEnd !== -1) {
241
+ result += md.slice(i, tagEnd);
242
+ i = tagEnd;
243
+ continue;
244
+ }
245
+ if (md.charCodeAt(i) === 91) {
246
+ const link = parseLink(md, i);
247
+ if (link) {
248
+ const url = link.url;
249
+ if (isEmptyLinkHref(url)) {
250
+ result += link.text;
251
+ i = link.end;
252
+ continue;
253
+ }
254
+ }
255
+ }
256
+ result += md[i];
257
+ i++;
258
+ }
259
+ return result;
260
+ }
261
+ function isAutolinkUri(s) {
262
+ if (!(s.startsWith("http://") || s.startsWith("https://") || s.startsWith("ftp://") || s.startsWith("mailto:"))) return false;
263
+ for (let i = 0; i < s.length; i++) {
264
+ const c = s.charCodeAt(i);
265
+ if (c === 32 || c === 60 || c === 62 || c === 10 || c === 13 || c === 9) return false;
266
+ }
267
+ return true;
268
+ }
269
+ function cleanRedundantLinks(md) {
270
+ const len = md.length;
271
+ const lastGt = md.lastIndexOf(">");
272
+ let result = "";
273
+ let i = 0;
274
+ while (i < len) {
275
+ const code = md.charCodeAt(i);
276
+ const tagEnd = code === 60 ? htmlTagEnd(md, i, lastGt) : -1;
277
+ if (tagEnd !== -1) {
278
+ result += md.slice(i, tagEnd);
279
+ i = tagEnd;
280
+ continue;
281
+ }
282
+ if (code === 91) {
283
+ const link = parseLink(md, i);
284
+ if (link && link.text === link.url) {
285
+ result += link.text;
286
+ i = link.end;
287
+ continue;
288
+ }
289
+ } else if (code === 60 && !isEscaped(md, i)) {
290
+ const close = md.indexOf(">", i + 1);
291
+ if (close !== -1) {
292
+ const inner = md.slice(i + 1, close);
293
+ if (isAutolinkUri(inner)) {
294
+ result += inner;
295
+ i = close + 1;
296
+ continue;
297
+ }
298
+ }
299
+ }
300
+ result += md[i];
301
+ i++;
302
+ }
303
+ return result;
304
+ }
305
+ function cleanSelfLinkHeadings(md) {
306
+ const len = md.length;
307
+ const lastGt = md.lastIndexOf(">");
308
+ let result = "";
309
+ let i = 0;
310
+ while (i < len) {
311
+ const tagEnd = md.charCodeAt(i) === 60 ? htmlTagEnd(md, i, lastGt) : -1;
312
+ if (tagEnd !== -1) {
313
+ result += md.slice(i, tagEnd);
314
+ i = tagEnd;
315
+ continue;
316
+ }
317
+ if (i === 0 || md.charCodeAt(i - 1) === 10) {
318
+ let hashes = 0;
319
+ let j = i;
320
+ while (j < len && md.charCodeAt(j) === 35) {
321
+ hashes++;
322
+ j++;
323
+ }
324
+ if (hashes >= 1 && hashes <= 6 && j < len && md.charCodeAt(j) === 32) {
325
+ j++;
326
+ if (j < len && md.charCodeAt(j) === 91) {
327
+ const link = parseLink(md, j);
328
+ if (link && link.url.charCodeAt(0) === 35) {
329
+ result += md.slice(i, j);
330
+ result += link.text;
331
+ i = link.end;
332
+ continue;
333
+ }
334
+ }
335
+ }
336
+ }
337
+ result += md[i];
338
+ i++;
339
+ }
340
+ return result;
341
+ }
342
+ function cleanEmptyImages(md) {
343
+ const len = md.length;
344
+ const lastGt = md.lastIndexOf(">");
345
+ let result = "";
346
+ let i = 0;
347
+ while (i < len) {
348
+ const tagEnd = md.charCodeAt(i) === 60 ? htmlTagEnd(md, i, lastGt) : -1;
349
+ if (tagEnd !== -1) {
350
+ result += md.slice(i, tagEnd);
351
+ i = tagEnd;
352
+ continue;
353
+ }
354
+ if (md.charCodeAt(i) === 33 && i + 1 < len && md.charCodeAt(i + 1) === 91) {
355
+ let j = i + 2;
356
+ const altStart = j;
357
+ while (j < len && md.charCodeAt(j) !== 93) j++;
358
+ if (j < len) {
359
+ if (md.slice(altStart, j).trim().length === 0) {
360
+ j++;
361
+ if (j < len && md.charCodeAt(j) === 40) {
362
+ let parenDepth = 1;
363
+ j++;
364
+ while (j < len && parenDepth > 0) {
365
+ if (md.charCodeAt(j) === 40) parenDepth++;
366
+ else if (md.charCodeAt(j) === 41) parenDepth--;
367
+ j++;
368
+ }
369
+ i = j;
370
+ continue;
371
+ }
372
+ }
373
+ }
374
+ }
375
+ result += md[i];
376
+ i++;
377
+ }
378
+ return result;
379
+ }
380
+ function cleanEmptyLinkText(md) {
381
+ const len = md.length;
382
+ const lastGt = md.lastIndexOf(">");
383
+ let result = "";
384
+ let i = 0;
385
+ while (i < len) {
386
+ const tagEnd = md.charCodeAt(i) === 60 ? htmlTagEnd(md, i, lastGt) : -1;
387
+ if (tagEnd !== -1) {
388
+ result += md.slice(i, tagEnd);
389
+ i = tagEnd;
390
+ continue;
391
+ }
392
+ if (md.charCodeAt(i) === 91) {
393
+ const link = parseLink(md, i);
394
+ if (link && link.text.trim().length === 0) {
395
+ i = link.end;
396
+ continue;
397
+ }
398
+ }
399
+ result += md[i];
400
+ i++;
401
+ }
402
+ return result;
403
+ }
404
+ function applyClean(md, opts) {
405
+ if (opts.emptyImages) md = cleanEmptyImages(md);
406
+ if (opts.emptyLinks) md = cleanEmptyLinks(md);
407
+ if (opts.emptyLinkText) md = cleanEmptyLinkText(md);
408
+ if (opts.redundantLinks) md = cleanRedundantLinks(md);
409
+ if (opts.selfLinkHeadings) md = cleanSelfLinkHeadings(md);
410
+ if (opts.fragments) md = cleanFragments(md);
411
+ return md;
412
+ }
3
413
  function createHtmlOutputState() {
4
414
  return { frames: [] };
5
415
  }
6
- function escapeHtml(value, attribute = false) {
7
- return value.replace(attribute ? /[&<>"]/g : /[&<>]/g, (character) => character === "&" ? "&amp;" : character === "<" ? "&lt;" : character === ">" ? "&gt;" : "&quot;");
8
- }
9
416
  function slugifyHeading(text) {
10
- return text.toLowerCase().replace(/[^a-z\d \t\n\r-]/g, "").trim().replace(/[ \t\n\r-]+/g, "-");
417
+ return slugify(stripHeadingFormatting(text));
11
418
  }
12
419
  function tagName(node, tagId) {
13
420
  switch (tagId) {
@@ -31,14 +438,8 @@ function resolveSafeUrl(url, options, image = false) {
31
438
  const resolved = resolveUrl(url, options.origin, options.clean);
32
439
  return isSafeHtmlUrl(resolved, image) ? resolved : void 0;
33
440
  }
34
- function safeAttributes(node, tagId, options) {
441
+ function safeAttributes(node, tagId) {
35
442
  const attributes = node.attributes;
36
- if (tagId === 26) {
37
- const href = attributes.href && resolveSafeUrl(attributes.href, options);
38
- if (!href) return void 0;
39
- const title = attributes.title === void 0 ? "" : ` title="${escapeHtml(attributes.title, true)}"`;
40
- return ` href="${escapeHtml(href, true)}"${title}`;
41
- }
42
443
  if (tagId === 33) {
43
444
  const start = parseUnsignedInteger(attributes.start);
44
445
  return start === void 0 ? "" : ` start="${start}"`;
@@ -134,14 +535,22 @@ function processHtmlOutputEvent(event, state, output, options) {
134
535
  if (tagId === 27) {
135
536
  if (type === 0) {
136
537
  const src = element.attributes.src && resolveSafeUrl(element.attributes.src, options, true);
137
- if (src) append(state, output, `<img src="${escapeHtml(src, true)}" alt="${escapeHtml(element.attributes.alt || "", true)}"${element.attributes.title === void 0 ? "" : ` title="${escapeHtml(element.attributes.title, true)}"`}>`);
538
+ if (src) {
539
+ append(state, output, `<img src="${escapeHtml(src, true)}" alt="${escapeHtml(element.attributes.alt || "", true)}"${element.attributes.title === void 0 ? "" : ` title="${escapeHtml(element.attributes.title, true)}"`}>`);
540
+ markRenderedChildContent(element);
541
+ }
138
542
  }
139
543
  return;
140
544
  }
545
+ if (tagId === 26) {
546
+ const rendered = safeAnchorOutput(element, options, type === 0);
547
+ if (rendered) append(state, output, rendered);
548
+ return;
549
+ }
141
550
  if (tagId === void 0) return;
142
551
  const name = tagName(element, tagId);
143
552
  if (!name) return;
144
- const attributes = safeAttributes(element, tagId, options);
553
+ const attributes = safeAttributes(element, tagId);
145
554
  if (attributes === void 0) return;
146
555
  append(state, output, type === 0 ? `<${name}${attributes}>` : `</${name}>`);
147
556
  }
@@ -181,12 +590,17 @@ function processPluginsForEvent(event, plugins, state, processEvent) {
181
590
  return false;
182
591
  }
183
592
  const INLINE_MARKER_TYPE = /* @__PURE__ */ new Uint8Array(113);
593
+ const MARKER_TYPE_MASK = 7;
594
+ const CAPTION_FRAME_SIZE = 4;
595
+ const CAPTION_OPEN = 1;
596
+ const CAPTION_INTERNAL_BREAK = 2;
597
+ const CAPTION_DEFAULT_SPACING = -1;
598
+ const CAPTION_NO_ANCHOR = -1;
184
599
  INLINE_MARKER_TYPE[14] = 1;
185
600
  INLINE_MARKER_TYPE[15] = 1;
186
601
  INLINE_MARKER_TYPE[91] = 1;
187
602
  INLINE_MARKER_TYPE[16] = 2;
188
603
  INLINE_MARKER_TYPE[17] = 2;
189
- INLINE_MARKER_TYPE[106] = 2;
190
604
  INLINE_MARKER_TYPE[18] = 3;
191
605
  INLINE_MARKER_TYPE[110] = 3;
192
606
  INLINE_MARKER_TYPE[111] = 3;
@@ -197,7 +611,7 @@ INLINE_MARKER_TYPE[82] = 5;
197
611
  INLINE_MARKER_TYPE[92] = 5;
198
612
  INLINE_MARKER_TYPE[81] = 6;
199
613
  function suppressesFormattingInPre(tagId) {
200
- return tagId === 26 || tagId === 46 || tagId === 110 || tagId === 111 || tagId >= 14 && tagId <= 21 || tagId >= 79 && tagId <= 83 || tagId >= 89 && tagId <= 94;
614
+ return tagId === 26 || tagId === 46 || tagId === 110 || tagId === 111 || tagId === 106 || tagId >= 14 && tagId <= 21 || tagId >= 79 && tagId <= 83 || tagId >= 89 && tagId <= 94;
201
615
  }
202
616
  function newlineRunBefore(buffer, index) {
203
617
  let run = 0;
@@ -210,6 +624,26 @@ function newlineRunBefore(buffer, index) {
210
624
  }
211
625
  return run;
212
626
  }
627
+ function newlineRunBeforePrefix(buffer, index, prefix) {
628
+ let fragment = index - 1;
629
+ let offset = fragment >= 0 ? buffer[fragment].length : 0;
630
+ for (let prefixIndex = prefix.length - 1; prefixIndex >= 0; prefixIndex--) {
631
+ while (offset === 0) {
632
+ if (--fragment < 0) return newlineRunBefore(buffer, index);
633
+ offset = buffer[fragment].length;
634
+ }
635
+ if (buffer[fragment].charCodeAt(--offset) !== prefix.charCodeAt(prefixIndex)) return newlineRunBefore(buffer, index);
636
+ }
637
+ let run = 0;
638
+ for (;;) {
639
+ while (offset === 0) {
640
+ if (--fragment < 0) return run;
641
+ offset = buffer[fragment].length;
642
+ }
643
+ if (buffer[fragment].charCodeAt(--offset) !== 10) return run;
644
+ run++;
645
+ }
646
+ }
213
647
  function recordItemMarker(state, index) {
214
648
  if (index !== 0 || newlineRunBefore(state.buffer, state.buffer.length - 1) !== 1) {
215
649
  state.emptyItemFragment = void 0;
@@ -217,7 +651,7 @@ function recordItemMarker(state, index) {
217
651
  }
218
652
  state.emptyItemFragment = state.buffer.length - 1;
219
653
  }
220
- function resolveItemMarker(state, atExit) {
654
+ function resolveItemMarker(state, atExit, unresolvedCaptionFragment = -1) {
221
655
  const fragment = state.emptyItemFragment;
222
656
  if (fragment === void 0) return;
223
657
  const buffer = state.buffer;
@@ -233,6 +667,14 @@ function resolveItemMarker(state, atExit) {
233
667
  }
234
668
  }
235
669
  if (first === -1 && !atExit) return;
670
+ if (!atExit && unresolvedCaptionFragment !== -1) {
671
+ let captionOpensItem = true;
672
+ for (let index = fragment + 1; index < unresolvedCaptionFragment; index++) if (hasNonWhitespace(buffer[index])) {
673
+ captionOpensItem = false;
674
+ break;
675
+ }
676
+ if (captionOpensItem) return;
677
+ }
236
678
  state.emptyItemFragment = void 0;
237
679
  if (first !== -1 && first !== 10) return;
238
680
  buffer[fragment] = `\n${buffer[fragment]}`;
@@ -295,9 +737,8 @@ function foldPreLinesToBr(value) {
295
737
  }
296
738
  return out;
297
739
  }
298
- function escapeRawHtmlText(value, depthMap) {
740
+ function escapeRawHtmlText(value, depthMap, protectLinkText) {
299
741
  const inTable = Boolean(depthMap[28]);
300
- const inLink = Boolean(depthMap[26]);
301
742
  let escaped = "";
302
743
  let copiedUntil = 0;
303
744
  let index = 0;
@@ -310,8 +751,8 @@ function escapeRawHtmlText(value, depthMap) {
310
751
  else if (code === 10) replacement = "&#10;";
311
752
  else if (code === 13) replacement = "&#13;";
312
753
  else if (inTable && code === 124) replacement = "&#124;";
313
- else if (inLink && code === 91) replacement = "&#91;";
314
- else if (inLink && code === 93) replacement = "&#93;";
754
+ else if (protectLinkText && code === 91) replacement = "&#91;";
755
+ else if (protectLinkText && code === 93) replacement = "&#93;";
315
756
  if (replacement) {
316
757
  escaped += value.slice(copiedUntil, index) + replacement;
317
758
  copiedUntil = index + 1;
@@ -459,13 +900,16 @@ function escapeGfmText(value, buffer, depthMap) {
459
900
  if (code === 10) {
460
901
  lineIndent = 0;
461
902
  orderedDigits = 0;
462
- } else if (lineIndent >= 0) if (code === 32 && lineIndent < 3) lineIndent++;
463
- else {
464
- orderedDigits = code >= 48 && code <= 57 ? 1 : 0;
465
- lineIndent = -1;
903
+ } else if (lineIndent >= 0) {
904
+ if (code === 32 && lineIndent < 3) lineIndent++;
905
+ else {
906
+ orderedDigits = code >= 48 && code <= 57 ? 1 : 0;
907
+ lineIndent = -1;
908
+ }
909
+ } else if (orderedDigits > 0) {
910
+ if (code >= 48 && code <= 57 && orderedDigits < 9) orderedDigits++;
911
+ else orderedDigits = 0;
466
912
  }
467
- else if (orderedDigits > 0) if (code >= 48 && code <= 57 && orderedDigits < 9) orderedDigits++;
468
- else orderedDigits = 0;
469
913
  }
470
914
  return copiedUntil === 0 ? value : escaped + value.slice(copiedUntil);
471
915
  }
@@ -513,11 +957,12 @@ function wrapText(value, col, width, prefix) {
513
957
  }
514
958
  function calculateNewLineConfig(node, depthMap, plainText) {
515
959
  const tagId = node.tagId;
960
+ if (plainText && tagId === 106) return NO_SPACING;
516
961
  if (tagId !== 25 && (depthMap[25] || 0) > 0 || plainText && tagId !== 22 && (depthMap[22] || 0) > 0) {
517
962
  if (plainText && tagId === 34) return [1, 1];
518
963
  return NO_SPACING;
519
964
  }
520
- const isBlockElement = tagId !== void 0 && (tagId >= 7 && tagId <= 12 || tagId === 35 || tagId === 36 || tagId === 25);
965
+ const isBlockElement = tagId !== void 0 && (tagId >= 7 && tagId <= 12 || tagId === 35 || tagId === 36 || tagId === 25 || tagId === 106);
521
966
  let currParent = node.parent;
522
967
  while (currParent) {
523
968
  if (currParent.tagHandler?.collapsesInnerWhiteSpace) {
@@ -536,7 +981,7 @@ function calculateNewLineConfig(node, depthMap, plainText) {
536
981
  function hasNonWhitespace(value) {
537
982
  for (let i = 0; i < value.length; i++) {
538
983
  const c = value.charCodeAt(i);
539
- if (c !== 32 && c !== 9 && c !== 10 && c !== 13) return true;
984
+ if (c !== 32 && c !== 9 && c !== 10 && c !== 12 && c !== 13) return true;
540
985
  }
541
986
  return false;
542
987
  }
@@ -564,15 +1009,31 @@ function trimBufferedWhitespacePosition(content, position) {
564
1009
  }
565
1010
  function dropEmptyMarker(buffer, packed, markerType) {
566
1011
  const idx = packed >> 3;
567
- if ((packed & 7) === markerType && idx < buffer.length) {
568
- for (let i = idx + 1; i < buffer.length; i++) {
569
- const fragment = buffer[i];
570
- if (fragment && hasNonWhitespace(fragment)) return -1;
1012
+ if ((packed & MARKER_TYPE_MASK) === markerType && idx < buffer.length) return dropEmptyLinkText(buffer, idx) ? idx : -1;
1013
+ return -1;
1014
+ }
1015
+ function resetRetractedCaptionFrames(frames, count, fragment) {
1016
+ if (!frames) return;
1017
+ for (let index = 0; index < count; index++) {
1018
+ const offset = index * CAPTION_FRAME_SIZE;
1019
+ if (frames[offset + 3] >= fragment) {
1020
+ frames[offset + 2] = frames[offset + 2] & -2;
1021
+ frames[offset + 3] = CAPTION_NO_ANCHOR;
571
1022
  }
572
- buffer.length = idx;
573
- return idx;
574
1023
  }
575
- return -1;
1024
+ }
1025
+ function dropEmptyLinkText(buffer, openFragment) {
1026
+ for (let index = openFragment + 1; index < buffer.length; index++) if (hasNonWhitespace(buffer[index])) return false;
1027
+ buffer.length = openFragment;
1028
+ return true;
1029
+ }
1030
+ function restoreCaptionBreakFlags(frames, snapshot, count) {
1031
+ if (!frames || !snapshot) return;
1032
+ const end = Math.min(count, snapshot.length);
1033
+ for (let index = 0; index < end; index++) {
1034
+ const offset = index * CAPTION_FRAME_SIZE + 2;
1035
+ frames[offset] = frames[offset] & -3 | snapshot[index];
1036
+ }
576
1037
  }
577
1038
  function maxBacktickRun(value) {
578
1039
  let max = 0;
@@ -671,15 +1132,19 @@ function flushPreFence(state) {
671
1132
  startCodeFence(state, state.buffer.length - 1, lang, state.listIndent);
672
1133
  state.lastContentCache = fence;
673
1134
  }
674
- function consumePendingPreChild(state, node, eventType) {
1135
+ function consumePendingPreChild(state, node, eventType, beforeFlush) {
675
1136
  if (eventType !== 0) return false;
676
1137
  if (node.type === 1) {
677
1138
  const element = node;
678
1139
  if (element.tagId === 23 && element.parent?.tagId === 34) state.preFencePending = false;
679
- else if (element.tagId !== 34) flushPreFence(state);
1140
+ else if (element.tagId !== 34 && element.tagId !== 106 && !suppressesFormattingInPre(element.tagId)) {
1141
+ beforeFlush();
1142
+ flushPreFence(state);
1143
+ }
680
1144
  return false;
681
1145
  }
682
1146
  if (hasNonWhitespace(node.value)) {
1147
+ beforeFlush();
683
1148
  flushPreFence(state);
684
1149
  return false;
685
1150
  }
@@ -759,8 +1224,12 @@ function getPlainTextOutput(node, eventType, state) {
759
1224
  if (tagId === 32 || tagId === 31) return (depthMap[28] || 0) > 1 || node.index === 0 ? "" : " ";
760
1225
  if (tagId === 27) {
761
1226
  const alt = node.attributes?.alt;
762
- if (alt !== void 0) return alt || void 0;
763
- return node.attributes?.title || resolveUrl(node.attributes?.src || "", state.options?.origin, state.options?.clean) || void 0;
1227
+ const clean = state.options?.clean;
1228
+ if ((clean === true || clean != null && clean !== false && clean.emptyImages === true) && !(alt !== void 0 && alt.trim().length > 0)) return void 0;
1229
+ const src = node.attributes?.src || "";
1230
+ const output = alt !== void 0 ? alt || void 0 : node.attributes?.title || resolveUrl(isDataUrl(src) ? "" : src, state.options?.origin, state.options?.clean) || void 0;
1231
+ if (output && hasNonWhitespace(output)) markRenderedChildContent(node);
1232
+ return output;
764
1233
  }
765
1234
  if (tagId === 81) return "\"";
766
1235
  return;
@@ -769,6 +1238,7 @@ function getPlainTextOutput(node, eventType, state) {
769
1238
  }
770
1239
  function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverrideHandlers) {
771
1240
  const outputFormat = options.format === "html" || options.format === "text" ? options.format : "markdown";
1241
+ const plainText = outputFormat === "text";
772
1242
  const htmlState = outputFormat === "html" ? createHtmlOutputState() : void 0;
773
1243
  const state = {
774
1244
  options,
@@ -778,7 +1248,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
778
1248
  listIndentWidths: [],
779
1249
  blockquotes: [],
780
1250
  bufferedBlockquoteDepth: 0,
781
- plainText: options.format === "text",
1251
+ plainText,
782
1252
  emptyItemFragment: void 0
783
1253
  };
784
1254
  const bufferScan = [
@@ -791,22 +1261,182 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
791
1261
  let inRawHtmlRegion = false;
792
1262
  const openMarkers = [];
793
1263
  let openMarkerCount = 0;
1264
+ let captionFrames;
1265
+ let captionFrameCount = 0;
1266
+ let captionBoundary = 0;
1267
+ let captionBoundarySpacing = 0;
1268
+ let captionBreakRun = 0;
794
1269
  const gfmLifecycle = { openCodeSpans: [] };
795
1270
  let openLinkFragment = -1;
1271
+ let openLinkCaptionBreakRun = 0;
1272
+ let openLinkCaptionFlags;
1273
+ const clean = options.clean;
1274
+ const cleanEmptyLinkText = clean === true || clean !== null && typeof clean === "object" && clean.emptyLinkText === true;
1275
+ let rawHtmlLink;
796
1276
  let lastYieldedLength = 0;
797
1277
  let hasYieldedContent = false;
798
1278
  let preserveLeadingWhitespace = false;
1279
+ function captionNeedsPreparation() {
1280
+ return captionBoundary !== 0 || captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1281
+ }
1282
+ function pushCaptionFrame(element, handler) {
1283
+ let enterSpacing = 0;
1284
+ let exitSpacing = 0;
1285
+ if (!state.depthMap[34] && figcaptionOwnsBlockSpacing(element, plainText)) {
1286
+ const spacing = handler?.spacing;
1287
+ if (spacing) {
1288
+ enterSpacing = spacing[0];
1289
+ exitSpacing = spacing[1];
1290
+ } else {
1291
+ enterSpacing = CAPTION_DEFAULT_SPACING;
1292
+ exitSpacing = CAPTION_DEFAULT_SPACING;
1293
+ }
1294
+ }
1295
+ const frames = captionFrames || (captionFrames = []);
1296
+ const offset = captionFrameCount * CAPTION_FRAME_SIZE;
1297
+ frames[offset] = enterSpacing;
1298
+ frames[offset + 1] = exitSpacing;
1299
+ frames[offset + 2] = 0;
1300
+ frames[offset + 3] = CAPTION_NO_ANCHOR;
1301
+ captionFrameCount++;
1302
+ }
1303
+ function captionSpacingPrefix(spacing, includeListIndent, beforeFragment) {
1304
+ if (spacing === 0) return "";
1305
+ if (spacing === CAPTION_DEFAULT_SPACING) spacing = DEFAULT_BLOCK_SPACING[0];
1306
+ const indent = includeListIndent ? state.listIndent : "";
1307
+ const blockPrefix = blockOpenPrefix(state.buffer, indent, beforeFragment);
1308
+ const trailingNewLines = newlineRunBeforePrefix(state.buffer, beforeFragment, indent);
1309
+ if (blockPrefix === void 0 && trailingNewLines === 0) return "";
1310
+ const missingNewLines = Math.max(0, spacing - trailingNewLines);
1311
+ const prefix = missingNewLines === 0 ? blockPrefix || "" : `${"\n".repeat(missingNewLines)}${indent}`;
1312
+ if (!prefix) return "";
1313
+ const lastIndex = beforeFragment - 1;
1314
+ const last = state.buffer[lastIndex];
1315
+ if (prefix.charCodeAt(0) === 10 && last?.endsWith(" ")) {
1316
+ const trimmed = last.slice(0, -1);
1317
+ state.buffer[lastIndex] = trimmed;
1318
+ if (state.lastContentCache === last) state.lastContentCache = trimmed;
1319
+ state.lastTextNode = void 0;
1320
+ }
1321
+ return prefix;
1322
+ }
1323
+ function appendCaptionSpacing(spacing, includeListIndent) {
1324
+ const prefix = captionSpacingPrefix(spacing, includeListIndent, state.buffer.length);
1325
+ if (!prefix) return false;
1326
+ state.buffer.push(prefix);
1327
+ state.lastContentCache = prefix;
1328
+ state.pendingInlineWhitespace = false;
1329
+ return true;
1330
+ }
1331
+ function prepareCaptionOutput(explicitTop, includeBoundaryListIndent = true) {
1332
+ let changed = false;
1333
+ if (captionBoundary === 1) changed = appendCaptionSpacing(captionBoundarySpacing, includeBoundaryListIndent);
1334
+ const frames = captionFrames;
1335
+ if (frames) for (let index = 0; index < captionFrameCount; index++) {
1336
+ const offset = index * CAPTION_FRAME_SIZE;
1337
+ let flags = frames[offset + 2];
1338
+ if (flags & CAPTION_OPEN) continue;
1339
+ const anchor = frames[offset + 3];
1340
+ const beforeFragment = anchor === CAPTION_NO_ANCHOR ? state.buffer.length : anchor;
1341
+ let opening = flags & CAPTION_INTERNAL_BREAK ? "" : captionSpacingPrefix(frames[offset], true, beforeFragment);
1342
+ flags |= CAPTION_OPEN;
1343
+ if (!plainText && (!explicitTop || index !== captionFrameCount - 1)) opening += "*";
1344
+ if (opening) {
1345
+ if (beforeFragment === state.buffer.length) {
1346
+ state.buffer.push(opening);
1347
+ state.lastContentCache = opening;
1348
+ } else {
1349
+ const anchored = state.buffer[beforeFragment];
1350
+ const replacement = opening + anchored;
1351
+ state.buffer[beforeFragment] = replacement;
1352
+ const codeSpan = gfmLifecycle.openCodeSpans.at(-1);
1353
+ if (codeSpan?.fragment === beforeFragment) codeSpan.prefix = opening + codeSpan.prefix;
1354
+ if (state.lastContentCache === anchored) state.lastContentCache = replacement;
1355
+ }
1356
+ changed = true;
1357
+ }
1358
+ frames[offset + 2] = flags;
1359
+ }
1360
+ return changed;
1361
+ }
1362
+ function consumeCaptionTransition(isInlineElement, tagId) {
1363
+ captionBoundary = isInlineElement && tagId !== 27 && tagId !== 6 ? 2 : 0;
1364
+ }
1365
+ function anchorPendingCaptions(fragment) {
1366
+ const frames = captionFrames;
1367
+ if (!frames) return;
1368
+ for (let index = 0; index < captionFrameCount; index++) {
1369
+ const offset = index * CAPTION_FRAME_SIZE;
1370
+ if ((frames[offset + 2] & CAPTION_OPEN) === 0 && frames[offset + 3] === CAPTION_NO_ANCHOR) frames[offset + 3] = fragment;
1371
+ }
1372
+ }
1373
+ function commitCaptionFrames() {
1374
+ const frames = captionFrames;
1375
+ if (!frames) return;
1376
+ for (let index = 0; index < captionFrameCount; index++) {
1377
+ const offset = index * CAPTION_FRAME_SIZE;
1378
+ if (frames[offset + 2] & CAPTION_OPEN) frames[offset + 3] = CAPTION_NO_ANCHOR;
1379
+ }
1380
+ }
1381
+ function flushCaptionBreakRun() {
1382
+ if (captionBreakRun === 0) return false;
1383
+ let index = state.buffer.length;
1384
+ while (index !== 0) {
1385
+ const value = state.buffer[--index];
1386
+ let end = value.length;
1387
+ while (end !== 0 && value.charCodeAt(end - 1) === 32) end--;
1388
+ if (end === value.length) break;
1389
+ if (end !== 0) {
1390
+ state.buffer[index] = value.slice(0, end);
1391
+ state.buffer.length = index + 1;
1392
+ break;
1393
+ }
1394
+ state.buffer.length = index;
1395
+ }
1396
+ const output = plainText ? "\n".repeat(captionBreakRun) : ` \n${state.listIndent}`.repeat(captionBreakRun);
1397
+ captionBreakRun = 0;
1398
+ state.buffer.push(output);
1399
+ state.lastContentCache = output;
1400
+ return true;
1401
+ }
1402
+ function finishCaptionFrame() {
1403
+ if (captionFrameCount === 0) return;
1404
+ const offset = (captionFrameCount - 1) * CAPTION_FRAME_SIZE;
1405
+ const frames = captionFrames;
1406
+ const exitSpacing = frames[offset + 1];
1407
+ const opened = (frames[offset + 2] & CAPTION_OPEN) !== 0;
1408
+ const anchor = frames[offset + 3];
1409
+ frames.length = offset;
1410
+ captionFrameCount--;
1411
+ if (opened) {
1412
+ captionBoundary = exitSpacing === 0 ? 0 : 1;
1413
+ captionBoundarySpacing = exitSpacing;
1414
+ } else if (anchor !== CAPTION_NO_ANCHOR) {
1415
+ state.buffer.length = anchor;
1416
+ state.lastContentCache = state.buffer.at(-1);
1417
+ state.lastTextNode = void 0;
1418
+ } else if (captionBreakRun !== 0 && captionFrameCount === 0) captionBoundary = 2;
1419
+ }
799
1420
  function processTextNode(textNode, lastNode, lastChar) {
800
1421
  if (textNode.value) {
801
1422
  if (textNode.excludedFromMarkdown) return;
1423
+ const ownsCaptionSpace = captionNeedsPreparation();
1424
+ if (ownsCaptionSpace) {
1425
+ if (textNode.value.charCodeAt(0) === 32) textNode.value = textNode.value.slice(1);
1426
+ if (!hasNonWhitespace(textNode.value)) return;
1427
+ flushCaptionBreakRun();
1428
+ prepareCaptionOutput(false);
1429
+ commitCaptionFrames();
1430
+ captionBoundary = 0;
1431
+ }
802
1432
  if (state.pendingInlineWhitespace) {
803
1433
  if (!textNode.value.trim()) return;
804
1434
  if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(textNode.value[0] || "")) textNode.value = ` ${textNode.value}`;
805
1435
  state.pendingInlineWhitespace = false;
806
1436
  }
807
- if (state.plainText && state.depthMap[34] && state.buffer.length === 0) preserveLeadingWhitespace = true;
1437
+ if (plainText && state.depthMap[34] && state.buffer.length === 0) preserveLeadingWhitespace = true;
808
1438
  if (textNode.value === " " && (lastChar === " " || lastChar === "\n" || lastChar === " " || lastChar === "\r")) return;
809
- if (!(state.plainText && state.depthMap[34]) && shouldAddSpacingBeforeText(lastChar, lastNode, textNode)) textNode.value = ` ${textNode.value}`;
1439
+ if (!ownsCaptionSpace && !(plainText && state.depthMap[34]) && shouldAddSpacingBeforeText(lastChar, lastNode, textNode)) textNode.value = ` ${textNode.value}`;
810
1440
  if ((state.depthMap[34] || 0) > 0 && (state.depthMap[25] || 0) > 0) {
811
1441
  const indent = state.listIndent;
812
1442
  let value = textNode.value.replace(/\n(?!\n|$)/g, `\n${indent}`);
@@ -817,8 +1447,12 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
817
1447
  const insideRawHtmlBlock = isInsideRawHtmlBlock(state.depthMap);
818
1448
  let rawHtmlMarkdown = false;
819
1449
  if (insideRawHtmlBlock) rawHtmlMarkdown = trackRawHtmlMarkdownContext(state.buffer, bufferScan);
820
- if (!state.plainText && !state.depthMap[34] && insideRawHtmlBlock) textNode.value = escapeRawHtmlText(textNode.value, state.depthMap);
821
- if (!state.plainText && !state.depthMap[34] && !state.depthMap[23] && (!insideRawHtmlBlock || rawHtmlMarkdown) && mayNeedGfmTextEscape(textNode.value, state.buffer, state.depthMap) && (!insideRawHtmlBlock || !lineOpensRawHtmlBlock(state.buffer, bufferScan))) textNode.value = escapeGfmText(textNode.value, state.buffer, state.depthMap);
1450
+ if (!plainText && !state.depthMap[34] && insideRawHtmlBlock) {
1451
+ let parent = rawHtmlLink ? textNode.parent : void 0;
1452
+ while (parent && parent !== rawHtmlLink) parent = parent.parent;
1453
+ textNode.value = escapeRawHtmlText(textNode.value, state.depthMap, rawHtmlLink !== void 0 && parent === rawHtmlLink);
1454
+ }
1455
+ if (!plainText && !state.depthMap[34] && !state.depthMap[23] && (!insideRawHtmlBlock || rawHtmlMarkdown) && mayNeedGfmTextEscape(textNode.value, state.buffer, state.depthMap) && (!insideRawHtmlBlock || !lineOpensRawHtmlBlock(state.buffer, bufferScan))) textNode.value = escapeGfmText(textNode.value, state.buffer, state.depthMap);
822
1456
  if (textNode.generatedMarkdown && textNode.value) textNode.value = `${textNode.generatedMarkdown.prefix}${textNode.value}${textNode.generatedMarkdown.suffix}`;
823
1457
  const wrapWidth = state.options?.wrapWidth;
824
1458
  if (wrapWidth && canWrapHere(state.depthMap)) {
@@ -829,7 +1463,14 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
829
1463
  state.buffer.push(textNode.value);
830
1464
  state.lastContentCache = textNode.value;
831
1465
  }
832
- if (openMarkerCount && hasNonWhitespace(textNode.value)) openMarkerCount = 0;
1466
+ if (openMarkerCount || openLinkFragment >= 0) {
1467
+ const hasVisibleText = textNode.containsWhitespace === false || hasNonWhitespace(textNode.value);
1468
+ if (openLinkFragment >= 0 && hasVisibleText) openLinkFragment = -openLinkFragment - 2;
1469
+ if (openMarkerCount && hasVisibleText) {
1470
+ openMarkerCount = 0;
1471
+ commitCaptionFrames();
1472
+ }
1473
+ }
833
1474
  }
834
1475
  state.lastTextNode = textNode;
835
1476
  }
@@ -855,9 +1496,31 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
855
1496
  const lastNode = state.lastNode;
856
1497
  state.lastNode = event.node;
857
1498
  const buff = state.buffer;
858
- if (!state.plainText && state.preFencePending && consumePendingPreChild(state, node, eventType)) return;
1499
+ if (!plainText && state.preFencePending) {
1500
+ const preparePendingPreFence = () => {
1501
+ if (captionNeedsPreparation()) {
1502
+ flushCaptionBreakRun();
1503
+ prepareCaptionOutput(false);
1504
+ captionBoundary = 0;
1505
+ }
1506
+ };
1507
+ if (node.type === 1) {
1508
+ const pendingElement = node;
1509
+ const pendingHandler = pendingElement.tagHandler;
1510
+ const literalOverride = eventType === 0 ? pendingHandler?.literalEnter : pendingHandler?.literalExit;
1511
+ if (literalOverride && pendingElement.tagId === 23 && pendingElement.parent?.tagId === 34) state.preFenceLang = getLanguageFromClass(pendingElement.attributes?.class);
1512
+ if (pendingElement.pluginOutput?.length || literalOverride) {
1513
+ preparePendingPreFence();
1514
+ flushPreFence(state);
1515
+ } else if (consumePendingPreChild(state, node, eventType, preparePendingPreFence)) return;
1516
+ } else if (consumePendingPreChild(state, node, eventType, preparePendingPreFence)) return;
1517
+ }
859
1518
  let lastBuffEntry = buff.at(-1);
860
1519
  let lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
1520
+ if (!lastChar && state.pendingInlineWhitespace && eventType === 0) {
1521
+ const code = lastOutputChar(buff);
1522
+ if (code !== -1) lastChar = String.fromCharCode(code);
1523
+ }
861
1524
  if (node.type === 2 && eventType === 0) {
862
1525
  processTextNode(node, lastNode, lastChar);
863
1526
  return;
@@ -865,6 +1528,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
865
1528
  if (node.type !== 1) return;
866
1529
  const element = node;
867
1530
  const handler = node.tagHandler;
1531
+ const tagId = element.tagId;
868
1532
  const insideRawHtmlRegion = isInsideRawHtmlBlock(state.depthMap);
869
1533
  if (insideRawHtmlRegion && !inRawHtmlRegion) {
870
1534
  bufferScan[0] = false;
@@ -873,9 +1537,26 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
873
1537
  }
874
1538
  if (eventType === 0 && handler === breakHandler && !element.pluginOutput?.length) {
875
1539
  const inPre = state.depthMap[34] !== 0;
876
- let breakOutput = state.plainText ? "\n" : renderBreak(element, state);
877
- if (state.plainText && !inPre && lastChar === "\n") {
878
- if ((lastBuffEntry.length > 1 ? lastBuffEntry.charAt(lastBuffEntry.length - 2) : buff.length > 1 ? buff[buff.length - 2]?.at(-1) : void 0) === "\n") breakOutput = void 0;
1540
+ let breakOutput = plainText ? "\n" : renderBreak(element, state);
1541
+ if (captionBoundary !== 0 || captionFrameCount !== 0) {
1542
+ const pendingCaption = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1543
+ if (!inPre && breakOutput && !hasNonWhitespace(breakOutput) && buff.length === 0 && !hasYieldedContent && state.blockquotes.length === 0 && pendingCaption) breakOutput = void 0;
1544
+ if (breakOutput && hasNonWhitespace(breakOutput) && captionNeedsPreparation()) {
1545
+ flushCaptionBreakRun();
1546
+ prepareCaptionOutput(false);
1547
+ commitCaptionFrames();
1548
+ consumeCaptionTransition(false, 6);
1549
+ lastBuffEntry = buff.at(-1);
1550
+ lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
1551
+ }
1552
+ }
1553
+ if (plainText && !inPre) {
1554
+ let trailingNewLines = captionBreakRun;
1555
+ if (lastChar === "\n") {
1556
+ trailingNewLines++;
1557
+ if ((lastBuffEntry.length > 1 ? lastBuffEntry.charAt(lastBuffEntry.length - 2) : buff.length > 1 ? buff[buff.length - 2]?.at(-1) : void 0) === "\n") trailingNewLines++;
1558
+ }
1559
+ if (trailingNewLines >= 2) breakOutput = void 0;
879
1560
  }
880
1561
  if (state.pendingInlineWhitespace) state.pendingInlineWhitespace = false;
881
1562
  const lastFragment = state.lastContentCache;
@@ -898,32 +1579,46 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
898
1579
  state.lastTextNode = void 0;
899
1580
  }
900
1581
  }
901
- if (breakOutput) {
1582
+ const pendingCaption = captionFrameCount !== 0 && (captionFrames[(captionFrameCount - 1) * CAPTION_FRAME_SIZE + 2] & CAPTION_OPEN) === 0;
1583
+ if (breakOutput && pendingCaption && !hasNonWhitespace(breakOutput)) {
1584
+ for (let index = 0; index < captionFrameCount; index++) {
1585
+ const offset = index * CAPTION_FRAME_SIZE + 2;
1586
+ if ((captionFrames[offset] & CAPTION_OPEN) === 0) captionFrames[offset] = captionFrames[offset] | CAPTION_INTERNAL_BREAK;
1587
+ }
1588
+ captionBreakRun++;
1589
+ } else if (breakOutput) {
902
1590
  buff.push(breakOutput);
903
1591
  state.lastContentCache = breakOutput;
904
1592
  if (openMarkerCount && hasNonWhitespace(breakOutput)) openMarkerCount = 0;
905
1593
  }
906
1594
  return;
907
1595
  }
908
- let secondLastChar;
909
- if (lastBuffEntry && lastBuffEntry.length > 1) secondLastChar = lastBuffEntry.charAt(lastBuffEntry.length - 2);
910
- else if (buff.length > 1) {
911
- const prevBuff = buff[buff.length - 2];
912
- if (prevBuff) secondLastChar = prevBuff.charAt(prevBuff.length - 1);
913
- }
914
1596
  let output;
915
1597
  if (element.pluginOutput?.length) {
916
1598
  output = element.pluginOutput;
917
1599
  element.pluginOutput = void 0;
918
1600
  }
919
- let lastFragment = state.lastContentCache;
1601
+ let captionBufferChanged = false;
920
1602
  const eventFn = eventType === 0 ? "enter" : "exit";
921
1603
  const isInlineElement = handler?.isInline === true;
922
1604
  let gfmAction;
923
1605
  let handlerOutput;
924
- const suppressedInPre = !state.plainText && (state.depthMap[34] || 0) > 0 && suppressesFormattingInPre(element.tagId);
1606
+ const suppressedInPre = !plainText && (state.depthMap[34] || 0) > 0 && suppressesFormattingInPre(tagId) && !(eventType === 0 ? handler?.literalEnter : handler?.literalExit);
925
1607
  if (!output && !suppressedInPre && handler?.[eventFn]) {
926
- const res = state.plainText ? getPlainTextOutput(element, eventType, state) : handler[eventFn]({
1608
+ if (openLinkFragment >= 0 && eventType === 1 && tagId === 26) {
1609
+ if (dropEmptyLinkText(buff, openLinkFragment)) {
1610
+ if (captionFrameCount !== 0) {
1611
+ captionBreakRun = openLinkCaptionBreakRun;
1612
+ restoreCaptionBreakFlags(captionFrames, openLinkCaptionFlags, captionFrameCount);
1613
+ resetRetractedCaptionFrames(captionFrames, captionFrameCount, openLinkFragment);
1614
+ }
1615
+ state.lastContentCache = buff.at(-1);
1616
+ state.lastTextNode = void 0;
1617
+ openLinkFragment = -1;
1618
+ return;
1619
+ }
1620
+ }
1621
+ const res = plainText ? getPlainTextOutput(element, eventType, state) : handler[eventFn]({
927
1622
  node: element,
928
1623
  state
929
1624
  });
@@ -936,32 +1631,98 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
936
1631
  gfmAction = res;
937
1632
  handlerOutput = consumeGfmAction(res, state, gfmLifecycle);
938
1633
  if (handlerOutput) output = [handlerOutput];
939
- if (res._tag === "BlockquoteExit") {
940
- lastFragment = state.lastContentCache;
941
- lastBuffEntry = buff.at(-1);
942
- lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
943
- secondLastChar = lastBuffEntry && lastBuffEntry.length > 1 ? lastBuffEntry.charAt(lastBuffEntry.length - 2) : buff.length > 1 ? buff[buff.length - 2]?.at(-1) : void 0;
1634
+ if (res._tag === "BlockquoteExit") captionBufferChanged = true;
1635
+ }
1636
+ }
1637
+ if (captionBreakRun && !(tagId === 106 && eventType === 1) && output) {
1638
+ flushCaptionBreakRun();
1639
+ if (gfmAction?._tag !== "BlockquoteEnter") anchorPendingCaptions(state.buffer.length);
1640
+ captionBufferChanged = true;
1641
+ }
1642
+ const captionEvent = tagId === 106;
1643
+ let captionTransition = false;
1644
+ if (captionEvent || captionBoundary !== 0 || captionFrameCount !== 0) {
1645
+ const captionEnter = captionEvent && eventType === 0 && !state.depthMap[34];
1646
+ const captionExit = captionEvent && eventType === 1 && !state.depthMap[34];
1647
+ if (captionEnter) pushCaptionFrame(element, handler);
1648
+ let dropBlockquoteOutput = false;
1649
+ if (captionBoundary === 1 && eventType === 0 && tagId === 22) {
1650
+ captionBufferChanged = appendCaptionSpacing(captionBoundarySpacing, false) || captionBufferChanged;
1651
+ captionTransition = true;
1652
+ captionBoundary = 0;
1653
+ dropBlockquoteOutput = true;
1654
+ output = void 0;
1655
+ handlerOutput = void 0;
1656
+ }
1657
+ let meaningfulOutput = !dropBlockquoteOutput && output?.some(hasNonWhitespace) === true;
1658
+ if (meaningfulOutput && handlerOutput !== void 0) {
1659
+ const markerType = INLINE_MARKER_TYPE[tagId];
1660
+ const literal = eventType === 0 ? handler?.literalEnter : handler?.literalExit;
1661
+ if ((markerType || tagId === 26 && eventType === 0) && !literal) {
1662
+ if (captionBoundary === 1) {
1663
+ captionBufferChanged = appendCaptionSpacing(captionBoundarySpacing, true) || captionBufferChanged;
1664
+ captionTransition = true;
1665
+ captionBoundary = 2;
1666
+ }
1667
+ if (eventType === 0) {
1668
+ anchorPendingCaptions(state.buffer.length);
1669
+ captionTransition = true;
1670
+ }
1671
+ meaningfulOutput = false;
944
1672
  }
945
1673
  }
1674
+ const defaultCaptionExit = captionExit && handlerOutput !== void 0 && !handler?.literalExit;
1675
+ if (defaultCaptionExit) meaningfulOutput = false;
1676
+ if (captionExit && captionFrameCount !== 0) {
1677
+ const offset = (captionFrameCount - 1) * CAPTION_FRAME_SIZE;
1678
+ const opened = (captionFrames[offset + 2] & CAPTION_OPEN) !== 0;
1679
+ if (!opened && defaultCaptionExit) {
1680
+ output = void 0;
1681
+ handlerOutput = void 0;
1682
+ } else if (meaningfulOutput && captionNeedsPreparation()) {
1683
+ if (flushCaptionBreakRun()) captionBufferChanged = true;
1684
+ captionBufferChanged = prepareCaptionOutput(false) || captionBufferChanged;
1685
+ captionTransition = true;
1686
+ consumeCaptionTransition(isInlineElement, tagId);
1687
+ }
1688
+ finishCaptionFrame();
1689
+ if (!opened && flushCaptionBreakRun()) captionBufferChanged = true;
1690
+ } else if (meaningfulOutput && captionNeedsPreparation()) {
1691
+ captionBufferChanged = prepareCaptionOutput(captionEnter, tagId !== 25) || captionBufferChanged;
1692
+ captionTransition = true;
1693
+ consumeCaptionTransition(isInlineElement, tagId);
1694
+ }
1695
+ if (meaningfulOutput) commitCaptionFrames();
1696
+ }
1697
+ const lastFragment = state.lastContentCache;
1698
+ if (captionBufferChanged) {
1699
+ lastBuffEntry = buff.at(-1);
1700
+ lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
1701
+ }
1702
+ const secondLastChar = lastBuffEntry && lastBuffEntry.length > 1 ? lastBuffEntry.charAt(lastBuffEntry.length - 2) : buff.length > 1 ? buff[buff.length - 2]?.at(-1) : void 0;
1703
+ if (element.tagId === 26) {
1704
+ if (eventType === 0) rawHtmlLink = insideRawHtmlRegion && handlerOutput !== void 0 && !handler?.literalExit ? element : void 0;
1705
+ else rawHtmlLink = void 0;
946
1706
  }
947
1707
  let lastNewLines = 0;
948
1708
  if (lastChar === "\n") lastNewLines++;
949
1709
  if (secondLastChar === "\n") lastNewLines++;
950
1710
  if (eventType === 1 && openMarkerCount) {
951
- const markerType = handlerOutput === void 0 ? 0 : INLINE_MARKER_TYPE[element.tagId];
952
- if (markerType && (element.tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && !handler?.literalExit) {
1711
+ const markerType = handlerOutput === void 0 ? 0 : INLINE_MARKER_TYPE[tagId];
1712
+ if (markerType && (tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && !handler?.literalExit) {
953
1713
  const idx = dropEmptyMarker(buff, openMarkers[--openMarkerCount], markerType);
954
1714
  if (idx >= 0) {
1715
+ resetRetractedCaptionFrames(captionFrames, captionFrameCount, idx);
955
1716
  state.lastContentCache = idx > 0 ? buff[idx - 1] : void 0;
956
1717
  return;
957
1718
  }
958
1719
  openMarkerCount = 0;
959
1720
  }
960
1721
  }
961
- if (element.tagId === 6 && !state.depthMap[34] && output?.length === 1 && output[0] === "\n" && lastChar === "\n" && secondLastChar === "\n") output = void 0;
962
- const newLineConfig = calculateNewLineConfig(node, state.depthMap, state.plainText === true);
1722
+ if (tagId === 6 && !state.depthMap[34] && output?.length === 1 && output[0] === "\n" && lastChar === "\n" && secondLastChar === "\n") output = void 0;
1723
+ const newLineConfig = suppressedInPre ? NO_SPACING : calculateNewLineConfig(node, state.depthMap, plainText);
963
1724
  const quoteAtStart = eventType === 0 && state.blockquotes.at(-1)?.fragment === state.buffer.length;
964
- const configuredNewLines = quoteAtStart ? 0 : eventType === 1 && element.tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, newLineConfig[eventType] || 0) : newLineConfig[eventType] || 0;
1725
+ const configuredNewLines = quoteAtStart || captionEvent || captionTransition ? 0 : eventType === 1 && tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, newLineConfig[eventType] || 0) : newLineConfig[eventType] || 0;
965
1726
  let effectiveLastNewLines = lastNewLines;
966
1727
  if (eventType === 1 && output) for (let i = output.length - 1; i >= 0; i--) {
967
1728
  const frag = output[i];
@@ -970,19 +1731,24 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
970
1731
  break;
971
1732
  }
972
1733
  }
973
- const newLines = Math.max(0, configuredNewLines - effectiveLastNewLines);
1734
+ let newLines = Math.max(0, configuredNewLines - effectiveLastNewLines);
1735
+ if (newLines > 0 && buff.length === 0 && !hasYieldedContent) newLines = 0;
974
1736
  if (state.pendingInlineWhitespace) {
975
1737
  const firstOutput = output?.[0]?.[0] || "";
976
1738
  if (eventType === 0) {
977
- if (!isInlineElement || element.tagId === 6 || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
1739
+ if (!isInlineElement || tagId === 6 || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
978
1740
  else if (firstOutput) {
979
- if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(firstOutput)) state.buffer.push(" ");
1741
+ if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(firstOutput)) {
1742
+ state.buffer.push(" ");
1743
+ state.lastContentCache = " ";
1744
+ lastChar = " ";
1745
+ }
980
1746
  state.pendingInlineWhitespace = false;
981
1747
  }
982
1748
  } else if (!isInlineElement || newLines > 0) state.pendingInlineWhitespace = false;
983
1749
  }
984
1750
  if (newLines > 0) {
985
- if (!buff.length) {
1751
+ if (!buff.length && !captionEvent && !captionTransition) {
986
1752
  if (output) {
987
1753
  for (const fragment of output) if (fragment) {
988
1754
  state.buffer.push(fragment);
@@ -998,9 +1764,10 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
998
1764
  buff[buff.length - 1] = buff.at(-1).substring(0, buff.at(-1).length - 1);
999
1765
  state.lastTextNode = void 0;
1000
1766
  }
1001
- if (eventType === 0) if (output) output.unshift(newlinesStr);
1002
- else output = [newlinesStr];
1003
- else if (output) output.push(newlinesStr);
1767
+ if (eventType === 0) {
1768
+ if (output) output.unshift(newlinesStr);
1769
+ else output = [newlinesStr];
1770
+ } else if (output) output.push(newlinesStr);
1004
1771
  else output = [newlinesStr];
1005
1772
  } else if (lastFragment && state.lastTextNode?.containsWhitespace && (!!node.parent || isInlineElement) && "value" in state.lastTextNode && typeof state.lastTextNode.value === "string") {
1006
1773
  let parent = node.parent;
@@ -1016,7 +1783,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1016
1783
  const collapsesWhiteSpace = node.tagHandler?.collapsesInnerWhiteSpace;
1017
1784
  const hasSpacing = node.tagHandler?.spacing && Array.isArray(node.tagHandler.spacing);
1018
1785
  const isBlockElement = !isInlineElement && !collapsesWhiteSpace && configuredNewLines > 0;
1019
- if (!quoteAtStart && (element.tagId === 6 && output?.[0]?.endsWith("\n") && !parentInPre || (!isInlineElement || eventType === 1) && !isBlockElement && !(collapsesWhiteSpace && eventType === 0) && !(hasSpacing && eventType === 0))) {
1786
+ if (!quoteAtStart && (tagId === 6 && output?.[0]?.endsWith("\n") && !parentInPre || (!isInlineElement || eventType === 1) && !isBlockElement && !(collapsesWhiteSpace && eventType === 0) && !(hasSpacing && eventType === 0))) {
1020
1787
  const originalLength = lastFragment.length;
1021
1788
  const trimmed = trimAsciiWhitespaceEnd(lastFragment);
1022
1789
  if (originalLength - trimmed.length > 0) {
@@ -1027,7 +1794,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1027
1794
  state.lastTextNode = void 0;
1028
1795
  }
1029
1796
  }
1030
- if (element.tagId !== 6 && output?.[0]?.[0] && eventType === 0 && !node.tagHandler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0], state)) {
1797
+ if (!captionTransition && tagId !== 6 && output?.[0]?.[0] && eventType === 0 && !handler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0], state)) {
1031
1798
  state.buffer.push(" ");
1032
1799
  state.lastContentCache = " ";
1033
1800
  }
@@ -1040,15 +1807,30 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1040
1807
  }
1041
1808
  }
1042
1809
  if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, outputStart);
1043
- if (element.tagId === 25 && !state.plainText && !isInsideTableCell(state)) if (eventType === 0) recordItemMarker(state, element.index);
1044
- else resolveItemMarker(state, true);
1045
- if (eventType === 0 && element.tagId === 26 && handlerOutput === "[" && buff.at(-1) === "[") openLinkFragment = buff.length - 1;
1810
+ if (tagId === 25 && !plainText && !isInsideTableCell(state)) {
1811
+ if (eventType === 0) recordItemMarker(state, element.index);
1812
+ else resolveItemMarker(state, true);
1813
+ }
1814
+ if (eventType === 0 && tagId === 26 && outputStart < buff.length && buff.at(-1) === "[") {
1815
+ const fragment = buff.length - 1;
1816
+ const cleanCaptionLink = captionFrameCount !== 0 && cleanEmptyLinkText;
1817
+ openLinkFragment = cleanCaptionLink ? fragment : -fragment - 2;
1818
+ if (cleanCaptionLink) {
1819
+ openLinkCaptionBreakRun = captionBreakRun;
1820
+ const snapshot = openLinkCaptionFlags?.length === captionFrameCount ? openLinkCaptionFlags : new Uint8Array(captionFrameCount);
1821
+ for (let index = 0; index < captionFrameCount; index++) snapshot[index] = captionFrames[index * CAPTION_FRAME_SIZE + 2] & CAPTION_INTERNAL_BREAK;
1822
+ openLinkCaptionFlags = snapshot;
1823
+ }
1824
+ }
1046
1825
  if (eventType === 0 && handlerOutput !== void 0 && isInlineElement && !handler?.literalEnter) {
1047
- const markerType = INLINE_MARKER_TYPE[element.tagId];
1048
- if (markerType && (element.tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && buff[buff.length - 1] === handlerOutput) openMarkers[openMarkerCount++] = buff.length - 1 << 3 | markerType;
1049
- else if (openMarkerCount && hasNonWhitespace(handlerOutput)) openMarkerCount = 0;
1050
- } else if (openMarkerCount && (handler?.literalExit || element.tagId !== -1 && !isInlineElement || output?.some(hasNonWhitespace))) openMarkerCount = 0;
1051
- if (eventType === 1 && element.tagId === 26) openLinkFragment = -1;
1826
+ const markerType = INLINE_MARKER_TYPE[tagId];
1827
+ if (markerType && (tagId !== 23 || !state.depthMap[34] && !isInsideRawHtmlBlock(state.depthMap)) && buff[buff.length - 1] === handlerOutput) openMarkers[openMarkerCount++] = buff.length - 1 << 3 | markerType;
1828
+ else if (openMarkerCount && !(tagId === 26 && cleanEmptyLinkText) && hasNonWhitespace(handlerOutput)) {
1829
+ openMarkerCount = 0;
1830
+ commitCaptionFrames();
1831
+ }
1832
+ } else if (openMarkerCount && (eventType === 1 && handler?.literalExit || tagId !== -1 && !isInlineElement || output?.some(hasNonWhitespace))) openMarkerCount = 0;
1833
+ if (eventType === 1 && tagId === 26) openLinkFragment = -1;
1052
1834
  updateListIndent(state, element, eventType);
1053
1835
  if (!insideRawHtmlRegion && inRawHtmlRegion) {
1054
1836
  bufferScan[0] = false;
@@ -1065,7 +1847,8 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1065
1847
  plainText: outputFormat !== "markdown"
1066
1848
  };
1067
1849
  const handleEvent = resolvedPlugins.length ? (event) => processPluginsForEvent(event, resolvedPlugins, state, processEvent) : processEvent;
1068
- finalizeParse(parseHtmlStream(html, parseState, handleEvent), parseState, handleEvent);
1850
+ const leftover = parseHtmlStream(html, parseState, handleEvent);
1851
+ finalizeParse(leftover, parseState, handleEvent);
1069
1852
  }
1070
1853
  function getMarkdown() {
1071
1854
  const content = state.buffer.join("");
@@ -1073,7 +1856,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1073
1856
  state.buffer.length = 0;
1074
1857
  return content;
1075
1858
  }
1076
- const result = state.plainText && preserveLeadingWhitespace ? content : content.trimStart();
1859
+ const result = plainText && preserveLeadingWhitespace ? content : content.trimStart();
1077
1860
  state.buffer.length = 0;
1078
1861
  preserveLeadingWhitespace = false;
1079
1862
  return result.trimEnd();
@@ -1084,16 +1867,25 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1084
1867
  state.buffer.length = 0;
1085
1868
  return chunk;
1086
1869
  }
1087
- resolveItemMarker(state, false);
1870
+ let unresolvedCaptionFragment = -1;
1871
+ if (state.emptyItemFragment !== void 0 && captionFrames) for (let index = 0; index < captionFrameCount; index++) {
1872
+ const offset = index * CAPTION_FRAME_SIZE;
1873
+ const anchor = captionFrames[offset + 3];
1874
+ if (anchor !== CAPTION_NO_ANCHOR) {
1875
+ unresolvedCaptionFragment = anchor;
1876
+ break;
1877
+ }
1878
+ }
1879
+ resolveItemMarker(state, false, unresolvedCaptionFragment);
1088
1880
  const content = state.buffer.join("");
1089
- const currentContent = hasYieldedContent || state.plainText && preserveLeadingWhitespace ? content : content.trimStart();
1881
+ const currentContent = hasYieldedContent || plainText && preserveLeadingWhitespace ? content : content.trimStart();
1090
1882
  const inPre = state.depthMap[34] !== 0;
1091
- const trailingCode = currentContent.charCodeAt(currentContent.length - 1);
1092
- let trailingSpaceEnd = currentContent.length;
1093
- while (trailingSpaceEnd > 0 && currentContent.charCodeAt(trailingSpaceEnd - 1) === 32) trailingSpaceEnd--;
1094
- let stableLength = trailingSpaceEnd;
1095
- let retainMutableFragments = stableLength < currentContent.length;
1883
+ let stableLength = currentContent.length;
1884
+ let retainMutableFragments = false;
1096
1885
  if (inPre) {
1886
+ const trailingCode = currentContent.charCodeAt(stableLength - 1);
1887
+ while (stableLength > 0 && currentContent.charCodeAt(stableLength - 1) === 32) stableLength--;
1888
+ retainMutableFragments = stableLength < currentContent.length;
1097
1889
  if (state.lastTextNode?.containsWhitespace && isAsciiWhitespace(trailingCode)) {
1098
1890
  stableLength = trimAsciiWhitespaceEnd(currentContent).length;
1099
1891
  retainMutableFragments = stableLength < currentContent.length;
@@ -1104,42 +1896,25 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1104
1896
  }
1105
1897
  }
1106
1898
  } else {
1107
- while (stableLength > 0 && (currentContent[stableLength - 1] === " " || currentContent[stableLength - 1] === "\n")) stableLength--;
1899
+ while (stableLength > 0) {
1900
+ const code = currentContent.charCodeAt(stableLength - 1);
1901
+ if (code !== 32 && code !== 10) break;
1902
+ stableLength--;
1903
+ }
1108
1904
  retainMutableFragments = stableLength < currentContent.length;
1109
1905
  }
1110
1906
  const leadingTrimmed = content.length - currentContent.length;
1111
- const markerHeld = openMarkerCount > 0;
1112
- if (markerHeld) {
1113
- const openFragment = openMarkers[0] >> 3;
1114
- const markerPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, openFragment) - leadingTrimmed));
1115
- if (markerPos < stableLength) stableLength = markerPos;
1116
- }
1117
- const codeSpanHeld = gfmLifecycle.openCodeSpans.length > 0;
1118
- if (codeSpanHeld) {
1119
- const spanPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, gfmLifecycle.openCodeSpans[0].fragment) - leadingTrimmed));
1120
- if (spanPos < stableLength) stableLength = spanPos;
1121
- }
1122
- const emptyItemFragment = state.emptyItemFragment;
1123
- const emptyItemHeld = emptyItemFragment !== void 0;
1124
- if (emptyItemHeld) {
1125
- const itemPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, emptyItemFragment) - leadingTrimmed));
1126
- if (itemPos < stableLength) stableLength = itemPos;
1127
- }
1128
- const codeFenceHeld = state.codeFence !== void 0;
1129
- if (codeFenceHeld) {
1130
- const fencePos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, state.codeFence.fragment) - leadingTrimmed));
1131
- if (fencePos < stableLength) stableLength = fencePos;
1132
- }
1133
- const blockquoteHeld = state.blockquotes.length > 0;
1134
- if (blockquoteHeld) {
1135
- const blockquotePos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, state.blockquotes[0].fragment) - leadingTrimmed));
1136
- if (blockquotePos < stableLength) stableLength = blockquotePos;
1137
- }
1138
- const linkHeld = openLinkFragment >= 0;
1139
- if (linkHeld) {
1140
- const linkPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, openLinkFragment) - leadingTrimmed));
1141
- if (linkPos < stableLength) stableLength = linkPos;
1907
+ let heldFragment = Math.min(openMarkerCount ? openMarkers[0] >> 3 : Infinity, gfmLifecycle.openCodeSpans[0]?.fragment ?? Infinity, state.emptyItemFragment ?? Infinity, state.codeFence?.fragment ?? Infinity, state.blockquotes[0]?.fragment ?? Infinity, openLinkFragment === -1 ? Infinity : openLinkFragment < -1 ? -openLinkFragment - 2 : openLinkFragment);
1908
+ for (let index = 0; index < captionFrameCount; index++) {
1909
+ const offset = index * CAPTION_FRAME_SIZE;
1910
+ const anchor = captionFrames[offset + 3];
1911
+ if ((captionFrames[offset + 2] & CAPTION_OPEN) === 0 && anchor !== CAPTION_NO_ANCHOR) {
1912
+ heldFragment = Math.min(heldFragment, anchor);
1913
+ break;
1914
+ }
1142
1915
  }
1916
+ const fragmentHeld = heldFragment !== Infinity;
1917
+ if (fragmentHeld) stableLength = Math.min(stableLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, heldFragment) - leadingTrimmed));
1143
1918
  const headingHeld = isInsideHeading(state.depthMap);
1144
1919
  if (headingHeld) {
1145
1920
  let headingPos = currentContent.length;
@@ -1154,8 +1929,8 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1154
1929
  const newContent = currentContent.slice(lastYieldedLength, stableLength);
1155
1930
  lastYieldedLength = stableLength;
1156
1931
  if (newContent) hasYieldedContent = true;
1157
- if (!markerHeld && !codeSpanHeld && !codeFenceHeld && !blockquoteHeld && !linkHeld && !emptyItemHeld && !headingHeld && (!retainMutableFragments || !inPre)) {
1158
- if (!resolvedPlugins.length && !options.wrapWidth && !state.depthMap[26]) {
1932
+ if (!fragmentHeld && !headingHeld && (!retainMutableFragments || !inPre)) {
1933
+ if (!resolvedPlugins.length && !options.wrapWidth) {
1159
1934
  if (retainMutableFragments && leadingTrimmed === 0) {
1160
1935
  const lastFragment = state.buffer.at(-1);
1161
1936
  const fragmentStart = currentContent.length - lastFragment.length;
@@ -1190,4 +1965,4 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
1190
1965
  state
1191
1966
  };
1192
1967
  }
1193
- export { createMarkdownProcessor, processPluginsForEvent };
1968
+ export { applyClean, createMarkdownProcessor, processPluginsForEvent, resolveClean };