1. Y-Log 上报 optDetail 前缀 B1-CM助手 → CM助手-全量(全量替换 44 个前端文件 + 文档) 2. 知识库入库 nodeName 改为只取 md5(标题).md(去掉时间戳),同一篇 md 每次入库一致,避免重复记录 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
506 lines
14 KiB
TypeScript
506 lines
14 KiB
TypeScript
/**
|
||
* Convert markdown text to a Word (.docx) Blob in the browser.
|
||
*
|
||
* Designed for scheduled-task reports that often contain Chinese text,
|
||
* markdown tables, and emojis. Compared to Word's stock heading styles we
|
||
* deliberately:
|
||
* - Force every run color to pure black (`#000000`) so headings, links,
|
||
* and inline code never render as Word's default blue / hyperlink theme.
|
||
* - Render markdown tables as real OOXML tables (full-width, auto-wrapping)
|
||
* instead of falling back to plain text rows that overflow the page.
|
||
* - Strip variation selectors, zero-width joiners, and other invisible
|
||
* characters that often break Word renderers when emojis leak into the
|
||
* report.
|
||
*
|
||
* Block grammar handled line-by-line:
|
||
* - ATX heading: `^(#{1,6})\s+(.*)$`
|
||
* - Fenced code: lines between ``` ``` are emitted verbatim in a mono font
|
||
* - Blockquote: `^>\s?(.*)$`
|
||
* - Ordered list: `^\s*(\d+)\.\s+(.*)$`
|
||
* - Unordered list: `^\s*[-*+]\s+(.*)$`
|
||
* - Horizontal rule: `^(---|\*\*\*|___)\s*$`
|
||
* - Pipe table: contiguous lines starting with `|` plus a separator row
|
||
* - Blank line: paragraph break
|
||
* - Anything else: paragraph (with inline formatting)
|
||
*
|
||
* Inline grammar handled:
|
||
* `code`, **bold**, __bold__, *italic*, _italic_, [text](url)
|
||
*/
|
||
|
||
import {
|
||
AlignmentType,
|
||
BorderStyle,
|
||
Document,
|
||
HeadingLevel,
|
||
Packer,
|
||
Paragraph,
|
||
Table,
|
||
TableCell,
|
||
TableRow,
|
||
TextRun,
|
||
WidthType,
|
||
type IRunOptions,
|
||
} from "docx";
|
||
|
||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||
|
||
const BLACK = "000000";
|
||
const BODY_FONT = { ascii: "Calibri", eastAsia: "Microsoft YaHei" };
|
||
const MONO_FONT = { ascii: "Consolas", eastAsia: "Microsoft YaHei" };
|
||
|
||
const HEADING_SIZES_HALF_PT: Record<number, number> = {
|
||
// Word "size" property is half-points. 32 = 16pt.
|
||
1: 36,
|
||
2: 32,
|
||
3: 28,
|
||
4: 26,
|
||
5: 24,
|
||
6: 22,
|
||
};
|
||
|
||
const BODY_SIZE_HALF_PT = 22; // 11pt
|
||
|
||
type InlineSegment = {
|
||
text: string;
|
||
bold?: boolean;
|
||
italic?: boolean;
|
||
code?: boolean;
|
||
};
|
||
|
||
/**
|
||
* Drop characters that Word renders inconsistently or that frequently smuggle
|
||
* emoji glitches into corporate reports.
|
||
*
|
||
* Removes:
|
||
* - Variation selectors (FE00–FE0F, E0100–E01EF)
|
||
* - Zero-width joiner / non-joiner / space (200C, 200D, FEFF, 200B)
|
||
* - Soft hyphen (00AD)
|
||
* - Object replacement character (FFFC)
|
||
*/
|
||
function sanitizeText(text: string): string {
|
||
return text
|
||
.replace(/[︀-️]/g, "")
|
||
.replace(/[-]/g, "")
|
||
.replace(//g, "")
|
||
.replace(//g, "")
|
||
.replace(/[\u{E0100}-\u{E01EF}]/gu, "");
|
||
}
|
||
|
||
/**
|
||
* Tokenise a single line of markdown into formatted segments.
|
||
*
|
||
* Recognised inline syntax:
|
||
* `code`, **bold**, __bold__, *italic*, _italic_, [text](url)
|
||
* Markdown links are flattened to their text content — we deliberately do not
|
||
* emit hyperlink runs because they pick up Word's blue theme color.
|
||
*/
|
||
function parseInlineSegments(text: string): InlineSegment[] {
|
||
const cleaned = sanitizeText(text);
|
||
// Strip markdown link syntax first so the regex below doesn't trip on `[...]`.
|
||
const withoutLinks = cleaned.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1");
|
||
|
||
const tokens: InlineSegment[] = [];
|
||
const pattern =
|
||
/(`+)([^`]+)\1|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|_([^_]+)_/g;
|
||
let cursor = 0;
|
||
let match: RegExpExecArray | null;
|
||
while ((match = pattern.exec(withoutLinks)) !== null) {
|
||
if (match.index > cursor) {
|
||
tokens.push({ text: withoutLinks.slice(cursor, match.index) });
|
||
}
|
||
if (match[2] !== undefined) tokens.push({ text: match[2], code: true });
|
||
else if (match[3] !== undefined) tokens.push({ text: match[3], bold: true });
|
||
else if (match[4] !== undefined) tokens.push({ text: match[4], bold: true });
|
||
else if (match[5] !== undefined)
|
||
tokens.push({ text: match[5], italic: true });
|
||
else if (match[6] !== undefined)
|
||
tokens.push({ text: match[6], italic: true });
|
||
cursor = pattern.lastIndex;
|
||
}
|
||
if (cursor < withoutLinks.length) {
|
||
tokens.push({ text: withoutLinks.slice(cursor) });
|
||
}
|
||
return tokens.length > 0 ? tokens : [{ text: withoutLinks }];
|
||
}
|
||
|
||
function segmentsToRuns(
|
||
segments: InlineSegment[],
|
||
extra?: Partial<IRunOptions>,
|
||
): TextRun[] {
|
||
return segments.map((seg) => {
|
||
const opts: IRunOptions = {
|
||
text: seg.text,
|
||
bold: seg.bold,
|
||
italics: seg.italic,
|
||
color: BLACK,
|
||
font: seg.code ? MONO_FONT : BODY_FONT,
|
||
size: extra?.size ?? BODY_SIZE_HALF_PT,
|
||
...extra,
|
||
};
|
||
return new TextRun(opts);
|
||
});
|
||
}
|
||
|
||
function makeParagraphFromInline(text: string): Paragraph {
|
||
return new Paragraph({
|
||
spacing: { after: 120 },
|
||
children: segmentsToRuns(parseInlineSegments(text)),
|
||
});
|
||
}
|
||
|
||
function makeHeadingParagraph(level: number, text: string): Paragraph {
|
||
const clamped = Math.max(1, Math.min(level, 6));
|
||
return new Paragraph({
|
||
// We attach a heading level so the table-of-contents still works, but the
|
||
// run-level color / font / size below override Word's blue theme.
|
||
heading:
|
||
({
|
||
1: HeadingLevel.HEADING_1,
|
||
2: HeadingLevel.HEADING_2,
|
||
3: HeadingLevel.HEADING_3,
|
||
4: HeadingLevel.HEADING_4,
|
||
5: HeadingLevel.HEADING_5,
|
||
6: HeadingLevel.HEADING_6,
|
||
}[clamped] as (typeof HeadingLevel)[keyof typeof HeadingLevel]) ?? undefined,
|
||
spacing: { before: 200, after: 120 },
|
||
children: segmentsToRuns(parseInlineSegments(text), {
|
||
bold: true,
|
||
color: BLACK,
|
||
size: HEADING_SIZES_HALF_PT[clamped] ?? BODY_SIZE_HALF_PT,
|
||
}),
|
||
});
|
||
}
|
||
|
||
function makeListItem(
|
||
text: string,
|
||
ordered: boolean,
|
||
level: number,
|
||
): Paragraph {
|
||
return new Paragraph({
|
||
spacing: { after: 80 },
|
||
children: segmentsToRuns(parseInlineSegments(text)),
|
||
numbering: ordered
|
||
? { reference: "ordered-list", level: Math.min(level, 8) }
|
||
: undefined,
|
||
bullet: ordered ? undefined : { level: Math.min(level, 8) },
|
||
});
|
||
}
|
||
|
||
function makeCodeParagraph(line: string): Paragraph {
|
||
return new Paragraph({
|
||
spacing: { after: 0 },
|
||
children: [
|
||
new TextRun({
|
||
text: sanitizeText(line) || " ",
|
||
font: MONO_FONT,
|
||
color: BLACK,
|
||
size: BODY_SIZE_HALF_PT,
|
||
}),
|
||
],
|
||
});
|
||
}
|
||
|
||
function makeQuoteParagraph(text: string): Paragraph {
|
||
return new Paragraph({
|
||
indent: { left: 720 },
|
||
spacing: { after: 120 },
|
||
children: segmentsToRuns(parseInlineSegments(text), { italics: true }),
|
||
});
|
||
}
|
||
|
||
function makeHorizontalRule(): Paragraph {
|
||
return new Paragraph({
|
||
alignment: AlignmentType.CENTER,
|
||
spacing: { before: 120, after: 120 },
|
||
children: [
|
||
new TextRun({
|
||
text: "────────",
|
||
color: BLACK,
|
||
font: BODY_FONT,
|
||
size: BODY_SIZE_HALF_PT,
|
||
}),
|
||
],
|
||
});
|
||
}
|
||
|
||
const CELL_BORDER = {
|
||
style: BorderStyle.SINGLE,
|
||
size: 4,
|
||
color: "BFBFBF",
|
||
};
|
||
|
||
function makeTableCell(
|
||
text: string,
|
||
options: { header?: boolean } = {},
|
||
): TableCell {
|
||
const segments = parseInlineSegments(text);
|
||
return new TableCell({
|
||
margins: { top: 80, bottom: 80, left: 100, right: 100 },
|
||
children: [
|
||
new Paragraph({
|
||
spacing: { after: 0 },
|
||
children: segmentsToRuns(segments, {
|
||
bold: options.header || undefined,
|
||
size: BODY_SIZE_HALF_PT,
|
||
}),
|
||
}),
|
||
],
|
||
});
|
||
}
|
||
|
||
function splitTableRow(line: string): string[] {
|
||
// Strip leading/trailing pipe and any escaped pipes (rare in agent output).
|
||
const trimmed = line.replace(/^\s*\|/, "").replace(/\|\s*$/, "");
|
||
return trimmed.split("|").map((cell) => cell.trim());
|
||
}
|
||
|
||
function buildTable(headerLine: string, bodyLines: string[]): Table {
|
||
const headerCells = splitTableRow(headerLine);
|
||
const colCount = headerCells.length;
|
||
const rows: TableRow[] = [];
|
||
rows.push(
|
||
new TableRow({
|
||
tableHeader: true,
|
||
children: headerCells.map((cell) =>
|
||
makeTableCell(cell, { header: true }),
|
||
),
|
||
}),
|
||
);
|
||
for (const row of bodyLines) {
|
||
const cells = splitTableRow(row);
|
||
// Pad/truncate to match the header column count so Word renders evenly.
|
||
const normalized = Array.from(
|
||
{ length: colCount },
|
||
(_, i) => cells[i] ?? "",
|
||
);
|
||
rows.push(
|
||
new TableRow({
|
||
children: normalized.map((c) => makeTableCell(c)),
|
||
}),
|
||
);
|
||
}
|
||
return new Table({
|
||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||
rows,
|
||
borders: {
|
||
top: CELL_BORDER,
|
||
bottom: CELL_BORDER,
|
||
left: CELL_BORDER,
|
||
right: CELL_BORDER,
|
||
insideHorizontal: CELL_BORDER,
|
||
insideVertical: CELL_BORDER,
|
||
},
|
||
});
|
||
}
|
||
|
||
function isTableSeparator(line: string): boolean {
|
||
// e.g. |---|:---:|---:| with optional spaces
|
||
return /^\s*\|?(\s*:?-{3,}:?\s*\|)+\s*:?-{3,}:?\s*\|?\s*$/.test(line);
|
||
}
|
||
|
||
function looksLikeTableRow(line: string): boolean {
|
||
return /^\s*\|.*\|\s*$/.test(line) || /^\s*\|.+/.test(line);
|
||
}
|
||
|
||
/**
|
||
* Convert markdown text into an array of docx block elements (Paragraph | Table).
|
||
*/
|
||
function markdownToBlocks(markdown: string): Array<Paragraph | Table> {
|
||
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
|
||
const blocks: Array<Paragraph | Table> = [];
|
||
|
||
let inFence = false;
|
||
let paragraphBuffer: string[] = [];
|
||
|
||
const flushParagraph = () => {
|
||
if (paragraphBuffer.length === 0) return;
|
||
blocks.push(makeParagraphFromInline(paragraphBuffer.join(" ")));
|
||
paragraphBuffer = [];
|
||
};
|
||
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const rawLine = lines[i] ?? "";
|
||
const line = rawLine.replace(/\t/g, " ");
|
||
|
||
if (line.trim().startsWith("```")) {
|
||
flushParagraph();
|
||
inFence = !inFence;
|
||
continue;
|
||
}
|
||
if (inFence) {
|
||
blocks.push(makeCodeParagraph(line));
|
||
continue;
|
||
}
|
||
|
||
if (!line.trim()) {
|
||
flushParagraph();
|
||
continue;
|
||
}
|
||
|
||
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
||
if (heading) {
|
||
flushParagraph();
|
||
blocks.push(
|
||
makeHeadingParagraph(heading[1]!.length, heading[2]!.trim()),
|
||
);
|
||
continue;
|
||
}
|
||
|
||
if (/^(?:---|\*\*\*|___)\s*$/.test(line)) {
|
||
flushParagraph();
|
||
blocks.push(makeHorizontalRule());
|
||
continue;
|
||
}
|
||
|
||
const blockquote = /^>\s?(.*)$/.exec(line);
|
||
if (blockquote) {
|
||
flushParagraph();
|
||
blocks.push(makeQuoteParagraph(blockquote[1] ?? ""));
|
||
continue;
|
||
}
|
||
|
||
// Table detection — a header row followed by a separator row.
|
||
if (
|
||
looksLikeTableRow(line) &&
|
||
i + 1 < lines.length &&
|
||
isTableSeparator(lines[i + 1] ?? "")
|
||
) {
|
||
flushParagraph();
|
||
const headerLine = line;
|
||
i += 2; // skip header + separator
|
||
const body: string[] = [];
|
||
while (i < lines.length && looksLikeTableRow(lines[i] ?? "")) {
|
||
body.push(lines[i] ?? "");
|
||
i++;
|
||
}
|
||
// Re-step back one so the outer loop's i++ lands on the next unprocessed
|
||
// line. Without this, blank lines after the table get swallowed.
|
||
i--;
|
||
blocks.push(buildTable(headerLine, body));
|
||
// Word's table rendering eats following spacing; inject a tiny gap.
|
||
blocks.push(
|
||
new Paragraph({ spacing: { after: 0 }, children: [new TextRun("")] }),
|
||
);
|
||
continue;
|
||
}
|
||
|
||
const orderedItem = /^(\s*)(\d+)\.\s+(.*)$/.exec(line);
|
||
if (orderedItem) {
|
||
flushParagraph();
|
||
const indent = Math.floor(orderedItem[1]!.length / 2);
|
||
blocks.push(makeListItem(orderedItem[3]!, true, indent));
|
||
continue;
|
||
}
|
||
|
||
const unorderedItem = /^(\s*)[-*+]\s+(.*)$/.exec(line);
|
||
if (unorderedItem) {
|
||
flushParagraph();
|
||
const indent = Math.floor(unorderedItem[1]!.length / 2);
|
||
blocks.push(makeListItem(unorderedItem[2]!, false, indent));
|
||
continue;
|
||
}
|
||
|
||
paragraphBuffer.push(line.trim());
|
||
}
|
||
|
||
flushParagraph();
|
||
return blocks;
|
||
}
|
||
|
||
/**
|
||
* Convert a markdown string into a .docx Blob suitable for download.
|
||
*/
|
||
export async function markdownToDocxBlob(
|
||
markdown: string,
|
||
title?: string,
|
||
): Promise<Blob> {
|
||
const children: Array<Paragraph | Table> = [];
|
||
if (title?.trim()) {
|
||
children.push(
|
||
new Paragraph({
|
||
spacing: { before: 0, after: 240 },
|
||
children: [
|
||
new TextRun({
|
||
text: sanitizeText(title.trim()),
|
||
bold: true,
|
||
color: BLACK,
|
||
font: BODY_FONT,
|
||
size: 40, // 20pt
|
||
}),
|
||
],
|
||
}),
|
||
);
|
||
}
|
||
children.push(...markdownToBlocks(markdown));
|
||
|
||
const doc = new Document({
|
||
styles: {
|
||
default: {
|
||
document: {
|
||
run: {
|
||
color: BLACK,
|
||
font: BODY_FONT,
|
||
size: BODY_SIZE_HALF_PT,
|
||
},
|
||
},
|
||
},
|
||
},
|
||
numbering: {
|
||
config: [
|
||
{
|
||
reference: "ordered-list",
|
||
levels: [
|
||
{
|
||
level: 0,
|
||
format: "decimal",
|
||
text: "%1.",
|
||
alignment: AlignmentType.START,
|
||
},
|
||
{
|
||
level: 1,
|
||
format: "decimal",
|
||
text: "%2.",
|
||
alignment: AlignmentType.START,
|
||
},
|
||
{
|
||
level: 2,
|
||
format: "decimal",
|
||
text: "%3.",
|
||
alignment: AlignmentType.START,
|
||
},
|
||
],
|
||
},
|
||
],
|
||
},
|
||
sections: [{ children }],
|
||
});
|
||
return Packer.toBlob(doc);
|
||
}
|
||
|
||
/**
|
||
* Trigger a browser download of the markdown source converted to .docx.
|
||
*/
|
||
export async function downloadMarkdownAsDocx(
|
||
markdown: string,
|
||
fileName: string,
|
||
title?: string,
|
||
): Promise<void> {
|
||
const blob = await markdownToDocxBlob(markdown, title);
|
||
writeYLog({
|
||
optType: OptType.export,
|
||
optDetail: "CM助手-全量-定时任务-导出",
|
||
url: "/scheduled-tasks/export/docx",
|
||
reqParam: { fileName, title },
|
||
});
|
||
const safeName = fileName.replace(/\.(md|markdown)$/i, "") || "document";
|
||
const url = URL.createObjectURL(blob);
|
||
const anchor = document.createElement("a");
|
||
anchor.href = url;
|
||
anchor.download = `${safeName}.docx`;
|
||
anchor.rel = "noopener";
|
||
document.body.appendChild(anchor);
|
||
anchor.click();
|
||
anchor.remove();
|
||
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||
}
|