@ai-react-markdown/engine 2.4.5 → 2.5.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.
package/dist/index.cjs CHANGED
@@ -31,7 +31,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  DEFAULT_PAYLOAD: () => DEFAULT_PAYLOAD,
34
- DEF_LINE_START_RE: () => DEF_LINE_START_RE,
35
34
  PIPELINE_STAGES: () => PIPELINE_STAGES,
36
35
  SENTINEL_FN_CONTENT: () => SENTINEL_FN_CONTENT,
37
36
  SENTINEL_LINK_URL: () => SENTINEL_LINK_URL,
@@ -66,7 +65,6 @@ __export(src_exports, {
66
65
  hasLoneSurrogate: () => hasLoneSurrogate,
67
66
  highlight: () => highlight,
68
67
  isFootnoteSection: () => isFootnoteSection,
69
- lastRegionStart: () => lastRegionStart,
70
68
  measureStage: () => measureStage,
71
69
  mergeClassNameAllowlist: () => mergeClassNameAllowlist,
72
70
  normalizeForMatch: () => normalizeForMatch,
@@ -270,10 +268,73 @@ var import_micromark_util_html_tag_name = require("micromark-util-html-tag-name"
270
268
  var import_micromark_util_normalize_identifier = require("micromark-util-normalize-identifier");
271
269
  var TYPE6_NAMES = new Set(import_micromark_util_html_tag_name.htmlBlockNames);
272
270
  var TABLE_PART_NAMES = /* @__PURE__ */ new Set(["td", "th", "tr", "tbody", "thead", "tfoot", "caption", "col", "colgroup"]);
271
+ var HTML_BREAKOUT_TAGS = /* @__PURE__ */ new Set([
272
+ "b",
273
+ "big",
274
+ "blockquote",
275
+ "body",
276
+ "br",
277
+ "center",
278
+ "code",
279
+ "dd",
280
+ "div",
281
+ "dl",
282
+ "dt",
283
+ "em",
284
+ "embed",
285
+ "h1",
286
+ "h2",
287
+ "h3",
288
+ "h4",
289
+ "h5",
290
+ "h6",
291
+ "head",
292
+ "hr",
293
+ "i",
294
+ "img",
295
+ "li",
296
+ "listing",
297
+ "menu",
298
+ "meta",
299
+ "nobr",
300
+ "ol",
301
+ "p",
302
+ "pre",
303
+ "ruby",
304
+ "s",
305
+ "small",
306
+ "span",
307
+ "strong",
308
+ "strike",
309
+ "sub",
310
+ "sup",
311
+ "table",
312
+ "tt",
313
+ "u",
314
+ "ul",
315
+ "var"
316
+ ]);
317
+ var HTML_INTEGRATION_POINTS = ["foreignobject", "desc", "mi", "mo", "mn", "ms", "mtext", "annotation-xml"];
273
318
  var TYPE1_NAMES = /* @__PURE__ */ new Set(["script", "pre", "style", "textarea"]);
319
+ var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set([
320
+ "script",
321
+ "style",
322
+ "textarea",
323
+ "title",
324
+ "xmp",
325
+ "iframe",
326
+ "noembed",
327
+ "noframes",
328
+ // NOT `noscript`: hast-util-raw constructs parse5 with
329
+ // `scriptingEnabled: false`, under which `<noscript>` content is ordinary
330
+ // HTML — modelling it as raw text ignored a `<b>` inside and under-blocked
331
+ // (oracle review of the r2 batch; regression caught before release).
332
+ "plaintext"
333
+ ]);
274
334
  var TYPE6_START_RE = /^<\/?([A-Za-z][A-Za-z0-9-]*)(?:[ \t\r]|\/?>|$)/;
275
335
  var TYPE1_START_RE = /^<(script|pre|style|textarea)(?:[ \t\r]|>|$)/i;
276
- var TYPE7_LINE_RE = /^<(\/?)([A-Za-z][A-Za-z0-9-]*)(?:[ \t\r][^>]*|\/)?>[ \t\r]*$/;
336
+ var TYPE7_LINE_RE = /^(?:<[A-Za-z][A-Za-z0-9-]*(?:[ \t\r][^>]*|\/)?>|<\/[A-Za-z][A-Za-z0-9-]*[ \t\r]*>)[ \t\r]*$/;
337
+ var t7Name = (line) => /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(line)[1];
277
338
  var VOID_TAGS = /* @__PURE__ */ new Set([
278
339
  "area",
279
340
  "base",
@@ -297,7 +358,35 @@ var DEF_RE = /^ {0,3}\[((?:[^[\]\\]|\\.)+)\]:/;
297
358
  var FENCE_RE = /^ {0,3}(`{3,}|~{3,})/;
298
359
  var MATH_RUN_RE = /^ {0,3}(\$\$+)/;
299
360
  var TAG_OR_COMMENT_RE = /<(\/?)([A-Za-z][A-Za-z0-9-]*)(?=[\s/>])([^>]*)>|<!--|-->|--!>/g;
300
- var TRUNCATED_TAG_RE = /<(\/?)([A-Za-z][A-Za-z0-9-]*)([^<>]*)$/;
361
+ var TRUNCATED_TAG_RE = /<(\/?)([A-Za-z][A-Za-z0-9-]*)([^>]*)$/;
362
+ var TAG_START_LT_RE = /<\/?[A-Za-z]/g;
363
+ function scanTagAttrs(text, from, to, out) {
364
+ let st = out.state;
365
+ for (let i = from; i < to; i++) {
366
+ const c = text[i];
367
+ if (st === '"' || st === "'") {
368
+ if (c === st) st = "outside";
369
+ continue;
370
+ }
371
+ const ws = c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
372
+ if (st === "afterEq") {
373
+ if (ws) continue;
374
+ if (c === '"' || c === "'") st = c;
375
+ else if (c === ">") return i;
376
+ else st = "unquoted";
377
+ continue;
378
+ }
379
+ if (st === "unquoted") {
380
+ if (ws) st = "outside";
381
+ else if (c === ">") return i;
382
+ continue;
383
+ }
384
+ if (c === "=") st = "afterEq";
385
+ else if (c === ">") return i;
386
+ }
387
+ out.state = st;
388
+ return -1;
389
+ }
301
390
  var REF_RE = /!?\[((?:[^[\]\\]|\\.)*)\]/g;
302
391
  var BACKTICK_RUN_RE = /`+/g;
303
392
  var MD_BLANK_RE = /^[ \t\r]*$/;
@@ -392,6 +481,8 @@ function freshCheckpoint(defListEnabled, mathFlow, referenceTaint) {
392
481
  openTotal: 0,
393
482
  commentOpen: false,
394
483
  piOpen: false,
484
+ bogusOpen: false,
485
+ rawTextOpen: null,
395
486
  declOpen: false,
396
487
  cdataOpen: false,
397
488
  inFence: false,
@@ -416,6 +507,7 @@ function freshCheckpoint(defListEnabled, mathFlow, referenceTaint) {
416
507
  pendingTruncatedCloses: [],
417
508
  tagAcrossLines: false,
418
509
  tagAcrossLinesIndent: 0,
510
+ tagAcrossLinesState: "outside",
419
511
  htmlFlowReal: false
420
512
  };
421
513
  }
@@ -515,11 +607,21 @@ function computeFreezeBoundary(text, options, resume) {
515
607
  let start = cp.confirmedOffset;
516
608
  let tailLine = null;
517
609
  while (start < text.length) {
518
- let end = text.indexOf("\n", start);
519
- if (end === -1) end = text.length;
520
- const confirmed = end < text.length;
521
- const rawLine = text.slice(start, end);
522
- const lineText = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
610
+ let end = text.length;
611
+ let textEnd = text.length;
612
+ {
613
+ const nl = text.indexOf("\n", start);
614
+ const cr = text.indexOf("\r", start);
615
+ if (cr !== -1 && (nl === -1 || cr < nl)) {
616
+ textEnd = cr;
617
+ end = text.charCodeAt(cr + 1) === 10 ? cr + 1 : cr;
618
+ } else if (nl !== -1) {
619
+ textEnd = nl;
620
+ end = nl;
621
+ }
622
+ }
623
+ const confirmed = end < text.length && !(end === text.length - 1 && text.charCodeAt(end) === 13);
624
+ const lineText = text.slice(start, textEnd);
523
625
  const ln = {
524
626
  start,
525
627
  end,
@@ -611,14 +713,33 @@ function processConfirmedLine(cp, ln, text) {
611
713
  newest.defListSettled = ln.blank ? true : !canBecomeDdLine(ln.text, true);
612
714
  }
613
715
  const isBlockStart = cp.prevLineBlank;
614
- if (cp.htmlSeamPending && !ln.blank && !cp.htmlFlowSinceBlank && !(cp.commentOpen || cp.piOpen || cp.declOpen || cp.cdataOpen)) {
716
+ if (cp.htmlSeamPending && !ln.blank && !cp.htmlFlowSinceBlank && !(cp.commentOpen || cp.piOpen || cp.declOpen || cp.cdataOpen || cp.bogusOpen)) {
615
717
  const defShapedLine = DEF_RE.test(ln.text) || FOOTNOTE_DEF_RE.test(ln.text);
616
718
  const commentOnly = ln.text.replace(/<!--[\s\S]*?-->/g, " ").replace(/<!--[\s\S]*$/, " ").replace(/[ \t\r]/g, "") === "";
617
719
  if (!defShapedLine && !commentOnly) {
618
720
  cp.htmlSeamPending = false;
619
721
  }
620
722
  }
723
+ const inForeignContent = () => (cp.tagBalance.get("svg") ?? 0) > 0 || (cp.tagBalance.get("math") ?? 0) > 0;
724
+ const honoursSelfClosing = (tag) => {
725
+ if (tag === "svg" || tag === "math") return true;
726
+ if (!inForeignContent() || HTML_BREAKOUT_TAGS.has(tag)) return false;
727
+ for (const ip of HTML_INTEGRATION_POINTS) if ((cp.tagBalance.get(ip) ?? 0) > 0) return false;
728
+ return true;
729
+ };
730
+ const htmlRulesApply = () => {
731
+ if (!inForeignContent()) return true;
732
+ for (const ip of HTML_INTEGRATION_POINTS) if ((cp.tagBalance.get(ip) ?? 0) > 0) return true;
733
+ return false;
734
+ };
621
735
  const applyTag = (tag, closing) => {
736
+ if (cp.rawTextOpen !== null) {
737
+ if (!(closing && tag === cp.rawTextOpen)) return;
738
+ cp.rawTextOpen = null;
739
+ } else if (!closing && RAW_TEXT_ELEMENTS.has(tag) && htmlRulesApply()) {
740
+ cp.rawTextOpen = tag;
741
+ if (tag === "plaintext") cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start);
742
+ }
622
743
  if (closing) {
623
744
  const count = cp.tagBalance.get(tag) ?? 0;
624
745
  if (count > 0) {
@@ -630,8 +751,9 @@ function processConfirmedLine(cp, ln, text) {
630
751
  cp.openTotal += 1;
631
752
  }
632
753
  };
754
+ const strayTablePart = (tag) => TABLE_PART_NAMES.has(tag) && (cp.tagBalance.get("table") ?? 0) === 0;
633
755
  const commentOpenAtLineStart = cp.commentOpen;
634
- const rawOpenAtLineStart = cp.commentOpen || cp.piOpen || cp.declOpen || cp.cdataOpen;
756
+ const rawOpenAtLineStart = cp.commentOpen || cp.piOpen || cp.declOpen || cp.cdataOpen || cp.bogusOpen;
635
757
  if (cp.inFence) {
636
758
  const close = FENCE_RE.exec(ln.text);
637
759
  if (close && close[1][0] === cp.fenceChar && close[1].length >= cp.fenceLen && isMdBlank(ln.text.slice(close[0].length))) {
@@ -714,13 +836,21 @@ function processConfirmedLine(cp, ln, text) {
714
836
  cp.pendingTruncatedTags = [];
715
837
  }
716
838
  cp.pendingTruncatedCloses = [];
839
+ if (cp.tagAcrossLines && (cp.tagAcrossLinesState === '"' || cp.tagAcrossLinesState === "'")) {
840
+ cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start);
841
+ }
717
842
  cp.tagAcrossLines = false;
843
+ cp.tagAcrossLinesState = "outside";
844
+ if (cp.bogusOpen) {
845
+ cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start);
846
+ cp.bogusOpen = false;
847
+ }
718
848
  cp.blankRun += 1;
719
849
  cp.lastBlankStart = ln.start;
720
850
  cp.candidates.push({
721
851
  offset: Math.min(ln.end + 1, text.length),
722
852
  blankRun: cp.blankRun,
723
- htmlBalanced: cp.openTotal === 0 && !cp.commentOpen && !cp.piOpen && !cp.declOpen && !cp.cdataOpen,
853
+ htmlBalanced: cp.openTotal === 0 && !cp.commentOpen && !cp.piOpen && !cp.declOpen && !cp.cdataOpen && !cp.bogusOpen,
724
854
  hazard: cp.hazardVerdict,
725
855
  seamRisk: cp.htmlSeamPending,
726
856
  defListSettled: null
@@ -750,7 +880,7 @@ function processConfirmedLine(cp, ln, text) {
750
880
  const t7 = TYPE7_LINE_RE.exec(t);
751
881
  if (t6 !== null && TYPE6_NAMES.has(t6[1].toLowerCase()) || TYPE1_START_RE.test(t) || // Type 7 cannot interrupt a paragraph, and excludes the raw-text
752
882
  // names (those are type 1 as start tags, paragraph as end tags).
753
- t7 !== null && !cp.prevLineWasText && !TYPE1_NAMES.has(t7[2].toLowerCase())) {
883
+ t7 !== null && !cp.prevLineWasText && !TYPE1_NAMES.has(t7Name(t).toLowerCase())) {
754
884
  cp.htmlFlowReal = true;
755
885
  }
756
886
  }
@@ -852,7 +982,7 @@ ${cont(scanText)}` };
852
982
  pos = c + 3;
853
983
  continue;
854
984
  }
855
- if (cp.declOpen) {
985
+ if (cp.declOpen || cp.bogusOpen) {
856
986
  const c = scanText.indexOf(">", pos);
857
987
  if (c === -1) {
858
988
  rawSpans.push([pos, scanText.length]);
@@ -860,6 +990,7 @@ ${cont(scanText)}` };
860
990
  }
861
991
  rawSpans.push([pos, c + 1]);
862
992
  cp.declOpen = false;
993
+ cp.bogusOpen = false;
863
994
  pos = c + 1;
864
995
  continue;
865
996
  }
@@ -867,10 +998,16 @@ ${cont(scanText)}` };
867
998
  const cd = scanText.indexOf("<![CDATA[", pos);
868
999
  const dm = scanText.slice(pos).search(/<![A-Za-z]/);
869
1000
  const decl = dm === -1 ? -1 : pos + dm;
870
- const starts = [pi, cd, decl].filter((x) => x !== -1);
1001
+ const bm = cp.htmlFlowReal ? scanText.slice(pos).search(/<!(?!--|[A-Za-z]|\[CDATA\[)|<\/(?![A-Za-z])/) : -1;
1002
+ const bogus = bm === -1 ? -1 : pos + bm;
1003
+ const starts = [pi, cd, decl, bogus].filter((x) => x !== -1);
871
1004
  if (starts.length === 0) break;
872
1005
  const first = Math.min(...starts);
873
- if (first === cd) {
1006
+ if (first === bogus) {
1007
+ rawSpans.push([bogus, bogus + 2]);
1008
+ cp.bogusOpen = true;
1009
+ pos = bogus + 2;
1010
+ } else if (first === cd) {
874
1011
  rawSpans.push([cd, cd + 9]);
875
1012
  cp.cdataOpen = true;
876
1013
  pos = cd + 9;
@@ -897,22 +1034,27 @@ ${cont(scanText)}` };
897
1034
  let skipTagScan = false;
898
1035
  if (cp.tagAcrossLines) {
899
1036
  if (ln.indent < cp.tagAcrossLinesIndent) poisonRawDivergence();
900
- const gt = ln.text.indexOf(">");
1037
+ const attrs = { state: cp.tagAcrossLinesState };
1038
+ const gt = scanTagAttrs(ln.text, 0, ln.text.length, attrs);
901
1039
  if (gt === -1) {
1040
+ scanTagAttrs("\n", 0, 1, attrs);
1041
+ cp.tagAcrossLinesState = attrs.state;
902
1042
  skipTagScan = true;
903
1043
  } else {
904
- if (/["']/.test(ln.text.slice(0, gt))) poisonRawDivergence();
905
1044
  for (const tag of cp.pendingTruncatedCloses) applyTag(tag, true);
906
1045
  cp.pendingTruncatedCloses = [];
907
1046
  cp.tagAcrossLines = false;
1047
+ cp.tagAcrossLinesState = "outside";
908
1048
  tagText = " ".repeat(gt + 1) + tagText.slice(gt + 1);
909
1049
  }
910
1050
  }
1051
+ let tagHandledAsTruncated = false;
911
1052
  if (!skipTagScan) {
912
1053
  TAG_OR_COMMENT_RE.lastIndex = 0;
913
1054
  let m;
914
1055
  let lastCommentOpenerIdx = -1;
915
1056
  while ((m = TAG_OR_COMMENT_RE.exec(tagText)) !== null) {
1057
+ if (cp.rawTextOpen !== null && (m[0] === "<!--" || m[0] === "-->" || m[0] === "--!>")) continue;
916
1058
  if (m[0] === "<!--") {
917
1059
  const next = tagText.slice(m.index + 4, m.index + 6);
918
1060
  if (cp.commentOpen) {
@@ -938,9 +1080,32 @@ ${cont(scanText)}` };
938
1080
  if (cp.commentOpen) continue;
939
1081
  const closing = m[1] === "/";
940
1082
  const tag = m[2].toLowerCase();
941
- if (TABLE_PART_NAMES.has(tag)) cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start + m.index);
942
- const selfClosing = m[3] !== void 0 && /\/\s*$/.test(m[3]);
943
- if (VOID_TAGS.has(tag) || selfClosing) continue;
1083
+ if (strayTablePart(tag)) cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start + m.index);
1084
+ let attrs = m[3] ?? "";
1085
+ if (cp.htmlFlowReal && (cp.rawTextOpen === null || closing && tag === cp.rawTextOpen)) {
1086
+ const attrStart = m.index + 1 + (closing ? 1 : 0) + m[2].length;
1087
+ const st = { state: "outside" };
1088
+ const gt = scanTagAttrs(tagText, attrStart, tagText.length, st);
1089
+ if (gt === -1) {
1090
+ if (!VOID_TAGS.has(tag)) {
1091
+ if (closing) cp.pendingTruncatedCloses.push(tag);
1092
+ else applyTag(tag, false);
1093
+ }
1094
+ scanTagAttrs("\n", 0, 1, st);
1095
+ cp.tagAcrossLines = true;
1096
+ cp.tagAcrossLinesIndent = ln.indent;
1097
+ cp.tagAcrossLinesState = st.state;
1098
+ tagHandledAsTruncated = true;
1099
+ break;
1100
+ }
1101
+ if (gt + 1 !== m.index + m[0].length) {
1102
+ attrs = tagText.slice(attrStart, gt);
1103
+ TAG_OR_COMMENT_RE.lastIndex = gt + 1;
1104
+ }
1105
+ }
1106
+ if (closing && !cp.htmlFlowReal && !/^\s*$/.test(attrs)) continue;
1107
+ const selfClosing = /\/\s*$/.test(attrs);
1108
+ if (VOID_TAGS.has(tag) || selfClosing && honoursSelfClosing(tag)) continue;
944
1109
  applyTag(tag, closing);
945
1110
  }
946
1111
  if (cp.commentOpen && lastCommentOpenerIdx !== -1 && !inRawText) {
@@ -959,26 +1124,40 @@ ${cont(scanText)}` };
959
1124
  if (startMasked || wholeVisible || inRaw(mr.index) || cp.commentOpen) continue;
960
1125
  const closing = mr[1] === "/";
961
1126
  const tag = mr[2].toLowerCase();
962
- if (TABLE_PART_NAMES.has(tag)) cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start + mr.index);
1127
+ if (strayTablePart(tag)) cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start + mr.index);
1128
+ if (closing && mr[3] !== void 0 && !/^\s*$/.test(mr[3])) continue;
963
1129
  const selfClosing = mr[3] !== void 0 && /\/\s*$/.test(mr[3]);
964
- if (VOID_TAGS.has(tag) || selfClosing) continue;
1130
+ if (VOID_TAGS.has(tag) || selfClosing && honoursSelfClosing(tag)) continue;
965
1131
  applyTag(tag, closing);
966
1132
  }
967
1133
  }
968
1134
  if (cp.pendingTruncatedTags.length > 0 && ln.text.includes(">")) {
1135
+ if (cp.pendingTruncatedTags.some((t) => strayTablePart(t))) {
1136
+ cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start);
1137
+ }
969
1138
  cp.pendingTruncatedTags = [];
970
1139
  }
971
- if (!cp.commentOpen) {
972
- const lastLt = tagText.lastIndexOf("<");
1140
+ if (!cp.commentOpen && !tagHandledAsTruncated) {
1141
+ let lastLt = -1;
1142
+ TAG_START_LT_RE.lastIndex = 0;
1143
+ for (let ms = TAG_START_LT_RE.exec(tagText); ms !== null; ms = TAG_START_LT_RE.exec(tagText)) {
1144
+ lastLt = ms.index;
1145
+ TAG_START_LT_RE.lastIndex = ms.index + 1;
1146
+ }
973
1147
  if (lastLt !== -1 && !tagText.includes(">", lastLt)) {
974
1148
  const m2 = TRUNCATED_TAG_RE.exec(tagText.slice(lastLt));
975
1149
  if (m2) {
976
1150
  const closing = m2[1] === "/";
977
1151
  const tag = m2[2].toLowerCase();
978
- if (TABLE_PART_NAMES.has(tag)) cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start + lastLt);
1152
+ if (strayTablePart(tag) && cp.htmlFlowReal) {
1153
+ cp.phasePoisonedAt = Math.min(cp.phasePoisonedAt, ln.start + lastLt);
1154
+ }
979
1155
  if (cp.htmlFlowReal) {
980
1156
  cp.tagAcrossLines = true;
981
1157
  cp.tagAcrossLinesIndent = ln.indent;
1158
+ const attrs = { state: "outside" };
1159
+ scanTagAttrs(m2[3] + "\n", 0, m2[3].length + 1, attrs);
1160
+ cp.tagAcrossLinesState = attrs.state;
982
1161
  }
983
1162
  if (closing) {
984
1163
  if (!VOID_TAGS.has(tag) && cp.htmlFlowReal) cp.pendingTruncatedCloses.push(tag);
@@ -1195,6 +1374,24 @@ function rebaseDualWalk(node, segments, maxEnd, offsetDelta, lineDelta) {
1195
1374
  }
1196
1375
  }
1197
1376
  var TABLE_PART_TAG_RE = /<(?:td|th|tr|tbody|thead|tfoot|caption|col|colgroup)\b/i;
1377
+ var TABLE_TOKEN_RE = /<(\/?)(table|td|th|tr|tbody|thead|tfoot|caption|col|colgroup)\b/gi;
1378
+ function hasStrayTablePart(values) {
1379
+ let depth = 0;
1380
+ for (const value of values) {
1381
+ TABLE_TOKEN_RE.lastIndex = 0;
1382
+ let m;
1383
+ while ((m = TABLE_TOKEN_RE.exec(value)) !== null) {
1384
+ const closing = m[1] === "/";
1385
+ const tag = m[2].toLowerCase();
1386
+ if (tag === "table") {
1387
+ depth = closing ? Math.max(0, depth - 1) : depth + 1;
1388
+ continue;
1389
+ }
1390
+ if (depth === 0) return true;
1391
+ }
1392
+ }
1393
+ return false;
1394
+ }
1198
1395
  var STRAY_SYNTHESIZED_END_TAG_RE = /<\/(?:br|p)\b/i;
1199
1396
  function spliceTrees(input) {
1200
1397
  const { prevMdast, prevHast, tailMdast, tailHast, content, boundary, injectionPrefix, injectedSegments } = input;
@@ -1252,7 +1449,7 @@ function spliceTrees(input) {
1252
1449
  return !(start !== void 0 && start < injectedLen);
1253
1450
  });
1254
1451
  const tailWrapVisible = tailMdastChildren.some((child) => !isWrapInvisible(child));
1255
- if (prefixMdast.some((c) => c.type === "html" && TABLE_PART_TAG_RE.test(c.value))) return null;
1452
+ if (hasStrayTablePart(prefixMdast.flatMap((c) => c.type === "html" ? [c.value] : []))) return null;
1256
1453
  for (const child of tailMdastChildren) {
1257
1454
  if (isWrapInvisible(child)) continue;
1258
1455
  if (child.type !== "html") break;
@@ -1647,7 +1844,7 @@ function normalizeId(s) {
1647
1844
  return (0, import_micromark_util_normalize_identifier3.normalizeIdentifier)(s);
1648
1845
  }
1649
1846
  function normalizeForMatch(s) {
1650
- return (0, import_micromark_util_normalize_identifier3.normalizeIdentifier)(s.replace(/\\([!-/:-@[-`{-~])/g, "$1"));
1847
+ return (0, import_micromark_util_normalize_identifier3.normalizeIdentifier)(s);
1651
1848
  }
1652
1849
 
1653
1850
  // src/components/collectDefLabels.ts
@@ -1965,22 +2162,68 @@ function createRegistry(onEmpty) {
1965
2162
  labelSet: { footnoteLabels: /* @__PURE__ */ new Set(), linkLabels: /* @__PURE__ */ new Set() },
1966
2163
  version: 0,
1967
2164
  _reactIdMap: /* @__PURE__ */ new Map(),
2165
+ /** Symbol → its `documentIndex`, for chunks that supplied one. */
2166
+ _chunkIndex: /* @__PURE__ */ new Map(),
1968
2167
  _subscribers: /* @__PURE__ */ new Set(),
1969
2168
  _notifyScheduled: false,
1970
- allocateSymbol(reactId) {
2169
+ allocateSymbol(reactId, rawDocumentIndex) {
2170
+ const documentIndex = rawDocumentIndex !== void 0 && Number.isFinite(rawDocumentIndex) ? rawDocumentIndex : void 0;
2171
+ if (false) {
2172
+ console.warn(
2173
+ `[ai-react-markdown] documentIndex must be a finite number \u2014 received ${String(rawDocumentIndex)}; ignoring it for this chunk.`
2174
+ );
2175
+ }
1971
2176
  const existing = this._reactIdMap.get(reactId);
1972
2177
  if (existing) {
1973
2178
  existing.refcount++;
2179
+ const moved = documentIndex !== void 0 ? this._chunkIndex.get(existing.symbol) !== documentIndex : this._chunkIndex.has(existing.symbol);
2180
+ if (moved) {
2181
+ const at = this.chunkOrder.indexOf(existing.symbol);
2182
+ if (at !== -1) this.chunkOrder.splice(at, 1);
2183
+ this._placeChunk(existing.symbol, documentIndex);
2184
+ this._notify();
2185
+ }
1974
2186
  return existing.symbol;
1975
2187
  }
1976
2188
  const sym = Symbol(reactId);
1977
2189
  this._reactIdMap.set(reactId, { symbol: sym, refcount: 1 });
1978
- this.chunkOrder.push(sym);
2190
+ this._placeChunk(sym, documentIndex);
1979
2191
  this._notify();
1980
2192
  return sym;
1981
2193
  },
1982
- registerChunk(reactId, footnotes, links) {
1983
- const sym = this.allocateSymbol(reactId);
2194
+ /** Put `sym` into `chunkOrder` at its document position. Without an index
2195
+ * it goes last (mount order — the historical behaviour); with one it
2196
+ * sorts before the first chunk that sits later, where a chunk WITHOUT an
2197
+ * index counts as "later" so an indexed chunk never lands behind one
2198
+ * whose position is unknown. */
2199
+ _placeChunk(sym, documentIndex) {
2200
+ if (false) {
2201
+ const anyIndexed = documentIndex !== void 0 || this.chunkOrder.some((s) => this._chunkIndex.has(s));
2202
+ const anyPlain = documentIndex === void 0 || this.chunkOrder.some((s) => !this._chunkIndex.has(s));
2203
+ if (anyIndexed && anyPlain) {
2204
+ console.warn(
2205
+ "[ai-react-markdown] Some chunks of this document supply `documentIndex` and some do not. Indexed chunks always sort ahead of un-indexed ones, so footnote numbering and aggregate-footer placement will not follow document order. Pass `documentIndex` to every chunk, or to none."
2206
+ );
2207
+ }
2208
+ }
2209
+ if (documentIndex === void 0) {
2210
+ this._chunkIndex.delete(sym);
2211
+ this.chunkOrder.push(sym);
2212
+ return;
2213
+ }
2214
+ this._chunkIndex.set(sym, documentIndex);
2215
+ let at = this.chunkOrder.length;
2216
+ for (let i = 0; i < this.chunkOrder.length; i++) {
2217
+ const other = this._chunkIndex.get(this.chunkOrder[i]);
2218
+ if (other === void 0 || other > documentIndex) {
2219
+ at = i;
2220
+ break;
2221
+ }
2222
+ }
2223
+ this.chunkOrder.splice(at, 0, sym);
2224
+ },
2225
+ registerChunk(reactId, footnotes, links, documentIndex) {
2226
+ const sym = this.allocateSymbol(reactId, documentIndex);
1984
2227
  this.contributeLabels(sym, footnotes, links);
1985
2228
  return sym;
1986
2229
  },
@@ -2003,6 +2246,7 @@ function createRegistry(onEmpty) {
2003
2246
  this._reactIdMap.delete(reactId);
2004
2247
  const idx = this.chunkOrder.indexOf(entry.symbol);
2005
2248
  if (idx !== -1) this.chunkOrder.splice(idx, 1);
2249
+ this._chunkIndex.delete(entry.symbol);
2006
2250
  this.chunkData.delete(entry.symbol);
2007
2251
  const nextFn = /* @__PURE__ */ new Set();
2008
2252
  const nextLink = /* @__PURE__ */ new Set();
@@ -3629,17 +3873,28 @@ function mergeClassNameAllowlist(existing, extraClassNames) {
3629
3873
  return entries;
3630
3874
  }
3631
3875
  var crossChunkTags = ["cross-chunk-link", "cross-chunk-image", "footnote-sup"];
3632
- var sanitizeSchema = cloneDeep_default({
3633
- ...import_rehype_sanitize2.defaultSchema,
3634
- tagNames: [...import_rehype_sanitize2.defaultSchema.tagNames || [], "mark", ...crossChunkTags],
3635
- attributes: {
3636
- ...import_rehype_sanitize2.defaultSchema.attributes,
3637
- code: mergeClassNameAllowlist(import_rehype_sanitize2.defaultSchema.attributes?.code, ["math-inline", "math-display"]),
3638
- "cross-chunk-link": ["label", "referenceType", "documentId", "localUrl", "localTitle"],
3639
- "cross-chunk-image": ["label", "referenceType", "documentId", "alt", "localUrl", "localTitle"],
3640
- "footnote-sup": ["label", "localOccurrence", "localNumber", "documentId"]
3641
- }
3642
- });
3876
+ function deepFreeze(value) {
3877
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
3878
+ Object.freeze(value);
3879
+ for (const key of Object.keys(value)) deepFreeze(value[key]);
3880
+ }
3881
+ return value;
3882
+ }
3883
+ var STRIPPED_TAGS = ["script", "style", "title", "textarea", "noframes", "noembed", "xmp", "iframe", "plaintext"];
3884
+ var sanitizeSchema = deepFreeze(
3885
+ cloneDeep_default({
3886
+ ...import_rehype_sanitize2.defaultSchema,
3887
+ tagNames: [...import_rehype_sanitize2.defaultSchema.tagNames || [], "mark", ...crossChunkTags],
3888
+ attributes: {
3889
+ ...import_rehype_sanitize2.defaultSchema.attributes,
3890
+ code: mergeClassNameAllowlist(import_rehype_sanitize2.defaultSchema.attributes?.code, ["math-inline", "math-display"]),
3891
+ "cross-chunk-link": ["label", "referenceType", "documentId", "localUrl", "localTitle"],
3892
+ "cross-chunk-image": ["label", "referenceType", "documentId", "alt", "localUrl", "localTitle"],
3893
+ "footnote-sup": ["label", "localOccurrence", "localNumber", "documentId"]
3894
+ },
3895
+ strip: [.../* @__PURE__ */ new Set([...import_rehype_sanitize2.defaultSchema.strip || [], ...STRIPPED_TAGS])]
3896
+ })
3897
+ );
3643
3898
 
3644
3899
  // src/components/crossChunkUrlSanitize.ts
3645
3900
  function fakeElement(tagName, key, url) {
@@ -3852,6 +4107,14 @@ var graphemeEnds = (text, base) => {
3852
4107
  }
3853
4108
  return ends;
3854
4109
  };
4110
+ var RESUME_LOOKBACK = 64;
4111
+ var isMidSurrogatePair = (text, at) => at > 0 && at < text.length && (text.charCodeAt(at - 1) & 64512) === 55296 && (text.charCodeAt(at) & 64512) === 56320;
4112
+ var RI_FIRST = 127462;
4113
+ var RI_LAST = 127487;
4114
+ var isRegionalIndicatorAt = (text, at) => {
4115
+ const cp = text.codePointAt(at);
4116
+ return cp !== void 0 && cp >= RI_FIRST && cp <= RI_LAST;
4117
+ };
3855
4118
  var createSmoothStreamController = (options = {}) => {
3856
4119
  const now = options.now ?? defaultNow;
3857
4120
  const schedule = options.schedule ?? defaultSchedule;
@@ -3860,6 +4123,7 @@ var createSmoothStreamController = (options = {}) => {
3860
4123
  let pending = [];
3861
4124
  let tentativeEnd = 0;
3862
4125
  let finished = false;
4126
+ let seam;
3863
4127
  let drainDeadlineAt;
3864
4128
  let initialized = false;
3865
4129
  let visibleCache = "";
@@ -3943,15 +4207,31 @@ var createSmoothStreamController = (options = {}) => {
3943
4207
  if (!disposed && !cancelFrame && pending.length > 0) cancelFrame = schedule(tick);
3944
4208
  };
3945
4209
  const resegmentTail = () => {
4210
+ if (seam !== void 0 && seam < source.length && pending[pending.length - 1] === seam) {
4211
+ pending.pop();
4212
+ }
3946
4213
  const from = pending.length > 0 ? pending[pending.length - 1] : visibleEnd;
3947
- const ends = graphemeEnds(source.slice(from), from);
4214
+ let anchor = from;
4215
+ if (seam !== void 0 && from <= seam) {
4216
+ anchor = Math.max(0, from - RESUME_LOOKBACK);
4217
+ if (isMidSurrogatePair(source, anchor)) anchor -= 1;
4218
+ while (anchor >= 2 && isRegionalIndicatorAt(source, anchor - 2)) anchor -= 2;
4219
+ } else {
4220
+ seam = void 0;
4221
+ }
4222
+ const ends = graphemeEnds(source.slice(anchor), anchor);
3948
4223
  if (ends.length === 0) {
3949
4224
  tentativeEnd = from;
3950
4225
  return;
3951
4226
  }
3952
4227
  tentativeEnd = ends[ends.length - 1];
3953
- const confirmedEnds = finished ? ends : ends.slice(0, -1);
3954
- for (const end of confirmedEnds) pending.push(end);
4228
+ let hold = 1;
4229
+ if (!finished && ends.length > 1) {
4230
+ const last = source.charCodeAt(source.length - 1);
4231
+ if (last >= 55296 && last <= 56319) hold = 2;
4232
+ }
4233
+ const confirmedEnds = finished ? ends : ends.slice(0, -hold);
4234
+ for (const end of confirmedEnds) if (end > from) pending.push(end);
3955
4235
  };
3956
4236
  const snap = (next) => {
3957
4237
  disposed = false;
@@ -3965,6 +4245,7 @@ var createSmoothStreamController = (options = {}) => {
3965
4245
  visibleEnd = next.length;
3966
4246
  tentativeEnd = next.length;
3967
4247
  pending = [];
4248
+ seam = next.length;
3968
4249
  credit = 0;
3969
4250
  cancelScheduled();
3970
4251
  if (visibleCache !== next) notify();
@@ -3999,6 +4280,7 @@ var createSmoothStreamController = (options = {}) => {
3999
4280
  if (tentativeEnd > (pending.length > 0 ? pending[pending.length - 1] : visibleEnd)) {
4000
4281
  pending.push(tentativeEnd);
4001
4282
  }
4283
+ seam = source.length;
4002
4284
  ensureScheduled();
4003
4285
  },
4004
4286
  snap,
@@ -4078,10 +4360,11 @@ function findClosingBacktickRun(content, start, n) {
4078
4360
  const runLen = getRepeatedMarkerLength(content, i, "`");
4079
4361
  if (runLen === n) return i;
4080
4362
  i += runLen;
4081
- } else if (ch === "\n") {
4363
+ } else if (ch === "\n" || ch === "\r") {
4082
4364
  let j = i + 1;
4083
- while (j < content.length && (content[j] === " " || content[j] === " " || content[j] === "\r")) j += 1;
4084
- if (j >= content.length || content[j] === "\n") return -1;
4365
+ if (ch === "\r" && content[j] === "\n") j += 1;
4366
+ while (j < content.length && (content[j] === " " || content[j] === " ")) j += 1;
4367
+ if (j >= content.length || content[j] === "\n" || content[j] === "\r") return -1;
4085
4368
  i += 1;
4086
4369
  } else {
4087
4370
  i += 1;
@@ -4182,26 +4465,54 @@ function escapeMhchemCommands(text) {
4182
4465
  return text.replaceAll("$\\ce{", "$\\\\ce{").replaceAll("$\\pu{", "$\\\\pu{");
4183
4466
  }
4184
4467
  var CURRENCY_REGEX = /(?<![\\$])\$(?!\$)(?=\d+(?:,\d{3})*(?:\.\d+)?(?:[KMBkmb])?(?:\s|$|[^a-zA-Z\d]))/g;
4185
- var NO_ESCAPED_DOLLAR_REGEX = /(?<![\\$])\$(?!\$)/g;
4186
4468
  var DELIMITERS_REGEX = /(?<!!)\\\[([\S\s]*?[^\\])\\](?!\()|\\\((.*?)\\\)/g;
4187
4469
  var ARRAY_COL_SPEC_OR_PIPE_REGEX = /(\\begin\{(?:array|tabular[x*]?)\}\{[^}]*\})|(?<!\\)\|/g;
4188
- var LATEX_BLOCK_REGEX = /\$\$([\S\s]*?)\$\$|(?<![\\$])\$(?!\$)((?:[^$\n]|\\\$)*?)(?<![\\`])\$(?!\$)/g;
4470
+ var EVEN_BACKSLASHES = String.raw`(?<=(?:^|[^\\])(?:\\\\)*)`;
4471
+ var LATEX_BLOCK_REGEX = new RegExp(
4472
+ String.raw`${EVEN_BACKSLASHES}\$\$([\S\s]*?)${EVEN_BACKSLASHES}\$\$|(?<![\\$])\$(?!\$)((?:[^$\n]|\\\$)*?)(?<![\\` + "`" + String.raw`])\$(?!\$)`,
4473
+ "g"
4474
+ );
4189
4475
  var TEXT_COMMAND = "\\text{";
4190
4476
  var SINGLE_DOLLAR_REGEX = /(?<![\\$])\$(?!\$)((?:[^$\n]|\\[$])+?)(?<!\\)(?<!`)\$(?!\$)/g;
4477
+ function countBareDollars(str, from, to, prev, next) {
4478
+ let n = 0;
4479
+ for (let j = from; j < to; j++) {
4480
+ if (str.charCodeAt(j) !== 36) continue;
4481
+ const before = j > from ? str[j - 1] : prev;
4482
+ const after = j + 1 < to ? str[j + 1] : next;
4483
+ if (before !== "\\" && before !== "$" && after !== "$") n += 1;
4484
+ }
4485
+ return n;
4486
+ }
4191
4487
  function escapeCurrencyDollarSigns(text) {
4192
4488
  const parts = [];
4193
4489
  let lastIndex = 0;
4194
4490
  const currencyMatches = Array.from(text.matchAll(CURRENCY_REGEX));
4195
4491
  let currentLineProcessed = "";
4492
+ let currentLineDollars = 0;
4493
+ const appendToLine = (piece) => {
4494
+ if (piece.length === 0) return;
4495
+ const prevLast = currentLineProcessed.length > 0 ? currentLineProcessed[currentLineProcessed.length - 1] : "";
4496
+ const prevBeforeLast = currentLineProcessed.length > 1 ? currentLineProcessed[currentLineProcessed.length - 2] : "";
4497
+ const prevLastCounted = prevLast === "$" && prevBeforeLast !== "\\" && prevBeforeLast !== "$";
4498
+ if (prevLastCounted && piece[0] === "$") currentLineDollars -= 1;
4499
+ currentLineDollars += countBareDollars(piece, 0, piece.length, prevLast, "");
4500
+ currentLineProcessed += piece;
4501
+ };
4502
+ const resetLine = (rest) => {
4503
+ currentLineProcessed = "";
4504
+ currentLineDollars = 0;
4505
+ appendToLine(rest);
4506
+ };
4196
4507
  for (let i = 0; i < currencyMatches.length; i++) {
4197
4508
  const match = currencyMatches[i];
4198
4509
  const segment = text.substring(lastIndex, match.index);
4199
4510
  parts.push(segment);
4200
4511
  const newlineIdx = Math.max(segment.lastIndexOf("\n"), segment.lastIndexOf("\r"));
4201
4512
  if (newlineIdx !== -1) {
4202
- currentLineProcessed = segment.substring(newlineIdx + 1);
4513
+ resetLine(segment.substring(newlineIdx + 1));
4203
4514
  } else {
4204
- currentLineProcessed += segment;
4515
+ appendToLine(segment);
4205
4516
  }
4206
4517
  let needEscape = true;
4207
4518
  const restStart = match.index + 1;
@@ -4218,15 +4529,21 @@ function escapeCurrencyDollarSigns(text) {
4218
4529
  }
4219
4530
  firstLineBeforeNextMatch = text.substring(restStart, eol);
4220
4531
  }
4221
- if (Array.from(firstLineBeforeNextMatch.matchAll(NO_ESCAPED_DOLLAR_REGEX)).length % 2 !== 0) {
4222
- const wholeLineBeforeNextMatchWithoutCurrentDollar = currentLineProcessed + firstLineBeforeNextMatch;
4223
- if (Array.from(wholeLineBeforeNextMatchWithoutCurrentDollar.matchAll(NO_ESCAPED_DOLLAR_REGEX)).length % 2 !== 0) {
4224
- needEscape = false;
4225
- }
4532
+ const restDollars = countBareDollars(firstLineBeforeNextMatch, 0, firstLineBeforeNextMatch.length, "", "");
4533
+ if (restDollars % 2 !== 0) {
4534
+ const L = currentLineProcessed;
4535
+ const lLast = L.length > 0 ? L[L.length - 1] : "";
4536
+ const lBeforeLast = L.length > 1 ? L[L.length - 2] : "";
4537
+ const lLastCounted = lLast === "$" && lBeforeLast !== "\\" && lBeforeLast !== "$";
4538
+ const f0 = firstLineBeforeNextMatch[0];
4539
+ let whole = currentLineDollars + restDollars;
4540
+ if (lLastCounted && f0 === "$") whole -= 1;
4541
+ if (f0 === "$" && (lLast === "\\" || lLast === "$") && firstLineBeforeNextMatch[1] !== "$") whole -= 1;
4542
+ if (whole % 2 !== 0) needEscape = false;
4226
4543
  }
4227
4544
  const replacement = needEscape ? "\\$" : "$";
4228
4545
  parts.push(replacement);
4229
- currentLineProcessed += replacement;
4546
+ appendToLine(replacement);
4230
4547
  lastIndex = match.index + 1;
4231
4548
  }
4232
4549
  parts.push(text.substring(lastIndex));
@@ -4294,8 +4611,7 @@ function escapeLatexPipesInUnclosed(text) {
4294
4611
  const tail = text.substring(unclosedStart + delimLen);
4295
4612
  return before + delim + replaceUnescapedPipes(tail);
4296
4613
  }
4297
- function truncateUnclosedLatexBlock(text) {
4298
- const unclosedStart = findUnclosedDelimiterStart(text, "double-only");
4614
+ function truncateUnclosedLatexBlock(text, unclosedStart = findUnclosedDelimiterStart(text, "double-only")) {
4299
4615
  if (unclosedStart === -1) return text;
4300
4616
  return text.substring(0, unclosedStart).trimEnd();
4301
4617
  }
@@ -4406,8 +4722,9 @@ function processSliceInstrumented(slice, probe = true) {
4406
4722
  if (probe && hasUnclosedTextCommand(text)) quiescent = false;
4407
4723
  text = escapeTextUnderscores(text);
4408
4724
  text = convertSingleToDoubleDollar(text);
4725
+ let unclosedDouble;
4409
4726
  if (probe || index === 0 && LEADING_DOUBLE_DOLLAR_RE.test(text)) {
4410
- const unclosedDouble = findUnclosedDelimiterStart(text, "double-only");
4727
+ unclosedDouble = findUnclosedDelimiterStart(text, "double-only");
4411
4728
  if (unclosedDouble !== -1) {
4412
4729
  quiescent = false;
4413
4730
  if (index === 0 && text.slice(0, unclosedDouble).trim() === "") {
@@ -4415,7 +4732,7 @@ function processSliceInstrumented(slice, probe = true) {
4415
4732
  }
4416
4733
  }
4417
4734
  }
4418
- text = truncateUnclosedLatexBlock(text);
4735
+ text = truncateUnclosedLatexBlock(text, unclosedDouble);
4419
4736
  parts.push(text);
4420
4737
  }
4421
4738
  return { out: parts.join(""), quiescent, truncatedAtSeamStart };
@@ -4544,7 +4861,6 @@ function createRemendPreprocessor(options) {
4544
4861
  // Annotate the CommonJS export names for ESM import in node:
4545
4862
  0 && (module.exports = {
4546
4863
  DEFAULT_PAYLOAD,
4547
- DEF_LINE_START_RE,
4548
4864
  PIPELINE_STAGES,
4549
4865
  SENTINEL_FN_CONTENT,
4550
4866
  SENTINEL_LINK_URL,
@@ -4579,7 +4895,6 @@ function createRemendPreprocessor(options) {
4579
4895
  hasLoneSurrogate,
4580
4896
  highlight,
4581
4897
  isFootnoteSection,
4582
- lastRegionStart,
4583
4898
  measureStage,
4584
4899
  mergeClassNameAllowlist,
4585
4900
  normalizeForMatch,