@heikeson/md-engine 0.3.0 → 0.4.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.
@@ -1,10 +1,11 @@
1
- import { mdxComponents, isSafeHref } from './chunk-QDDS7MPU.js';
1
+ import { mdxComponents, isSafeHref } from './chunk-V7T7I5HE.js';
2
2
  import { asciiAlpha, asciiAlphanumeric, markdownLineEnding } from 'micromark-util-character';
3
3
  import { fromMarkdown } from 'mdast-util-from-markdown';
4
4
  import { gfm } from 'micromark-extension-gfm';
5
5
  import { gfmFromMarkdown } from 'mdast-util-gfm';
6
6
  import { math } from 'micromark-extension-math';
7
7
  import { mathFromMarkdown } from 'mdast-util-math';
8
+ import { visit } from 'unist-util-visit';
8
9
  import { useMemo } from 'react';
9
10
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
10
11
  import { unified } from 'unified';
@@ -15,7 +16,6 @@ import remarkRehype from 'remark-rehype';
15
16
  import rehypeSlug from 'rehype-slug';
16
17
  import rehypeKatex from 'rehype-katex';
17
18
  import { toJsxRuntime } from 'hast-util-to-jsx-runtime';
18
- import { visit } from 'unist-util-visit';
19
19
 
20
20
  // src/registry.ts
21
21
  var MAX_CONTAINER_DEPTH = 3;
@@ -56,6 +56,20 @@ var COMPONENTS = {
56
56
  attrs: ["src", "alt", "align", "width", "caption"],
57
57
  boolAttrs: ["zoom"],
58
58
  defaultAttrs: { align: "center" }
59
+ },
60
+ // 通用分块容器:作者需要一层可挂 class / id 的 div 做局部样式或锚点时用它;
61
+ // 属性原样透传到 DOM(不套组件),内容照常按 Markdown 解析。
62
+ div: { name: "div", mode: "visual", attrs: ["class", "id"] },
63
+ // 图表容器:容器体是 mermaid 源码,必须原样保留(rawBody),否则 `#`、`|`、`-->`
64
+ // 与行首 `-` 会被当成 Markdown 语法。mode=source:编辑器里只按源码块处理,不做结构化编辑。
65
+ // 渲染与交互不在本仓库主入口:主入口只出源码骨架,交互由 `/mermaid` 入口在客户端增强。
66
+ Mermaid: {
67
+ name: "Mermaid",
68
+ mode: "source",
69
+ attrs: ["title", "height"],
70
+ rawBody: true,
71
+ // `<Mermaid />` 等价于空源码(给 MERMAID_EMPTY 诊断):允许自闭合,否则会被当成未知 HTML
72
+ selfClosing: true
59
73
  }
60
74
  };
61
75
  function getComponent(name) {
@@ -76,6 +90,7 @@ var SLASH = 47;
76
90
  var DQUOTE = 34;
77
91
  var SQUOTE = 39;
78
92
  var SPACE = 32;
93
+ var TAB = 9;
79
94
  function isKnownName(name) {
80
95
  return Boolean(COMPONENTS[name]) || Boolean(ITEMS[name]);
81
96
  }
@@ -119,6 +134,7 @@ function tokenizeJsxBlock(effects, ok, nok) {
119
134
  let nestedDepth = 0;
120
135
  const closeConstruct = { tokenize: tokenizeCloseTag, partial: true };
121
136
  const openConstruct = { tokenize: tokenizeOpenProbe, partial: true };
137
+ const indentConstruct = { tokenize: tokenizeIndentTag, partial: true };
122
138
  return start;
123
139
  function start(code) {
124
140
  if (code !== LT) return nok(code);
@@ -204,6 +220,21 @@ function tokenizeJsxBlock(effects, ok, nok) {
204
220
  return lineStart(code);
205
221
  }
206
222
  function lineStart(code) {
223
+ return effects.check(indentConstruct, indentDetected, plainLineStart)(code);
224
+ }
225
+ function indentDetected(code) {
226
+ effects.enter("jsxBlockIndent");
227
+ return consumeIndent(code);
228
+ }
229
+ function consumeIndent(code) {
230
+ if (code === SPACE || code === TAB) {
231
+ effects.consume(code);
232
+ return consumeIndent;
233
+ }
234
+ effects.exit("jsxBlockIndent");
235
+ return plainLineStart(code);
236
+ }
237
+ function plainLineStart(code) {
207
238
  return effects.check(closeConstruct, closeDetected, notClose)(code);
208
239
  }
209
240
  function closeDetected(code) {
@@ -352,6 +383,50 @@ function tokenizeJsxBlock(effects, ok, nok) {
352
383
  return probeAttrs;
353
384
  }
354
385
  }
386
+ function tokenizeIndentTag(effects2, ok2, nok2) {
387
+ let probe = "";
388
+ return indentStart;
389
+ function indentStart(code) {
390
+ if (code !== SPACE && code !== TAB) return nok2(code);
391
+ effects2.enter("jsxBlockIndent");
392
+ return indentSpace(code);
393
+ }
394
+ function indentSpace(code) {
395
+ if (code === SPACE || code === TAB) {
396
+ effects2.consume(code);
397
+ return indentSpace;
398
+ }
399
+ if (code === LT) {
400
+ effects2.consume(code);
401
+ return indentLt;
402
+ }
403
+ return nok2(code);
404
+ }
405
+ function indentLt(code) {
406
+ if (code === SLASH) {
407
+ effects2.consume(code);
408
+ return indentNameStart;
409
+ }
410
+ return indentNameStart(code);
411
+ }
412
+ function indentNameStart(code) {
413
+ if (code !== null && asciiAlpha(code)) {
414
+ probe = String.fromCharCode(code);
415
+ effects2.consume(code);
416
+ return indentNameRest;
417
+ }
418
+ return nok2(code);
419
+ }
420
+ function indentNameRest(code) {
421
+ if (code !== null && asciiAlphanumeric(code)) {
422
+ probe += String.fromCharCode(code);
423
+ effects2.consume(code);
424
+ return indentNameRest;
425
+ }
426
+ effects2.exit("jsxBlockIndent");
427
+ return isKnownName(probe) ? ok2(code) : nok2(code);
428
+ }
429
+ }
355
430
  function tokenizeNonLazyLine(effects2, ok2, nok2) {
356
431
  return nonLazyStart;
357
432
  function nonLazyStart(code) {
@@ -420,7 +495,35 @@ function exitOpenTag(token) {
420
495
  node.selfClosing = parsed.selfClosing;
421
496
  node.data = { closed: true };
422
497
  }
498
+ function openTagEnd(raw) {
499
+ let quote = "";
500
+ for (let i = 0; i < raw.length; i += 1) {
501
+ const ch = raw[i];
502
+ if (quote) {
503
+ if (ch === quote) quote = "";
504
+ continue;
505
+ }
506
+ if (ch === '"' || ch === "'") quote = ch;
507
+ else if (ch === ">") return i;
508
+ }
509
+ return -1;
510
+ }
511
+ function sliceRawBody(raw, name, selfClosing) {
512
+ if (selfClosing) return "";
513
+ const openEnd = openTagEnd(raw);
514
+ if (openEnd < 0) return "";
515
+ const bodyStart = openEnd + 1;
516
+ const close = new RegExp(`</${name}\\s*>\\s*$`).exec(raw);
517
+ if (!close) return raw.slice(bodyStart);
518
+ return raw.slice(bodyStart, close.index);
519
+ }
423
520
  function exitBlock(token) {
521
+ const node = this.stack[this.stack.length - 1];
522
+ if (node && COMPONENTS[node.name]?.rawBody) {
523
+ node.children = [];
524
+ const rawBody = sliceRawBody(this.sliceSerialize(token), node.name, node.selfClosing);
525
+ node.data = { ...node.data ?? {}, rawBody };
526
+ }
424
527
  this.exit(token);
425
528
  }
426
529
  function serializeAttributes(attributes) {
@@ -429,18 +532,54 @@ function serializeAttributes(attributes) {
429
532
  return ` ${key}="${String(value).replace(/"/g, "&quot;")}"`;
430
533
  }).join("");
431
534
  }
535
+ function isInlineLayout(node) {
536
+ return node.data?.inline === true;
537
+ }
538
+ function needsBlankLine(prevLine, nextLine) {
539
+ if (typeof prevLine !== "number" || typeof nextLine !== "number") return true;
540
+ return nextLine - prevLine > 1;
541
+ }
432
542
  function handleJsxBlock(node, _parent, state, info) {
433
543
  const attrs = serializeAttributes(node.attributes ?? {});
544
+ const open = `<${node.name}${attrs}>`;
545
+ if (node.data?.degraded && typeof node.data.degradedText === "string") return node.data.degradedText;
434
546
  if (node.selfClosing) return `<${node.name}${attrs} />`;
435
- const inner = state.containerFlow(node, info);
436
- if (node.data?.closed === false) return `<${node.name}${attrs}>
437
-
438
- ${inner}`;
439
- return `<${node.name}${attrs}>
440
-
441
- ${inner}
442
-
547
+ if (typeof node.data?.rawBody === "string") {
548
+ const closing = node.data.closed === false ? "" : `</${node.name}>`;
549
+ return `${open}${node.data.rawBody}${closing}`;
550
+ }
551
+ const children = node.children ?? [];
552
+ if (children.length === 0) {
553
+ const position = node.position;
554
+ const sameLine = position ? position.start.line === position.end.line : false;
555
+ return sameLine ? `${open}</${node.name}>` : `${open}
443
556
  </${node.name}>`;
557
+ }
558
+ if (isInlineLayout(node)) {
559
+ const flat = children.flatMap((child) => child.type === "paragraph" ? child.children : [child]);
560
+ if (flat.length === 0) return `${open}</${node.name}>`;
561
+ const body2 = state.containerPhrasing(
562
+ { type: "paragraph", children: flat },
563
+ { ...info, before: ">", after: "<" }
564
+ );
565
+ return `${open}${body2}</${node.name}>`;
566
+ }
567
+ const tracker = state.createTracker(info);
568
+ let body = "";
569
+ let prevEnd = node.position?.start.line;
570
+ for (const child of children) {
571
+ const gap = needsBlankLine(prevEnd, child.position?.start.line) ? "\n\n" : "\n";
572
+ const piece = state.handle(child, node, state, {
573
+ before: "\n",
574
+ after: "\n",
575
+ ...tracker.current()
576
+ });
577
+ body += gap + tracker.move(piece);
578
+ prevEnd = child.position?.end.line;
579
+ }
580
+ if (node.data?.closed === false) return `${open}${body}`;
581
+ const closeGap = needsBlankLine(prevEnd, node.position?.end.line) ? "\n\n" : "\n";
582
+ return `${open}${body}${closeGap}</${node.name}>`;
444
583
  }
445
584
 
446
585
  // src/syntax/jsx-remark.ts
@@ -452,10 +591,154 @@ function remarkJsxBlocks() {
452
591
  return void 0;
453
592
  }
454
593
 
455
- // src/blocks.ts
594
+ // src/policy.ts
595
+ var MERMAID_MAX_BYTES = 20 * 1024;
456
596
  function isJsxBlock(node) {
457
597
  return node.type === "jsxBlock";
458
598
  }
599
+ function sliceNode(source, node) {
600
+ const start = node.position?.start.offset;
601
+ const end = node.position?.end.offset;
602
+ if (typeof start !== "number" || typeof end !== "number") return "";
603
+ return source.slice(start, end);
604
+ }
605
+ function walk(parent, source, depth, maxDepth, out) {
606
+ const children = parent.children;
607
+ if (!children) return;
608
+ const next = [];
609
+ for (const child of children) {
610
+ if (!isJsxBlock(child)) {
611
+ walk(child, source, depth, maxDepth, out);
612
+ next.push(child);
613
+ continue;
614
+ }
615
+ const isContainer = Boolean(COMPONENTS[child.name]);
616
+ const childDepth = depth + (isContainer ? 1 : 0);
617
+ if (isContainer && childDepth > maxDepth) {
618
+ const text = sliceNode(source, child);
619
+ const line = child.position?.start.line ?? 1;
620
+ out.push({
621
+ code: "DEPTH_EXCEEDED",
622
+ level: "warn",
623
+ line,
624
+ message: `\u7B2C ${childDepth} \u5C42\u5BB9\u5668 ${child.name} \u8D85\u51FA\u4E0A\u9650 ${maxDepth}\uFF0C\u5DF2\u6309\u6E90\u7801\u663E\u793A`,
625
+ range: [child.position?.start.offset ?? 0, child.position?.end.offset ?? 0]
626
+ });
627
+ child.data = { ...child.data ?? {}, degraded: true, degradedText: text };
628
+ next.push(child);
629
+ continue;
630
+ }
631
+ walk(child, source, childDepth, maxDepth, out);
632
+ next.push(child);
633
+ }
634
+ parent.children = next;
635
+ }
636
+ function enforceMaxDepth(tree, source, maxDepth = MAX_CONTAINER_DEPTH) {
637
+ const diagnostics = [];
638
+ walk(tree, source, 0, maxDepth, diagnostics);
639
+ return diagnostics;
640
+ }
641
+ function hasCloseTag(block, source) {
642
+ const start = block.position?.start.offset ?? 0;
643
+ const end = block.position?.end.offset ?? 0;
644
+ if (end <= start) return false;
645
+ const body = new RegExp(`</${block.name}\\s*>`);
646
+ if (body.test(source.slice(start, end))) return true;
647
+ return new RegExp(`^\\s*</${block.name}\\s*>`).test(source.slice(end, end + 64));
648
+ }
649
+ function collectIndentAsCode(tree, source) {
650
+ const diagnostics = [];
651
+ const visit7 = (node, inside) => {
652
+ if (node.type === "code") {
653
+ const start = node.position?.start.offset;
654
+ const end = node.position?.end.offset;
655
+ if (inside && typeof start === "number" && typeof end === "number") {
656
+ const raw = source.slice(start, end);
657
+ if (!/^ {0,3}(`{3,}|~{3,})/.test(raw)) {
658
+ diagnostics.push({
659
+ code: "INDENT_AS_CODE",
660
+ level: "warn",
661
+ line: node.position?.start.line ?? 1,
662
+ message: "\u5BB9\u5668\u5185\u8FD9\u6BB5\u5185\u5BB9\u56E0\u7F29\u8FDB\uFF08\u22654 \u7A7A\u683C\u6216 tab\uFF09\u88AB\u5F53\u6210\u4EE3\u7801\u5757\uFF1B\u82E5\u662F\u6392\u7248\u7F29\u8FDB\uFF0C\u8BF7\u9876\u683C\u4E66\u5199",
663
+ range: [start, end]
664
+ });
665
+ }
666
+ }
667
+ return;
668
+ }
669
+ const children = node.children;
670
+ if (!children) return;
671
+ for (const child of children) visit7(child, inside || node.type === "jsxBlock");
672
+ };
673
+ visit7(tree, false);
674
+ return diagnostics;
675
+ }
676
+ function collectUnclosed(tree, source) {
677
+ const diagnostics = [];
678
+ const visit7 = (node) => {
679
+ if (node.type === "jsxBlock") {
680
+ const block = node;
681
+ if (!block.selfClosing && !hasCloseTag(block, source)) {
682
+ block.data = { ...block.data ?? {}, closed: false };
683
+ diagnostics.push({
684
+ code: "UNCLOSED_TAG",
685
+ level: "warn",
686
+ line: block.position?.start.line ?? 1,
687
+ message: `<${block.name}> \u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5EF6\u4F38\u5230\u6587\u672B\u5904\u7406`,
688
+ range: [block.position?.start.offset ?? 0, block.position?.end.offset ?? 0]
689
+ });
690
+ }
691
+ }
692
+ const children = node.children;
693
+ if (children) for (const child of children) visit7(child);
694
+ };
695
+ visit7(tree);
696
+ return diagnostics;
697
+ }
698
+ function collectMermaid(tree) {
699
+ const diagnostics = [];
700
+ const visit7 = (node) => {
701
+ if (node.type === "jsxBlock") {
702
+ const block = node;
703
+ if (COMPONENTS[block.name]?.rawBody) {
704
+ const raw = block.data?.rawBody ?? "";
705
+ const line = block.position?.start.line ?? 1;
706
+ const range = [
707
+ block.position?.start.offset ?? 0,
708
+ block.position?.end.offset ?? 0
709
+ ];
710
+ if (raw.trim() === "") {
711
+ diagnostics.push({
712
+ code: "MERMAID_EMPTY",
713
+ level: "warn",
714
+ line,
715
+ message: `<${block.name}> \u5BB9\u5668\u4F53\u4E3A\u7A7A\uFF0C\u672A\u751F\u6210\u56FE\u8868`,
716
+ range
717
+ });
718
+ } else if (new TextEncoder().encode(raw).length > MERMAID_MAX_BYTES) {
719
+ block.data = { ...block.data ?? {}, mermaidTooLarge: true };
720
+ diagnostics.push({
721
+ code: "MERMAID_TOO_LARGE",
722
+ level: "warn",
723
+ line,
724
+ message: `<${block.name}> \u6E90\u7801\u8D85\u8FC7 ${MERMAID_MAX_BYTES / 1024} KB\uFF0C\u5DF2\u6539\u4E3A\u663E\u793A\u6E90\u7801`,
725
+ range
726
+ });
727
+ }
728
+ }
729
+ }
730
+ const children = node.children;
731
+ if (children) for (const child of children) visit7(child);
732
+ };
733
+ visit7(tree);
734
+ return diagnostics;
735
+ }
736
+
737
+ // src/blocks.ts
738
+ var CONTAINERISH = /* @__PURE__ */ new Set(["list", "listItem", "blockquote"]);
739
+ function isJsxBlock2(node) {
740
+ return node.type === "jsxBlock";
741
+ }
459
742
  function rangeOf(node) {
460
743
  const start = node.position?.start.offset ?? 0;
461
744
  const end = node.position?.end.offset ?? start;
@@ -466,12 +749,18 @@ function toBlocks(children, source, depth) {
466
749
  }
467
750
  function toBlock(node, source, depth) {
468
751
  const [start, end] = rangeOf(node);
469
- if (isJsxBlock(node)) {
752
+ if (isJsxBlock2(node)) {
753
+ if (node.data?.degraded) {
754
+ return { kind: "source", text: source.slice(start, end), reason: "depth-exceeded", start, end };
755
+ }
470
756
  const spec = COMPONENTS[node.name];
757
+ if (spec?.rawBody) {
758
+ return { kind: "source", text: source.slice(start, end), reason: "mermaid", start, end };
759
+ }
471
760
  const children = node.children ?? [];
472
761
  const itemNames = spec?.items ? Array.isArray(spec.items) ? spec.items : [spec.items] : [];
473
762
  if (itemNames.length > 0) {
474
- const items = children.filter(isJsxBlock).filter((child) => itemNames.includes(child.name)).map((child) => {
763
+ const items = children.filter(isJsxBlock2).filter((child) => itemNames.includes(child.name)).map((child) => {
475
764
  const [itemStart, itemEnd] = rangeOf(child);
476
765
  return {
477
766
  name: child.name,
@@ -510,87 +799,191 @@ function toBlock(node, source, depth) {
510
799
  if (node.type === "definition") {
511
800
  return { kind: "source", text: source.slice(start, end), reason: "definition", start, end };
512
801
  }
802
+ if (CONTAINERISH.has(node.type)) {
803
+ const children = node.children ?? [];
804
+ return { kind: "visual", type: node.type, start, end, blocks: toBlocks(children, source, depth) };
805
+ }
513
806
  return { kind: "visual", type: node.type, start, end };
514
807
  }
515
808
  function extractBlocks(tree, source) {
516
809
  return toBlocks(tree.children, source, 1);
517
810
  }
518
811
 
519
- // src/policy.ts
520
- function isJsxBlock2(node) {
521
- return node.type === "jsxBlock";
812
+ // src/syntax/jsx-inline.ts
813
+ var CLOSE_TAG_RE = /^<\/([A-Za-z][\w]*)\s*>$/;
814
+ function itemsOf(name) {
815
+ const items = COMPONENTS[name]?.items;
816
+ if (!items) return [];
817
+ return typeof items === "string" ? [items] : items;
522
818
  }
523
- function sliceNode(source, node) {
524
- const start = node.position?.start.offset;
525
- const end = node.position?.end.offset;
526
- if (typeof start !== "number" || typeof end !== "number") return "";
527
- return source.slice(start, end);
819
+ function isBlank(node) {
820
+ return node.type === "text" && !String(node.value).trim();
528
821
  }
529
- function walk(parent, source, depth, maxDepth, out) {
530
- const children = parent.children;
531
- if (!children) return;
532
- const next = [];
533
- for (const child of children) {
534
- if (!isJsxBlock2(child)) {
535
- walk(child, source, depth, maxDepth, out);
536
- next.push(child);
537
- continue;
822
+ function allBlank(nodes) {
823
+ return nodes.every((node) => isBlank(node));
824
+ }
825
+ function spanPosition(first, last) {
826
+ const start = first?.position?.start;
827
+ const end = last?.position?.end;
828
+ if (!start || !end) return void 0;
829
+ return { start, end };
830
+ }
831
+ function makeItem(name, raw, selfClosing, children, inline, open, close) {
832
+ const { attributes } = parseOpenTag(raw);
833
+ const node = {
834
+ type: "jsxBlock",
835
+ name,
836
+ attributes,
837
+ selfClosing,
838
+ children
839
+ };
840
+ node.data = inline ? { closed: true, inline: true } : { closed: true };
841
+ const position = spanPosition(open, close);
842
+ if (position) node.position = position;
843
+ return node;
844
+ }
845
+ function toParagraph(nodes, fallback) {
846
+ if (nodes.length === 0 || allBlank(nodes)) return null;
847
+ const position = spanPosition(nodes[0], nodes[nodes.length - 1]) ?? fallback;
848
+ const paragraph = { type: "paragraph", children: nodes };
849
+ if (position) paragraph.position = position;
850
+ return paragraph;
851
+ }
852
+ function firstMeaningful(nodes, from) {
853
+ for (let index = from; index < nodes.length; index += 1) {
854
+ if (!isBlank(nodes[index])) return index;
855
+ }
856
+ return -1;
857
+ }
858
+ function findClose(nodes, from, name) {
859
+ for (let index = from; index < nodes.length; index += 1) {
860
+ const candidate = nodes[index];
861
+ if (candidate.type !== "html") continue;
862
+ const match = CLOSE_TAG_RE.exec(String(candidate.value).trim());
863
+ if (match && match[1] === name) return index;
864
+ }
865
+ return -1;
866
+ }
867
+ function tryFoldAt(children, index, allowed) {
868
+ const paragraph = children[index];
869
+ if (paragraph.type !== "paragraph") return null;
870
+ const nodes = paragraph.children;
871
+ const openIndex = firstMeaningful(nodes, 0);
872
+ if (openIndex === -1) return null;
873
+ const openNode = nodes[openIndex];
874
+ if (openNode.type !== "html") return null;
875
+ const parsed = parseOpenTag(String(openNode.value).trim());
876
+ if (!parsed.name || !allowed.includes(parsed.name)) return null;
877
+ if (parsed.selfClosing) {
878
+ const head = toParagraph(nodes.slice(0, openIndex), paragraph.position);
879
+ const tail = toParagraph(nodes.slice(openIndex + 1), paragraph.position);
880
+ const item = makeItem(parsed.name, String(openNode.value).trim(), true, [], true, openNode, openNode);
881
+ return { nodes: [...head ? [head] : [], item, ...tail ? [tail] : []], consume: 1, itemOffset: head ? 1 : 0 };
882
+ }
883
+ const inlineClose = findClose(nodes, openIndex + 1, parsed.name);
884
+ if (inlineClose !== -1) {
885
+ const inner = toParagraph(nodes.slice(openIndex + 1, inlineClose), paragraph.position);
886
+ const head = toParagraph(nodes.slice(0, openIndex), paragraph.position);
887
+ const tail = toParagraph(nodes.slice(inlineClose + 1), paragraph.position);
888
+ const closeNode = nodes[inlineClose];
889
+ const item = makeItem(parsed.name, String(openNode.value).trim(), false, inner ? [inner] : [], true, openNode, closeNode);
890
+ return { nodes: [...head ? [head] : [], item, ...tail ? [tail] : []], consume: 1, itemOffset: head ? 1 : 0 };
891
+ }
892
+ for (let probe = index + 1; probe < children.length; probe += 1) {
893
+ const sibling = children[probe];
894
+ if (sibling.type !== "paragraph") return null;
895
+ const siblingNodes = sibling.children;
896
+ const closeIndex = findClose(siblingNodes, 0, parsed.name);
897
+ const inner = [];
898
+ const firstBody = toParagraph(nodes.slice(openIndex + 1), paragraph.position);
899
+ if (firstBody) inner.push(firstBody);
900
+ for (let middle = index + 1; middle < probe; middle += 1) inner.push(children[middle]);
901
+ const head = toParagraph(nodes.slice(0, openIndex), paragraph.position);
902
+ if (closeIndex !== -1) {
903
+ const lastBody = toParagraph(siblingNodes.slice(0, closeIndex), sibling.position);
904
+ if (lastBody) inner.push(lastBody);
905
+ const tail = toParagraph(siblingNodes.slice(closeIndex + 1), sibling.position);
906
+ const item = makeItem(
907
+ parsed.name,
908
+ String(openNode.value).trim(),
909
+ false,
910
+ inner,
911
+ false,
912
+ openNode,
913
+ siblingNodes[closeIndex]
914
+ );
915
+ return {
916
+ nodes: [...head ? [head] : [], item, ...tail ? [tail] : []],
917
+ consume: probe - index + 1,
918
+ itemOffset: head ? 1 : 0
919
+ };
538
920
  }
539
- const isContainer = Boolean(COMPONENTS[child.name]);
540
- const childDepth = depth + (isContainer ? 1 : 0);
541
- if (isContainer && childDepth > maxDepth) {
542
- const text = sliceNode(source, child);
543
- const line = child.position?.start.line ?? 1;
544
- out.push({
545
- code: "DEPTH_EXCEEDED",
546
- level: "warn",
547
- line,
548
- message: `\u7B2C ${childDepth} \u5C42\u5BB9\u5668 ${child.name} \u8D85\u51FA\u4E0A\u9650 ${maxDepth}\uFF0C\u5DF2\u6309\u6E90\u7801\u663E\u793A`,
549
- range: [child.position?.start.offset ?? 0, child.position?.end.offset ?? 0]
550
- });
551
- const fallback = { type: "text", value: text };
552
- next.push(fallback);
921
+ }
922
+ return null;
923
+ }
924
+ function foldChildren(parent) {
925
+ const allowed = parent.type === "jsxBlock" ? itemsOf(parent.name) : [];
926
+ if (allowed.length === 0) return;
927
+ const children = parent.children;
928
+ let index = 0;
929
+ while (index < children.length) {
930
+ const folded = tryFoldAt(children, index, allowed);
931
+ if (!folded) {
932
+ index += 1;
553
933
  continue;
554
934
  }
555
- walk(child, source, childDepth, maxDepth, out);
556
- next.push(child);
935
+ children.splice(index, folded.consume, ...folded.nodes);
936
+ index += folded.itemOffset + 1;
557
937
  }
558
- parent.children = next;
559
938
  }
560
- function enforceMaxDepth(tree, source, maxDepth = MAX_CONTAINER_DEPTH) {
561
- const diagnostics = [];
562
- walk(tree, source, 0, maxDepth, diagnostics);
563
- return diagnostics;
939
+ function walk2(parent) {
940
+ if (parent.type === "root" || parent.type === "jsxBlock") foldChildren(parent);
941
+ const children = parent.children;
942
+ if (!children) return;
943
+ for (const child of children) walk2(child);
564
944
  }
565
- function hasCloseTag(block, source) {
566
- const start = block.position?.start.offset ?? 0;
567
- const end = block.position?.end.offset ?? 0;
568
- if (end <= start) return false;
569
- const body = new RegExp(`</${block.name}\\s*>`);
570
- if (body.test(source.slice(start, end))) return true;
571
- return new RegExp(`^\\s*</${block.name}\\s*>`).test(source.slice(end, end + 64));
945
+ function foldInlineItems(tree) {
946
+ walk2(tree);
572
947
  }
573
- function collectUnclosed(tree, source) {
574
- const diagnostics = [];
575
- const visit5 = (node) => {
576
- if (node.type === "jsxBlock") {
577
- const block = node;
578
- if (!block.selfClosing && !hasCloseTag(block, source)) {
579
- block.data = { ...block.data ?? {}, closed: false };
580
- diagnostics.push({
581
- code: "UNCLOSED_TAG",
582
- level: "warn",
583
- line: block.position?.start.line ?? 1,
584
- message: `<${block.name}> \u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5EF6\u4F38\u5230\u6587\u672B\u5904\u7406`,
585
- range: [block.position?.start.offset ?? 0, block.position?.end.offset ?? 0]
586
- });
587
- }
588
- }
589
- const children = node.children;
590
- if (children) for (const child of children) visit5(child);
948
+ function remarkInlineItems() {
949
+ return (tree) => {
950
+ foldInlineItems(tree);
951
+ return void 0;
591
952
  };
592
- visit5(tree);
593
- return diagnostics;
953
+ }
954
+ function isSingleLineBlockMath(raw) {
955
+ if (!raw.startsWith("$$") || !raw.endsWith("$$")) return false;
956
+ if (raw.length <= 4) return false;
957
+ return !raw.slice(2, -2).includes("$$");
958
+ }
959
+ function promoteBlockMath(tree, source) {
960
+ visit(tree, "paragraph", (node, index, parent) => {
961
+ if (typeof index !== "number" || !parent) return;
962
+ if (node.children.length !== 1) return;
963
+ const only = node.children[0];
964
+ if (only.type !== "inlineMath") return;
965
+ const start = node.position?.start.offset;
966
+ const end = node.position?.end.offset;
967
+ if (typeof start !== "number" || typeof end !== "number") return;
968
+ if (!isSingleLineBlockMath(source.slice(start, end).trim())) return;
969
+ parent.children[index] = {
970
+ type: "math",
971
+ meta: null,
972
+ value: only.value,
973
+ data: {
974
+ hName: "pre",
975
+ hChildren: [
976
+ {
977
+ type: "element",
978
+ tagName: "code",
979
+ properties: { className: ["language-math", "math-display"] },
980
+ children: [{ type: "text", value: only.value }]
981
+ }
982
+ ]
983
+ },
984
+ position: node.position
985
+ };
986
+ });
594
987
  }
595
988
 
596
989
  // src/policy-tags.ts
@@ -660,11 +1053,17 @@ function parse(md, options) {
660
1053
  extensions: [gfm(), math(), jsxBlocks()],
661
1054
  mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown(), jsxFromMarkdown()]
662
1055
  });
1056
+ foldInlineItems(tree);
1057
+ promoteBlockMath(tree, source);
663
1058
  const diagnostics = [
664
1059
  ...enforceMaxDepth(tree, source, options?.maxDepth),
665
1060
  ...collectUnclosed(tree, source),
666
1061
  ...collectUnsafeUrls(tree),
667
- ...collectUnknownTags(tree)
1062
+ ...collectUnknownTags(tree),
1063
+ ...collectIndentAsCode(tree, source),
1064
+ // 图表容器:空源码 / 超限。必须在 enforceMaxDepth 之后——
1065
+ // 被深度裁剪降级的图表块不再出图,也就不该再报图表自身的诊断
1066
+ ...collectMermaid(tree)
668
1067
  ];
669
1068
  const blocks = extractBlocks(tree, source);
670
1069
  return { tree, blocks, diagnostics };
@@ -711,6 +1110,17 @@ function normalizeMarkdown(md) {
711
1110
  while (out.length > 0 && out[out.length - 1] === "") out.pop();
712
1111
  return out.join("\n");
713
1112
  }
1113
+ function remarkHtmlAsText() {
1114
+ return (tree) => {
1115
+ visit(tree, "html", (node, index, parent) => {
1116
+ if (typeof index !== "number" || !parent) return;
1117
+ const replacement = { type: "text", value: node.value };
1118
+ if (node.position) replacement.position = node.position;
1119
+ parent.children[index] = replacement;
1120
+ });
1121
+ return void 0;
1122
+ };
1123
+ }
714
1124
  var URL_PROPS = ["href", "src"];
715
1125
  function rehypeSafeUrls() {
716
1126
  return (tree) => {
@@ -808,10 +1218,30 @@ function rehypeSourcePositions() {
808
1218
  };
809
1219
  }
810
1220
  function jsxBlockToHast(state, node) {
1221
+ if (node.data?.degraded && typeof node.data.degradedText === "string") {
1222
+ return {
1223
+ type: "element",
1224
+ tagName: "pre",
1225
+ properties: { className: ["md-degraded"] },
1226
+ children: [
1227
+ {
1228
+ type: "element",
1229
+ tagName: "code",
1230
+ properties: {},
1231
+ children: [{ type: "text", value: node.data.degradedText }]
1232
+ }
1233
+ ]
1234
+ };
1235
+ }
811
1236
  const properties = {};
812
1237
  for (const [key, value] of Object.entries(node.attributes ?? {})) {
813
1238
  properties[key] = value;
814
1239
  }
1240
+ if (typeof node.data?.rawBody === "string") {
1241
+ properties.raw = node.data.rawBody;
1242
+ properties.code = node.data.rawBody;
1243
+ if (node.data.mermaidTooLarge) properties.tooLarge = true;
1244
+ }
815
1245
  return {
816
1246
  type: "element",
817
1247
  tagName: node.name,
@@ -820,7 +1250,7 @@ function jsxBlockToHast(state, node) {
820
1250
  };
821
1251
  }
822
1252
  function createProcessor(extraRemark, extraRehype, sourcePositions) {
823
- return unified().use(remarkParse).use(remarkJsxBlocks).use(remarkGfm).use(remarkMath).use(extraRemark ?? []).use(remarkRehype, { handlers: { jsxBlock: jsxBlockToHast } }).use(rehypeSafeUrls).use(rehypeSafeAnchors).use(sourcePositions ? [rehypeSourcePositions] : []).use(rehypeCodeMeta).use(rehypeSlug).use(extraRehype ?? []).use(rehypeKatex);
1253
+ return unified().use(remarkParse).use(remarkJsxBlocks).use(remarkGfm).use(remarkMath).use(remarkInlineItems).use(remarkHtmlAsText).use(extraRemark ?? []).use(remarkRehype, { handlers: { jsxBlock: jsxBlockToHast } }).use(rehypeSafeUrls).use(rehypeSafeAnchors).use(sourcePositions ? [rehypeSourcePositions] : []).use(rehypeCodeMeta).use(rehypeSlug).use(extraRehype ?? []).use(rehypeKatex);
824
1254
  }
825
1255
  function MarkdownRenderer({
826
1256
  content,
@@ -838,7 +1268,9 @@ function MarkdownRenderer({
838
1268
  const rendered = useMemo(() => {
839
1269
  const source = content ?? "";
840
1270
  const mdast = processor.parse(source);
1271
+ promoteBlockMath(mdast, source);
841
1272
  enforceMaxDepth(mdast, source);
1273
+ collectMermaid(mdast);
842
1274
  const hast = processor.runSync(mdast);
843
1275
  return toJsxRuntime(hast, {
844
1276
  Fragment,
@@ -850,6 +1282,6 @@ function MarkdownRenderer({
850
1282
  return /* @__PURE__ */ jsx("div", { className, children: rendered });
851
1283
  }
852
1284
 
853
- export { COMPONENTS, ITEMS, MAX_CONTAINER_DEPTH, MarkdownRenderer, extractBlocks, getComponent, getItemSpec, isContainerWithItems, jsxBlocks, jsxFromMarkdown, jsxToMarkdown, listComponents, normalizeMarkdown, parse, parseOpenTag, remarkJsxBlocks };
854
- //# sourceMappingURL=chunk-3GDOWIMO.js.map
855
- //# sourceMappingURL=chunk-3GDOWIMO.js.map
1285
+ export { COMPONENTS, ITEMS, MAX_CONTAINER_DEPTH, MERMAID_MAX_BYTES, MarkdownRenderer, extractBlocks, getComponent, getItemSpec, isContainerWithItems, jsxBlocks, jsxFromMarkdown, jsxToMarkdown, listComponents, normalizeMarkdown, parse, parseOpenTag, remarkJsxBlocks, sliceRawBody };
1286
+ //# sourceMappingURL=chunk-7RXVCGFM.js.map
1287
+ //# sourceMappingURL=chunk-7RXVCGFM.js.map