import { Injectable } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; import { marked } from 'marked'; /** * Markdown → SafeHtml 渲染器。 * * 用于把 LLM 返回的 markdown 文本转成可绑定到 [innerHTML] 的安全 HTML。 * 内容来源是受信任的后端代理(fmode LLM 网关),未引入 DOMPurify 以减小包体; * 若未来接入用户提供的 markdown,建议补一道 DOMPurify。 */ @Injectable({ providedIn: 'root' }) export class MarkdownService { constructor(private sanitizer: DomSanitizer) { marked.setOptions({ gfm: true, breaks: true, // 单换行视为
,更贴近聊天显示 }); } /** 渲染完整 markdown,绑定到 [innerHTML]。流式过程也可调用(marked 容忍不完整 markdown)。 */ render(text: string): SafeHtml { const html = marked.parse(text || '', { async: false }) as string; return this.sanitizer.bypassSecurityTrustHtml(html); } }