@mdream/js 1.5.4 → 1.5.6

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,5 +1,5 @@
1
1
  import { DEFAULT_BLOCK_SPACING, NO_SPACING } from "./const.mjs";
2
- import { continuationPrefix, finalizeParse, parseHtmlStream } from "./parse.mjs";
2
+ import { breakHandler, continuationPrefix, finalizeParse, parseHtmlStream, renderBreak, resolveUrl } from "./parse.mjs";
3
3
  function processPluginsForEvent(event, plugins, state, processEvent) {
4
4
  if (plugins?.length) {
5
5
  if (event.node.type === 1 && event.type === 0) {
@@ -35,7 +35,7 @@ function processPluginsForEvent(event, plugins, state, processEvent) {
35
35
  processEvent(event);
36
36
  return false;
37
37
  }
38
- const INLINE_MARKER_TYPE = /* @__PURE__ */ new Uint8Array(110);
38
+ const INLINE_MARKER_TYPE = /* @__PURE__ */ new Uint8Array(112);
39
39
  INLINE_MARKER_TYPE[14] = 1;
40
40
  INLINE_MARKER_TYPE[15] = 1;
41
41
  INLINE_MARKER_TYPE[91] = 1;
@@ -43,6 +43,8 @@ INLINE_MARKER_TYPE[16] = 2;
43
43
  INLINE_MARKER_TYPE[17] = 2;
44
44
  INLINE_MARKER_TYPE[106] = 2;
45
45
  INLINE_MARKER_TYPE[18] = 3;
46
+ INLINE_MARKER_TYPE[110] = 3;
47
+ INLINE_MARKER_TYPE[111] = 3;
46
48
  INLINE_MARKER_TYPE[90] = 4;
47
49
  INLINE_MARKER_TYPE[46] = 5;
48
50
  INLINE_MARKER_TYPE[23] = 5;
@@ -131,6 +133,118 @@ function foldPreLinesToBr(value) {
131
133
  }
132
134
  return out;
133
135
  }
136
+ function isInsideRawHtmlBlock(depthMap) {
137
+ return Boolean(depthMap[2] || depthMap[3] || depthMap[100] || depthMap[101] || depthMap[99] || depthMap[98]);
138
+ }
139
+ function markdownLineIndent(buffer) {
140
+ let spaces = 0;
141
+ for (let fragmentIndex = buffer.length - 1; fragmentIndex >= 0; fragmentIndex--) {
142
+ const fragment = buffer[fragmentIndex];
143
+ for (let index = fragment.length - 1; index >= 0; index--) {
144
+ const code = fragment.charCodeAt(index);
145
+ if (code === 10) return spaces <= 3 ? spaces : -1;
146
+ if (code !== 32) return -1;
147
+ if (++spaces > 3) return -1;
148
+ }
149
+ }
150
+ return spaces <= 3 ? spaces : -1;
151
+ }
152
+ function isMarkdownMarkerWhitespace(code) {
153
+ return code === 0 || code === 9 || code === 10 || code === 13 || code === 32;
154
+ }
155
+ function canStartGfmAngleConstruct(code) {
156
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 33 || code === 47 || code === 63;
157
+ }
158
+ function isThematicBreak(value, start, marker) {
159
+ let count = 0;
160
+ for (let index = start; index < value.length; index++) {
161
+ const code = value.charCodeAt(index);
162
+ if (code === marker) count++;
163
+ else if (code === 10 || code === 13) break;
164
+ else if (code !== 32 && code !== 9) return false;
165
+ }
166
+ return count >= 3;
167
+ }
168
+ function isParserProtectedEscape(depthMap, next) {
169
+ return next === 124 && Boolean(depthMap[28]) || (next === 91 || next === 93) && Boolean(depthMap[26]) || next === 62 && Boolean(depthMap[22]);
170
+ }
171
+ function isEntityReferenceAfterAmpersand(value, ampersand) {
172
+ let index = ampersand + 1;
173
+ if (value.charCodeAt(index) === 35) {
174
+ index++;
175
+ const hex = value.charCodeAt(index) === 120 || value.charCodeAt(index) === 88;
176
+ if (hex) index++;
177
+ const start = index;
178
+ while (index < value.length) {
179
+ const code = value.charCodeAt(index);
180
+ if (!(code >= 48 && code <= 57 || hex && (code >= 65 && code <= 70 || code >= 97 && code <= 102))) break;
181
+ index++;
182
+ }
183
+ return index > start && value.charCodeAt(index) === 59;
184
+ }
185
+ const start = index;
186
+ while (index < value.length) {
187
+ const code = value.charCodeAt(index);
188
+ if (!(code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122)) break;
189
+ index++;
190
+ }
191
+ return index > start && value.charCodeAt(index) === 59;
192
+ }
193
+ const GFM_TEXT_NATIVE_TRIGGER = /[\\*_~`[<\r\n]/;
194
+ function mayNeedGfmTextEscape(value, buffer) {
195
+ if (value.search(GFM_TEXT_NATIVE_TRIGGER) !== -1) return true;
196
+ let lineIndent = markdownLineIndent(buffer);
197
+ if (lineIndent < 0) return false;
198
+ let index = 0;
199
+ while (index < value.length && lineIndent < 3 && value.charCodeAt(index) === 32) {
200
+ index++;
201
+ lineIndent++;
202
+ }
203
+ if (index >= value.length) return false;
204
+ const code = value.charCodeAt(index);
205
+ return code === 35 || code === 43 || code === 45 || code === 62 || code >= 48 && code <= 57;
206
+ }
207
+ function escapeGfmText(value, buffer, depthMap) {
208
+ let lineIndent = markdownLineIndent(buffer);
209
+ let orderedDigits = 0;
210
+ let copiedUntil = 0;
211
+ let escaped = "";
212
+ for (let index = 0; index < value.length; index++) {
213
+ const code = value.charCodeAt(index);
214
+ const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;
215
+ if (code === 92 && (isParserProtectedEscape(depthMap, next) || next === 38 && isEntityReferenceAfterAmpersand(value, index + 1))) {
216
+ lineIndent = -1;
217
+ orderedDigits = 0;
218
+ index++;
219
+ continue;
220
+ }
221
+ let shouldEscape = code === 92 || code === 42 || code === 95 || code === 126 || code === 96 || code === 91 || code === 60 && canStartGfmAngleConstruct(value.charCodeAt(index + 1));
222
+ if (!shouldEscape && lineIndent >= 0) {
223
+ if (code === 35) {
224
+ let end = index + 1;
225
+ while (end < value.length && value.charCodeAt(end) === 35) end++;
226
+ shouldEscape = end - index <= 6 && (end === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(end)));
227
+ } else if (code === 45 || code === 43) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1)) || code === 45 && isThematicBreak(value, index, code);
228
+ else if (code === 62) shouldEscape = true;
229
+ } else if (!shouldEscape && orderedDigits > 0 && (code === 46 || code === 41)) shouldEscape = index + 1 === value.length || isMarkdownMarkerWhitespace(value.charCodeAt(index + 1));
230
+ if (shouldEscape) {
231
+ escaped += value.slice(copiedUntil, index);
232
+ escaped += `\\${value[index]}`;
233
+ copiedUntil = index + 1;
234
+ }
235
+ if (code === 10) {
236
+ lineIndent = 0;
237
+ orderedDigits = 0;
238
+ } else if (lineIndent >= 0) if (code === 32 && lineIndent < 3) lineIndent++;
239
+ else {
240
+ orderedDigits = code >= 48 && code <= 57 ? 1 : 0;
241
+ lineIndent = -1;
242
+ }
243
+ else if (orderedDigits > 0) if (code >= 48 && code <= 57 && orderedDigits < 9) orderedDigits++;
244
+ else orderedDigits = 0;
245
+ }
246
+ return copiedUntil === 0 ? value : escaped + value.slice(copiedUntil);
247
+ }
134
248
  function currentColumn(buffer) {
135
249
  let col = 0;
136
250
  for (let i = buffer.length - 1; i >= 0; i--) {
@@ -175,7 +289,7 @@ function wrapText(value, col, width, prefix) {
175
289
  }
176
290
  function calculateNewLineConfig(node, depthMap, plainText) {
177
291
  const tagId = node.tagId;
178
- if (tagId !== 25 && (depthMap[25] || 0) > 0 || tagId !== 22 && (depthMap[22] || 0) > 0) {
292
+ if (tagId !== 25 && (depthMap[25] || 0) > 0 || plainText && tagId !== 22 && (depthMap[22] || 0) > 0) {
179
293
  if (plainText && tagId === 34) return [1, 1];
180
294
  return NO_SPACING;
181
295
  }
@@ -202,6 +316,28 @@ function hasNonWhitespace(value) {
202
316
  }
203
317
  return false;
204
318
  }
319
+ function isAsciiWhitespace(code) {
320
+ return code === 32 || code >= 9 && code <= 13;
321
+ }
322
+ function trimAsciiWhitespaceEnd(value) {
323
+ let end = value.length;
324
+ while (end > 0 && isAsciiWhitespace(value.charCodeAt(end - 1))) end--;
325
+ return end === value.length ? value : value.slice(0, end);
326
+ }
327
+ function fragmentPosition(buffer, fragment) {
328
+ let position = 0;
329
+ for (let index = 0; index < fragment; index++) position += buffer[index].length;
330
+ return position;
331
+ }
332
+ function trimBufferedWhitespacePosition(content, position) {
333
+ let end = Math.max(0, position);
334
+ while (end > 0) {
335
+ const code = content.charCodeAt(end - 1);
336
+ if (code !== 32 && code !== 10) break;
337
+ end--;
338
+ }
339
+ return end;
340
+ }
205
341
  function dropEmptyMarker(buffer, packed, markerType) {
206
342
  const idx = packed >> 3;
207
343
  if ((packed & 7) === markerType && idx < buffer.length) {
@@ -214,6 +350,89 @@ function dropEmptyMarker(buffer, packed, markerType) {
214
350
  }
215
351
  return -1;
216
352
  }
353
+ function maxBacktickRun(value) {
354
+ let max = 0;
355
+ let run = 0;
356
+ for (let index = 0; index < value.length; index++) if (value.charCodeAt(index) === 96) {
357
+ run++;
358
+ if (run > max) max = run;
359
+ } else run = 0;
360
+ return max;
361
+ }
362
+ function maxLineLeadingRun(value, marker, indent) {
363
+ let max = 0;
364
+ let lineStart = 0;
365
+ while (lineStart <= value.length) {
366
+ let index = lineStart;
367
+ if (indent && value.startsWith(indent, index)) index += indent.length;
368
+ let spaces = 0;
369
+ while (spaces < 3 && value.charCodeAt(index) === 32) {
370
+ spaces++;
371
+ index++;
372
+ }
373
+ let run = 0;
374
+ while (value.charCodeAt(index + run) === marker) run++;
375
+ if (run > max) max = run;
376
+ const newline = value.indexOf("\n", lineStart);
377
+ if (newline === -1) break;
378
+ lineStart = newline + 1;
379
+ }
380
+ return max;
381
+ }
382
+ function finalizeCodeSpan(state, span) {
383
+ const content = state.buffer.slice(span.fragment + 1).join("");
384
+ const delimiter = "`".repeat(Math.max(1, maxBacktickRun(content) + 1));
385
+ const padded = content.startsWith("`") || content.endsWith("`");
386
+ state.buffer[span.fragment] = `${span.prefix}${delimiter}${padded ? " " : ""}`;
387
+ return `${padded ? " " : ""}${delimiter}`;
388
+ }
389
+ function startCodeFence(state, fragment, language, indent) {
390
+ state.codeFence = {
391
+ fragment,
392
+ markerOffset: state.buffer[fragment].lastIndexOf("```"),
393
+ indent,
394
+ language
395
+ };
396
+ }
397
+ function finalizeCodeFence(state) {
398
+ const fence = state.codeFence;
399
+ if (!fence) return;
400
+ state.codeFence = void 0;
401
+ const marker = fence.language.includes("`") ? "~" : "`";
402
+ const markerCode = marker.charCodeAt(0);
403
+ const content = state.buffer.slice(fence.fragment + 1).join("");
404
+ const delimiter = marker.repeat(Math.max(3, maxLineLeadingRun(content, markerCode, fence.indent) + 1));
405
+ const opening = state.buffer[fence.fragment];
406
+ state.buffer[fence.fragment] = `${opening.slice(0, fence.markerOffset)}${delimiter}${opening.slice(fence.markerOffset + 3)}`;
407
+ return delimiter;
408
+ }
409
+ function stripBlockquoteListIndent(line, listIndent) {
410
+ return listIndent && line.startsWith(listIndent) ? line.slice(listIndent.length) : line;
411
+ }
412
+ function finalizeBlockquote(state) {
413
+ const frame = state.blockquotes.pop();
414
+ if (!frame) return;
415
+ state.bufferedBlockquoteDepth = state.blockquotes.length;
416
+ const content = state.buffer.slice(frame.fragment).join("").replace(/[ \t\r\n]+$/, "");
417
+ const prefix = `${frame.listIndent}>`;
418
+ const quoted = content.split("\n").map((line) => {
419
+ const unindented = stripBlockquoteListIndent(line, frame.listIndent);
420
+ return unindented ? `${prefix} ${unindented}` : prefix;
421
+ }).join("\n");
422
+ state.buffer.splice(frame.fragment, state.buffer.length - frame.fragment, quoted);
423
+ state.lastContentCache = quoted;
424
+ }
425
+ function collapseNestedBlockquoteSeparator(buffer) {
426
+ let trailingNewlines = 0;
427
+ for (let fragmentIndex = buffer.length - 1; fragmentIndex >= 0 && trailingNewlines < 2; fragmentIndex--) {
428
+ const fragment = buffer[fragmentIndex];
429
+ for (let index = fragment.length - 1; index >= 0 && fragment.charCodeAt(index) === 10; index--) trailingNewlines++;
430
+ }
431
+ if (trailingNewlines < 2) return;
432
+ const last = buffer.at(-1);
433
+ if (last.length === 1) buffer.pop();
434
+ else buffer[buffer.length - 1] = last.slice(0, -1);
435
+ }
217
436
  function flushPreFence(state) {
218
437
  if (state.plainText) {
219
438
  state.preFencePending = false;
@@ -225,8 +444,82 @@ function flushPreFence(state) {
225
444
  const lang = state.preFenceLang || "";
226
445
  const fence = (state.depthMap[25] || 0) > 0 ? `\n\n${state.listIndent}\`\`\`${lang}\n${state.listIndent}` : `\`\`\`${lang}\n`;
227
446
  state.buffer.push(fence);
447
+ startCodeFence(state, state.buffer.length - 1, lang, state.listIndent);
228
448
  state.lastContentCache = fence;
229
449
  }
450
+ function consumePendingPreChild(state, node, eventType) {
451
+ if (eventType !== 0) return false;
452
+ if (node.type === 1) {
453
+ const element = node;
454
+ if (element.tagId === 23 && element.parent?.tagId === 34) state.preFencePending = false;
455
+ else if (element.tagId !== 34) flushPreFence(state);
456
+ return false;
457
+ }
458
+ if (hasNonWhitespace(node.value)) {
459
+ flushPreFence(state);
460
+ return false;
461
+ }
462
+ return true;
463
+ }
464
+ function consumeGfmAction(action, state, lifecycle) {
465
+ switch (action._tag) {
466
+ case "BlockquoteEnter": return action.output;
467
+ case "BlockquoteExit":
468
+ finalizeBlockquote(state);
469
+ return;
470
+ case "PreEnter":
471
+ state.preFencePending = true;
472
+ state.preOwnFence = false;
473
+ state.preFenceLang = action.language;
474
+ return;
475
+ case "PreExit": {
476
+ const ownFence = state.preOwnFence;
477
+ state.preFencePending = false;
478
+ state.preOwnFence = false;
479
+ if (!ownFence) return void 0;
480
+ const indent = state.listIndent;
481
+ const output = (state.depthMap[25] || 0) > 0 ? `\n${indent}\`\`\`\n\n${indent}` : `\n\`\`\``;
482
+ const delimiter = finalizeCodeFence(state);
483
+ return delimiter ? output.replace("```", delimiter) : output;
484
+ }
485
+ case "CodeSpanEnter": return action.output;
486
+ case "CodeSpanExit": {
487
+ const span = lifecycle.openCodeSpans.pop();
488
+ return span ? finalizeCodeSpan(state, span) : "`";
489
+ }
490
+ case "CodeFenceEnter":
491
+ state.preFencePending = false;
492
+ return action.output;
493
+ case "CodeFenceExit": {
494
+ const delimiter = finalizeCodeFence(state);
495
+ return delimiter ? action.output.replace("```", delimiter) : action.output;
496
+ }
497
+ }
498
+ }
499
+ function commitGfmAction(action, state, lifecycle, outputStart) {
500
+ switch (action._tag) {
501
+ case "BlockquoteEnter":
502
+ if (state.blockquotes.length > 0) collapseNestedBlockquoteSeparator(state.buffer);
503
+ state.blockquotes.push({
504
+ fragment: state.buffer.length,
505
+ listIndent: state.listIndent
506
+ });
507
+ state.bufferedBlockquoteDepth = state.blockquotes.length;
508
+ break;
509
+ case "CodeSpanEnter":
510
+ lifecycle.openCodeSpans.push({
511
+ fragment: outputStart,
512
+ prefix: action.output.slice(0, -1)
513
+ });
514
+ break;
515
+ case "CodeFenceEnter": {
516
+ const fenceFragment = state.buffer.findIndex((fragment, index) => index >= outputStart && fragment.includes("```"));
517
+ if (fenceFragment < 0) throw new Error("code fence opener missing from output");
518
+ startCodeFence(state, fenceFragment, action.language, state.listIndent);
519
+ break;
520
+ }
521
+ }
522
+ }
230
523
  function getPlainTextOutput(node, eventType, state) {
231
524
  const override = state.options?.plugins?.tagOverrides?.[node.name];
232
525
  if (override && typeof override !== "string") {
@@ -243,7 +536,11 @@ function getPlainTextOutput(node, eventType, state) {
243
536
  if (lastChar && lastChar !== " " && lastChar !== "\n") return "\n\n";
244
537
  }
245
538
  if (tagId === 32 || tagId === 31) return (depthMap[28] || 0) > 1 || node.index === 0 ? "" : " ";
246
- if (tagId === 27) return node.attributes?.alt || void 0;
539
+ if (tagId === 27) {
540
+ const alt = node.attributes?.alt;
541
+ if (alt !== void 0) return alt || void 0;
542
+ return node.attributes?.title || resolveUrl(node.attributes?.src || "", state.options?.origin, state.options?.clean) || void 0;
543
+ }
247
544
  if (tagId === 81) return "\"";
248
545
  return;
249
546
  }
@@ -253,16 +550,53 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
253
550
  const state = {
254
551
  options,
255
552
  buffer: [],
256
- depthMap: /* @__PURE__ */ new Uint8Array(110),
553
+ depthMap: /* @__PURE__ */ new Uint8Array(112),
257
554
  listIndent: "",
258
555
  listIndentWidths: [],
556
+ blockquotes: [],
557
+ bufferedBlockquoteDepth: 0,
259
558
  plainText: options.format === "text"
260
559
  };
261
560
  const openMarkers = [];
262
561
  let openMarkerCount = 0;
562
+ const gfmLifecycle = { openCodeSpans: [] };
563
+ let openLinkFragment = -1;
263
564
  let lastYieldedLength = 0;
264
565
  let hasYieldedContent = false;
265
566
  let preserveLeadingWhitespace = false;
567
+ function processTextNode(textNode, lastNode, lastChar) {
568
+ if (textNode.value) {
569
+ if (textNode.excludedFromMarkdown) return;
570
+ if (state.pendingInlineWhitespace) {
571
+ if (!textNode.value.trim()) return;
572
+ if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(textNode.value[0] || "")) textNode.value = ` ${textNode.value}`;
573
+ state.pendingInlineWhitespace = false;
574
+ }
575
+ if (state.plainText && state.depthMap[34] && state.buffer.length === 0) preserveLeadingWhitespace = true;
576
+ if (textNode.value === " " && (lastChar === " " || lastChar === "\n" || lastChar === " " || lastChar === "\r")) return;
577
+ if (!(state.plainText && state.depthMap[34]) && shouldAddSpacingBeforeText(lastChar, lastNode, textNode)) textNode.value = ` ${textNode.value}`;
578
+ if ((state.depthMap[34] || 0) > 0 && (state.depthMap[25] || 0) > 0) {
579
+ const indent = state.listIndent;
580
+ let value = textNode.value.replace(/\n(?!\n|$)/g, `\n${indent}`);
581
+ if (lastChar === "\n" && value[0] && value[0] !== "\n") value = indent + value;
582
+ textNode.value = value;
583
+ }
584
+ if (state.depthMap[34] > 0 && (state.depthMap[32] > 0 || state.depthMap[31] > 0)) textNode.value = foldPreLinesToBr(textNode.value);
585
+ if (!state.plainText && !state.depthMap[34] && !state.depthMap[23] && !isInsideRawHtmlBlock(state.depthMap) && mayNeedGfmTextEscape(textNode.value, state.buffer)) textNode.value = escapeGfmText(textNode.value, state.buffer, state.depthMap);
586
+ if (textNode.generatedMarkdown && textNode.value) textNode.value = `${textNode.generatedMarkdown.prefix}${textNode.value}${textNode.generatedMarkdown.suffix}`;
587
+ const wrapWidth = state.options?.wrapWidth;
588
+ if (wrapWidth && canWrapHere(state.depthMap)) {
589
+ const wrapped = wrapText(textNode.value, currentColumn(state.buffer), wrapWidth, continuationPrefix(textNode, state.listIndentWidths, state.blockquotes.length === 0));
590
+ state.buffer.push(wrapped);
591
+ state.lastContentCache = wrapped;
592
+ } else {
593
+ state.buffer.push(textNode.value);
594
+ state.lastContentCache = textNode.value;
595
+ }
596
+ if (openMarkerCount && hasNonWhitespace(textNode.value)) openMarkerCount = 0;
597
+ }
598
+ state.lastTextNode = textNode;
599
+ }
266
600
  function processEvent(event) {
267
601
  const { type: eventType, node } = event;
268
602
  state.depth = node.depth;
@@ -270,80 +604,91 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
270
604
  const lastNode = state.lastNode;
271
605
  state.lastNode = event.node;
272
606
  const buff = state.buffer;
273
- if (!state.plainText && state.preFencePending && eventType === 0) {
274
- if (node.type === 1) {
275
- const el = node;
276
- if (el.tagId === 23 && el.parent?.tagId === 34) state.preFencePending = false;
277
- else if (el.tagId !== 34) flushPreFence(state);
278
- } else if (node.type === 2 && hasNonWhitespace(node.value)) flushPreFence(state);
279
- }
280
- const lastBuffEntry = buff.at(-1);
281
- const lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
282
- let secondLastChar;
283
- if (lastBuffEntry && lastBuffEntry.length > 1) secondLastChar = lastBuffEntry.charAt(lastBuffEntry.length - 2);
284
- else if (buff.length > 1) {
285
- const prevBuff = buff[buff.length - 2];
286
- if (prevBuff) secondLastChar = prevBuff.charAt(prevBuff.length - 1);
287
- }
607
+ if (!state.plainText && state.preFencePending && consumePendingPreChild(state, node, eventType)) return;
608
+ let lastBuffEntry = buff.at(-1);
609
+ let lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
288
610
  if (node.type === 2 && eventType === 0) {
289
- const textNode = node;
290
- if (textNode.value) {
291
- if (textNode.excludedFromMarkdown) return;
292
- if (state.preFencePending) return;
293
- if (state.pendingInlineWhitespace) {
294
- if (!textNode.value.trim()) return;
295
- if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(textNode.value[0] || "")) textNode.value = ` ${textNode.value}`;
296
- state.pendingInlineWhitespace = false;
297
- }
298
- if (state.plainText && state.depthMap[34] && state.buffer.length === 0) preserveLeadingWhitespace = true;
299
- if (textNode.value === " " && (lastChar === " " || lastChar === "\n" || lastChar === " " || lastChar === "\r")) return;
300
- if (!(state.plainText && state.depthMap[34]) && shouldAddSpacingBeforeText(lastChar, lastNode, textNode)) textNode.value = ` ${textNode.value}`;
301
- if ((state.depthMap[34] || 0) > 0 && (state.depthMap[25] || 0) > 0) {
302
- const indent = state.listIndent;
303
- let value = textNode.value.replace(/\n(?!\n|$)/g, `\n${indent}`);
304
- if (lastChar === "\n" && value[0] && value[0] !== "\n") value = indent + value;
305
- textNode.value = value;
611
+ processTextNode(node, lastNode, lastChar);
612
+ return;
613
+ }
614
+ if (node.type !== 1) return;
615
+ const element = node;
616
+ const handler = node.tagHandler;
617
+ if (eventType === 0 && handler === breakHandler && !element.pluginOutput?.length) {
618
+ const inPre = state.depthMap[34] !== 0;
619
+ let breakOutput = state.plainText ? "\n" : renderBreak(element, state);
620
+ if (state.plainText && !inPre && lastChar === "\n") {
621
+ if ((lastBuffEntry.length > 1 ? lastBuffEntry.charAt(lastBuffEntry.length - 2) : buff.length > 1 ? buff[buff.length - 2]?.at(-1) : void 0) === "\n") breakOutput = void 0;
622
+ }
623
+ if (state.pendingInlineWhitespace) state.pendingInlineWhitespace = false;
624
+ const lastFragment = state.lastContentCache;
625
+ const lastTextNode = state.lastTextNode;
626
+ if (lastFragment && lastTextNode?.containsWhitespace && typeof lastTextNode.value === "string") {
627
+ let parent = element.parent;
628
+ let parentInPre = false;
629
+ while (parent) {
630
+ if (parent.tagId === 34) {
631
+ parentInPre = true;
632
+ break;
633
+ }
634
+ parent = parent.parent;
306
635
  }
307
- if (state.depthMap[34] > 0 && (state.depthMap[32] > 0 || state.depthMap[31] > 0)) textNode.value = foldPreLinesToBr(textNode.value);
308
- const wrapWidth = state.options?.wrapWidth;
309
- if (wrapWidth && canWrapHere(state.depthMap)) {
310
- const wrapped = wrapText(textNode.value, currentColumn(state.buffer), wrapWidth, continuationPrefix(textNode, state.listIndentWidths));
311
- state.buffer.push(wrapped);
312
- state.lastContentCache = wrapped;
313
- } else {
314
- state.buffer.push(textNode.value);
315
- state.lastContentCache = textNode.value;
636
+ if (!parentInPre || element.parent?.tagId === 34) {
637
+ if (breakOutput?.endsWith("\n") && !parentInPre) {
638
+ const trimmed = trimAsciiWhitespaceEnd(lastFragment);
639
+ if (trimmed.length !== lastFragment.length && buff.at(-1) === lastFragment) buff[buff.length - 1] = trimmed;
640
+ }
641
+ state.lastTextNode = void 0;
316
642
  }
317
- if (openMarkerCount && hasNonWhitespace(textNode.value)) openMarkerCount = 0;
318
643
  }
319
- state.lastTextNode = textNode;
644
+ if (breakOutput) {
645
+ buff.push(breakOutput);
646
+ state.lastContentCache = breakOutput;
647
+ if (openMarkerCount && hasNonWhitespace(breakOutput)) openMarkerCount = 0;
648
+ }
320
649
  return;
321
650
  }
322
- if (node.type !== 1) return;
651
+ let secondLastChar;
652
+ if (lastBuffEntry && lastBuffEntry.length > 1) secondLastChar = lastBuffEntry.charAt(lastBuffEntry.length - 2);
653
+ else if (buff.length > 1) {
654
+ const prevBuff = buff[buff.length - 2];
655
+ if (prevBuff) secondLastChar = prevBuff.charAt(prevBuff.length - 1);
656
+ }
323
657
  let output;
324
- const element = node;
325
658
  if (element.pluginOutput?.length) {
326
659
  output = element.pluginOutput;
327
660
  element.pluginOutput = void 0;
328
661
  }
329
- const lastFragment = state.lastContentCache;
330
- let lastNewLines = 0;
331
- if (lastChar === "\n") lastNewLines++;
332
- if (secondLastChar === "\n") lastNewLines++;
662
+ let lastFragment = state.lastContentCache;
333
663
  const eventFn = eventType === 0 ? "enter" : "exit";
334
- const handler = node.tagHandler;
335
664
  const isInlineElement = handler?.isInline === true;
665
+ let gfmAction;
336
666
  let handlerOutput;
337
667
  if (!output && handler?.[eventFn]) {
338
668
  const res = state.plainText ? getPlainTextOutput(element, eventType, state) : handler[eventFn]({
339
669
  node: element,
340
670
  state
341
671
  });
342
- if (res) {
343
- output = [res];
344
- handlerOutput = res;
672
+ if (typeof res === "string") {
673
+ if (res) {
674
+ output = [res];
675
+ handlerOutput = res;
676
+ }
677
+ } else if (res) {
678
+ gfmAction = res;
679
+ handlerOutput = consumeGfmAction(res, state, gfmLifecycle);
680
+ if (handlerOutput) output = [handlerOutput];
681
+ if (res._tag === "BlockquoteExit") {
682
+ lastFragment = state.lastContentCache;
683
+ lastBuffEntry = buff.at(-1);
684
+ lastChar = lastBuffEntry?.charAt(lastBuffEntry.length - 1) || "";
685
+ secondLastChar = lastBuffEntry && lastBuffEntry.length > 1 ? lastBuffEntry.charAt(lastBuffEntry.length - 2) : buff.length > 1 ? buff[buff.length - 2]?.at(-1) : void 0;
686
+ }
345
687
  }
346
688
  }
689
+ let lastNewLines = 0;
690
+ if (lastChar === "\n") lastNewLines++;
691
+ if (secondLastChar === "\n") lastNewLines++;
347
692
  if (eventType === 1 && openMarkerCount) {
348
693
  const markerType = handlerOutput === void 0 ? 0 : INLINE_MARKER_TYPE[element.tagId];
349
694
  if (markerType && (element.tagId !== 23 || !state.depthMap[34]) && !handler?.literalExit) {
@@ -356,12 +701,13 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
356
701
  }
357
702
  }
358
703
  if (element.tagId === 6 && !state.depthMap[34] && output?.length === 1 && output[0] === "\n" && lastChar === "\n" && secondLastChar === "\n") output = void 0;
359
- const configuredNewLines = calculateNewLineConfig(node, state.depthMap, state.plainText === true)[eventType] || 0;
704
+ const newLineConfig = calculateNewLineConfig(node, state.depthMap, state.plainText === true);
705
+ const configuredNewLines = eventType === 0 && state.blockquotes.at(-1)?.fragment === state.buffer.length ? 0 : eventType === 1 && element.tagId === 13 && state.blockquotes.length > 0 ? Math.min(1, newLineConfig[eventType] || 0) : newLineConfig[eventType] || 0;
360
706
  let effectiveLastNewLines = lastNewLines;
361
707
  if (eventType === 1 && output) for (let i = output.length - 1; i >= 0; i--) {
362
708
  const frag = output[i];
363
709
  if (frag) {
364
- if (frag.charCodeAt(frag.length - 1) === 96) effectiveLastNewLines = 0;
710
+ if (frag.endsWith("```") || frag.endsWith("~~~")) effectiveLastNewLines = 0;
365
711
  break;
366
712
  }
367
713
  }
@@ -369,7 +715,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
369
715
  if (state.pendingInlineWhitespace) {
370
716
  const firstOutput = output?.[0]?.[0] || "";
371
717
  if (eventType === 0) {
372
- if (!isInlineElement || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
718
+ if (!isInlineElement || element.tagId === 6 || newLines > 0 || firstOutput === "\n" || firstOutput === "\r") state.pendingInlineWhitespace = false;
373
719
  else if (firstOutput) {
374
720
  if (lastChar && !" \n \r".includes(lastChar) && !" \n \r".includes(firstOutput)) state.buffer.push(" ");
375
721
  state.pendingInlineWhitespace = false;
@@ -384,6 +730,7 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
384
730
  state.lastContentCache = fragment;
385
731
  }
386
732
  }
733
+ if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, state.buffer.length);
387
734
  updateListIndent(state, element, eventType);
388
735
  return;
389
736
  }
@@ -410,9 +757,9 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
410
757
  const collapsesWhiteSpace = node.tagHandler?.collapsesInnerWhiteSpace;
411
758
  const hasSpacing = node.tagHandler?.spacing && Array.isArray(node.tagHandler.spacing);
412
759
  const isBlockElement = !isInlineElement && !collapsesWhiteSpace && configuredNewLines > 0;
413
- if (element.tagId === 6 && output?.[0]?.[0] === "\n" && !parentInPre || (!isInlineElement || eventType === 1) && !isBlockElement && !(collapsesWhiteSpace && eventType === 0) && !(hasSpacing && eventType === 0)) {
760
+ if (element.tagId === 6 && output?.[0]?.endsWith("\n") && !parentInPre || (!isInlineElement || eventType === 1) && !isBlockElement && !(collapsesWhiteSpace && eventType === 0) && !(hasSpacing && eventType === 0)) {
414
761
  const originalLength = lastFragment.length;
415
- const trimmed = lastFragment.trimEnd();
762
+ const trimmed = trimAsciiWhitespaceEnd(lastFragment);
416
763
  if (originalLength - trimmed.length > 0) {
417
764
  if (buff?.length && buff.at(-1) === lastFragment) buff[buff.length - 1] = trimmed;
418
765
  if (eventType === 1 && isInlineElement) state.pendingInlineWhitespace = true;
@@ -421,21 +768,26 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
421
768
  state.lastTextNode = void 0;
422
769
  }
423
770
  }
424
- if (output?.[0]?.[0] && eventType === 0 && !node.tagHandler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0], state)) {
771
+ if (element.tagId !== 6 && output?.[0]?.[0] && eventType === 0 && !node.tagHandler?.literalEnter && lastChar && needsSpacing(lastChar, output[0][0], state)) {
425
772
  state.buffer.push(" ");
426
773
  state.lastContentCache = " ";
427
774
  }
775
+ let outputStart = state.buffer.length;
428
776
  if (output) {
777
+ outputStart = state.buffer.length;
429
778
  for (const fragment of output) if (fragment) {
430
779
  state.buffer.push(fragment);
431
780
  state.lastContentCache = fragment;
432
781
  }
433
782
  }
783
+ if (gfmAction) commitGfmAction(gfmAction, state, gfmLifecycle, outputStart);
784
+ if (eventType === 0 && element.tagId === 26 && handlerOutput === "[" && buff.at(-1) === "[") openLinkFragment = buff.length - 1;
434
785
  if (eventType === 0 && handlerOutput !== void 0 && isInlineElement && !handler?.literalEnter) {
435
786
  const markerType = INLINE_MARKER_TYPE[element.tagId];
436
787
  if (markerType && (element.tagId !== 23 || !state.depthMap[34]) && buff[buff.length - 1] === handlerOutput) openMarkers[openMarkerCount++] = buff.length - 1 << 3 | markerType;
437
788
  else if (openMarkerCount && hasNonWhitespace(handlerOutput)) openMarkerCount = 0;
438
789
  } else if (openMarkerCount && (handler?.literalExit || element.tagId !== -1 && !isInlineElement || output?.some(hasNonWhitespace))) openMarkerCount = 0;
790
+ if (eventType === 1 && element.tagId === 26) openLinkFragment = -1;
439
791
  updateListIndent(state, element, eventType);
440
792
  }
441
793
  function processHtml(html) {
@@ -459,30 +811,76 @@ function createMarkdownProcessor(options = {}, resolvedPlugins = [], tagOverride
459
811
  function getMarkdownChunk() {
460
812
  const content = state.buffer.join("");
461
813
  const currentContent = hasYieldedContent || state.plainText && preserveLeadingWhitespace ? content : content.trimStart();
462
- const hasMutableTrailingSpace = state.lastTextNode?.containsWhitespace && !state.depthMap[34] && currentContent.endsWith(" ");
463
- let stableLength = currentContent.length;
464
- if (hasMutableTrailingSpace) while (stableLength > 0 && currentContent[stableLength - 1] === " ") stableLength--;
814
+ const inPre = state.depthMap[34] !== 0;
815
+ const trailingCode = currentContent.charCodeAt(currentContent.length - 1);
816
+ let trailingSpaceEnd = currentContent.length;
817
+ while (trailingSpaceEnd > 0 && currentContent.charCodeAt(trailingSpaceEnd - 1) === 32) trailingSpaceEnd--;
818
+ let stableLength = trailingSpaceEnd;
819
+ let retainMutableFragments = stableLength < currentContent.length;
820
+ if (inPre) {
821
+ if (state.lastTextNode?.containsWhitespace && isAsciiWhitespace(trailingCode)) {
822
+ stableLength = trimAsciiWhitespaceEnd(currentContent).length;
823
+ retainMutableFragments = stableLength < currentContent.length;
824
+ } else if (stableLength < currentContent.length) {
825
+ if (!(stableLength === 0 || currentContent.charCodeAt(stableLength - 1) === 10)) {
826
+ stableLength = currentContent.length;
827
+ retainMutableFragments = false;
828
+ }
829
+ }
830
+ } else {
831
+ while (stableLength > 0 && (currentContent[stableLength - 1] === " " || currentContent[stableLength - 1] === "\n")) stableLength--;
832
+ retainMutableFragments = stableLength < currentContent.length;
833
+ }
834
+ const leadingTrimmed = content.length - currentContent.length;
465
835
  const markerHeld = openMarkerCount > 0;
466
836
  if (markerHeld) {
467
837
  const openFragment = openMarkers[0] >> 3;
468
- let markerPos = 0;
469
- for (let i = 0; i < openFragment; i++) markerPos += state.buffer[i].length;
470
- markerPos -= content.length - currentContent.length;
471
- if (markerPos < lastYieldedLength) markerPos = lastYieldedLength;
838
+ const markerPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, openFragment) - leadingTrimmed));
472
839
  if (markerPos < stableLength) stableLength = markerPos;
473
840
  }
841
+ const codeSpanHeld = gfmLifecycle.openCodeSpans.length > 0;
842
+ if (codeSpanHeld) {
843
+ const spanPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, gfmLifecycle.openCodeSpans[0].fragment) - leadingTrimmed));
844
+ if (spanPos < stableLength) stableLength = spanPos;
845
+ }
846
+ const codeFenceHeld = state.codeFence !== void 0;
847
+ if (codeFenceHeld) {
848
+ const fencePos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, state.codeFence.fragment) - leadingTrimmed));
849
+ if (fencePos < stableLength) stableLength = fencePos;
850
+ }
851
+ const blockquoteHeld = state.blockquotes.length > 0;
852
+ if (blockquoteHeld) {
853
+ const blockquotePos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, state.blockquotes[0].fragment) - leadingTrimmed));
854
+ if (blockquotePos < stableLength) stableLength = blockquotePos;
855
+ }
856
+ const linkHeld = openLinkFragment >= 0;
857
+ if (linkHeld) {
858
+ const linkPos = Math.max(lastYieldedLength, trimBufferedWhitespacePosition(currentContent, fragmentPosition(state.buffer, openLinkFragment) - leadingTrimmed));
859
+ if (linkPos < stableLength) stableLength = linkPos;
860
+ }
861
+ if (stableLength < lastYieldedLength) stableLength = lastYieldedLength;
474
862
  const newContent = currentContent.slice(lastYieldedLength, stableLength);
475
863
  lastYieldedLength = stableLength;
476
864
  if (newContent) hasYieldedContent = true;
477
- if (!markerHeld && !hasMutableTrailingSpace) {
865
+ if (!markerHeld && !codeSpanHeld && !codeFenceHeld && !blockquoteHeld && !linkHeld && (!retainMutableFragments || !inPre)) {
478
866
  if (!resolvedPlugins.length && !options.wrapWidth && !state.depthMap[26]) {
479
- const tailStart = Math.max(0, stableLength - 2);
480
- const emittedTail = currentContent.slice(tailStart, stableLength);
481
- const mutableTail = currentContent.slice(stableLength);
482
- state.buffer.length = 0;
483
- if (emittedTail || mutableTail) state.buffer.push(emittedTail + mutableTail);
484
- lastYieldedLength = emittedTail.length;
485
- } else if (state.buffer.length > 1) {
867
+ if (retainMutableFragments && leadingTrimmed === 0) {
868
+ const lastFragment = state.buffer.at(-1);
869
+ const fragmentStart = currentContent.length - lastFragment.length;
870
+ const tailStart = Math.max(0, Math.min(stableLength - 2, fragmentStart));
871
+ const emittedTail = currentContent.slice(tailStart, fragmentStart);
872
+ state.buffer.length = 0;
873
+ if (emittedTail) state.buffer.push(emittedTail);
874
+ state.buffer.push(lastFragment);
875
+ lastYieldedLength = stableLength - tailStart;
876
+ } else if (!retainMutableFragments) {
877
+ const tailStart = Math.max(0, stableLength - 2);
878
+ const emittedTail = currentContent.slice(tailStart, stableLength);
879
+ state.buffer.length = 0;
880
+ if (emittedTail) state.buffer.push(emittedTail);
881
+ lastYieldedLength = emittedTail.length;
882
+ }
883
+ } else if (!retainMutableFragments && state.buffer.length > 1) {
486
884
  state.buffer.length = 0;
487
885
  state.buffer.push(currentContent);
488
886
  }