import { buildDocxEditSurface } from "./docxTrackedChanges"; export interface DocxComment { id: string; author: string; date: string; text: string; parent_word_comment_id: string | null; done: boolean | null; paragraph_id: string; native_para_id: string | null; stable_id: string | null; anchor_text: string; comment_para_id: string | null; } type CommentExMeta = { parentParaId: string | null; done: boolean | null; }; function toArray(value: T | T[] | undefined | null): T[] { if (value == null) return []; return Array.isArray(value) ? value : [value]; } function cleanString(value: unknown): string | null { if (value == null) return null; const str = String(value).trim(); return str.length > 0 ? str : null; } function parseDone(value: unknown): boolean | null { if (value == null) return null; const normalized = String(value).toLowerCase(); if (normalized === "1" || normalized === "true") return true; if (normalized === "0" || normalized === "false") return false; return null; } function readTextFromCommentParagraphs(comment: any): string { let text = ""; const paragraphs = comment["w:p"]; for (const p of toArray(paragraphs)) { const runs = p["w:r"]; for (const r of toArray(runs)) { const t = r["w:t"]; if (typeof t === "string") text += t; else if (t?.["#text"]) text += t["#text"]; else if (Array.isArray(t)) { for (const part of t) { if (typeof part === "string") text += part; else if (part?.["#text"]) text += part["#text"]; } } } } return text.trim(); } function firstCommentParagraphId(comment: any): string | null { const paragraphs = toArray(comment["w:p"]); for (const p of paragraphs) { const paraId = cleanString(p?.["@_w14:paraId"]) ?? cleanString(p?.["@_w15:paraId"]) ?? cleanString(p?.["@_w:paraId"]); if (paraId) return paraId; } return null; } function findAll(node: any, tagName: string): any[] { const results: any[] = []; if (!node || typeof node !== "object") return results; if (Array.isArray(node)) { for (const item of node) results.push(...findAll(item, tagName)); return results; } if (node[tagName]) { const items = Array.isArray(node[tagName]) ? node[tagName] : [node[tagName]]; results.push(...items); } for (const [key, val] of Object.entries(node)) { if (key.startsWith("@_") || key === "#text") continue; results.push(...findAll(val, tagName)); } return results; } async function extractCommentsExtendedMeta(zip: any, parser: any): Promise> { const entry = zip.file("word/commentsExtended.xml") ?? zip.file("word\\commentsExtended.xml"); const metaByCommentParaId = new Map(); if (!entry) return metaByCommentParaId; const xml = await entry.async("text"); const parsed = parser.parse(xml); const commentExNodes = findAll(parsed, "w15:commentEx"); for (const node of commentExNodes) { const paraId = cleanString(node["@_w15:paraId"]) ?? cleanString(node["@_w14:paraId"]) ?? cleanString(node["@_paraId"]); if (!paraId) continue; const parentParaId = cleanString(node["@_w15:parentId"]) ?? cleanString(node["@_w15:paraIdParent"]) ?? cleanString(node["@_parentId"]) ?? null; const done = parseDone(node["@_w15:done"] ?? node["@_done"]); metaByCommentParaId.set(paraId, { parentParaId, done }); } return metaByCommentParaId; } export async function extractDocxComments(buf: Buffer): Promise { const JSZip = (await import("jszip")).default; const { XMLParser } = await import("fast-xml-parser"); const zip = await JSZip.loadAsync(buf); const commentsEntry = zip.file("word/comments.xml") ?? zip.file("word\\comments.xml"); if (!commentsEntry) return []; const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@_", trimValues: false, isArray: (name) => [ "w:comment", "w:p", "w:r", "w:t", "w:commentRangeStart", "w:commentRangeEnd", "w15:commentEx", ].includes(name), }); const commentsExtendedMeta = await extractCommentsExtendedMeta(zip, parser); const commentsXml = await commentsEntry.async("text"); const commentsParsed = parser.parse(commentsXml); const rawComments = commentsParsed?.["w:comments"]?.["w:comment"]; if (!rawComments) return []; const comments: Array<{ id: string; author: string; date: string; text: string; comment_para_id: string | null; }> = []; for (const c of toArray(rawComments)) { const id = String(c["@_w:id"] ?? ""); const author = String(c["@_w:author"] ?? ""); const date = String(c["@_w:date"] ?? ""); const text = readTextFromCommentParagraphs(c); const commentParaId = firstCommentParagraphId(c); comments.push({ id, author, date, text, comment_para_id: commentParaId }); } const wordIdByCommentParaId = new Map(); for (const c of comments) { if (c.comment_para_id) wordIdByCommentParaId.set(c.comment_para_id, c.id); } const docEntry = zip.file("word/document.xml") ?? zip.file("word\\document.xml"); if (!docEntry) { return comments.map((c) => { const meta = c.comment_para_id ? commentsExtendedMeta.get(c.comment_para_id) : undefined; const parentWordCommentId = meta?.parentParaId ? wordIdByCommentParaId.get(meta.parentParaId) ?? meta.parentParaId : null; return { ...c, parent_word_comment_id: parentWordCommentId, done: meta?.done ?? null, paragraph_id: "", native_para_id: null, stable_id: null, anchor_text: "", }; }); } const docXml = await docEntry.async("text"); const orderedParser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@_", preserveOrder: true, trimValues: false, }); const orderedDocParsed = orderedParser.parse(docXml); const anchorMap = new Map< string, { paragraph_id: string; native_para_id: string | null; stable_id: string | null; anchor_text: string; } >(); const orderedParagraphs = collectOrderedParagraphs(orderedDocParsed); orderedParagraphs.forEach((pData, index) => { const pId = `P_${String(index + 1).padStart(4, "0")}`; const nativeId = typeof pData.attrs?.["@_w14:paraId"] === "string" ? pData.attrs["@_w14:paraId"] : null; const stableId = nativeId ? `para:${nativeId}` : null; const anchors = extractCommentAnchorsFromOrderedParagraph(pData.kids); for (const [commentId, anchorText] of anchors) { if (commentId && !anchorMap.has(commentId)) { anchorMap.set(commentId, { paragraph_id: pId, native_para_id: nativeId, stable_id: stableId, anchor_text: anchorText || extractOrderedText(pData.kids).slice(0, 200), }); } } }); return comments.map((c) => { const meta = c.comment_para_id ? commentsExtendedMeta.get(c.comment_para_id) : undefined; const parentWordCommentId = meta?.parentParaId ? wordIdByCommentParaId.get(meta.parentParaId) ?? meta.parentParaId : null; return { ...c, parent_word_comment_id: parentWordCommentId, done: meta?.done ?? null, paragraph_id: anchorMap.get(c.id)?.paragraph_id ?? "", native_para_id: anchorMap.get(c.id)?.native_para_id ?? null, stable_id: anchorMap.get(c.id)?.stable_id ?? null, anchor_text: anchorMap.get(c.id)?.anchor_text ?? "", }; }); } function collectOrderedParagraphs(nodes: any): { attrs: any; kids: any[] }[] { const paragraphs: { attrs: any; kids: any[] }[] = []; const visit = (value: any): void => { if (!value || typeof value !== "object") return; if (Array.isArray(value)) { for (const item of value) visit(item); return; } if (Array.isArray(value["w:p"])) { paragraphs.push({ attrs: value[":@"] || {}, kids: value["w:p"] }); return; } for (const [key, child] of Object.entries(value)) { if (key === ":@" || key === "#text") continue; visit(child); } }; visit(nodes); return paragraphs; } function orderedNodeAttrs(node: any): Record { return node?.[":@"] && typeof node[":@"] === "object" ? node[":@"] : {}; } function orderedNodeText(node: any): string { if (!node || typeof node !== "object") return ""; if (typeof node["#text"] === "string") return node["#text"]; let text = ""; for (const [key, value] of Object.entries(node)) { if (key === ":@") continue; if (Array.isArray(value)) text += extractOrderedText(value); } return text; } function extractOrderedText(nodes: any[]): string { let text = ""; for (const node of nodes) { text += orderedNodeText(node); } return text; } function extractCommentAnchorsFromOrderedParagraph(pNodes: any[]): Map { const active = new Set(); const anchors = new Map(); const visit = (nodes: any[]): void => { for (const node of nodes) { if (!node || typeof node !== "object") continue; const attrs = orderedNodeAttrs(node); if (Array.isArray(node["w:commentRangeStart"])) { const id = String(attrs["@_w:id"] ?? ""); if (id) { active.add(id); if (!anchors.has(id)) anchors.set(id, ""); } } if (active.size > 0 && Array.isArray(node["w:t"])) { const text = extractOrderedText(node["w:t"]); for (const id of active) { anchors.set(id, (anchors.get(id) ?? "") + text); } } for (const [key, value] of Object.entries(node)) { if (key === ":@" || key === "#text" || key === "w:t") continue; if (Array.isArray(value)) visit(value); } if (Array.isArray(node["w:commentRangeEnd"])) { const id = String(attrs["@_w:id"] ?? ""); if (id) active.delete(id); } } }; visit(pNodes); return anchors; } function compactDisplayText(value: string): string { return value.replace(/\s+/g, " ").trim(); } function limitDisplayText(value: string, maxLength = 90): string { const compact = compactDisplayText(value); if (compact.length <= maxLength) return compact; return `${compact.slice(0, maxLength - 1)}…`; } export function inferSectionLabelFromComment(comment: DocxComment): string | null { const candidates = [comment.anchor_text, comment.text] .map((value) => compactDisplayText(value ?? "")) .filter((value) => value.length > 0); for (const text of candidates) { const sectionMatch = text.match(/\b[Ss]ection\s+([0-9]+(?:\.[0-9]+)*[A-Za-z]?)(?:\s*[:\-–—]\s*([^.;\n]{1,80}))?/); if (sectionMatch) { const number = sectionMatch[1]; const title = sectionMatch[2] ? `: ${limitDisplayText(sectionMatch[2], 70)}` : ""; return `Section ${number}${title}`; } const clauseMatch = text.match(/\b[Cc]lause\s+([0-9]+(?:\.[0-9]+)*[A-Za-z]?)(?:\s*[:\-–—]\s*([^.;\n]{1,80}))?/); if (clauseMatch) { const number = clauseMatch[1]; const title = clauseMatch[2] ? `: ${limitDisplayText(clauseMatch[2], 70)}` : ""; return `Clause ${number}${title}`; } const numberedHeadingWithDot = text.match(/^([0-9]{1,2}(?:\.[0-9]+)*)\.\s+([A-Z][^.;\n]{2,80})/); if (numberedHeadingWithDot) { return `${numberedHeadingWithDot[1]}. ${limitDisplayText(numberedHeadingWithDot[2], 70)}`; } const numberedSubclause = text.match(/^([0-9]{1,2}(?:\.[0-9]+){1,4}[A-Za-z]?)\s+([A-Z][^.;\n]{2,80})/); if (numberedSubclause) { return `${numberedSubclause[1]} ${limitDisplayText(numberedSubclause[2], 70)}`; } } return null; } /** * Resolves section labels for comments by inspecting document structure. * Builds the DOCX edit surface, walks forward through all paragraphs tracking * the current heading, then maps each comment's paragraph_id to its preceding heading. * Falls back to inferSectionLabelFromComment if the surface approach yields nothing. */ export async function resolveSectionLabelFromSurface( docxBytes: Buffer, comments: DocxComment[], versionId?: string | null, ): Promise> { const result = new Map(); if (comments.length === 0) return result; // Build the edit surface from the same DOCX bytes let surface: Awaited>; try { surface = await buildDocxEditSurface(docxBytes, { versionId }); } catch { // If we can't build the surface, fall back to text-only inference for all for (const c of comments) { result.set(c.id, inferSectionLabelFromComment(c)); } return result; } // ─── Heading detection: separate regexes to avoid false positives ─── // // DO NOT merge these into one big regex with /i. // The /i flag on a single combined regex would make the ALL-CAPS // pattern [A-Z][A-Z0-9 ,/&()\-]{6,} also match normal title-case // or lowercase text, causing ordinary paragraphs to be classified // as headings — which would produce WRONG section labels. // Wrong labels are worse than blank labels because users trust them. // Matches: "Section 17", "Section 2.1A", "Clause 3.1", "Article 4" // Also matches trailing subtitles after a delimiter: // "Section 17: Confidentiality", "Clause 2.1 – Payment" const LABELED_NUMERIC_HEADING_RE = /^\s*(section|clause|article)\s+\d+(?:\.\d+)*[A-Za-z]?(?:\s*[:.\-–—]\s*\S.*)?$/i; // Matches: "Schedule A", "Exhibit 1", "Annex B", "Appendix C" // (letters OR digits after the label — the old regex only matched \d+) const LABELED_ALPHA_NUMERIC_HEADING_RE = /^\s*(schedule|exhibit|annex|appendix)\s+[A-Za-z0-9]+(?:\s*[:.\-–—]\s*\S.*)?$/i; // Matches: "1. Introduction", "1.1 Limitation of Liability", "2.3.4 Title" // The optional trailing dot after the number covers "1. Introduction" // which the old regex missed (it required a space after the number, // not a dot). const NUMBERED_HEADING_RE = /^\s*\d+(?:\.\d+)*\.?\s+[A-Z][^\n]{1,120}$/; // Matches: "GENERAL PROVISIONS", "TERMINATION", "FORCE MAJEURE" // NOTE: No /i flag! This MUST be case-sensitive so that only // truly ALL-CAPS text matches. With /i it would match normal sentences. const ALL_CAPS_HEADING_RE = /^\s*[A-Z][A-Z0-9 ,/&()\-]{6,}$/; function isHeadingText(text: string): boolean { const trimmed = text.trim(); if (!trimmed || trimmed.length > 200) return false; return ( LABELED_NUMERIC_HEADING_RE.test(trimmed) || LABELED_ALPHA_NUMERIC_HEADING_RE.test(trimmed) || NUMBERED_HEADING_RE.test(trimmed) || ALL_CAPS_HEADING_RE.test(trimmed) ); } // Word heading style pattern (Heading1, Heading2, etc.) const HEADING_STYLE_RE = /^heading\s*\d/i; // Walk forward through all blocks, tracking the current heading. // This is O(N) for N blocks, versus O(N*M) walking backward per comment. let currentHeading: string | null = null; const blockIdToHeading = new Map(); // Build a map from block_id to anchor. // DO NOT use surface.anchors[i] with the same index as surface.blocks[i]. // The explicit relationship is block.id === anchor.block_id. // Using the map is safer and does not rely on array index alignment. const anchorByBlockId = new Map( surface.anchors.map((anchor) => [anchor.block_id, anchor]), ); for (const block of surface.blocks) { const anchor = anchorByBlockId.get(block.id); const text = block.text.trim(); // Signal 1: Word paragraph style (Heading1, Heading2, etc.) const styleId = typeof anchor?.style_id === "string" ? anchor.style_id : ""; const isHeadingByStyle = HEADING_STYLE_RE.test(styleId); // Signal 2: Text content matches a heading pattern const isHeadingByText = isHeadingText(text); if (isHeadingByStyle || isHeadingByText) { currentHeading = text; } blockIdToHeading.set(block.id, currentHeading); } // Build a parallel map keyed by native Word paragraph ID (w14:paraId). // The synthetic P_XXXX block IDs diverge between extractDocxComments and // buildDocxEditSurface (one counts empty paragraphs, the other skips them), // so we need the native ID for reliable matching. const nativeParaIdToHeading = new Map(); for (const block of surface.blocks) { const anchor = anchorByBlockId.get(block.id); if (anchor?.native_para_id) { nativeParaIdToHeading.set(anchor.native_para_id, blockIdToHeading.get(block.id) ?? null); } } // Now resolve each comment's section label for (const comment of comments) { let sectionLabel: string | null = null; if (comment.native_para_id) { sectionLabel = nativeParaIdToHeading.get(comment.native_para_id) ?? null; } else if (comment.paragraph_id) { sectionLabel = blockIdToHeading.get(comment.paragraph_id) ?? null; } // If we didn't find a heading via the surface (or the comment has no paragraph_id), // fall back to the old text-based inference if (!sectionLabel) { sectionLabel = inferSectionLabelFromComment(comment); } result.set(comment.id, sectionLabel); } return result; }