katex-render.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/env node
  2. /**
  3. * KaTeX 服务端渲染脚本
  4. * 用法: echo "HTML内容" | node katex-render.js
  5. * 或: node katex-render.js < input.html > output.html
  6. *
  7. * 将 HTML 中的 LaTeX 公式渲染为 KaTeX HTML
  8. */
  9. import { createRequire } from 'module';
  10. const require = createRequire(import.meta.url);
  11. // 尝试多个路径加载 KaTeX
  12. let katex;
  13. const possiblePaths = [
  14. '/usr/local/lib/node_modules/katex', // npm -g 全局安装路径
  15. '/usr/lib/node_modules/katex', // Alpine 系统路径
  16. 'katex', // 本地 node_modules
  17. ];
  18. let loadError = null;
  19. for (const modulePath of possiblePaths) {
  20. try {
  21. katex = require(modulePath);
  22. break;
  23. } catch (e) {
  24. loadError = e;
  25. }
  26. }
  27. if (!katex) {
  28. console.error('Error: KaTeX module not found.');
  29. console.error('Tried paths:', possiblePaths.join(', '));
  30. if (loadError) console.error('Last error:', loadError.message);
  31. process.exit(1);
  32. }
  33. // 读取标准输入
  34. let input = '';
  35. process.stdin.setEncoding('utf8');
  36. process.stdin.on('readable', () => {
  37. let chunk;
  38. while ((chunk = process.stdin.read()) !== null) {
  39. input += chunk;
  40. }
  41. });
  42. process.stdin.on('end', () => {
  43. try {
  44. const output = renderMathInHtml(input);
  45. process.stdout.write(output);
  46. } catch (error) {
  47. console.error('KaTeX render error:', error.message);
  48. process.exit(1);
  49. }
  50. });
  51. /**
  52. * 解码 HTML 实体
  53. */
  54. function decodeHtmlEntities(text) {
  55. return text
  56. .replace(/&lt;/g, '<')
  57. .replace(/&gt;/g, '>')
  58. .replace(/&amp;/g, '&')
  59. .replace(/&quot;/g, '"')
  60. .replace(/&#39;/g, "'")
  61. .replace(/&nbsp;/g, ' ');
  62. }
  63. /**
  64. * 编码 HTML 实体(用于安全输出)
  65. */
  66. function encodeHtmlEntities(text) {
  67. return text
  68. .replace(/&/g, '&amp;')
  69. .replace(/</g, '&lt;')
  70. .replace(/>/g, '&gt;');
  71. }
  72. /**
  73. * 渲染 HTML 中的所有数学公式
  74. */
  75. function renderMathInHtml(html) {
  76. // 定界符配置(按优先级排序)
  77. const delimiters = [
  78. { left: '$$', right: '$$', display: true },
  79. { left: '\\[', right: '\\]', display: true },
  80. { left: '\\(', right: '\\)', display: false },
  81. { left: '$', right: '$', display: false },
  82. ];
  83. let result = html;
  84. // 按顺序处理每种定界符
  85. for (const delimiter of delimiters) {
  86. result = processDelimiter(result, delimiter.left, delimiter.right, delimiter.display);
  87. }
  88. return result;
  89. }
  90. /**
  91. * 处理特定定界符的公式
  92. */
  93. function processDelimiter(html, left, right, displayMode) {
  94. // 转义正则特殊字符
  95. const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  96. const leftEscaped = escapeRegex(left);
  97. const rightEscaped = escapeRegex(right);
  98. // 构建正则表达式
  99. // 【关键修复】排除包含 HTML 标签的内容(不匹配 < 或 >)
  100. let pattern;
  101. if (left === '$' && right === '$') {
  102. // 单个 $...$:不匹配 $$,不匹配包含 < > 的内容
  103. pattern = new RegExp(`(?<!\\$)\\$(?!\\$)([^$<>]+?)(?<!\\$)\\$(?!\\$)`, 'g');
  104. } else if (left === '$$' && right === '$$') {
  105. // $$...$$:不匹配包含 < > 的内容
  106. pattern = new RegExp(`\\$\\$([^<>]*?)\\$\\$`, 'g');
  107. } else {
  108. // \(...\) 和 \[...\]:不匹配包含 < > 的内容
  109. pattern = new RegExp(`${leftEscaped}([^<>]*?)${rightEscaped}`, 'g');
  110. }
  111. return html.replace(pattern, (match, latex) => {
  112. try {
  113. // 清理 LaTeX 内容 - 先解码 HTML 实体
  114. let cleanLatex = decodeHtmlEntities(latex.trim());
  115. // 跳过空内容
  116. if (!cleanLatex) {
  117. return match;
  118. }
  119. // 【安全检查】如果内容看起来不像 LaTeX,跳过
  120. // 跳过只有普通文本的内容(没有任何 LaTeX 特征)
  121. if (!/[\\^_{}]/.test(cleanLatex) && !/[a-zA-Z]{2,}/.test(cleanLatex)) {
  122. // 可能只是普通数字或单字母,检查是否有意义
  123. if (/^[\d\s\.\,\-\+]+$/.test(cleanLatex)) {
  124. return match; // 纯数字,不渲染
  125. }
  126. }
  127. // 渲染 KaTeX
  128. const rendered = katex.renderToString(cleanLatex, {
  129. displayMode: displayMode,
  130. throwOnError: false,
  131. strict: false,
  132. trust: true,
  133. output: 'html',
  134. });
  135. return rendered;
  136. } catch (error) {
  137. // 渲染失败时保留原始内容
  138. // console.error(`KaTeX error for "${latex.substring(0, 50)}...":`, error.message);
  139. return match;
  140. }
  141. });
  142. }