@heikeson/md-engine 0.5.2 → 0.5.4

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.
Files changed (35) hide show
  1. package/README.md +133 -259
  2. package/dist/{chunk-KC6CBSFU.js → chunk-2A72VTCO.js} +9 -11
  3. package/dist/{chunk-YJGGJP2V.js → chunk-P4SAIRGF.js} +0 -2
  4. package/dist/{chunk-RJZKMZOI.js → chunk-QEMURI4I.js} +353 -224
  5. package/dist/{chunk-OG47YL3H.js → chunk-RWT2RMCY.js} +0 -2
  6. package/dist/{chunk-OJQDOFGL.js → chunk-SGORBOHN.js} +2 -4
  7. package/dist/components/index.d.ts +16 -20
  8. package/dist/components/index.js +4 -6
  9. package/dist/editor/index.d.ts +15 -5
  10. package/dist/editor/index.js +50 -24
  11. package/dist/index.d.ts +36 -18
  12. package/dist/index.js +14 -10
  13. package/dist/locales/en-US.js +1 -3
  14. package/dist/locales/zh-CN.js +1 -3
  15. package/dist/mermaid/index.d.ts +1 -15
  16. package/dist/mermaid/index.js +11 -7
  17. package/dist/{mermaid-placeholder-DYfFG3_f.d.ts → mermaid-placeholder-D97goALt.d.ts} +0 -3
  18. package/dist/{render-DbUepYgE.d.ts → render-CCAfJ__u.d.ts} +1 -3
  19. package/package.json +5 -1
  20. package/styles/cards.css +0 -1
  21. package/styles/files.css +0 -1
  22. package/styles/index.css +0 -2
  23. package/styles/mermaid.css +0 -6
  24. package//345/257/271/346/216/245/345/245/221/347/272/246.md +17 -7
  25. package/dist/chunk-KC6CBSFU.js.map +0 -1
  26. package/dist/chunk-OG47YL3H.js.map +0 -1
  27. package/dist/chunk-OJQDOFGL.js.map +0 -1
  28. package/dist/chunk-RJZKMZOI.js.map +0 -1
  29. package/dist/chunk-YJGGJP2V.js.map +0 -1
  30. package/dist/components/index.js.map +0 -1
  31. package/dist/editor/index.js.map +0 -1
  32. package/dist/index.js.map +0 -1
  33. package/dist/locales/en-US.js.map +0 -1
  34. package/dist/locales/zh-CN.js.map +0 -1
  35. package/dist/mermaid/index.js.map +0 -1
@@ -1,7 +1,9 @@
1
- import { mdxComponents, isSafeHref } from './chunk-KC6CBSFU.js';
2
- import { useShallowStable, MdEngineProvider } from './chunk-OJQDOFGL.js';
3
- import { asciiAlpha, asciiAlphanumeric, markdownLineEnding } from 'micromark-util-character';
1
+ import { mdxComponents, isSafeHref } from './chunk-2A72VTCO.js';
2
+ import { useShallowStable, MdEngineProvider } from './chunk-SGORBOHN.js';
3
+ import { asciiAlpha, asciiAlphanumeric, markdownLineEnding, markdownSpace } from 'micromark-util-character';
4
4
  import { fromMarkdown } from 'mdast-util-from-markdown';
5
+ import remarkGfm from 'remark-gfm';
6
+ import remarkMath from 'remark-math';
5
7
  import { gfm } from 'micromark-extension-gfm';
6
8
  import { gfmFromMarkdown } from 'mdast-util-gfm';
7
9
  import { math } from 'micromark-extension-math';
@@ -9,11 +11,9 @@ import { mathFromMarkdown } from 'mdast-util-math';
9
11
  import { visit } from 'unist-util-visit';
10
12
  import GithubSlugger from 'github-slugger';
11
13
  import { useMemo } from 'react';
12
- import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
14
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
13
15
  import { unified } from 'unified';
14
16
  import remarkParse from 'remark-parse';
15
- import remarkGfm from 'remark-gfm';
16
- import remarkMath from 'remark-math';
17
17
  import remarkRehype from 'remark-rehype';
18
18
  import rehypeSlug from 'rehype-slug';
19
19
  import rehypeKatex from 'rehype-katex';
@@ -98,8 +98,9 @@ var GT = 62;
98
98
  var SLASH = 47;
99
99
  var DQUOTE = 34;
100
100
  var SQUOTE = 39;
101
- var SPACE = 32;
102
- var TAB = 9;
101
+ function isIndentCode(code) {
102
+ return code !== null && markdownSpace(code);
103
+ }
103
104
  function isKnownName(name) {
104
105
  return Boolean(COMPONENTS[name]) || Boolean(ITEMS[name]);
105
106
  }
@@ -236,7 +237,7 @@ function tokenizeJsxBlock(effects, ok, nok) {
236
237
  return consumeIndent(code);
237
238
  }
238
239
  function consumeIndent(code) {
239
- if (code === SPACE || code === TAB) {
240
+ if (isIndentCode(code)) {
240
241
  effects.consume(code);
241
242
  return consumeIndent;
242
243
  }
@@ -359,7 +360,7 @@ function tokenizeJsxBlock(effects, ok, nok) {
359
360
  index += 1;
360
361
  return probeName;
361
362
  }
362
- if (code === SPACE) {
363
+ if (isIndentCode(code)) {
363
364
  effects2.consume(code);
364
365
  return probeAttrs;
365
366
  }
@@ -396,12 +397,12 @@ function tokenizeJsxBlock(effects, ok, nok) {
396
397
  let probe = "";
397
398
  return indentStart;
398
399
  function indentStart(code) {
399
- if (code !== SPACE && code !== TAB) return nok2(code);
400
+ if (!isIndentCode(code)) return nok2(code);
400
401
  effects2.enter("jsxBlockIndent");
401
402
  return indentSpace(code);
402
403
  }
403
404
  function indentSpace(code) {
404
- if (code === SPACE || code === TAB) {
405
+ if (isIndentCode(code)) {
405
406
  effects2.consume(code);
406
407
  return indentSpace;
407
408
  }
@@ -453,6 +454,21 @@ function tokenizeJsxBlock(effects, ok, nok) {
453
454
  // src/syntax/jsx-mdast.ts
454
455
  var OPEN_TAG_RE = /^<([A-Za-z][\w]*)([\s\S]*?)(\/?)>$/;
455
456
  var ATTR_RE = /([A-Za-z_][\w-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g;
457
+ var CLOSE_TAG_RE = /^<\/([A-Za-z][\w]*)\s*>$/;
458
+ var CLOSE_TAG_CACHE = /* @__PURE__ */ new Map();
459
+ function escapeRegExp(value) {
460
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
461
+ }
462
+ function closeTagRe(name, where = "any") {
463
+ const key = `${where}:${name}`;
464
+ const cached = CLOSE_TAG_CACHE.get(key);
465
+ if (cached) return cached;
466
+ const escaped = escapeRegExp(name);
467
+ const pattern = where === "end" ? `</${escaped}\\s*>\\s*$` : where === "start" ? `^\\s*</${escaped}\\s*>` : `</${escaped}\\s*>`;
468
+ const created = new RegExp(pattern);
469
+ CLOSE_TAG_CACHE.set(key, created);
470
+ return created;
471
+ }
456
472
  function parseOpenTag(raw) {
457
473
  const match = OPEN_TAG_RE.exec(raw.trim());
458
474
  if (!match) return { name: "", attributes: {}, selfClosing: false };
@@ -483,7 +499,9 @@ function jsxToMarkdown() {
483
499
  return {
484
500
  handlers: {
485
501
  jsxBlock: handleJsxBlock
486
- }
502
+ },
503
+ // 容器块与兄弟节点之间按原文行距连接,不替用户补空行
504
+ join: [joinJsxBlocks]
487
505
  };
488
506
  }
489
507
  function enterBlock(token) {
@@ -522,7 +540,7 @@ function sliceRawBody(raw, name, selfClosing) {
522
540
  const openEnd = openTagEnd(raw);
523
541
  if (openEnd < 0) return "";
524
542
  const bodyStart = openEnd + 1;
525
- const close = new RegExp(`</${name}\\s*>\\s*$`).exec(raw);
543
+ const close = closeTagRe(name, "end").exec(raw);
526
544
  if (!close) return raw.slice(bodyStart);
527
545
  return raw.slice(bodyStart, close.index);
528
546
  }
@@ -544,9 +562,9 @@ function serializeAttributes(attributes) {
544
562
  function isInlineLayout(node) {
545
563
  return node.data?.inline === true;
546
564
  }
547
- function needsBlankLine(prevLine, nextLine) {
548
- if (typeof prevLine !== "number" || typeof nextLine !== "number") return true;
549
- return nextLine - prevLine > 1;
565
+ function lineBreaks(prevLine, nextLine) {
566
+ if (typeof prevLine !== "number" || typeof nextLine !== "number") return "\n\n";
567
+ return "\n".repeat(Math.max(1, nextLine - prevLine));
550
568
  }
551
569
  function handleJsxBlock(node, _parent, state, info) {
552
570
  const attrs = serializeAttributes(node.attributes ?? {});
@@ -577,7 +595,7 @@ function handleJsxBlock(node, _parent, state, info) {
577
595
  let body = "";
578
596
  let prevEnd = node.position?.start.line;
579
597
  for (const child of children) {
580
- const gap = needsBlankLine(prevEnd, child.position?.start.line) ? "\n\n" : "\n";
598
+ const gap = lineBreaks(prevEnd, child.position?.start.line);
581
599
  const piece = state.handle(child, node, state, {
582
600
  before: "\n",
583
601
  after: "\n",
@@ -587,8 +605,14 @@ function handleJsxBlock(node, _parent, state, info) {
587
605
  prevEnd = child.position?.end.line;
588
606
  }
589
607
  if (node.data?.closed === false) return `${open}${body}`;
590
- const closeGap = needsBlankLine(prevEnd, node.position?.end.line) ? "\n\n" : "\n";
591
- return `${open}${body}${closeGap}</${node.name}>`;
608
+ return `${open}${body}${lineBreaks(prevEnd, node.position?.end.line)}</${node.name}>`;
609
+ }
610
+ function joinJsxBlocks(left, right) {
611
+ if (left.type !== "jsxBlock" && right.type !== "jsxBlock") return void 0;
612
+ const endLine = left.position?.end.line;
613
+ const startLine = right.position?.start.line;
614
+ if (typeof endLine !== "number" || typeof startLine !== "number") return void 0;
615
+ return Math.max(0, startLine - endLine - 1);
592
616
  }
593
617
 
594
618
  // src/syntax/jsx-remark.ts
@@ -600,6 +624,19 @@ function remarkJsxBlocks() {
600
624
  return void 0;
601
625
  }
602
626
 
627
+ // src/internal/walk.ts
628
+ function childrenOf(node) {
629
+ return node.children;
630
+ }
631
+ function walkMdast(node, visit4) {
632
+ const children = childrenOf(node);
633
+ if (!children) return;
634
+ for (const child of children) {
635
+ visit4(child);
636
+ walkMdast(child, visit4);
637
+ }
638
+ }
639
+
603
640
  // src/policy.ts
604
641
  var MERMAID_MAX_BYTES = 20 * 1024;
605
642
  function isJsxBlock(node) {
@@ -652,13 +689,12 @@ function hasCloseTag(block, source) {
652
689
  const start = block.position?.start.offset ?? 0;
653
690
  const end = block.position?.end.offset ?? 0;
654
691
  if (end <= start) return false;
655
- const body = new RegExp(`</${block.name}\\s*>`);
656
- if (body.test(source.slice(start, end))) return true;
657
- return new RegExp(`^\\s*</${block.name}\\s*>`).test(source.slice(end, end + 64));
692
+ if (closeTagRe(block.name).test(source.slice(start, end))) return true;
693
+ return closeTagRe(block.name, "start").test(source.slice(end, end + 64));
658
694
  }
659
695
  function collectIndentAsCode(tree, source) {
660
696
  const diagnostics = [];
661
- const visit7 = (node, inside) => {
697
+ const visit4 = (node, inside) => {
662
698
  if (node.type === "code") {
663
699
  const start = node.position?.start.offset;
664
700
  const end = node.position?.end.offset;
@@ -678,14 +714,14 @@ function collectIndentAsCode(tree, source) {
678
714
  }
679
715
  const children = node.children;
680
716
  if (!children) return;
681
- for (const child of children) visit7(child, inside || node.type === "jsxBlock");
717
+ for (const child of children) visit4(child, inside || node.type === "jsxBlock");
682
718
  };
683
- visit7(tree, false);
719
+ visit4(tree, false);
684
720
  return diagnostics;
685
721
  }
686
722
  function collectUnclosed(tree, source) {
687
723
  const diagnostics = [];
688
- const visit7 = (node) => {
724
+ walkMdast(tree, (node) => {
689
725
  if (node.type === "jsxBlock") {
690
726
  const block = node;
691
727
  if (!block.selfClosing && !hasCloseTag(block, source)) {
@@ -700,15 +736,12 @@ function collectUnclosed(tree, source) {
700
736
  });
701
737
  }
702
738
  }
703
- const children = node.children;
704
- if (children) for (const child of children) visit7(child);
705
- };
706
- visit7(tree);
739
+ });
707
740
  return diagnostics;
708
741
  }
709
742
  function collectMermaid(tree) {
710
743
  const diagnostics = [];
711
- const visit7 = (node) => {
744
+ walkMdast(tree, (node) => {
712
745
  if (node.type === "jsxBlock") {
713
746
  const block = node;
714
747
  if (COMPONENTS[block.name]?.rawBody) {
@@ -740,10 +773,7 @@ function collectMermaid(tree) {
740
773
  }
741
774
  }
742
775
  }
743
- const children = node.children;
744
- if (children) for (const child of children) visit7(child);
745
- };
746
- visit7(tree);
776
+ });
747
777
  return diagnostics;
748
778
  }
749
779
 
@@ -823,7 +853,6 @@ function extractBlocks(tree, source) {
823
853
  }
824
854
 
825
855
  // src/syntax/jsx-inline.ts
826
- var CLOSE_TAG_RE = /^<\/([A-Za-z][\w]*)\s*>$/;
827
856
  function itemsOf(name) {
828
857
  const items = COMPONENTS[name]?.items;
829
858
  if (!items) return [];
@@ -964,6 +993,17 @@ function remarkInlineItems() {
964
993
  return void 0;
965
994
  };
966
995
  }
996
+ function remarkHtmlAsText() {
997
+ return (tree) => {
998
+ visit(tree, "html", (node, index, parent) => {
999
+ if (typeof index !== "number" || !parent) return;
1000
+ const replacement = { type: "text", value: node.value };
1001
+ if (node.position) replacement.position = node.position;
1002
+ parent.children[index] = replacement;
1003
+ });
1004
+ return void 0;
1005
+ };
1006
+ }
967
1007
  function isSingleLineBlockMath(raw) {
968
1008
  if (!raw.startsWith("$$") || !raw.endsWith("$$")) return false;
969
1009
  if (raw.length <= 4) return false;
@@ -998,15 +1038,25 @@ function promoteBlockMath(tree, source) {
998
1038
  };
999
1039
  });
1000
1040
  }
1041
+
1042
+ // src/pipeline.ts
1043
+ var MARKDOWN_EXTENSIONS = [gfm(), math(), jsxBlocks()];
1044
+ var MARKDOWN_MDAST_EXTENSIONS = [
1045
+ gfmFromMarkdown(),
1046
+ mathFromMarkdown(),
1047
+ jsxFromMarkdown()
1048
+ ];
1049
+ var REMARK_PARSE_PLUGINS = [remarkJsxBlocks, remarkGfm, remarkMath];
1050
+ var REMARK_TRANSFORMS = [remarkInlineItems, remarkHtmlAsText];
1051
+ function applySourceTransforms(tree, source, maxDepth) {
1052
+ promoteBlockMath(tree, source);
1053
+ const depth = enforceMaxDepth(tree, source, maxDepth);
1054
+ const mermaid = collectMermaid(tree);
1055
+ return { depth, mermaid };
1056
+ }
1001
1057
  var URL_ATTRS = ["href", "src"];
1002
1058
  var HTML_OPEN_TAG = /^<([A-Z][A-Za-z0-9]*)/;
1003
1059
  var KNOWN_NAMES = /* @__PURE__ */ new Set([...Object.keys(COMPONENTS), ...Object.keys(ITEMS)]);
1004
- function forEachNode(node, fn) {
1005
- if (node.type !== "root") fn(node);
1006
- const children = node.children;
1007
- if (!children) return;
1008
- for (const child of children) forEachNode(child, fn);
1009
- }
1010
1060
  function collectUnsafeUrls(tree) {
1011
1061
  const diagnostics = [];
1012
1062
  const report = (line, kind, label, url) => {
@@ -1018,7 +1068,7 @@ function collectUnsafeUrls(tree) {
1018
1068
  params: { kind, label, url }
1019
1069
  });
1020
1070
  };
1021
- forEachNode(tree, (node) => {
1071
+ walkMdast(tree, (node) => {
1022
1072
  const line = node.position?.start.line ?? 1;
1023
1073
  if (node.type === "jsxBlock") {
1024
1074
  const block = node;
@@ -1048,52 +1098,43 @@ function collectDuplicateIds(tree) {
1048
1098
  const diagnostics = [];
1049
1099
  const slugger = new GithubSlugger();
1050
1100
  const headingSlugs = /* @__PURE__ */ new Set();
1051
- const collectHeadings = (node) => {
1101
+ walkMdast(tree, (node) => {
1052
1102
  if (node.type === "heading") headingSlugs.add(slugger.slug(nodeText(node)));
1053
- const children = node.children;
1054
- if (children) for (const child of children) collectHeadings(child);
1055
- };
1056
- collectHeadings(tree);
1103
+ });
1057
1104
  const seen = /* @__PURE__ */ new Map();
1058
- const checkDivs = (node) => {
1059
- if (node.type === "jsxBlock") {
1060
- const block = node;
1061
- if (block.name === "div") {
1062
- const id = block.attributes?.id;
1063
- const line = block.position?.start.line ?? 1;
1064
- if (typeof id === "string" && id.length > 0) {
1065
- const first = seen.get(id);
1066
- if (headingSlugs.has(id)) {
1067
- diagnostics.push({
1068
- code: "DUPLICATE_ID_ANCHOR",
1069
- level: "warn",
1070
- line,
1071
- message: `div id="${id}" \u4E0E\u6807\u9898\u751F\u6210\u7684\u951A\u70B9\u91CD\u590D\uFF0C\u9875\u9762\u5C06\u51FA\u73B0\u4E24\u4E2A\u540C\u540D id`,
1072
- params: { id }
1073
- });
1074
- } else if (first !== void 0) {
1075
- diagnostics.push({
1076
- code: "DUPLICATE_ID_DIV",
1077
- level: "warn",
1078
- line,
1079
- message: `div id="${id}" \u4E0E\u7B2C ${first} \u884C\u7684 div \u91CD\u590D\uFF0C\u9875\u9762\u5C06\u51FA\u73B0\u4E24\u4E2A\u540C\u540D id`,
1080
- params: { id, first }
1081
- });
1082
- } else {
1083
- seen.set(id, line);
1084
- }
1085
- }
1086
- }
1105
+ walkMdast(tree, (node) => {
1106
+ if (node.type !== "jsxBlock") return;
1107
+ const block = node;
1108
+ if (block.name !== "div") return;
1109
+ const id = block.attributes?.id;
1110
+ const line = block.position?.start.line ?? 1;
1111
+ if (typeof id !== "string" || id.length === 0) return;
1112
+ const first = seen.get(id);
1113
+ if (headingSlugs.has(id)) {
1114
+ diagnostics.push({
1115
+ code: "DUPLICATE_ID_ANCHOR",
1116
+ level: "warn",
1117
+ line,
1118
+ message: `div id="${id}" \u4E0E\u6807\u9898\u751F\u6210\u7684\u951A\u70B9\u91CD\u590D\uFF0C\u9875\u9762\u5C06\u51FA\u73B0\u4E24\u4E2A\u540C\u540D id`,
1119
+ params: { id }
1120
+ });
1121
+ } else if (first !== void 0) {
1122
+ diagnostics.push({
1123
+ code: "DUPLICATE_ID_DIV",
1124
+ level: "warn",
1125
+ line,
1126
+ message: `div id="${id}" \u4E0E\u7B2C ${first} \u884C\u7684 div \u91CD\u590D\uFF0C\u9875\u9762\u5C06\u51FA\u73B0\u4E24\u4E2A\u540C\u540D id`,
1127
+ params: { id, first }
1128
+ });
1129
+ } else {
1130
+ seen.set(id, line);
1087
1131
  }
1088
- const children = node.children;
1089
- if (children) for (const child of children) checkDivs(child);
1090
- };
1091
- checkDivs(tree);
1132
+ });
1092
1133
  return diagnostics;
1093
1134
  }
1094
1135
  function collectUnknownTags(tree) {
1095
1136
  const diagnostics = [];
1096
- forEachNode(tree, (node) => {
1137
+ walkMdast(tree, (node) => {
1097
1138
  if (node.type !== "html") return;
1098
1139
  const match = HTML_OPEN_TAG.exec(String(node.value ?? "").trim());
1099
1140
  if (!match) return;
@@ -1114,107 +1155,165 @@ function collectUnknownTags(tree) {
1114
1155
  function parse(md, options) {
1115
1156
  const source = md ?? "";
1116
1157
  const tree = fromMarkdown(source, {
1117
- // GFM(表格 / 删除线 / 任务列表)、数学公式与尖括号块并列注册,解析与序列化保持同一口径。
1158
+ // 扩展在 pipeline 里构造一次并复用:GFM(表格 / 删除线 / 任务列表)、数学公式与
1159
+ // 尖括号块并列注册,解析与序列化保持同一口径。
1118
1160
  // math 必须在此注册:否则 `$…$` 会退化成普通文本,序列化时把 `_`、`\` 当文本转义,
1119
1161
  // 保存一次公式即变形(渲染侧走 remark-math,故表现为"看着正常、存下来坏了")。
1120
- extensions: [gfm(), math(), jsxBlocks()],
1121
- mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown(), jsxFromMarkdown()]
1162
+ extensions: MARKDOWN_EXTENSIONS,
1163
+ mdastExtensions: MARKDOWN_MDAST_EXTENSIONS
1122
1164
  });
1123
1165
  foldInlineItems(tree);
1124
- promoteBlockMath(tree, source);
1166
+ const transforms = applySourceTransforms(tree, source, options?.maxDepth);
1125
1167
  const diagnostics = [
1126
- ...enforceMaxDepth(tree, source, options?.maxDepth),
1168
+ ...transforms.depth,
1127
1169
  ...collectUnclosed(tree, source),
1128
1170
  ...collectUnsafeUrls(tree),
1129
1171
  ...collectUnknownTags(tree),
1130
1172
  ...collectIndentAsCode(tree, source),
1131
1173
  ...collectDuplicateIds(tree),
1132
- // 图表容器:空源码 / 超限。必须在 enforceMaxDepth 之后——
1174
+ // 图表容器:空源码 / 超限。必须排在深度裁剪之后——
1133
1175
  // 被深度裁剪降级的图表块不再出图,也就不该再报图表自身的诊断
1134
- ...collectMermaid(tree)
1176
+ ...transforms.mermaid
1135
1177
  ];
1136
- const blocks = extractBlocks(tree, source);
1178
+ const blocks = options?.blocks === false ? [] : extractBlocks(tree, source);
1137
1179
  return { tree, blocks, diagnostics };
1138
1180
  }
1181
+ function diagnose(md, options) {
1182
+ return parse(md, { ...options, blocks: false }).diagnostics;
1183
+ }
1139
1184
 
1140
- // src/format.ts
1141
- var TAG_LINE = /^(\s*)<(\/?)([A-Z][A-Za-z0-9]*)((?:\s[^>]*)?)(\/?)>\s*$/;
1142
- var FENCE_LINE = /^\s*(`{3,}|~{3,})/;
1143
- function normalizeMarkdown(md) {
1144
- const lines = (md ?? "").replace(/\r\n?/g, "\n").split("\n");
1145
- const out = [];
1146
- let fenceChar = null;
1147
- const pushBlank = () => {
1148
- if (out.length > 0 && out[out.length - 1].trim() !== "") out.push("");
1149
- };
1150
- for (let i = 0; i < lines.length; i += 1) {
1151
- const line = lines[i];
1152
- const fence = FENCE_LINE.exec(line);
1153
- if (fenceChar !== null) {
1154
- out.push(line);
1155
- if (fence && fence[1].startsWith(fenceChar)) fenceChar = null;
1156
- continue;
1185
+ // src/rehype-safe-urls.ts
1186
+ var URL_PROPS = ["poster", "formAction"];
1187
+ var FORM_ACTION_LEGACY = "formaction";
1188
+ var SRCSET_PROPS = ["srcSet", "srcset"];
1189
+ function isSafeSrcset(value) {
1190
+ const candidates = value.split(",").map((candidate) => candidate.trim()).filter((candidate) => candidate.length > 0);
1191
+ if (candidates.length === 0) return false;
1192
+ return candidates.every((candidate) => {
1193
+ const url = candidate.split(/\s+/)[0] ?? "";
1194
+ return isSafeHref(url);
1195
+ });
1196
+ }
1197
+ function sanitizeUrlProps(node) {
1198
+ const properties = node.properties;
1199
+ if (!properties) return;
1200
+ const href = properties.href;
1201
+ if (href !== void 0 && href !== null) {
1202
+ if (typeof href !== "string" || href.length > 0 && !isSafeHref(href)) {
1203
+ properties.href = "#";
1157
1204
  }
1158
- if (fence) {
1159
- fenceChar = fence[1][0];
1160
- out.push(line);
1205
+ }
1206
+ for (const key of URL_PROPS) {
1207
+ const value = properties[key];
1208
+ if (value === void 0 || value === null) continue;
1209
+ if (typeof value !== "string") {
1210
+ delete properties[key];
1161
1211
  continue;
1162
1212
  }
1163
- const tag = TAG_LINE.exec(line);
1164
- if (tag && tag[1] === "") {
1165
- pushBlank();
1166
- out.push(line.trim());
1167
- const next = lines[i + 1];
1168
- if (next !== void 0 && next.trim() !== "") out.push("");
1169
- continue;
1213
+ if (value.length > 0 && !isSafeHref(value)) delete properties[key];
1214
+ }
1215
+ const legacyAction = properties[FORM_ACTION_LEGACY];
1216
+ if (legacyAction !== void 0 && legacyAction !== null) {
1217
+ if (typeof legacyAction !== "string" || legacyAction.length > 0 && !isSafeHref(legacyAction)) {
1218
+ delete properties[FORM_ACTION_LEGACY];
1170
1219
  }
1171
- if (line.trim() === "") {
1172
- if (out.length > 0 && out[out.length - 1].trim() === "") continue;
1173
- out.push("");
1174
- continue;
1220
+ }
1221
+ const src = properties.src;
1222
+ if (src !== void 0 && src !== null) {
1223
+ if (typeof src !== "string" || src.length > 0 && !isSafeHref(src)) {
1224
+ delete properties.src;
1175
1225
  }
1176
- out.push(line);
1177
1226
  }
1178
- while (out.length > 0 && out[out.length - 1] === "") out.pop();
1179
- return out.join("\n");
1180
- }
1181
- function remarkHtmlAsText() {
1182
- return (tree) => {
1183
- visit(tree, "html", (node, index, parent) => {
1184
- if (typeof index !== "number" || !parent) return;
1185
- const replacement = { type: "text", value: node.value };
1186
- if (node.position) replacement.position = node.position;
1187
- parent.children[index] = replacement;
1188
- });
1189
- return void 0;
1190
- };
1227
+ for (const key of SRCSET_PROPS) {
1228
+ const value = properties[key];
1229
+ if (value === void 0 || value === null) continue;
1230
+ if (typeof value !== "string" || !isSafeSrcset(value)) delete properties[key];
1231
+ }
1191
1232
  }
1192
- var URL_PROPS = ["href", "src"];
1193
- function rehypeSafeUrls() {
1194
- return (tree) => {
1195
- visit(tree, "element", (node) => {
1196
- for (const key of URL_PROPS) {
1197
- const value = node.properties[key];
1198
- if (typeof value !== "string" || value.length === 0) continue;
1199
- if (isSafeHref(value)) continue;
1200
- if (key === "href") node.properties[key] = "#";
1201
- else delete node.properties[key];
1233
+
1234
+ // src/rehype-safe-anchors.ts
1235
+ function percentByteAt(text, index) {
1236
+ if (text[index] !== "%") return null;
1237
+ const hex = text.slice(index + 1, index + 3);
1238
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return null;
1239
+ return { byte: parseInt(hex, 16), next: index + 3 };
1240
+ }
1241
+ function sequenceLength(lead) {
1242
+ if (lead >= 194 && lead <= 223) return 2;
1243
+ if (lead >= 224 && lead <= 239) return 3;
1244
+ if (lead >= 240 && lead <= 244) return 4;
1245
+ return 1;
1246
+ }
1247
+ function restoreMultibyte(fragment) {
1248
+ if (!fragment.includes("%")) return fragment;
1249
+ let out = "";
1250
+ let index = 0;
1251
+ while (index < fragment.length) {
1252
+ const lead = percentByteAt(fragment, index);
1253
+ const size = lead ? sequenceLength(lead.byte) : 1;
1254
+ if (lead && size > 1) {
1255
+ let cursor = lead.next;
1256
+ const bytes = [lead.byte];
1257
+ let complete = true;
1258
+ for (let step = 1; step < size; step++) {
1259
+ const cont = percentByteAt(fragment, cursor);
1260
+ if (!cont || cont.byte < 128 || cont.byte > 191) {
1261
+ complete = false;
1262
+ break;
1263
+ }
1264
+ bytes.push(cont.byte);
1265
+ cursor = cont.next;
1202
1266
  }
1203
- });
1204
- };
1205
- }
1206
- function rehypeSafeAnchors() {
1207
- return (tree) => {
1208
- visit(tree, "element", (node) => {
1209
- const href = node.properties?.href;
1210
- if (typeof href !== "string" || !href.startsWith("#")) return;
1211
- try {
1212
- node.properties.href = `#${decodeURIComponent(href.slice(1))}`;
1213
- } catch {
1267
+ if (complete) {
1268
+ try {
1269
+ out += decodeURIComponent(fragment.slice(index, cursor));
1270
+ index = cursor;
1271
+ continue;
1272
+ } catch {
1273
+ }
1214
1274
  }
1215
- });
1216
- };
1275
+ }
1276
+ out += fragment[index];
1277
+ index += 1;
1278
+ }
1279
+ return out;
1280
+ }
1281
+ function restoreAnchors(node) {
1282
+ const href = node.properties?.href;
1283
+ if (typeof href !== "string" || !href.startsWith("#")) return;
1284
+ const fragment = href.slice(1);
1285
+ const restored = restoreMultibyte(fragment);
1286
+ if (restored !== fragment) node.properties.href = `#${restored}`;
1287
+ }
1288
+
1289
+ // src/rehype-source-positions.ts
1290
+ var BLOCK_TAGS = /* @__PURE__ */ new Set([
1291
+ "p",
1292
+ "h1",
1293
+ "h2",
1294
+ "h3",
1295
+ "h4",
1296
+ "h5",
1297
+ "h6",
1298
+ "ul",
1299
+ "ol",
1300
+ "li",
1301
+ "blockquote",
1302
+ "pre",
1303
+ "table",
1304
+ "figure",
1305
+ "hr"
1306
+ ]);
1307
+ function applySourcePosition(node) {
1308
+ const tag = node.tagName.toLowerCase();
1309
+ if (!BLOCK_TAGS.has(tag)) return;
1310
+ const start = node.position?.start.offset;
1311
+ if (typeof start !== "number") return;
1312
+ node.properties = node.properties ?? {};
1313
+ node.properties["data-src-start"] = String(start);
1217
1314
  }
1315
+
1316
+ // src/rehype-code-meta.ts
1218
1317
  function textOf(node) {
1219
1318
  let out = "";
1220
1319
  for (const child of node.children ?? []) {
@@ -1238,51 +1337,29 @@ function titleOf(code) {
1238
1337
  function isCodeElement(child) {
1239
1338
  return child.type === "element" && child.tagName === "code";
1240
1339
  }
1241
- function rehypeCodeMeta() {
1242
- return (tree) => {
1243
- visit(tree, "element", (node) => {
1244
- if (node.tagName !== "pre") return;
1245
- const code = (node.children ?? []).find(isCodeElement);
1246
- if (!code) return;
1247
- const title = titleOf(code);
1248
- node.properties = {
1249
- ...node.properties,
1250
- "data-code-raw": textOf(code),
1251
- "data-code-lang": langOf(code),
1252
- ...title ? { "data-code-title": title } : {}
1253
- };
1254
- });
1255
- return void 0;
1340
+ function applyCodeMeta(node) {
1341
+ if (node.tagName !== "pre") return;
1342
+ const code = (node.children ?? []).find(isCodeElement);
1343
+ if (!code) return;
1344
+ const title = titleOf(code);
1345
+ node.properties = {
1346
+ ...node.properties,
1347
+ "data-code-raw": textOf(code),
1348
+ "data-code-lang": langOf(code),
1349
+ ...title ? { "data-code-title": title } : {}
1256
1350
  };
1257
1351
  }
1258
- var BLOCK_TAGS = /* @__PURE__ */ new Set([
1259
- "p",
1260
- "h1",
1261
- "h2",
1262
- "h3",
1263
- "h4",
1264
- "h5",
1265
- "h6",
1266
- "ul",
1267
- "ol",
1268
- "li",
1269
- "blockquote",
1270
- "pre",
1271
- "table",
1272
- "figure",
1273
- "hr"
1274
- ]);
1275
- function rehypeSourcePositions() {
1352
+
1353
+ // src/rehype-postprocess.ts
1354
+ function rehypePostprocess(options) {
1355
+ const withPositions = options?.sourcePositions === true;
1276
1356
  return (tree) => {
1277
1357
  visit(tree, "element", (node) => {
1278
- const tag = node.tagName.toLowerCase();
1279
- if (!BLOCK_TAGS.has(tag)) return;
1280
- const start = node.position?.start.offset;
1281
- if (typeof start !== "number") return;
1282
- node.properties = node.properties ?? {};
1283
- node.properties["data-src-start"] = String(start);
1358
+ sanitizeUrlProps(node);
1359
+ restoreAnchors(node);
1360
+ if (withPositions) applySourcePosition(node);
1361
+ applyCodeMeta(node);
1284
1362
  });
1285
- return void 0;
1286
1363
  };
1287
1364
  }
1288
1365
  function jsxBlockToHast(state, node) {
@@ -1318,13 +1395,39 @@ function jsxBlockToHast(state, node) {
1318
1395
  };
1319
1396
  }
1320
1397
  function createProcessor(extraRemark, extraRehype, sourcePositions) {
1321
- 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);
1398
+ return unified().use(remarkParse).use(REMARK_PARSE_PLUGINS).use(REMARK_TRANSFORMS).use(extraRemark ?? []).use(remarkRehype, { handlers: { jsxBlock: jsxBlockToHast } }).use(rehypePostprocess, { sourcePositions: sourcePositions === true }).use(rehypeSlug).use(extraRehype ?? []).use(rehypeKatex);
1399
+ }
1400
+ var NO_PLUGINS = [];
1401
+ var baseProcessorCache = /* @__PURE__ */ new Map();
1402
+ var hostProcessorCache = /* @__PURE__ */ new WeakMap();
1403
+ function getProcessor(extraRemark, extraRehype, sourcePositions) {
1404
+ const remarkKey = extraRemark ?? NO_PLUGINS;
1405
+ const rehypeKey = extraRehype ?? NO_PLUGINS;
1406
+ const variant = sourcePositions ? "source-positions" : "default";
1407
+ if (remarkKey === NO_PLUGINS && rehypeKey === NO_PLUGINS) {
1408
+ const cached2 = baseProcessorCache.get(variant);
1409
+ if (cached2) return cached2;
1410
+ const created2 = createProcessor(void 0, void 0, sourcePositions);
1411
+ baseProcessorCache.set(variant, created2);
1412
+ return created2;
1413
+ }
1414
+ let byRehype = hostProcessorCache.get(remarkKey);
1415
+ if (!byRehype) {
1416
+ byRehype = /* @__PURE__ */ new WeakMap();
1417
+ hostProcessorCache.set(remarkKey, byRehype);
1418
+ }
1419
+ let byVariant = byRehype.get(rehypeKey);
1420
+ if (!byVariant) {
1421
+ byVariant = /* @__PURE__ */ new Map();
1422
+ byRehype.set(rehypeKey, byVariant);
1423
+ }
1424
+ const cached = byVariant.get(variant);
1425
+ if (cached) return cached;
1426
+ const created = createProcessor(extraRemark, extraRehype, sourcePositions);
1427
+ byVariant.set(variant, created);
1428
+ return created;
1322
1429
  }
1323
- function MarkdownRenderer({
1324
- content,
1325
- className,
1326
- config
1327
- }) {
1430
+ function useRenderPipeline(config) {
1328
1431
  const overrides = useShallowStable(config?.components);
1329
1432
  const extraRemark = useShallowStable(config?.remarkPlugins);
1330
1433
  const extraRehype = useShallowStable(config?.rehypePlugins);
@@ -1337,33 +1440,61 @@ function MarkdownRenderer({
1337
1440
  return { ...text, ...messages };
1338
1441
  }, [text, messages]);
1339
1442
  const processor = useMemo(
1340
- () => createProcessor(extraRemark, extraRehype, sourcePositions),
1443
+ () => getProcessor(extraRemark, extraRehype, sourcePositions),
1341
1444
  [extraRemark, extraRehype, sourcePositions]
1342
1445
  );
1343
- const rendered = useMemo(() => {
1344
- const source = content ?? "";
1345
- const mdast = processor.parse(source);
1346
- promoteBlockMath(mdast, source);
1347
- enforceMaxDepth(mdast, source);
1348
- collectMermaid(mdast);
1349
- const hast = processor.runSync(mdast);
1350
- return toJsxRuntime(hast, {
1351
- Fragment,
1352
- jsx,
1353
- jsxs,
1354
- components: { ...mdxComponents, ...overrides }
1355
- });
1356
- }, [content, overrides, processor]);
1446
+ return { overrides, processor, textPatch };
1447
+ }
1448
+ function hastToReact(hast, overrides) {
1449
+ return toJsxRuntime(hast, {
1450
+ Fragment,
1451
+ jsx,
1452
+ jsxs,
1453
+ components: { ...mdxComponents, ...overrides }
1454
+ });
1455
+ }
1456
+ function RenderShell({
1457
+ className,
1458
+ config,
1459
+ textPatch,
1460
+ children
1461
+ }) {
1357
1462
  return /* @__PURE__ */ jsx(
1358
1463
  MdEngineProvider,
1359
1464
  {
1360
1465
  locale: config?.locale,
1361
1466
  fallbackLocale: config?.fallbackLocale,
1362
1467
  messages: textPatch,
1363
- children: /* @__PURE__ */ jsx("div", { className, children: rendered })
1468
+ children: /* @__PURE__ */ jsx("div", { className, children })
1364
1469
  }
1365
1470
  );
1366
1471
  }
1472
+ function MarkdownRenderer({
1473
+ content,
1474
+ className,
1475
+ config
1476
+ }) {
1477
+ const { overrides, processor, textPatch } = useRenderPipeline(config);
1478
+ const rendered = useMemo(() => {
1479
+ const source = content ?? "";
1480
+ const mdast = processor.parse(source);
1481
+ applySourceTransforms(mdast, source);
1482
+ return hastToReact(processor.runSync(mdast), overrides);
1483
+ }, [content, overrides, processor]);
1484
+ return /* @__PURE__ */ jsx(RenderShell, { className, config, textPatch, children: rendered });
1485
+ }
1486
+ function MarkdownTreeRenderer({
1487
+ tree,
1488
+ className,
1489
+ config
1490
+ }) {
1491
+ const { overrides, processor, textPatch } = useRenderPipeline(config);
1492
+ const rendered = useMemo(
1493
+ () => hastToReact(processor.runSync(tree), overrides),
1494
+ [tree, overrides, processor]
1495
+ );
1496
+ return /* @__PURE__ */ jsx(RenderShell, { className, config, textPatch, children: rendered });
1497
+ }
1367
1498
 
1368
1499
  // src/internal/diagnostics.ts
1369
1500
  var KEY_BY_CODE = {
@@ -1389,6 +1520,4 @@ function formatDiagnostic(t, diagnostic) {
1389
1520
  return rendered || diagnostic.message;
1390
1521
  }
1391
1522
 
1392
- export { COMPONENTS, ITEMS, MAX_CONTAINER_DEPTH, MERMAID_MAX_BYTES, MarkdownRenderer, diagnosticTextKey, extractBlocks, formatDiagnostic, getComponent, getItemSpec, isContainerWithItems, jsxBlocks, jsxFromMarkdown, jsxToMarkdown, listComponents, normalizeMarkdown, parse, parseOpenTag, remarkJsxBlocks, sliceRawBody };
1393
- //# sourceMappingURL=chunk-RJZKMZOI.js.map
1394
- //# sourceMappingURL=chunk-RJZKMZOI.js.map
1523
+ export { COMPONENTS, ITEMS, MAX_CONTAINER_DEPTH, MERMAID_MAX_BYTES, MarkdownRenderer, MarkdownTreeRenderer, diagnose, diagnosticTextKey, extractBlocks, formatDiagnostic, getComponent, getItemSpec, isContainerWithItems, jsxBlocks, jsxFromMarkdown, jsxToMarkdown, listComponents, parse, parseOpenTag, remarkJsxBlocks, sliceRawBody };