import { marked, Renderer } from 'marked';
import type { Tokens } from 'marked';
import katex from 'katex';
import DOMPurify from 'dompurify';
const mdRenderer = new Renderer();
const defaultLinkRenderer = mdRenderer.link.bind(mdRenderer);
mdRenderer.link = (token: Tokens.Link): string => {
const html = defaultLinkRenderer(token);
return html.replace(/^ {
// 匹配块级公式($$...$$)
html = html.replace(/\$\$(.*?)\$\$/gs, (_match, formula) => {
return katex.renderToString(formula.trim(), {
displayMode: true,
throwOnError: false,
strict: false,
trust: true,
});
});
// 匹配行内公式($...$)
html = html.replace(/\$(.*?)\$/g, (_match, formula) => {
return katex.renderToString(formula.trim(), {
displayMode: false,
throwOnError: false,
strict: false,
});
});
return html;
};
const processFootnotes = (html: string, maxId?: number): string => {
if (maxId === undefined) {
// 无 citations 上下文,剥离所有 [^n] 标记
return html.replace(/\[\^\d+\]/g, '');
}
// 有效编号范围 [1, maxId],范围外的剥离
return html.replace(/\[\^(\d+)\]/g, (_match, n) => {
const id = parseInt(n, 10);
if (id >= 1 && id <= maxId) {
return ``;
}
return '';
});
};
export const renderMarkdown = (
text: string,
icons?: { copy: string; download: string; preview: string; copySuccess: string },
maxCitationId?: number
): string => {
if (!text) return '';
const processed = text.replace(/
/gi, ' \n');
let html = marked.parse(processed, { renderer: mdRenderer }) as string;
html = processFootnotes(html, maxCitationId);
html = renderLatexInHtml(html);
// Sanitize HTML to prevent XSS attacks
html = DOMPurify.sanitize(html, {
ADD_TAGS: ['img'],
ADD_ATTR: ['target', 'data-action', 'data-table', 'data-icon', 'data-icon-success', 'data-n'],
});
// 原始 HTML 锚点不经过 marked link renderer,统一补 target/rel
html = html.replace(/]*>/gi, (tag) => {
let attrs = '';
if (!/\btarget\s*=/i.test(tag)) attrs += ' target="_blank"';
if (!/\brel\s*=/i.test(tag)) attrs += ' rel="noopener"';
return attrs ? tag.replace(/^ {
return html.replace(/
([\s\S]*?)<\/table>/g, (match) => {
const encodedTable = encodeURIComponent(match);
return ``;
});
};
export const tableHtmlToMarkdown = (tableHtml: string): string => {
const parser = new DOMParser();
const doc = parser.parseFromString(tableHtml, 'text/html');
const table = doc.querySelector('table');
if (!table) return tableHtml;
const rows: string[][] = [];
table.querySelectorAll('tr').forEach((tr) => {
const cells: string[] = [];
tr.querySelectorAll('th, td').forEach((cell) => {
cells.push(cell.textContent?.trim() || '');
});
rows.push(cells);
});
if (rows.length === 0) return tableHtml;
const colCount = Math.max(...rows.map((r) => r.length));
const normalized = rows.map((r) => {
while (r.length < colCount) r.push('');
return r;
});
const lines: string[] = [];
lines.push('| ' + normalized[0].join(' | ') + ' |');
lines.push('| ' + normalized[0].map(() => '---').join(' | ') + ' |');
for (let i = 1; i < normalized.length; i++) {
lines.push('| ' + normalized[i].join(' | ') + ' |');
}
return lines.join('\n');
};
export const tableHtmlToCsv = (tableHtml: string): string => {
const parser = new DOMParser();
const doc = parser.parseFromString(tableHtml, 'text/html');
const table = doc.querySelector('table');
if (!table) return '';
const rows: string[] = [];
table.querySelectorAll('tr').forEach((tr) => {
const cells: string[] = [];
tr.querySelectorAll('th, td').forEach((cell) => {
const text = (cell.textContent?.trim() || '').replace(/"/g, '""');
cells.push(`"${text}"`);
});
rows.push(cells.join(','));
});
return '' + rows.join('\n');
};
export const formatFileSize = (bytes: number): string => {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
};
export const isImageFile = (filename: string): boolean => /\.(jpg|jpeg|png|gif|bmp|webp|svg|ico|tiff|tif)$/i.test(filename);
export const isPdfFile = (filename: string): boolean => /\.pdf$/i.test(filename);
export const isVideoFile = (filename: string): boolean => /\.(mp4|webm|ogg|mov|avi|mkv|flv|wmv|m4v)$/i.test(filename);
export const isAudioFile = (filename: string): boolean => /\.(mp3|wav|ogg|aac|flac|wma|m4a|opus)$/i.test(filename);
export const isMdFile = (filename: string): boolean => /\.md$/i.test(filename);
export const isWordFile = (filename: string): boolean => /\.(doc|docx)$/i.test(filename);
export const isOldDocFile = (filename: string): boolean => /\.doc$/i.test(filename) && !/\.docx$/i.test(filename);
export const isExcelFile = (filename: string): boolean => /\.(xls|xlsx)$/i.test(filename);
export const isCsvFile = (filename: string): boolean => /\.csv$/i.test(filename);
export const isTextFile = (filename: string): boolean =>
/\.(txt|md|json|csv|xml|yaml|yml|log|ini|toml|cfg|conf|env|gitignore|dockerignore|editorconfig|prettierrc|eslintrc|babelrc|properties|sh|bat|ps1|cmd|bash|zsh|fish|sql|graphql|proto|js|ts|jsx|tsx|vue|css|scss|sass|less|html|htm|svelte|py|java|kt|kts|c|cpp|h|hpp|cc|cxx|cs|go|rs|rb|php|swift|m|mm|r|R|lua|pl|pm|hs|ex|exs|erl|clj|scala|dart|zig|nim|v|sol|tf|hcl|gradle|cmake|makefile|mk)$/i.test(
filename
);
export const getFileExtension = (filename: string): string => {
const match = filename.match(/\.([^.]+)$/);
return match ? `.${match[1]}`.toUpperCase() : '';
};