@ai-matrx/content-ir 0.16.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/source.js CHANGED
@@ -252,65 +252,313 @@ function classifyInnerFenceLine(trimmed, openTicks, nests, nestedDepth) {
252
252
  return "content";
253
253
  }
254
254
 
255
- // source/math.ts
256
- var TEX_SIGNAL = /\\[A-Za-z]+|[\\^_{}=<>+]/;
257
- var LONE_VARIABLE = /^[A-Za-z](?:'|[0-9])?$/;
258
- var MATH_SHAPE_CHARS = /^[A-Za-z0-9'\s(),.*\/-]+$/;
259
- var FUNCTION_NAMES = /* @__PURE__ */ new Set([
260
- "sin",
261
- "cos",
262
- "tan",
263
- "sec",
264
- "csc",
265
- "cot",
266
- "log",
267
- "ln",
268
- "exp",
269
- "lim",
270
- "max",
271
- "min",
272
- "det",
273
- "gcd",
274
- "mod",
275
- "arg",
276
- "sinh",
277
- "cosh",
278
- "tanh"
279
- ]);
280
- function isMathShape(content) {
281
- if (!MATH_SHAPE_CHARS.test(content)) return false;
282
- const words = content.match(/[A-Za-z]+/g);
283
- if (!words) return false;
284
- if (!words.every((w) => w.length === 1 || FUNCTION_NAMES.has(w))) return false;
285
- if (/[A-Za-z]'+[A-Za-z]/.test(content) || /(?:^|[\s(,])[A-Za-z]\.(?:[A-Za-z]\.|\s|$)/.test(content)) return false;
286
- return /[A-Za-z]'*\(|[A-Za-z]'|\b[A-Za-z]\s+[A-Za-z]\b|\([^)]*[A-Za-z][^)]*\)/.test(content);
255
+ // source/code-ranges.ts
256
+ function fenceOpenerOf(content) {
257
+ const t = content.trimStart();
258
+ if (t.startsWith("```")) {
259
+ let ticks = 0;
260
+ while (ticks < t.length && t[ticks] === "`") ticks++;
261
+ return { char: "`", ticks, lang: parseFenceOpener(t)?.lang ?? "" };
262
+ }
263
+ if (content.length - t.length <= 3 && t.startsWith("~~~")) {
264
+ const open = /^(~{3,})(.*)$/.exec(t);
265
+ if (!open) return null;
266
+ return { char: "~", ticks: open[1].length, lang: open[2].trim().split(/\s/)[0] ?? "" };
267
+ }
268
+ return null;
287
269
  }
288
- function isSingleDollarMath(content, after) {
289
- if (!content || content.length > 400) return false;
290
- if (/^\s/.test(content) || /\s$/.test(content)) return false;
291
- if (after !== void 0 && /[0-9]/.test(after)) return false;
292
- if (LONE_VARIABLE.test(content)) return true;
293
- if (/^[0-9]/.test(content)) return /\\[A-Za-z]+|[\\^_{}]/.test(content);
294
- return TEX_SIGNAL.test(content) || isMathShape(content);
270
+ var FenceReader = class {
271
+ constructor(opener, options = {}) {
272
+ this.opener = opener;
273
+ this.isJson = opener.char === "`" && opener.lang === "json";
274
+ this.nesting = opener.char === "`" && (options.nesting ?? fenceNestsInnerFences(opener.lang));
275
+ this.tildeCloser = opener.char === "~" ? new RegExp(`^ {0,3}~{${opener.ticks},}[ \\t]*$`) : null;
276
+ }
277
+ opener;
278
+ state = { inString: false, escaped: false };
279
+ depth = 0;
280
+ /** A nested fence was opened at some point. */
281
+ sawNested = false;
282
+ isJson;
283
+ nesting;
284
+ tildeCloser;
285
+ /** How many nested fences are open right now. */
286
+ get nestedDepth() {
287
+ return this.depth;
288
+ }
289
+ feed(line) {
290
+ if (this.tildeCloser) return this.tildeCloser.test(line);
291
+ const trimmedLine = trimFenceLine(line);
292
+ const at = line.indexOf("```");
293
+ if (at === -1) {
294
+ if (this.isJson) this.state = jsonStringState(line, 0, line.length, this.state);
295
+ return false;
296
+ }
297
+ if (this.isJson) {
298
+ const probe = jsonStringState(line, 0, at, this.state);
299
+ if (probe.inString) {
300
+ this.state = jsonStringState(line, at, line.length, probe);
301
+ return false;
302
+ }
303
+ }
304
+ if (trimmedLine.startsWith("```")) {
305
+ const kind = classifyInnerFenceLine(trimmedLine, this.opener.ticks, this.nesting, this.depth);
306
+ if (kind === "close-outer") return true;
307
+ if (kind === "open-nested") {
308
+ this.depth++;
309
+ this.sawNested = true;
310
+ }
311
+ if (kind === "close-nested") this.depth--;
312
+ } else {
313
+ const closeTicks = backtickRunLength(line, at);
314
+ const after = trimFenceLine(line.slice(at + closeTicks));
315
+ if (closeTicks >= this.opener.ticks && after === "" && this.depth === 0) return true;
316
+ }
317
+ if (this.isJson) this.state = jsonStringState(line, 0, line.length, this.state);
318
+ return false;
319
+ }
320
+ };
321
+ function closeFence(src, open, opener) {
322
+ const first = readFence(src, open, new FenceReader(opener));
323
+ if (first.closed || !first.reader.sawNested || first.reader.nestedDepth <= 0) return { line: first.line, closed: first.closed };
324
+ const strict = readFence(src, open, new FenceReader(opener, { nesting: false }));
325
+ return { line: strict.line, closed: strict.closed };
295
326
  }
296
- function singleDollarMathEnd(text, open, limit = text.length) {
297
- const bound = Math.min(limit, open + 403);
298
- let close = -1;
299
- for (let k = open + 1; k < bound; k += 1) {
300
- const c = text[k];
301
- if (c === "\n") break;
302
- if (c === "\\") {
303
- k += 1;
327
+ function readFence(src, open, reader) {
328
+ for (let k = open + 1; k < src.count; k++) {
329
+ if (src.openTail?.(k)) continue;
330
+ const line = src.line(k);
331
+ if (line === null) return { line: k - 1, closed: false, reader };
332
+ if (reader.feed(line)) return { line: k, closed: true, reader };
333
+ }
334
+ return { line: src.count - 1, closed: false, reader };
335
+ }
336
+ function jsonStringState(line, from, upTo, state) {
337
+ let { inString, escaped } = state;
338
+ for (let idx = from; idx < upTo; idx++) {
339
+ const ch = line[idx];
340
+ if (escaped) {
341
+ escaped = false;
304
342
  continue;
305
343
  }
306
- if (c === "$") {
307
- close = k;
308
- break;
344
+ if (ch === "\\" && inString) {
345
+ escaped = true;
346
+ continue;
309
347
  }
348
+ if (ch === '"') inString = !inString;
310
349
  }
311
- if (close === -1 || text[close + 1] === "$") return -1;
312
- const content = text.slice(open + 1, close);
313
- return isSingleDollarMath(content, text[close + 1]) ? close + 1 : -1;
350
+ return { inString, escaped };
351
+ }
352
+ function backtickRunLength(str, pos) {
353
+ let n = 0;
354
+ while (pos + n < str.length && str[pos + n] === "`") n++;
355
+ return n;
356
+ }
357
+ function quotePrefix(line) {
358
+ let depth = 0;
359
+ let offset = 0;
360
+ for (; ; ) {
361
+ const m = /^ {0,3}> ?/.exec(line.slice(offset));
362
+ if (!m) return { depth, offset };
363
+ depth++;
364
+ offset += m[0].length;
365
+ }
366
+ }
367
+ function stripQuotes(line, depth) {
368
+ let offset = 0;
369
+ for (let d = 0; d < depth; d++) {
370
+ const m = /^ {0,3}> ?/.exec(line.slice(offset));
371
+ if (!m) return null;
372
+ offset += m[0].length;
373
+ }
374
+ return line.slice(offset);
375
+ }
376
+ var LIST_ITEM = /^( *)([-*+]|\d{1,9}[.)])( +|\t|$)/;
377
+ function leadingSpaces(s) {
378
+ let i = 0;
379
+ while (i < s.length && s[i] === " ") i++;
380
+ return i;
381
+ }
382
+ function scan(text) {
383
+ const starts = [];
384
+ const ends = [];
385
+ for (let pos = 0; ; ) {
386
+ const nl = text.indexOf("\n", pos);
387
+ const lineEnd = nl === -1 ? text.length : nl;
388
+ starts.push(pos);
389
+ ends.push(lineEnd > pos && text.charCodeAt(lineEnd - 1) === 13 ? lineEnd - 1 : lineEnd);
390
+ if (nl === -1) break;
391
+ pos = nl + 1;
392
+ }
393
+ const count = starts.length;
394
+ const raw = (k) => text.slice(starts[k], ends[k]);
395
+ const out = { ranges: [], paragraphs: [], endsInFence: false, pendingPara: -1 };
396
+ const rawLines = { count, line: raw };
397
+ let segment = 0;
398
+ for (let k = 0; k < count; k++) {
399
+ const opener = fenceOpenerOf(raw(k));
400
+ if (!opener || opener.char !== "`") continue;
401
+ prose(text, starts, ends, raw, segment, k, out);
402
+ const end = closeFence(rawLines, k, opener);
403
+ out.ranges.push({ start: starts[k], end: ends[end.line], kind: "fence" });
404
+ out.pendingPara = -1;
405
+ if (!end.closed && end.line === count - 1) out.endsInFence = true;
406
+ k = end.line;
407
+ segment = k + 1;
408
+ }
409
+ prose(text, starts, ends, raw, segment, count, out);
410
+ return out;
411
+ }
412
+ function prose(text, starts, ends, raw, from, to, out) {
413
+ let para = -1;
414
+ let quoteDepth = 0;
415
+ let lists = [];
416
+ const closePara = (at) => {
417
+ if (para !== -1) out.paragraphs.push([para, at]);
418
+ para = -1;
419
+ };
420
+ for (let k = from; k < to; k++) {
421
+ const line = raw(k);
422
+ const { depth, offset } = quotePrefix(line);
423
+ if (depth !== quoteDepth) {
424
+ quoteDepth = depth;
425
+ lists = [];
426
+ }
427
+ let content = line.slice(offset);
428
+ if (content.trim() === "") {
429
+ closePara(starts[k]);
430
+ if (!(k === starts.length - 1 && line === "")) out.pendingPara = -1;
431
+ continue;
432
+ }
433
+ const indent = leadingSpaces(content);
434
+ while (lists.length && indent < lists[lists.length - 1]) lists.pop();
435
+ const item = LIST_ITEM.exec(content);
436
+ let column = lists.length ? lists[lists.length - 1] : 0;
437
+ if (item) {
438
+ const gap = item[3].length;
439
+ column = item[1].length + item[2].length + (gap >= 1 && gap <= 4 ? gap : 1);
440
+ lists.push(column);
441
+ content = content.slice(Math.min(column, content.length));
442
+ } else {
443
+ content = content.slice(Math.min(indent, column));
444
+ }
445
+ const opener = fenceOpenerOf(content);
446
+ if (!opener) {
447
+ if (para === -1) para = starts[k];
448
+ if (out.pendingPara === -1) out.pendingPara = starts[k];
449
+ continue;
450
+ }
451
+ closePara(starts[k]);
452
+ out.pendingPara = -1;
453
+ const col = column;
454
+ const src = {
455
+ count: to,
456
+ line: (j) => {
457
+ const inner = stripQuotes(raw(j), depth);
458
+ if (inner === null) return null;
459
+ if (opener.char === "~" && col > 0) {
460
+ const ind = leadingSpaces(inner);
461
+ if (inner.trim() !== "" && ind < col) return null;
462
+ return inner.slice(Math.min(ind, col));
463
+ }
464
+ return inner;
465
+ }
466
+ };
467
+ const end = closeFence(src, k, opener);
468
+ out.ranges.push({ start: starts[k], end: ends[end.line], kind: "fence" });
469
+ if (!end.closed && end.line === starts.length - 1) out.endsInFence = true;
470
+ k = end.line;
471
+ }
472
+ closePara(to < starts.length ? starts[to] : text.length);
473
+ }
474
+ var BacktickRuns = class {
475
+ /** Every run, in order: [start, length]. */
476
+ all = [];
477
+ byLength = /* @__PURE__ */ new Map();
478
+ indexOf = /* @__PURE__ */ new Map();
479
+ constructor(text, from, to) {
480
+ for (let k = from; k < to; ) {
481
+ if (text.charCodeAt(k) !== 96) {
482
+ k++;
483
+ continue;
484
+ }
485
+ let len = 1;
486
+ while (k + len < to && text.charCodeAt(k + len) === 96) len++;
487
+ this.indexOf.set(k, this.all.length);
488
+ this.all.push([k, len]);
489
+ const list = this.byLength.get(len);
490
+ if (list) list.push(k);
491
+ else this.byLength.set(len, [k]);
492
+ k += len;
493
+ }
494
+ }
495
+ /** Start of the first run of exactly `n` backticks at or after `after`, or -1. */
496
+ next(n, after) {
497
+ const list = this.byLength.get(n);
498
+ if (!list) return -1;
499
+ let lo = 0;
500
+ let hi = list.length;
501
+ while (lo < hi) {
502
+ const mid = lo + hi >>> 1;
503
+ if (list[mid] < after) lo = mid + 1;
504
+ else hi = mid;
505
+ }
506
+ return list[lo] ?? -1;
507
+ }
508
+ /** Index of the run starting at `start` in `all`. */
509
+ index(start) {
510
+ return this.indexOf.get(start) ?? -1;
511
+ }
512
+ };
513
+ function codeSpans(text, from, to, out) {
514
+ const runs = new BacktickRuns(text, from, to);
515
+ for (let r = 0; r < runs.all.length; ) {
516
+ const [start, n] = runs.all[r];
517
+ const close = runs.next(n, start + n);
518
+ if (close === -1) {
519
+ r++;
520
+ continue;
521
+ }
522
+ out.push({ start, end: close + n, kind: "span" });
523
+ r = runs.index(close) + 1;
524
+ }
525
+ }
526
+ function findCodeRanges(text) {
527
+ const s = scan(text);
528
+ const ranges = [...s.ranges];
529
+ for (const [from, to] of s.paragraphs) codeSpans(text, from, to, ranges);
530
+ return ranges.sort((a, b) => a.start - b.start);
531
+ }
532
+ function pendingCodeSpanStart(text) {
533
+ const n = text.length;
534
+ if (n === 0 || /\n[ \t]*\n[ \t]*$/.test(text)) return -1;
535
+ const s = scan(text);
536
+ const para = s.pendingPara;
537
+ if (s.endsInFence || para === -1) return -1;
538
+ const runs = [];
539
+ for (let k = para; k < n; ) {
540
+ if (text.charCodeAt(k) !== 96) {
541
+ k++;
542
+ continue;
543
+ }
544
+ let len = 1;
545
+ while (k + len < n && text.charCodeAt(k + len) === 96) len++;
546
+ runs.push([k, len]);
547
+ k += len;
548
+ }
549
+ const growing = (r) => {
550
+ const [start, len] = runs[r];
551
+ return start + len === n;
552
+ };
553
+ for (let r = 0; r < runs.length; ) {
554
+ if (growing(r)) return runs[r][0];
555
+ const len = runs[r][1];
556
+ let j = r + 1;
557
+ while (j < runs.length && (runs[j][1] !== len || growing(j))) j++;
558
+ if (j >= runs.length) return runs[r][0];
559
+ r = j + 1;
560
+ }
561
+ return -1;
314
562
  }
315
563
 
316
564
  // source/math-pairs.ts
@@ -339,86 +587,7 @@ function looksLikeDisplayMath(inner, flow = false) {
339
587
  return (s.match(PROSE_WORD) ?? []).length < PROSE_WORD_LIMIT;
340
588
  }
341
589
  function codeRanges(text) {
342
- const ranges = [];
343
- const n = text.length;
344
- let fence = null;
345
- let para = -1;
346
- const spans = (from, to) => {
347
- const runs = [];
348
- for (let k = from; k < to; ) {
349
- if (text.charCodeAt(k) !== 96) {
350
- k++;
351
- continue;
352
- }
353
- let len = 1;
354
- while (k + len < to && text.charCodeAt(k + len) === 96) len++;
355
- runs.push([k, len]);
356
- k += len;
357
- }
358
- const nextSame = new Array(runs.length).fill(-1);
359
- const last = /* @__PURE__ */ new Map();
360
- for (let r = runs.length - 1; r >= 0; r--) {
361
- const len = runs[r][1];
362
- nextSame[r] = last.get(len) ?? -1;
363
- last.set(len, r);
364
- }
365
- for (let r = 0; r < runs.length; ) {
366
- const j = nextSame[r];
367
- if (j === -1) {
368
- r++;
369
- continue;
370
- }
371
- const [s0] = runs[r];
372
- const [s1, l1] = runs[j];
373
- ranges.push([s0, s1 + l1]);
374
- r = j + 1;
375
- }
376
- };
377
- let pos = 0;
378
- while (pos <= n) {
379
- const nl = text.indexOf("\n", pos);
380
- const lineEnd = nl === -1 ? n : nl;
381
- const line = text.slice(pos, lineEnd);
382
- let indent = 0;
383
- while (indent < line.length && line[indent] === " ") indent++;
384
- const body = line.slice(indent);
385
- if (fence) {
386
- const trimmed = trimFenceLine(line);
387
- let closes = false;
388
- if (fence.char === "`") {
389
- const kind = classifyInnerFenceLine(trimmed, fence.len, fence.nests, fence.depth);
390
- if (kind === "open-nested") fence.depth++;
391
- else if (kind === "close-nested") fence.depth--;
392
- else if (kind === "close-outer") closes = indent <= 3;
393
- } else {
394
- let t = 0;
395
- while (t < trimmed.length && trimmed[t] === "~") t++;
396
- closes = indent <= 3 && t >= fence.len && trimFenceLine(trimmed.slice(t)) === "";
397
- }
398
- if (closes) {
399
- ranges.push([fence.start, lineEnd]);
400
- fence = null;
401
- }
402
- } else {
403
- const opener = indent <= 3 ? /^(`{3,}|~{3,})(.*)$/.exec(body) : null;
404
- const info = opener ? opener[2] : "";
405
- if (opener && !(opener[1][0] === "`" && info.includes("`"))) {
406
- if (para !== -1) spans(para, pos);
407
- para = -1;
408
- const char = opener[1][0];
409
- const parsed = char === "`" ? parseFenceOpener(line) : null;
410
- fence = { char, len: opener[1].length, start: pos, nests: fenceNestsInnerFences(parsed?.lang), depth: 0 };
411
- } else if (body.trim() === "") {
412
- if (para !== -1) spans(para, pos);
413
- para = -1;
414
- } else if (para === -1) para = pos;
415
- }
416
- if (nl === -1) break;
417
- pos = nl + 1;
418
- }
419
- if (fence) ranges.push([fence.start, n]);
420
- else if (para !== -1) spans(para, n);
421
- return ranges.sort((a, b) => a[0] - b[0]);
590
+ return findCodeRanges(text).map((r) => [r.start, r.end]);
422
591
  }
423
592
  function pendingDisplayMathOpener(text) {
424
593
  if (!text.includes("$$")) return -1;
@@ -502,6 +671,83 @@ function pairDisplayMath(text) {
502
671
  return pairs;
503
672
  }
504
673
 
674
+ // source/math.ts
675
+ var TEX_SIGNAL = /\\[A-Za-z]+|[\\^_{}=<>+]/;
676
+ var LONE_VARIABLE = /^[A-Za-z](?:'|[0-9])?$/;
677
+ var MATH_SHAPE_CHARS = /^[A-Za-z0-9'\s(),.*\/-]+$/;
678
+ function isSingleDollarMath(content, after) {
679
+ if (!content || content.length > 400) return false;
680
+ if (/^\s/.test(content) || /\s$/.test(content)) return false;
681
+ if (after !== void 0 && /[0-9]/.test(after)) return false;
682
+ if (/(?:^|[^\\])%/.test(content)) return false;
683
+ if (/^[)\]}"/]/.test(content) || /[(\[{":;,/]$/.test(content)) return false;
684
+ if (/^[0-9]/.test(content) && after !== void 0 && /[A-Za-z]/.test(after)) return false;
685
+ if (isMathPlaceholder(content)) return false;
686
+ return TEX_SIGNAL.test(content) || !readsAsProse(content);
687
+ }
688
+ var FUNCTION_NAMES = /* @__PURE__ */ new Set([
689
+ "sin",
690
+ "cos",
691
+ "tan",
692
+ "sec",
693
+ "csc",
694
+ "cot",
695
+ "log",
696
+ "ln",
697
+ "exp",
698
+ "lim",
699
+ "max",
700
+ "min",
701
+ "det",
702
+ "gcd",
703
+ "mod",
704
+ "arg",
705
+ "sinh",
706
+ "cosh",
707
+ "tanh"
708
+ ]);
709
+ function readsAsProse(content) {
710
+ if (/[A-Za-z]'[a-z]/.test(content)) return true;
711
+ if (/(?:^|[\s(,])[A-Za-z]\.(?:[A-Za-z]\.|\s|$)/.test(content)) return true;
712
+ if (!/\s/.test(content)) return false;
713
+ const words = (content.match(/[A-Za-z]{3,}/g) ?? []).filter((w) => !FUNCTION_NAMES.has(w.toLowerCase()));
714
+ return words.length >= 2;
715
+ }
716
+ function looksLikeOpenInlineMath(partial) {
717
+ if (!partial || partial.length > 400) return false;
718
+ if (/^\s/.test(partial) || /\s$/.test(partial)) return false;
719
+ if (LONE_VARIABLE.test(partial)) return true;
720
+ if (/^[0-9]/.test(partial)) return /\\[A-Za-z]+|[\\^_{}]/.test(partial);
721
+ return TEX_SIGNAL.test(partial) || isMathShape(partial);
722
+ }
723
+ function isMathShape(content) {
724
+ if (!MATH_SHAPE_CHARS.test(content)) return false;
725
+ const words = content.match(/[A-Za-z]+/g);
726
+ if (!words) return false;
727
+ if (!words.every((w) => w.length === 1 || FUNCTION_NAMES.has(w))) return false;
728
+ if (/[A-Za-z]'+[A-Za-z]/.test(content) || /(?:^|[\s(,])[A-Za-z]\.(?:[A-Za-z]\.|\s|$)/.test(content)) return false;
729
+ return /[A-Za-z]'*\(|[A-Za-z]'|\b[A-Za-z]\s+[A-Za-z]\b|\([^)]*[A-Za-z][^)]*\)/.test(content);
730
+ }
731
+ function singleDollarMathEnd(text, open, limit = text.length) {
732
+ const bound = Math.min(limit, open + 403);
733
+ let close = -1;
734
+ for (let k = open + 1; k < bound; k += 1) {
735
+ const c = text[k];
736
+ if (c === "\n") break;
737
+ if (c === "\\") {
738
+ k += 1;
739
+ continue;
740
+ }
741
+ if (c === "$") {
742
+ close = k;
743
+ break;
744
+ }
745
+ }
746
+ if (close === -1 || text[close + 1] === "$") return -1;
747
+ const content = text.slice(open + 1, close);
748
+ return isSingleDollarMath(content, text[close + 1]) ? close + 1 : -1;
749
+ }
750
+
505
751
  // source/xml-tag.ts
506
752
  var XML_NAME_START = /[A-Za-z_]/;
507
753
  var XML_NAME_CHARACTER = /[\w.:-]/;
@@ -794,27 +1040,6 @@ function isUnclosedGenericXmlOpening(source) {
794
1040
  }
795
1041
  return true;
796
1042
  }
797
- function jsonStringState(line, from, upTo, state) {
798
- let { inString, escaped } = state;
799
- for (let idx = from; idx < upTo; idx++) {
800
- const ch = line[idx];
801
- if (escaped) {
802
- escaped = false;
803
- continue;
804
- }
805
- if (ch === "\\" && inString) {
806
- escaped = true;
807
- continue;
808
- }
809
- if (ch === '"') inString = !inString;
810
- }
811
- return { inString, escaped };
812
- }
813
- function backtickRunLength(str, pos) {
814
- let n = 0;
815
- while (pos + n < str.length && str[pos + n] === "`") n++;
816
- return n;
817
- }
818
1043
  function isSplitterTreeLine(line) {
819
1044
  return TREE_GLYPHS.test(line) || /^[\s│|]*[├└+|][\s─\-]+/.test(line);
820
1045
  }
@@ -830,6 +1055,14 @@ var Tokenizer = class {
830
1055
  this.provisionalFrom = streaming ? pendingDisplayMathOpener(text) : -1;
831
1056
  if (this.provisionalFrom === -1) this.provisionalFrom = Number.POSITIVE_INFINITY;
832
1057
  if (streaming && text.includes("$$")) {
1058
+ const span = pendingCodeSpanStart(text);
1059
+ if (span !== -1) {
1060
+ const firstToken = text.indexOf("$$", span);
1061
+ if (firstToken !== -1) this.provisionalFrom = Math.min(this.provisionalFrom, firstToken);
1062
+ for (const [open, close] of this.mathPairs) {
1063
+ if (close >= span) this.provisionalFrom = Math.min(this.provisionalFrom, open);
1064
+ }
1065
+ }
833
1066
  for (const pad of ["`", "``", "```", "~~~"]) {
834
1067
  const alt = pairDisplayMath(text + pad);
835
1068
  for (const [open, close] of this.mathPairs) {
@@ -1038,11 +1271,9 @@ var Tokenizer = class {
1038
1271
  const footnote = this.footnoteDefinition(p, li, t);
1039
1272
  if (footnote) return footnote;
1040
1273
  }
1041
- if (t.startsWith("```")) return this.backtickFence(p, li, t);
1042
- if (indent <= 3 && t.startsWith("~~~")) {
1043
- const tilde = this.tildeFence(p, li, t);
1044
- if (tilde) return tilde;
1045
- }
1274
+ const fence = fenceOpenerOf(seg);
1275
+ if (fence?.char === "`") return this.backtickFence(p, li, fence);
1276
+ if (fence?.char === "~") return this.tildeFence(p, li, fence);
1046
1277
  if (t.startsWith("$$")) {
1047
1278
  const math = this.mathBlock(p, tp);
1048
1279
  if (math) return math;
@@ -1185,8 +1416,8 @@ var Tokenizer = class {
1185
1416
  last = k;
1186
1417
  continue;
1187
1418
  }
1188
- if (FOOTNOTE_DEF.test(line.trimStart()) || this.detectBlock(this.lineStarts[k], k, false)) break;
1189
1419
  if (this.isOpenTail(k)) return this.heldFootnote(p, open[1]);
1420
+ if (FOOTNOTE_DEF.test(line.trimStart()) || this.detectBlock(this.lineStarts[k], k, false)) break;
1190
1421
  last = k;
1191
1422
  }
1192
1423
  const end = this.contentEnds[last];
@@ -1197,74 +1428,31 @@ var Tokenizer = class {
1197
1428
  heldFootnote(p, id) {
1198
1429
  return this.island("footnote_def", p, this.n, false, { id });
1199
1430
  }
1431
+ /** The text's lines as the one fence closer reads them (streaming: the open tail closes nothing). */
1432
+ get fenceLines() {
1433
+ return {
1434
+ count: this.lineCount,
1435
+ line: (k) => this.lineText(k),
1436
+ openTail: (k) => this.isOpenTail(k)
1437
+ };
1438
+ }
1200
1439
  /**
1201
- * Backtick fence — the renderer splitter's close rules: JSON-string aware for
1202
- * ```json, and THE nested-fence rule (source/fence-nesting.ts) for markdown
1203
- * fences, with the splitter's strict-CommonMark retry when a nested fence is
1204
- * still open at the end of the text.
1440
+ * Backtick fence — THE one closer (`closeFence`, source/code-ranges.ts): the
1441
+ * nested-fence rule for markdown fences with the strict-CommonMark retry, the
1442
+ * renderer's line-end closer, JSON-string awareness for ```json.
1205
1443
  */
1206
- backtickFence(p, li, t) {
1207
- const openTicks = backtickRunLength(t, 0);
1208
- const lang = parseFenceOpener(t)?.lang ?? "";
1444
+ backtickFence(p, li, opener) {
1445
+ const lang = opener.lang;
1209
1446
  const isJson = lang === "json";
1210
1447
  const normalized = normalizeFenceLanguage(lang);
1211
- const meta = { fence: "`", ticks: openTicks, lang };
1448
+ const meta = { fence: "`", ticks: opener.ticks, lang };
1212
1449
  if (normalized && SPECIAL_CODE_LANGUAGES.has(normalized)) meta.special = normalized;
1213
- const nesting = fenceNestsInnerFences(lang);
1214
- let close = this.backtickFenceClose(li, openTicks, isJson, nesting);
1215
- if (close === "retry-strict") close = this.backtickFenceClose(li, openTicks, isJson, false);
1216
- if (typeof close === "number") {
1217
- return this.fenceIsland(p, this.contentEnds[close], true, meta, li, close, isJson);
1450
+ const end = closeFence(this.fenceLines, li, opener);
1451
+ if (end.closed) {
1452
+ return this.fenceIsland(p, this.contentEnds[end.line], true, meta, li, end.line, isJson);
1218
1453
  }
1219
1454
  return this.fenceIsland(p, this.n, false, meta, li, this.lineCount, isJson);
1220
1455
  }
1221
- /** The closing line of a backtick fence opened on line `li`, or null when it never closes. */
1222
- backtickFenceClose(li, openTicks, isJson, nesting) {
1223
- let state = { inString: false, escaped: false };
1224
- let nestedDepth = 0;
1225
- let sawNested = false;
1226
- for (let k = li + 1; k < this.lineCount; k++) {
1227
- if (this.isOpenTail(k)) continue;
1228
- const line = this.lineText(k);
1229
- const trimmedLine = trimFenceLine(line);
1230
- if (trimmedLine.startsWith("```")) {
1231
- const at2 = line.indexOf("```");
1232
- if (isJson) {
1233
- const probe = jsonStringState(line, 0, at2, state);
1234
- if (probe.inString) {
1235
- state = jsonStringState(line, at2, line.length, probe);
1236
- continue;
1237
- }
1238
- }
1239
- const kind = classifyInnerFenceLine(trimmedLine, openTicks, nesting, nestedDepth);
1240
- if (kind === "close-outer") return k;
1241
- if (kind === "open-nested") {
1242
- nestedDepth++;
1243
- sawNested = true;
1244
- }
1245
- if (kind === "close-nested") nestedDepth--;
1246
- if (isJson) state = jsonStringState(line, 0, line.length, state);
1247
- continue;
1248
- }
1249
- const at = line.indexOf("```");
1250
- if (at !== -1) {
1251
- if (isJson) {
1252
- const probe = jsonStringState(line, 0, at, state);
1253
- if (probe.inString) {
1254
- state = jsonStringState(line, at, line.length, probe);
1255
- continue;
1256
- }
1257
- }
1258
- const closeTicks = backtickRunLength(line, at);
1259
- const after = trimFenceLine(line.slice(at + closeTicks));
1260
- if (closeTicks >= openTicks && after === "" && nestedDepth === 0) return k;
1261
- if (isJson) state = jsonStringState(line, 0, line.length, state);
1262
- continue;
1263
- }
1264
- if (isJson) state = jsonStringState(line, 0, line.length, state);
1265
- }
1266
- return sawNested && nestedDepth > 0 ? "retry-strict" : null;
1267
- }
1268
1456
  fenceIsland(p, end, complete, meta, openLine, closeLine, isJson) {
1269
1457
  if (isJson && openLine + 1 < this.lineCount) {
1270
1458
  const bodyEnd = closeLine < this.lineCount ? this.lineStarts[closeLine] : this.n;
@@ -1273,22 +1461,16 @@ var Tokenizer = class {
1273
1461
  }
1274
1462
  return this.island("fence", p, end, complete, meta);
1275
1463
  }
1276
- tildeFence(p, li, t) {
1277
- const open = /^(~{3,})(.*)$/.exec(t);
1278
- if (!open) return null;
1279
- const ticks = open[1].length;
1280
- const lang = open[2].trim().split(/\s/)[0] ?? "";
1281
- const meta = { fence: "~", ticks, lang };
1464
+ tildeFence(p, li, opener) {
1465
+ const lang = opener.lang;
1466
+ const meta = { fence: "~", ticks: opener.ticks, lang };
1282
1467
  const normalized = normalizeFenceLanguage(lang);
1283
1468
  if (normalized && SPECIAL_CODE_LANGUAGES.has(normalized)) meta.special = normalized;
1284
- const close = new RegExp(`^ {0,3}~{${ticks},}[ \\t]*$`);
1285
- for (let k = li + 1; k < this.lineCount; k++) {
1286
- if (this.isOpenTail(k)) continue;
1287
- if (close.test(this.lineText(k))) {
1288
- const tildeEnd = this.contentEnds[k];
1289
- const end = this.rendererOverflow(li + 1, k, tildeEnd);
1290
- return this.island("fence", p, end, end === this.n ? this.overflowComplete : true, meta);
1291
- }
1469
+ const close = closeFence(this.fenceLines, li, opener);
1470
+ if (close.closed) {
1471
+ const tildeEnd = this.contentEnds[close.line];
1472
+ const end = this.rendererOverflow(li + 1, close.line, tildeEnd);
1473
+ return this.island("fence", p, end, end === this.n ? this.overflowComplete : true, meta);
1292
1474
  }
1293
1475
  return this.island("fence", p, this.n, false, meta);
1294
1476
  }
@@ -1308,7 +1490,7 @@ var Tokenizer = class {
1308
1490
  for (let j = firstLine; j <= closeLine && j < this.lineCount; j++) {
1309
1491
  const start = this.lineStarts[j];
1310
1492
  if (this.lineIsBlank(j)) continue;
1311
- if (this.lineText(j).trimStart().startsWith("~~~")) continue;
1493
+ if (fenceOpenerOf(this.lineText(j))?.char === "~") continue;
1312
1494
  const inner = this.detectBlockUncached(start, j, false);
1313
1495
  if (!inner) continue;
1314
1496
  if (inner.end > end) {
@@ -1556,9 +1738,9 @@ var Tokenizer = class {
1556
1738
  const tree = { ...breakIsland, start: treeStart };
1557
1739
  if (treeStart > pos) {
1558
1740
  const proseEnd = this.contentEnds[root - 1];
1559
- const scan2 = this.scanInline(pos, proseEnd);
1560
- if (!scan2.breakIsland) {
1561
- this.push({ kind: "prose", start: pos, end: proseEnd, island: null, inlines: scan2.inlines });
1741
+ const scan3 = this.scanInline(pos, proseEnd);
1742
+ if (!scan3.breakIsland) {
1743
+ this.push({ kind: "prose", start: pos, end: proseEnd, island: null, inlines: scan3.inlines });
1562
1744
  this.push({ kind: "gap", start: proseEnd, end: treeStart, island: null, inlines: [] });
1563
1745
  this.push({ kind: "island", start: treeStart, end: tree.end, island: tree, inlines: [] });
1564
1746
  return tree.end;
@@ -1570,13 +1752,13 @@ var Tokenizer = class {
1570
1752
  }
1571
1753
  }
1572
1754
  }
1573
- const scan = this.scanInline(pos, end);
1574
- if (!scan.breakIsland) {
1575
- this.push({ kind: "prose", start: pos, end, island: null, inlines: scan.inlines });
1755
+ const scan2 = this.scanInline(pos, end);
1756
+ if (!scan2.breakIsland) {
1757
+ this.push({ kind: "prose", start: pos, end, island: null, inlines: scan2.inlines });
1576
1758
  return end;
1577
1759
  }
1578
- const br = scan.breakIsland;
1579
- if (scan.orphan) {
1760
+ const br = scan2.breakIsland;
1761
+ if (scan2.orphan) {
1580
1762
  let start = pos;
1581
1763
  while (this.blocks.length) {
1582
1764
  const last = this.blocks[this.blocks.length - 1];
@@ -1593,7 +1775,7 @@ var Tokenizer = class {
1593
1775
  start: pos,
1594
1776
  end: br.start,
1595
1777
  island: null,
1596
- inlines: scan.inlines.filter((inline) => inline.end <= br.start)
1778
+ inlines: scan2.inlines.filter((inline) => inline.end <= br.start)
1597
1779
  });
1598
1780
  this.push({ kind: "island", start: br.start, end: br.end, island: br, inlines: [] });
1599
1781
  return br.end;
@@ -1613,30 +1795,10 @@ var Tokenizer = class {
1613
1795
  const codeSpanClose = (n, from) => {
1614
1796
  if (!runs) {
1615
1797
  this.tick(pe - ps);
1616
- runs = /* @__PURE__ */ new Map();
1617
- for (let k = ps; k < pe; ) {
1618
- if (text.charCodeAt(k) !== 96) {
1619
- k++;
1620
- continue;
1621
- }
1622
- const len = backtickRunLength(text, k);
1623
- const list2 = runs.get(len);
1624
- if (list2) list2.push(k);
1625
- else runs.set(len, [k]);
1626
- k += len;
1627
- }
1628
- }
1629
- const list = runs.get(n);
1630
- if (!list) return -1;
1631
- let lo = 0;
1632
- let hi = list.length;
1633
- while (lo < hi) {
1634
- const mid = lo + hi >>> 1;
1635
- if (list[mid] < from) lo = mid + 1;
1636
- else hi = mid;
1798
+ runs = new BacktickRuns(text, ps, pe);
1637
1799
  }
1638
- const at = list[lo];
1639
- return at !== void 0 && at + n <= pe ? at : -1;
1800
+ const at = runs.next(n, from);
1801
+ return at !== -1 && at + n <= pe ? at : -1;
1640
1802
  };
1641
1803
  let i = ps;
1642
1804
  const scanEnd = Math.min(pe, this.provisionalFrom);
@@ -2173,6 +2335,6 @@ function mapRange(changes, start, end, unit = "utf16") {
2173
2335
  return { start: newStart, end: newEnd, touched, collapsed: newEnd === newStart && end > start };
2174
2336
  }
2175
2337
 
2176
- export { CALLOUT_NAMES, FENCE_OPENER_WHITESPACE, FENCE_WHITESPACE, NESTING_FENCE_LANGUAGES, SourceSpliceError, XmlContainerTracker, blockAt, blockEdit, blockRangeEdit, buildCodePointIndex, classifyInnerFenceLine, fenceNestsInnerFences, isMathPlaceholder, isSingleDollarMath, islandEdit, joinSource, listIslands, looksLikeDisplayMath, mapPosition, mapRange, pairDisplayMath, parseFenceOpener, pendingDisplayMathOpener, readXmlTag, singleDollarMathEnd, spliceSave, splitsSurrogatePair, toCodePointOffset, toUtf16Offset, tokenizeSource, trimFenceLine };
2338
+ export { CALLOUT_NAMES, FENCE_OPENER_WHITESPACE, FENCE_WHITESPACE, NESTING_FENCE_LANGUAGES, SourceSpliceError, XmlContainerTracker, blockAt, blockEdit, blockRangeEdit, buildCodePointIndex, classifyInnerFenceLine, fenceNestsInnerFences, findCodeRanges, isMathPlaceholder, isSingleDollarMath, islandEdit, joinSource, listIslands, looksLikeDisplayMath, looksLikeOpenInlineMath, mapPosition, mapRange, pairDisplayMath, parseFenceOpener, pendingDisplayMathOpener, readXmlTag, singleDollarMathEnd, spliceSave, splitsSurrogatePair, toCodePointOffset, toUtf16Offset, tokenizeSource, trimFenceLine };
2177
2339
  //# sourceMappingURL=source.js.map
2178
2340
  //# sourceMappingURL=source.js.map