// What changed? The comparison engine. // Splits two versions of a document into clauses, lines them up, diffs the words, and pulls out // the changes that usually matter: money, dates, durations, percentages, other numbers, // obligation wording, names, and clauses added or removed. // Pure functions with no DOM, so the same code runs in a Web Worker, on the page and in Node tests. // Built by Suman Mukherjee. Apache-2.0. export const CATEGORY_ORDER = ["Money", "Date", "Duration", "Percent", "Number", "Obligation", "Party", "Clause added", "Clause removed"]; /* ------------------------------------------------------------------ 1. Clean-up */ export function normalizeText(raw) { let t = String(raw == null ? "" : raw); t = t.replace(/\r\n?/g, "\n").replace(/\f/g, "\n\n").replace(/\t/g, " ") .replace(/[\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]/g, " ") .replace(/[\u200b-\u200d\u2060\ufeff\u00ad]/g, "") .replace(/[\u2028\u2029]/g, "\n"); return t.split("\n").map((l) => l.replace(/ {2,}/g, " ").trim()).join("\n").replace(/\n{3,}/g, "\n\n").trim(); } const QUOTE1 = /[\u2018\u2019\u201a\u201b\u2032`\u00b4]/g; const QUOTE2 = /[\u201c\u201d\u201e\u201f\u2033\u00ab\u00bb]/g; const DASH = /[\u2010-\u2015\u2212]/g; export const plain = (s) => String(s).replace(QUOTE1, "'").replace(QUOTE2, '"').replace(DASH, "-"); /* ------------------------------------------------------------------ 2. Tokens */ const TOKEN_RE = /\d+(?:[.,:/-]\d+)*|[\p{L}\p{M}]+(?:['\u2019\u2010\u2011\u2013-][\p{L}\p{M}]+)*|\S/gu; const IS_WORD = /[\p{L}\p{N}]/u; export function tokenize(text) { const out = []; TOKEN_RE.lastIndex = 0; let m; while ((m = TOKEN_RE.exec(text))) out.push({ t: m[0], s: m.index, e: m.index + m[0].length, k: plain(m[0]), w: IS_WORD.test(m[0]) }); return out; } const wordsOf = (text) => (plain(text).toLowerCase().match(/\d+(?:[.,:/-]\d+)*|[\p{L}\p{M}]+(?:['-][\p{L}\p{M}]+)*/gu) || []); /* ------------------------------------------------------------------ 3. Blocks (clauses and paragraphs) */ const WORD_LABEL_RE = /^(?:clause|section|article|schedule|annexure|appendix|part|chapter)\s+(?:\d+[a-z]?(?:\.\d+)*|[ivxlc]+)\b[.:)]?/i; const NUM_LABEL_RE = /^\(?\d{1,3}(?:\.\d{1,3}){0,4}(?:[.)]|(?=\s+[A-Z(\u201c"'\u2018]))/; const LETTER_LABEL_RE = /^(?:\((?:[a-z]{1,2}|[ivxlc]{1,6})\)|(?:[a-z]|[ivx]{1,5})[.)](?=\s)|[IVXLC]{1,6}\.(?=\s))/; const BULLET_RE = /^[\u2022\u25aa\u25e6\u00b7\u2023\u2219\u25cf\u25cb\u25a0\u25a1\u27a2\u25ba*\u2013\u2014-]\s+/; const SMALL_WORDS = new Set("a an and as at by for from in into of on or the to with under per vs via".split(" ")); function labelOf(line) { const m = WORD_LABEL_RE.exec(line) || NUM_LABEL_RE.exec(line) || LETTER_LABEL_RE.exec(line); if (m) return m[0]; const b = BULLET_RE.exec(line); return b ? b[0] : ""; } function isHeadingLine(line) { const lab = labelOf(line); const rest = line.slice(lab.length).replace(/^[\s\u2013\u2014:.-]+/, "").trim(); if (!rest) return !!lab && !BULLET_RE.test(line); if (rest.length > 64 || /[\d\u20b9$\u20ac\u00a3%]/.test(rest) || /^[^:]{1,40}:\s+\S/.test(rest)) return false; const words = rest.split(/\s+/); if (words.length > 8) return false; if (/[.;,!?]$/.test(rest) && !/^[A-Z &/'\u2019()-]+\.$/.test(rest)) return false; const letters = rest.replace(/[^A-Za-z]/g, ""); if (letters.length < 3) return false; if (letters === letters.toUpperCase()) return true; if (/:$/.test(rest)) return true; // "Clause 3 - Licence fee", "7. Notice period": a numbered line with a short capitalised title if (lab && !BULLET_RE.test(line) && words.length <= 6 && /^[A-Z]/.test(rest) && !/[.;,!?]$/.test(rest)) return true; return words.every((w) => /^[A-Z"'\u2018\u201c&]|^\([A-Z0-9]/.test(w) || SMALL_WORDS.has(w.toLowerCase())); } const ENDS_SENTENCE = /[.:;!?)][\]"'\u201d\u2019]?$/; const FIELD_RE = /^[A-Z][A-Za-z0-9 ()/&'\u2019.,-]{0,40}:\s+\S/; function splitLines(norm) { const chunks = norm.split(/\n\n+/); // Hard-wrapped text (from a PDF or an e-mail) has many lines close to one width. Then a line that does // not end a sentence continues on the next line, even if that line starts with "(6)" or a capital. const all = norm.split("\n").filter((l) => l.length >= 25); const lens = all.map((l) => l.length).sort((a, b) => a - b); const width = lens.length ? lens[Math.floor(0.9 * (lens.length - 1))] : 0; const openEnded = all.filter((l) => l.length >= 0.75 * width && !ENDS_SENTENCE.test(l)).length; const wrapMode = lens.length >= 4 && width <= 110 && openEnded >= 3 && lens.filter((l) => l >= 0.75 * width).length >= 0.5 * lens.length; const paras = []; chunks.forEach((chunk, ci) => { const lines = chunk.split("\n"); let cur = []; const flush = () => { if (cur.length) paras.push({ text: cur.reduce((acc, l) => (!acc ? l : /\p{L}-$/u.test(acc) && /^\p{Ll}/u.test(l) ? acc + l : acc + " " + l), ""), chunk: ci, alone: false }); cur = []; }; for (const line of lines) { if (cur.length) { const prev = cur[cur.length - 1]; const prevEnds = ENDS_SENTENCE.test(prev); let split; const prevIsHead = cur.length === 1 && (isHeadingLine(prev) || isCaption(prev)); const continues = !prevEnds && !prevIsHead && (!FIELD_RE.test(prev) || prev.length >= 45) && !FIELD_RE.test(line) && prev.length >= 40 && !BULLET_RE.test(line) && !/^\(?\d{1,3}(?:\.\d{1,3})+/.test(line) && !(isHeadingLine(line) && line === line.toUpperCase() && /[A-Z]{3}/.test(line)); if (continues) split = false; else if (isHeadingLine(line) || prevIsHead) split = true; else if (labelOf(line)) split = !(wrapMode && !prevEnds && !isHeadingLine(prev) && /^\(?\d{1,3}\)?(?![.\d])/.test(line)); else if (FIELD_RE.test(line) && (prevEnds || !wrapMode || FIELD_RE.test(prev))) split = true; else if (wrapMode) split = prevEnds && prev.length < 0.8 * width; else split = !(!prevEnds && /^[a-z(\u20b9$\u20ac\u00a3\d]/.test(line)); if (split) flush(); } cur.push(line); } flush(); }); for (let k = 0; k < paras.length; k++) paras[k].alone = (k === 0 || paras[k - 1].chunk !== paras[k].chunk) && (k === paras.length - 1 || paras[k + 1].chunk !== paras[k].chunk); return paras; } // A short sentence-case caption such as "Joining date" or "Work from home" that introduces the next paragraph. function isCaption(line) { if (labelOf(line) || line.length > 48 || /[\d\u20b9$\u20ac\u00a3%@]/.test(line) || /[.;,!?]$/.test(line) || FIELD_RE.test(line)) return false; const words = line.replace(/:$/, "").split(/\s+/); return words.length <= 6 && /^[A-Z]/.test(line) && !/^(?:Dear|Yours|Regards|Sincerely|Thank|Thanks|Signed|For|By|Witness)\b/.test(line); } const INLINE_HEAD_RE = /^([A-Z][A-Za-z&/'\u2019 -]{2,44}?)\s*(?:[.:]|\s[\u2013\u2014-])\s+(?=[A-Z"\u201c(\u20b9$\d])/; function toSentenceCase(s) { const t = s.trim().replace(/[:.\s]+$/, ""); if (!t) return ""; if (t === t.toUpperCase()) { // Keep short acronyms (EMI, GST, PAN, KYC, TDS) in capitals; sentence-case the other words. const KEEP_SMALL = new Set(["THE", "AND", "FOR", "OF", "TO", "IN", "ON", "AT", "BY", "OR", "A", "AN"]); const words = t.split(/(\s+)/).map((w, i) => { if (/^\s+$/.test(w)) return w; if (/^[A-Z]{2,3}$/.test(w) && !KEEP_SMALL.has(w)) return w; const low = w.toLowerCase(); return i === 0 ? low.charAt(0).toUpperCase() + low.slice(1) : low; }); return words.join(""); } return t.charAt(0).toUpperCase() + t.slice(1); } function inlineHeading(rest) { const m = INLINE_HEAD_RE.exec(rest); if (!m) return ""; const words = m[1].trim().split(/\s+/); if (words.length > 5) return ""; const caps = m[1] === m[1].toUpperCase(); const title = words.every((w) => /^[A-Z]/.test(w) || SMALL_WORDS.has(w.toLowerCase())); if (!caps && !title) return ""; if (/^(?:mr|mrs|ms|dr|shri|smt|no|rs|inr|usd)$/i.test(words[words.length - 1])) return ""; return toSentenceCase(m[1]); } const isTopLabel = (lab) => /^\(?\d+[.)]?$|^(?:clause|section|article|schedule|annexure|appendix|part|chapter)\s+\S+$|^[IVXLC]+\.$/i.test(lab.trim()); const cleanLabel = (lab) => lab.trim().replace(/[.:]$/, "").replace(/^\((\d+)\)$/, "$1"); export function segment(text) { const norm = normalizeText(text); if (!norm) return []; const paras = splitLines(norm); const blocks = []; // hard headings (numbered or capitals) last until the next one; soft captions only cover their own paragraph group let heading = "", soft = "", softUntil = -1, softLeft = 0, clause = "", prevWasHeading = false; for (let k = 0; k < paras.length; k++) { const { text: p, chunk, alone } = paras[k]; const lab = labelOf(p); const isBullet = !!lab && BULLET_RE.test(p); const rest = p.slice(lab.length).replace(/^[\s\u2013\u2014:.-]+/, "").trim(); const next = paras[k + 1]; const hard = isHeadingLine(p) && (!!lab || rest === rest.toUpperCase() || !isCaption(p) || !next); const cap = !hard && next && isCaption(p) && !isCaption(next.text); const isHead = hard || cap; if (k > 0 && (chunk > softUntil || softLeft <= 0)) soft = ""; const b = { i: blocks.length, text: p, label: isBullet ? "" : cleanLabel(lab), labelEnd: lab.length, isHeading: isHead, chunk }; if (hard) { heading = rest ? toSentenceCase(rest) : heading; soft = ""; if (b.label) clause = b.label; b.heading = heading; prevWasHeading = true; } else if (cap) { soft = toSentenceCase(rest); softUntil = alone ? chunk + 1 : chunk; softLeft = 4; b.heading = soft; prevWasHeading = true; } else { const inl = inlineHeading(rest); if (b.label && isTopLabel(lab)) { clause = b.label; if (inl) heading = inl; else if (!prevWasHeading) heading = ""; } else if (b.label && inl && !prevWasHeading) { heading = inl; } else if (b.label && !clause) clause = b.label; if (b.label && !isTopLabel(lab) && clause && !b.label.startsWith(clause.replace(/[.)]$/, ""))) clause = b.label; b.heading = inl || soft || heading; softLeft--; prevWasHeading = false; } b.ref = b.label || clause; const w = wordsOf(rest); b.key = w.length ? w.join(" ") : plain(p).toLowerCase(); b.words = w; blocks.push(b); } return blocks; } /* ------------------------------------------------------------------ 4. Sequence matching (patience diff with an LCS fallback) */ function lis(cand) { // cand: [i, j] sorted by i; returns the longest subsequence with increasing j const tails = [], prev = new Int32Array(cand.length).fill(-1), tailIdx = []; for (let k = 0; k < cand.length; k++) { const j = cand[k][1]; let lo = 0, hi = tails.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (tails[mid] < j) lo = mid + 1; else hi = mid; } tails[lo] = j; tailIdx[lo] = k; prev[k] = lo > 0 ? tailIdx[lo - 1] : -1; } const out = []; let k = tailIdx[tails.length - 1]; while (k !== undefined && k >= 0) { out.push(cand[k]); k = prev[k]; } return out.reverse(); } function lcsDP(ak, bk, a0, a1, b0, b1, out) { const n = a1 - a0, m = b1 - b0, W = m + 1; const T = new Uint32Array((n + 1) * (m + 1)); for (let i = n - 1; i >= 0; i--) { for (let j = m - 1; j >= 0; j--) { T[i * W + j] = ak[a0 + i] === bk[b0 + j] ? T[(i + 1) * W + j + 1] + 1 : Math.max(T[(i + 1) * W + j], T[i * W + j + 1]); } } let i = 0, j = 0; while (i < n && j < m) { if (ak[a0 + i] === bk[b0 + j]) { out.push([a0 + i, b0 + j]); i++; j++; } else if (T[(i + 1) * W + j] >= T[i * W + j + 1]) i++; else j++; } } function matchRange(ak, bk, a0, a1, b0, b1, out, limit, depth) { while (a0 < a1 && b0 < b1 && ak[a0] === bk[b0]) { out.push([a0, b0]); a0++; b0++; } const tail = []; while (a0 < a1 && b0 < b1 && ak[a1 - 1] === bk[b1 - 1]) { a1--; b1--; tail.push([a1, b1]); } if (a0 < a1 && b0 < b1) { const cnt = new Map(); for (let i = a0; i < a1; i++) { let c = cnt.get(ak[i]); if (!c) { c = { a: 0, b: 0, ia: i, ib: -1 }; cnt.set(ak[i], c); } c.a++; c.ia = i; } for (let j = b0; j < b1; j++) { const c = cnt.get(bk[j]); if (c) { c.b++; c.ib = j; } } const cand = []; for (const c of cnt.values()) if (c.a === 1 && c.b === 1) cand.push([c.ia, c.ib]); if (cand.length && depth < 2000) { cand.sort((x, y) => x[0] - y[0]); let pa = a0, pb = b0; for (const [i, j] of lis(cand)) { matchRange(ak, bk, pa, i, pb, j, out, limit, depth + 1); out.push([i, j]); pa = i + 1; pb = j + 1; } matchRange(ak, bk, pa, a1, pb, b1, out, limit, depth + 1); } else if ((a1 - a0) * (b1 - b0) <= limit) { lcsDP(ak, bk, a0, a1, b0, b1, out); } } for (let t = tail.length - 1; t >= 0; t--) out.push(tail[t]); } export function matchSequences(ak, bk, limit = 1500000) { const out = []; matchRange(ak, bk, 0, ak.length, 0, bk.length, out, limit, 0); return out; } /* ------------------------------------------------------------------ 5. Similarity between blocks */ function bagOf(words) { const m = new Map(); for (const w of words) m.set(w, (m.get(w) || 0) + 1); return m; } function makeSim(B, A) { const df = new Map(); for (const b of [...B, ...A]) for (const w of new Set(b.words)) df.set(w, (df.get(w) || 0) + 1); const N = B.length + A.length || 1; const idf = (w) => Math.log(1 + N / (df.get(w) || 1)); const bags = new Map(); const bag = (side, i) => { const key = side + i; let g = bags.get(key); if (!g) { g = bagOf((side === "b" ? B : A)[i].words); bags.set(key, g); } return g; }; const weight = (g) => { let t = 0; for (const [w, c] of g) t += c * idf(w); return t; }; const fieldKey = (b) => { const m = /^([A-Z][A-Za-z0-9 ()/&'.-]{0,40}):\s+\S/.exec(b.text.slice(b.labelEnd)); return m ? m[1].toLowerCase() : ""; }; const sim = (bi, aj) => { const fk = fieldKey(B[bi]); const floor = fk && fk === fieldKey(A[aj]) ? 0.5 : 0; return Math.max(floor, simWords(bi, aj)); }; const simWords = (bi, aj) => { const x = bag("b", bi), y = bag("a", aj); let inter = 0; for (const [w, c] of x) { const d = y.get(w); if (d) inter += Math.min(c, d) * idf(w); } const wx = weight(x), wy = weight(y), tot = wx + wy; if (!tot) return B[bi].key === A[aj].key ? 1 : 0; const dice = (2 * inter) / tot; // A clause that only lost or gained a sentence still mostly contains the other one. const small = Math.min(B[bi].words.length, A[aj].words.length); const contain = small >= 4 ? inter / Math.min(wx, wy) : 0; return Math.max(dice, 0.75 * contain); }; const residualCover = (fullBag, partBag, extraBag) => { // how much of extraBag is explained by fullBag once partBag is taken out let hit = 0, tot = 0; for (const [w, c] of extraBag) { const left = (fullBag.get(w) || 0) - (partBag.get(w) || 0); tot += c * idf(w); hit += Math.max(0, Math.min(c, left)) * idf(w); } return tot ? hit / tot : 0; }; return { sim, bag, residualCover, idf }; } /* ------------------------------------------------------------------ 6. Aligning the two documents */ const PAIR_MIN = 0.35, MOVE_MIN = 0.6; function pairGap(dels, ins, S, pairs) { const n = dels.length, m = ins.length; if (!n || !m) return; if (n * m <= 40000) { const W = m + 1, score = new Float64Array((n + 1) * W), step = new Uint8Array((n + 1) * W); for (let i = 1; i <= n; i++) { for (let j = 1; j <= m; j++) { let best = score[(i - 1) * W + j], p = 1; if (score[i * W + j - 1] > best) { best = score[i * W + j - 1]; p = 2; } const s = S.sim(dels[i - 1], ins[j - 1]); if (s >= PAIR_MIN && score[(i - 1) * W + j - 1] + s > best) { best = score[(i - 1) * W + j - 1] + s; p = 3; } score[i * W + j] = best; step[i * W + j] = p; } } const got = []; let i = n, j = m; while (i > 0 && j > 0) { const p = step[i * W + j]; if (p === 3) { got.push([dels[i - 1], ins[j - 1]]); i--; j--; } else if (p === 2) j--; else i--; } pairs.push(...got.reverse()); return; } // Large gap: best partner by shared rare words, then keep the pairs that stay in order. const index = new Map(); ins.forEach((aj) => { for (const w of new Set(S.bag("a", aj).keys())) { let l = index.get(w); if (!l) index.set(w, (l = [])); l.push(aj); } }); const cand = []; for (const bi of dels) { const votes = new Map(); for (const w of S.bag("b", bi).keys()) { const l = index.get(w); if (l && l.length < 50) for (const aj of l) votes.set(aj, (votes.get(aj) || 0) + S.idf(w)); } const top = [...votes.entries()].sort((x, y) => y[1] - x[1]).slice(0, 8); let best = null, bs = PAIR_MIN; for (const [aj] of top) { const s = S.sim(bi, aj); if (s >= bs) { bs = s; best = aj; } } if (best !== null) cand.push([bi, best]); } pairs.push(...lis(cand)); } export function alignBlocks(B, A, S) { const exact = matchSequences(B.map((b) => b.key), A.map((a) => a.key), 4000000); const pairOfB = new Int32Array(B.length).fill(-1), pairOfA = new Int32Array(A.length).fill(-1); const inOrder = []; let pb = 0, pa = 0; for (const [i, j] of [...exact, [B.length, A.length]]) { const dels = [], ins = []; for (let x = pb; x < i; x++) dels.push(x); for (let y = pa; y < j; y++) ins.push(y); const got = []; pairGap(dels, ins, S, got); for (const [x, y] of got) { inOrder.push([x, y]); pairOfB[x] = y; pairOfA[y] = x; } if (i < B.length) { inOrder.push([i, j]); pairOfB[i] = j; pairOfA[j] = i; } pb = i + 1; pa = j + 1; } // Moves: an unpaired removal and an unpaired addition that say much the same thing. const freeB = [], freeA = []; B.forEach((_, i) => { if (pairOfB[i] < 0) freeB.push(i); }); A.forEach((_, j) => { if (pairOfA[j] < 0) freeA.push(j); }); const moves = []; if (freeB.length && freeA.length && freeB.length * freeA.length <= 250000) { const cand = []; for (const i of freeB) for (const j of freeA) { if (B[i].words.length < 4 && B[i].key !== A[j].key) continue; const s = B[i].key === A[j].key ? 1.01 : S.sim(i, j); if (s >= MOVE_MIN) cand.push([s, i, j]); } cand.sort((x, y) => y[0] - x[0]); for (const [, i, j] of cand) { if (pairOfB[i] >= 0 || pairOfA[j] >= 0) continue; pairOfB[i] = j; pairOfA[j] = i; moves.push([i, j]); } } return { inOrder, moves, pairOfB, pairOfA }; } /* ------------------------------------------------------------------ 7. Word-level diff of two texts */ export function diffTexts(bt, at) { const tb = tokenize(bt), ta = tokenize(at); const pairs = matchSequences(tb.map((t) => t.k), ta.map((t) => t.k)); const chB = new Uint8Array(tb.length).fill(1), chA = new Uint8Array(ta.length).fill(1); for (const [x, y] of pairs) { chB[x] = 0; chA[y] = 0; } let hunks = []; let px = -1, py = -1; for (const [x, y] of [...pairs, [tb.length, ta.length]]) { if (x > px + 1 || y > py + 1) hunks.push({ b0: px + 1, b1: x, a0: py + 1, a1: y }); px = x; py = y; } // Join hunks separated only by punctuation, so "one (1) month" -> "two (2) months" reads as one change. const merged = []; for (const h of hunks) { const last = merged[merged.length - 1]; if (last) { const gapB = tb.slice(last.b1, h.b0); if (gapB.length <= 2 && gapB.every((t) => !t.w)) { last.b1 = h.b1; last.a1 = h.a1; continue; } } merged.push({ ...h }); } hunks = merged; const hB = new Int32Array(tb.length).fill(-1), hA = new Int32Array(ta.length).fill(-1); hunks.forEach((h, n) => { for (let x = h.b0; x < h.b1; x++) hB[x] = n; for (let y = h.a0; y < h.a1; y++) hA[y] = n; }); return { tb, ta, chB, chA, hB, hA, hunks }; } function segmentsFor(text, toks, hun) { const segs = []; const push = (s, f) => { if (!s) return; const l = segs[segs.length - 1]; if (l && l[1] === f) l[0] += s; else segs.push([s, f]); }; let pos = 0; for (let k = 0; k < toks.length; k++) { const t = toks[k], f = hun[k] >= 0 ? 1 : 0; if (t.s > pos) push(text.slice(pos, t.s), k > 0 && f && hun[k - 1] >= 0 ? 1 : 0); push(t.t, f); pos = t.e; } push(text.slice(pos), 0); return segs; } /* ------------------------------------------------------------------ 8. Facts: money, dates, durations, percentages, numbers, names */ const NUMW_LIST = "zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred"; const NUMW = `(?:${NUMW_LIST})(?:[\\s-]+(?:and[\\s-]+)?(?:${NUMW_LIST}))*`; const WORDVAL = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }; export function parseNumWords(s) { let cur = 0, any = false; for (const w of String(s).toLowerCase().split(/[\s-]+/)) { if (!w || w === "and") continue; if (w === "hundred") { cur = (cur || 1) * 100; any = true; continue; } if (w in WORDVAL) { cur += WORDVAL[w]; any = true; } else return null; } return any ? cur : null; } const NUMS = "\\d{1,3}(?:,\\d{2,3})+(?:\\.\\d+)?|\\d+(?:\\.\\d+)?"; const SCALE = "lakhs?|lacs?|crores?|cr|million|mn|billion|bn|thousand|k|m|lpa"; const MONEY_RE = new RegExp( `(\u20b9|rs\\.?|inr|us\\$|usd|\\$|eur|\u20ac|\u00a3|gbp|aed|sgd)\\s?(${NUMS})(?:\\s?(${SCALE})(?![a-z]))?(?:\\s?\\/-)?` + `|\\b(${NUMS})\\s?(${SCALE})?\\s?(rupees|inr|usd|dollars|euros?|eur)\\b` + `|\\b(${NUMS})\\s?(lakhs?|lacs?|crores?|lpa)\\b`, "gi"); const SCALE_VAL = { lakh: 1e5, lakhs: 1e5, lac: 1e5, lacs: 1e5, lpa: 1e5, crore: 1e7, crores: 1e7, cr: 1e7, million: 1e6, mn: 1e6, m: 1e6, billion: 1e9, bn: 1e9, thousand: 1e3, k: 1e3 }; function currencyOf(s) { const c = String(s || "").toLowerCase().replace(/\.$/, ""); if (["\u20b9", "rs", "inr", "rupees", "lakh", "lakhs", "lac", "lacs", "crore", "crores", "lpa"].includes(c)) return "INR"; if (["$", "us$", "usd", "dollars"].includes(c)) return "USD"; if (["eur", "\u20ac", "euro", "euros"].includes(c)) return "EUR"; if (["\u00a3", "gbp"].includes(c)) return "GBP"; return c.toUpperCase(); } const numVal = (s) => parseFloat(String(s).replace(/,/g, "")); const PCT_RE = /\b(\d+(?:\.\d+)?)\s?(%|per\s?cent\b|percent\b|percentage points?\b)/gi; const DUR_UNIT = "(?:(?:calendar|working|business|banking|clear)\\s+)?(?:days?|weeks?|months?|years?|hours?|fortnights?)"; const DUR_RE = new RegExp( `\\b(?:(${NUMW})\\s*\\(\\s*(\\d+(?:\\.\\d+)?)\\s*\\)|(\\d+(?:\\.\\d+)?)\\s*\\(\\s*(${NUMW})\\s*\\)|(\\d+(?:\\.\\d+)?)|(${NUMW}))[\\s-]*(${DUR_UNIT})(?:\\s*\\(s\\))?(?:['\u2019]s?)?(?![\\w])`, "gi"); const UNIT_DAYS = { hour: 1 / 24, day: 1, week: 7, fortnight: 14, month: 30.44, year: 365.25 }; const MON = "jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sept?(?:ember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"; const MONTH_NUM = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }; const ORD_WORDS = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5, sixth: 6, seventh: 7, eighth: 8, ninth: 9, tenth: 10, fifteenth: 15, twentieth: 20, last: 99 }; const DATE_RES = [ ["iso", /\b(\d{4})-(\d{1,2})-(\d{1,2})\b/g], ["num", /\b(\d{1,2})([/.-])(\d{1,2})\2(\d{4}|\d{2})\b/g], ["dmy", new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?(?:\\s+day)?(?:\\s+of)?\\s+(${MON})\\.?,?\\s+(\\d{4})\\b`, "gi")], ["mdy", new RegExp(`\\b(${MON})\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s+(\\d{4})\\b`, "gi")], ["dom", /\b(\d{1,2})(?:st|nd|rd|th)(?:\s+day)?\s+of\s+(?:each|every|the|every\s+calendar|each\s+calendar)\s+(?:calendar\s+|english\s+)?month\b/gi], ["domw", /\b(first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|fifteenth|twentieth|last)\s+(?:working\s+|business\s+)?day\s+of\s+(?:each|every|the)\s+(?:calendar\s+)?month\b/gi], ["by", /\b(?:on or before|not later than|by|before)\s+the\s+(\d{1,2})(?:st|nd|rd|th)\b/gi], ["my", new RegExp(`\\b(${MON})\\.?,?\\s+(\\d{4})\\b`, "gi")], ]; const REF_RE = /\b(?:clauses?|sections?|articles?|para(?:graph)?s?|schedules?|annexures?|appendix|appendices|exhibits?|pages?|items?|rules?|sub-clauses?)\s+\(?[\dIVXivx]+[a-z]?(?:\.\d+)*\)?(?:\([a-z0-9]+\))*(?:\s*(?:and|or|to|,)\s*\(?\d+(?:\.\d+)*\)?)*/gi; const NUMBER_RE = new RegExp(`\\b(${NUMW})\\s*\\(\\s*(\\d+)\\s*\\)|\\b(\\d+)\\s*\\(\\s*(${NUMW})\\s*\\)|\\b\\d+(?:[.,]\\d+)*\\b`, "gi"); const HONOR_RE = /\b(?:Mr|Mrs|Ms|Mx|Dr|Shri|Smt|Sri|Kum|Prof)\.?\s+(?:[A-Z][a-zA-Z'\u2019-]+|[A-Z]\.)(?:\s+(?:[A-Z][a-zA-Z'\u2019-]+|[A-Z]\.))*/g; const ORG_RE = /\b(?:[A-Z][\w&'\u2019.-]*\s+){1,6}?(?:Pvt\.?\s+Ltd\.?|Private\s+Limited|Limited|Ltd\.?|LLP|LLC|Inc\.?|Corp\.?|Corporation|GmbH|PLC|Pte\.?\s+Ltd\.?)(?![\w])/g; const EMAIL_RE = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g; const STOP = new Set(( "a about above accepted accordingly acknowledged additional address after again against agreed agreement agreements all allowance also amendment amount an and annexure annual annum any appendix applicable appointment april arbitration article as assignment at august authorised authorized balance basic be before being below benefits between bonus both but by ceo cfo charges claim claims clause commencement commercial company compensation conditions confidentiality congratulations contract cost counterparts cover coverage crore crores ctc date dated day days dear december default definitions deposit deed designation details dispute duties during each effective either electricity employment end entire escalation events every except exclusions february fee fees for force from further furthermore general governing grade gross gst hereby herein hereinafter however hours hundred i if in indemnity india indian insurance interest interpretation into is it its january july june jurisdiction kindly lakh lakhs late law leave letter liability limitation loan location lock maintenance majeure march may me miscellaneous month monthly months my name net no none not note notes notice notices notwithstanding november now october of offer office on only or our page parties party payment payments penalty per period place please policy position premises premium prepayment probation processing property provided purpose rate re recitals ref reference regards renewal rent repairs representations residential resignation responsibilities retirement rights rupee rupees salary sanction schedule section security september services service severability she signature signed sincerely sir madam so sub subject such sum tax taxes tds tenure term termination terms thank thanks that the their them then there therefore these they this those thousand to total under unless upon us use variable warranties warranty water we welcome whereas which while who whose will with within without witness witnesses year yearly years you your yours " + "monday tuesday wednesday thursday friday saturday sunday first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth " + "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety million billion dollars euros euro only " + "annexures schedules clauses sections articles part chapter definitions purpose scope background summary key table total subtotal particulars description amount remarks status yes" ).split(/\s+/)); const MONTH_WORDS = new Set("jan january feb february mar march apr april may jun june jul july aug august sep sept september oct october nov november dec december".split(" ")); const ROLE_WORDS = new Set("landlord tenant licensor licensee lessor lessee owner occupant employer employee company candidate borrower lender bank insurer insured policyholder proposer client vendor supplier provider consultant contractor customer buyer seller discloser recipient guarantor member subscriber nominee co-borrower".split(" ")); export function docContext(beforeText, afterText) { const all = plain(beforeText + "\n" + afterText); const lowerVocab = new Set(all.match(/\b[a-z][a-z'-]*\b/g) || []); const roleTerms = new Set(); const re = /["']([A-Z][A-Za-z-]+(?:\s[A-Z][A-Za-z-]+)?)["']/g; let m; while ((m = re.exec(all))) { const w = m[1].toLowerCase(); if (ROLE_WORDS.has(w) || ROLE_WORDS.has(w.split(" ").pop())) w.split(" ").forEach((x) => roleTerms.add(x)); } for (const w of ROLE_WORDS) if (new RegExp(`\\b${w.charAt(0).toUpperCase() + w.slice(1)}\\b`).test(all)) roleTerms.add(w); return { lowerVocab, roleTerms, beforeLow: plain(beforeText).toLowerCase(), afterLow: plain(afterText).toLowerCase() }; } function nameLike(word, ctx) { if (!/^[A-Z][a-z'\u2019-]*[a-z]$|^[A-Z][a-z]+[A-Z][a-z]+$/.test(word)) return false; const lw = plain(word).toLowerCase(); if (ctx.roleTerms.has(lw)) return true; if (STOP.has(lw) || MONTH_WORDS.has(lw)) return false; return !ctx.lowerVocab.has(lw); } export function extractFacts(text, ctx, excluded = []) { const facts = []; const busy = new Uint8Array(text.length + 1); for (const [s, e] of excluded) busy.fill(1, s, e); const free = (s, e) => { for (let k = s; k < e; k++) if (busy[k]) return false; return true; }; const take = (f) => { if (f.e <= f.s || !free(f.s, f.e)) return false; busy.fill(1, f.s, f.e); facts.push(f); return true; }; const scan = (re, fn) => { re.lastIndex = 0; let m; while ((m = re.exec(text))) { if (!m[0]) { re.lastIndex++; continue; } fn(m); } }; const before = (s) => (s > 0 ? text[s - 1] : " "); scan(REF_RE, (m) => { busy.fill(1, m.index, m.index + m[0].length); }); for (const [kind, re] of DATE_RES) { scan(re, (m) => { const s = m.index, e = s + m[0].length, raw = m[0]; let norm = "", sortKey = null, ambiguous = false, note = ""; if (kind === "iso") { norm = `${+m[1]}-${+m[2]}-${+m[3]}`; sortKey = +m[1] * 10000 + +m[2] * 100 + +m[3]; } else if (kind === "num") { const a = +m[1], b = +m[3], y = m[4].length === 2 ? 2000 + +m[4] : +m[4]; if (a > 31 || b > 31 || (a > 12 && b > 12)) return; if (a > 12) { norm = `${y}-${b}-${a}`; sortKey = y * 10000 + b * 100 + a; } else if (b > 12) { norm = `${y}-${a}-${b}`; sortKey = y * 10000 + a * 100 + b; } else if (a === b) { norm = `${y}-${a}-${b}`; sortKey = y * 10000 + a * 100 + b; } else { norm = `amb:${a}/${b}/${y}`; ambiguous = true; note = `${m[1]}${m[2]}${m[3]} could mean ${a} ${MONTHS_FULL[b]} or ${b} ${MONTHS_FULL[a]}`; } } else if (kind === "dmy" || kind === "mdy") { const d = kind === "dmy" ? +m[1] : +m[2], mon = MONTH_NUM[(kind === "dmy" ? m[2] : m[1]).slice(0, 3).toLowerCase()], y = +m[3]; norm = `${y}-${mon}-${d}`; sortKey = y * 10000 + mon * 100 + d; } else if (kind === "my") { const mon = MONTH_NUM[m[1].slice(0, 3).toLowerCase()]; norm = `${+m[2]}-${mon}`; sortKey = +m[2] * 10000 + mon * 100; } else if (kind === "dom" || kind === "by") { norm = `dom:${+m[1]}`; sortKey = +m[1]; } else if (kind === "domw") { const v = ORD_WORDS[m[1].toLowerCase()]; norm = `dom:${v}`; sortKey = v; } take({ type: "Date", s, e, text: raw, norm, sortKey, ambiguous, note, recurring: kind === "dom" || kind === "domw" || kind === "by" }); }); } scan(MONEY_RE, (m) => { const s = m.index, e = s + m[0].length; let cur, num, scale; if (m[1]) { if (/^[a-z]/i.test(m[1]) && /[A-Za-z]/.test(before(s))) return; cur = m[1]; num = m[2]; scale = m[3]; } else if (m[4]) { num = m[4]; scale = m[5]; cur = m[6]; } else { num = m[7]; scale = m[8]; cur = scale; } if (/[\d.,]/.test(before(s))) return; const value = numVal(num) * (scale ? SCALE_VAL[scale.toLowerCase()] || 1 : 1); const currency = currencyOf(cur); take({ type: "Money", s, e, text: m[0].replace(/\s?\/-$/, "").trim(), norm: `${currency}:${Math.round(value * 100) / 100}`, value, currency }); }); scan(PCT_RE, (m) => { const s = m.index, e = s + m[0].length; if (/[\d.,]/.test(before(s))) return; take({ type: "Percent", s, e, text: m[0], norm: `pct:${parseFloat(m[1])}`, value: parseFloat(m[1]), points: /point/i.test(m[2]) }); }); scan(DUR_RE, (m) => { const s = m.index, e = s + m[0].length; if (/[\d.,]/.test(before(s))) return; const n = m[2] ? parseFloat(m[2]) : m[3] ? parseFloat(m[3]) : m[5] ? parseFloat(m[5]) : parseNumWords(m[1] || m[4] || m[6]); if (n == null || Number.isNaN(n)) return; const unitRaw = m[7].toLowerCase(); const qual = (unitRaw.match(/^(calendar|working|business|banking|clear)/) || [""])[0]; const base = unitRaw.replace(/^(calendar|working|business|banking|clear)\s+/, "").replace(/s$/, ""); const q = qual === "working" || qual === "banking" ? "business" : qual === "clear" ? "" : qual; take({ type: "Duration", s, e, text: m[0].replace(/['\u2019]s?$/, ""), norm: `${n} ${q ? q + " " : ""}${base}`, value: n, unit: base, qual: q, days: n * (UNIT_DAYS[base] || 1) }); }); scan(/\bnet\s+(\d{1,3})\b(?!\s*(?:%|per\b|days?\b|amount|worth|of\b))/gi, (m) => { const n = +m[1]; take({ type: "Duration", s: m.index, e: m.index + m[0].length, text: m[0], norm: `${n} day`, value: n, unit: "day", qual: "", days: n, net: true }); }); scan(EMAIL_RE, (m) => take({ type: "Party", s: m.index, e: m.index + m[0].length, text: m[0], norm: m[0].toLowerCase(), contact: true })); scan(ORG_RE, (m) => { let s = m.index, t = m[0]; const lead = /^(?:(?:The|For|And|Of|M\/s|Between|With|By|To|From|On|Behalf)\s+)+/.exec(t); if (lead) { s += lead[0].length; t = t.slice(lead[0].length); } if (!/\s/.test(t.trim())) return; take({ type: "Party", s, e: s + t.length, text: t, norm: plain(t).toLowerCase().replace(/[.,]/g, "").replace(/\s+/g, " ") }); }); scan(HONOR_RE, (m) => take({ type: "Party", s: m.index, e: m.index + m[0].length, text: m[0], norm: plain(m[0]).toLowerCase().replace(/\./g, "").replace(/\s+/g, " ").replace(/^(?:mr|mrs|ms|mx|dr|shri|smt|sri|kum|prof) /, "") })); // Runs of capitalised words that look like names: not common words, never written in lower case in either version. if (ctx) { const toks = tokenize(text); let run = null; const endRun = () => { if (run && run.n === 1 && !ctx.roleTerms.has(plain(text.slice(run.s, run.e)).toLowerCase()) && /(?:^|[.!?:;]["')\u201d\u2019]?)\s*["'(\u201c\u2018]?$/.test(text.slice(Math.max(0, run.s - 4), run.s))) run = null; if (run) { const t = text.slice(run.s, run.e); take({ type: "Party", s: run.s, e: run.e, text: t, norm: plain(t).toLowerCase().replace(/\./g, "").replace(/\s+/g, " ") }); } run = null; }; for (let k = 0; k < toks.length; k++) { const tk = toks[k]; const ok = nameLike(tk.t, ctx) || (run && /^[A-Z]$/.test(tk.t) && toks[k + 1] && toks[k + 1].t === "."); if (ok && !busy[tk.s]) { if (run && text.slice(run.e, tk.s).match(/^\.?\s$/)) { run.e = tk.e; run.n++; } else { endRun(); run = { s: tk.s, e: tk.e, n: 1 }; } if (/^[A-Z]$/.test(tk.t)) { run.e = toks[k + 1].e; k++; } } else endRun(); } endRun(); } scan(NUMBER_RE, (m) => { const s = m.index, e = s + m[0].length; if (m[1]) take({ type: "Number", s, e, text: m[0], norm: `n:${+m[2]}`, value: +m[2] }); else if (m[3]) take({ type: "Number", s, e, text: m[0], norm: `n:${+m[3]}`, value: +m[3] }); else if (free(s, e)) { if (/^\d{1,2}$/.test(m[0]) && /^\s*(?:st|nd|rd|th)\b/.test(text.slice(e, e + 3))) return; take({ type: "Number", s, e, text: m[0], norm: `n:${numVal(m[0])}`, value: numVal(m[0]) }); } }); return facts.sort((x, y) => x.s - y.s); } const MONTHS_FULL = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; /* ------------------------------------------------------------------ 9. What is the fact about? (a short label from the words around it) */ const GLUE_BEFORE = new Set("of at is are be been being was were to as".split(" ")); const SKIP_BACK = new Set("shall will would must may can be is are was were been being hereby fixed set revised increased decreased reduced raised enhanced payable paid charged agreed amounting amounts equal equivalent a an the sum total approximately about upto up maximum minimum not exceeding than less more rs inr usd eur only costing worth valued priced capped limited".split(" ")); const STOP_COLLECT = new Set("a an the this that these those any each every such its their his her your our my of at to for by with within on in from under after before upon per as and or but you we it they he she i shall will would must may can be is are was were been being pays receive receives get give giving charge levy which who whose when where if than also has have had entitled eligible report earn granted given offered provided allowed permitted required limited capped restricted use using including includes include".split(" ")); function labelFor(text, f) { const pre = text.slice(Math.max(0, f.s - 90), f.s); if (/:\s*$/.test(pre)) { const seg = pre.replace(/:\s*$/, "").split(/[.;\n]|\s[\u2013\u2014-]\s/).pop().trim(); const w = seg.split(/\s+/).filter(Boolean).slice(-4); const lab = w.join(" ").replace(/^[^\p{L}]+/u, ""); if (lab && lab.length <= 40 && !/\d/.test(lab)) return lab; } const toks = (pre.match(/[\p{L}\p{N}'\u2019-]+|[^\s\p{L}\p{N}]/gu) || []); let k = toks.length - 1; if (k < 0) return ""; const first = toks[k] ? toks[k].toLowerCase() : ""; if (!GLUE_BEFORE.has(first)) { if (/^[\u20b9$\u20ac\u00a3]$/.test(toks[k]) || first === "rs" || first === "inr" || first === "usd") { k--; if (k >= 0 && !GLUE_BEFORE.has(toks[k].toLowerCase())) return ""; } else return ""; } while (k >= 0 && (SKIP_BACK.has(toks[k].toLowerCase()) || GLUE_BEFORE.has(toks[k].toLowerCase()))) k--; if (k >= 0 && toks[k] === ")") { let j = k - 1; const inner = []; while (j >= 0 && toks[j] !== "(") inner.unshift(toks[j--]); if (j >= 0 && inner.length && inner.length <= 3 && inner.every((x) => /^[A-Z0-9]+$/.test(x))) return inner.join(" "); k = j - 1; } const got = []; const content = (w) => w && /[\p{L}]/u.test(w) && !STOP_COLLECT.has(w.toLowerCase()); while (k >= 0 && got.length < 4) { const w = toks[k]; if (w.toLowerCase() === "of" && got.length && got.length < 3 && content(toks[k - 1])) { got.unshift(w); k--; continue; } if (!content(w)) break; got.unshift(w); k--; } return got.join(" "); } function postLabel(text, f) { const post = text.slice(f.e, f.e + 40); const m = /^(?:['\u2019]s?)?\s+((?:prior\s+|advance\s+|written\s+)?notice)\b/i.exec(post); return m ? "Notice period" : ""; } function capFirst(s) { return s ? s.charAt(0).toUpperCase() + s.slice(1) : s; } /* ------------------------------------------------------------------ 10. Obligation wording */ const OBL_STRONG = new Set("shall must will required obliged obligated agrees agree undertakes undertake mandatory liable responsible".split(" ")); const OBL_PERMIT = new Set("may can entitled permitted allowed optional discretion".split(" ")); const OBL_NEG = new Set("not never without nor neither cannot".split(" ")); function obligationSignature(words) { const sig = { strong: 0, permit: 0, neg: 0, cond: 0 }; for (let i = 0; i < words.length; i++) { const w = words[i], nx = words[i + 1] || ""; if (OBL_STRONG.has(w)) sig.strong++; else if (OBL_PERMIT.has(w)) sig.permit++; if (OBL_NEG.has(w) || /^non-/.test(w) || (w === "no" && /^[a-z]/.test(nx) && nx !== "objection")) sig.neg++; if (w === "cannot") sig.permit++; if (w === "unless" || w === "except" || w === "notwithstanding" || (w === "subject" && nx === "to") || (w === "provided" && nx === "that") || (w === "only" && /^(?:if|when|after|upon|where|with)$/.test(nx))) sig.cond++; } return sig; } const sigKey = (s) => `${s.strong}/${s.permit}/${s.neg}/${s.cond}`; function hasOblWord(toks) { return toks.some((t) => { const w = t.k.toLowerCase(); return OBL_STRONG.has(w) || OBL_PERMIT.has(w) || OBL_NEG.has(w) || /^non-/.test(w) || w === "no" || w === "unless" || w === "except" || w === "subject" || w === "provided" || w === "only" || w === "notwithstanding"; }); } /* ------------------------------------------------------------------ 11. Changes that matter within one aligned pair */ function sentenceBounds(toks, k) { let s = k, e = k; while (s > 0 && !/^[.;!?]$/.test(toks[s - 1].t)) s--; while (e < toks.length - 1 && !/^[.;!?]$/.test(toks[e].t)) e++; return [s, e]; } function phrase(text, toks, a, b) { if (!toks.length || b <= a) return ""; return text.slice(toks[a].s, toks[b - 1].e); } function windowAround(text, toks, h0, h1, pad, skipTo = 0) { if (!toks.length) return ""; const anchor = Math.min(Math.max(h0, 0), toks.length - 1); const [ss, se] = sentenceBounds(toks, h1 > h0 ? h0 : anchor); let a = Math.max(ss, h0 - pad, 0); while (a < toks.length && toks[a].s < skipTo) a++; let b = Math.min(se + 1, h1 + pad, toks.length); if (se + 1 - b <= 5) b = Math.min(se + 1, toks.length); return phrase(text, toks, a, Math.max(b, a + 1)).replace(/[\s,;:.]+$/, ""); } function snippetAround(text, s, e) { const st = Math.max(0, text.lastIndexOf(". ", s) + 1, s - 110); const en = Math.min(text.length, Math.max(e + 90, text.indexOf(".", e) + 1 || text.length)); let t = text.slice(st, Math.min(en, e + 140)).trim(); if (st > 0) t = "\u2026" + t; if (en < text.length && !/[.!?]$/.test(t)) t += "\u2026"; return t; } function excerpt(text, n = 16) { const w = text.trim().split(/\s+/); return w.length > n ? w.slice(0, n).join(" ") + "\u2026" : text.trim(); } function pctChange(b, a) { if (!b) return ""; const p = ((a - b) / b) * 100; if (Math.abs(p) < 0.05) return ""; const r = Math.abs(p) >= 10 || Number.isInteger(Math.round(p * 10) / 10) ? Math.round(p * 10) / 10 : Math.round(p * 10) / 10; return `${p > 0 ? "+" : "\u2212"}${String(Math.abs(r)).replace(/\.0$/, "")}%`; } const trimNum = (x) => String(Math.round(x * 1000) / 1000); function describeFact(type, bf, af) { if (bf && af) { if (type === "Money") { if (bf.currency === af.currency) { const d = pctChange(bf.value, af.value); return d ? `(${d})` : ""; } return "(different currency)"; } if (type === "Percent") { const d = af.value - bf.value; return d ? `(${d > 0 ? "+" : "\u2212"}${trimNum(Math.abs(d))} percentage points)` : ""; } if (type === "Duration") { if (bf.days === af.days) return ""; const r = af.days / bf.days; if (bf.qual !== af.qual && bf.unit === af.unit && bf.value === af.value) return `(${af.qual || "calendar"} instead of ${bf.qual || "calendar"})`; if (r > 0.97 && r < 1.03) return "(about the same length, different unit)"; return r > 1 ? "(longer)" : "(shorter)"; } if (type === "Date") { const notes = [...new Set([bf.note, af.note].filter(Boolean))]; if (notes.length) return `(ambiguous date format: ${notes.join("; ")}; check which is meant)`; if (bf.recurring !== af.recurring || bf.sortKey == null || af.sortKey == null) return ""; return af.sortKey > bf.sortKey ? "(later)" : af.sortKey < bf.sortKey ? "(earlier)" : ""; } return ""; } const f = bf || af; if (f.type === "Date" && f.note) return `(ambiguous date format: ${f.note}; check which is meant)`; return ""; } const labelEndOf = (excl) => (excl.length && excl[0][0] === 0 ? excl[0][1] : 0); function rowChanges(row, bText, aText, bExcl, aExcl, ctx) { const d = diffTexts(bText, aText); const items = []; const fb = extractFacts(bText, ctx, bExcl), fa = extractFacts(aText, ctx, aExcl); const tagFacts = (facts, toks, ch, hun) => { let k = 0; for (const f of facts) { while (k < toks.length && toks[k].e <= f.s) k++; f.touched = false; f.hunks = new Set(); f.t0 = k; let j = k; for (; j < toks.length && toks[j].s < f.e; j++) { if (ch[j]) f.touched = true; if (hun[j] >= 0) f.hunks.add(hun[j]); } f.t1 = j; } }; tagFacts(fb, d.tb, d.chB, d.hB); tagFacts(fa, d.ta, d.chA, d.hA); const usedHunks = new Set(); const minH = (f) => (f.hunks.size ? Math.min(...f.hunks) : -9); for (const type of ["Money", "Date", "Duration", "Percent", "Number", "Party"]) { const B = fb.filter((f) => f.type === type && f.touched), A = fa.filter((f) => f.type === type && f.touched); const pairs = [], ub = new Set(), ua = new Set(); for (const b of B) { const a = A.find((x) => !ua.has(x) && [...x.hunks].some((h) => b.hunks.has(h))); if (a) { pairs.push([b, a]); ub.add(b); ua.add(a); } } for (const b of B) { if (ub.has(b)) continue; const a = A.find((x) => !ua.has(x) && Math.abs(minH(x) - minH(b)) <= 1); if (a) { pairs.push([b, a]); ub.add(b); ua.add(a); } } const allA = fa.filter((f) => f.type === type), allB = fb.filter((f) => f.type === type); const mk = (bf, af) => { const f = af || bf; const src = af ? aText : bText; let label = type === "Party" ? row.heading || "" : ""; label = label || (af && labelFor(aText, af)) || (bf && labelFor(bText, bf)) || (af && postLabel(aText, af)) || (bf && postLabel(bText, bf)); if (!label && type === "Date") { const pre = (af ? aText : bText).slice(Math.max(0, f.s - 60), f.s); if (/\b(?:by|before|not later than)\s+$/i.test(pre)) label = "Deadline"; else if (/\b(?:made|executed|signed|entered into)\b[^.;]{0,40}\bon\s+$|\b(?:dated|as of)\s+$/i.test(pre)) label = "Agreement date"; else if (/\b(?:from|starting|commencing|with effect from|effective from|effective)\s+$/i.test(pre)) label = "Start date"; else if (/\b(?:to|until|till|ending on|ends on)\s+$/i.test(pre) && /\bfrom\b/i.test(pre)) label = "End date"; } label = label || row.heading || ""; if (!label) label = type === "Party" ? (f.contact ? "Contact" : "Name") : type === "Number" ? "Number" : type; const one = (x) => x.replace(/\s+/g, " "); items.push({ cat: type, label: capFirst(label), before: bf ? one(bf.text) : "", after: af ? one(af.text) : "", note: describeFact(type, bf, af), snippet: snippetAround(src, f.s, f.e), row: row.id, kind: bf && af ? "changed" : af ? "added" : "removed", hunks: [...(bf ? bf.hunks : []), ...(af ? af.hunks : [])], key: `${type}|${bf ? bf.norm : ""}|${af ? af.norm : ""}`, }); for (const h of bf ? bf.hunks : []) usedHunks.add(h); for (const h of af ? af.hunks : []) usedHunks.add(h); }; for (const [b, a] of pairs) if (b.norm !== a.norm) mk(b, a); else { b.hunks.forEach((h) => usedHunks.add(h)); } const stillThere = (f, low) => type === "Party" && low.includes(plain(f.text).toLowerCase()); for (const b of B) if (!ub.has(b) && !allA.some((x) => x.norm === b.norm) && !stillThere(b, ctx.afterLow)) mk(b, null); for (const a of A) if (!ua.has(a) && !allB.some((x) => x.norm === a.norm) && !stillThere(a, ctx.beforeLow)) mk(null, a); } // Obligation wording: a hunk that changes shall/may/must/not/unless and the like. d.hunks.forEach((h, n) => { const dt = d.tb.slice(h.b0, h.b1), it = d.ta.slice(h.a0, h.a1); const dWords = dt.filter((t) => t.w).map((t) => t.k.toLowerCase()), iWords = it.filter((t) => t.w).map((t) => t.k.toLowerCase()); if (dWords.join(" ") === iWords.join(" ")) return; if (usedHunks.has(n)) return; if (hasOblWord(dt) || hasOblWord(it)) { const ctxB = d.tb.slice(Math.max(0, h.b0 - 2), h.b0).concat(dt, d.tb.slice(h.b1, h.b1 + 2)).filter((t) => t.w).map((t) => t.k.toLowerCase()); const ctxA = d.ta.slice(Math.max(0, h.a0 - 2), h.a0).concat(it, d.ta.slice(h.a1, h.a1 + 2)).filter((t) => t.w).map((t) => t.k.toLowerCase()); if (sigKey(obligationSignature(ctxB)) !== sigKey(obligationSignature(ctxA))) { const added = dWords.length === 0 && iWords.length >= 4, removed = iWords.length === 0 && dWords.length >= 4; const bw = added ? "" : windowAround(bText, d.tb, h.b0, h.b1, 4, labelEndOf(bExcl)); const aw = removed ? "" : windowAround(aText, d.ta, h.a0, h.a1, 4, labelEndOf(aExcl)); const src = aw ? aText : bText; const at = aw ? d.ta[Math.min(h.a0, d.ta.length - 1)] : d.tb[Math.min(h.b0, d.tb.length - 1)]; items.push({ cat: "Obligation", label: "", before: bw, after: aw, note: "", snippet: at ? snippetAround(src, at.s, at.e) : "", row: row.id, kind: added ? "added" : removed ? "removed" : "changed", hunks: [n], key: `Obligation|${plain(bw).toLowerCase()}|${plain(aw).toLowerCase()}` }); usedHunks.add(n); return; } } // A whole new sentence inside an existing clause, with no figures or obligation words in it. const wholeSentence = (toks, x0, x1, start) => { const atStart = x0 <= 0 || toks[x0 - 1].s < start || /^[.;!?:]$/.test(toks[x0 - 1].t); const ends = x1 >= toks.length || toks.slice(x0, x1).some((t) => /^[.!?]$/.test(t.t)); return atStart && ends; }; if (iWords.length >= 8 && dWords.length <= 2 && wholeSentence(d.ta, h.a0, h.a1, labelEndOf(aExcl))) { const t = phrase(aText, d.ta, h.a0, h.a1); items.push({ cat: "Clause added", label: "New text in an existing clause", before: "", after: t, note: "", snippet: "", row: row.id, kind: "added", hunks: [n], key: `Clause added|${plain(t).toLowerCase()}`, sentence: true }); } else if (dWords.length >= 8 && iWords.length <= 2 && wholeSentence(d.tb, h.b0, h.b1, labelEndOf(bExcl))) { const t = phrase(bText, d.tb, h.b0, h.b1); items.push({ cat: "Clause removed", label: "Text removed from an existing clause", before: t, after: "", note: "", snippet: "", row: row.id, kind: "removed", hunks: [n], key: `Clause removed|${plain(t).toLowerCase()}`, sentence: true }); } }); return { d, items }; } /* ------------------------------------------------------------------ 12. The whole comparison */ function factsSummary(text, ctx, excl) { const fs = extractFacts(text, ctx, excl).filter((f) => f.type !== "Party" && f.type !== "Number"); const seen = new Set(), out = []; for (const f of fs) if (!seen.has(f.text)) { seen.add(f.text); out.push(f.text); } return out.slice(0, 4); } function whereOf(blocks) { const b = blocks[0]; if (!b) return ""; const ref = b.ref ? (/^\d/.test(b.ref) || /^\(/.test(b.ref) ? `Clause ${b.ref}` : capFirst(b.ref)) : ""; const head = b.heading && !b.isHeading ? b.heading : b.isHeading ? (b.text.slice(b.labelEnd).trim() ? toSentenceCase(b.text.slice(b.labelEnd)) : "") : ""; return [ref, head].filter(Boolean).join(" \u00b7 ") || `Paragraph ${b.i + 1}`; } export function compare(beforeRaw, afterRaw, onProgress = () => {}) { const t0 = Date.now(); onProgress("Splitting both versions into clauses", 0.02); const B = segment(beforeRaw), A = segment(afterRaw); const ctx = docContext(normalizeText(beforeRaw), normalizeText(afterRaw)); onProgress("Lining up clauses", 0.08); const S = makeSim(B, A); const al = alignBlocks(B, A, S); // Rows: in-order pairs, moves, additions, removals. Then split or merged paragraphs. const rowOfB = new Array(B.length), rowOfA = new Array(A.length); for (const [i, j] of al.inOrder) { const r = { type: "pair", b: [i], a: [j] }; rowOfB[i] = r; rowOfA[j] = r; } for (const [i, j] of al.moves) { const r = { type: "moved", b: [i], a: [j] }; const from = { type: "movedFrom", b: [i], a: [], target: r }; r.from = from; rowOfB[i] = from; rowOfA[j] = r; } B.forEach((_, i) => { if (!rowOfB[i]) rowOfB[i] = { type: "removed", b: [i], a: [] }; }); A.forEach((_, j) => { if (!rowOfA[j]) rowOfA[j] = { type: "added", b: [], a: [j] }; }); const joinBag = (side, idx) => { const m = new Map(); for (const k of idx) for (const [w, c] of S.bag(side, k)) m.set(w, (m.get(w) || 0) + c); return m; }; for (const r of new Set(rowOfB)) { if (r.type !== "pair") continue; for (const dir of [1, -1]) { for (;;) { const j = dir > 0 ? r.a[r.a.length - 1] + 1 : r.a[0] - 1; const cand = rowOfA[j]; if (!cand || cand.type !== "added" || (A[j].words.length < 3 && !A[j].isHeading)) break; const cov = S.residualCover(joinBag("b", r.b), joinBag("a", r.a), S.bag("a", j)); if (cov < 0.75) break; if (dir > 0) r.a.push(j); else r.a.unshift(j); rowOfA[j] = r; } for (;;) { const i = dir > 0 ? r.b[r.b.length - 1] + 1 : r.b[0] - 1; const cand = rowOfB[i]; if (!cand || cand.type !== "removed" || (B[i].words.length < 3 && !B[i].isHeading)) break; const cov = S.residualCover(joinBag("a", r.a), joinBag("b", r.b), S.bag("b", i)); if (cov < 0.75) break; if (dir > 0) r.b.push(i); else r.b.unshift(i); rowOfB[i] = r; } } } const rows = [], emitted = new Set(); let i = 0, j = 0; while (i < B.length || j < A.length) { const rb = i < B.length ? rowOfB[i] : null, ra = j < A.length ? rowOfA[j] : null; if (rb && emitted.has(rb)) { i++; continue; } if (ra && emitted.has(ra)) { j++; continue; } if (rb && (rb.type === "removed" || rb.type === "movedFrom")) { rows.push(rb); emitted.add(rb); i++; continue; } if (ra && (ra.type === "added" || ra.type === "moved")) { rows.push(ra); emitted.add(ra); j++; continue; } if (rb && ra && rb !== ra) { // Should not happen with in-order pairs; emit whichever is earlier to stay safe. if (rb.a[0] <= j) { rows.push(rb); emitted.add(rb); i++; } else { rows.push(ra); emitted.add(ra); j++; } continue; } const r = rb || ra; rows.push(r); emitted.add(r); i++; j++; } rows.forEach((r, n) => { r.id = n + 1; }); const textOf = (blocks, idx) => idx.map((k) => blocks[k].text).join("\n"); const exclOf = (blocks, idx) => { const out = []; let off = 0; for (const k of idx) { const b = blocks[k]; if (b.labelEnd) out.push([off, off + b.labelEnd]); off += b.text.length + 1; } return out; }; let items = []; const changedRows = rows.filter((r) => r.type === "pair" || r.type === "moved"); let done = 0; const total = changedRows.length || 1; for (const r of rows) { const bt = textOf(B, r.b), at = textOf(A, r.a); r.where = whereOf(r.a.length ? r.a.map((k) => A[k]) : r.b.map((k) => B[k])); r.bRef = r.b.length ? whereOf([B[r.b[0]]]) : ""; r.aRef = r.a.length ? whereOf([A[r.a[0]]]) : ""; const hb = r.a.length ? A[r.a[0]] : B[r.b[0]]; r.heading = hb && !hb.isHeading ? hb.heading || "" : ""; if (r.type === "pair" || r.type === "moved") { if (bt === at) { r.kind = r.type === "moved" ? "moved" : "same"; r.bSegs = [[bt, 0]]; r.aSegs = [[at, 0]]; } else { const { d, items: its } = rowChanges(r, bt, at, exclOf(B, r.b), exclOf(A, r.a), ctx); r.bSegs = segmentsFor(bt, d.tb, d.hB); r.aSegs = segmentsFor(at, d.ta, d.hA); const plainSame = r.b.map((k) => B[k].key).join(" ") === r.a.map((k) => A[k].key).join(" "); r.kind = r.type === "moved" ? "moved" : plainSame ? "minor" : "changed"; r.items = its.length; items.push(...its); } done++; if (done % 25 === 0) onProgress(`Comparing words in clause ${done} of ${total}`, 0.1 + 0.8 * (done / total)); } else if (r.type === "added" || r.type === "removed") { r.kind = r.type; if (r.type === "added") r.aSegs = [[at, 1]]; else r.bSegs = [[bt, 1]]; } else if (r.type === "movedFrom") { r.kind = "movedFrom"; r.bSegs = [[bt, 0]]; } } onProgress("Picking out the changes that matter", 0.92); // Added or removed clauses: one item per clause; a heading joins the clause that follows it. const clauseItems = []; for (const side of ["added", "removed"]) { let group = null; const blocks = side === "added" ? A : B; const flush = () => { if (!group) return; const idx = group.flatMap((r) => (side === "added" ? r.a : r.b)); const bl = idx.map((k) => blocks[k]); const body = bl.filter((b) => !b.isHeading).map((b) => b.text.slice(b.labelEnd).trim()).join(" ") || bl.map((b) => b.text.slice(b.labelEnd).trim()).join(" "); const all = bl.map((b) => b.text).join(" "); if (wordsOf(all).length >= 2) { const mentions = factsSummary(all, ctx, []); clauseItems.push({ cat: side === "added" ? "Clause added" : "Clause removed", label: whereOf(bl), before: side === "removed" ? all : "", after: side === "added" ? all : "", note: mentions.length ? `Mentions ${mentions.join(", ")}` : "", snippet: excerpt(body, 16), row: group[0].id, rows: group.map((r) => r.id), kind: side, key: `${side}|${group[0].id}`, }); } group = null; }; for (const r of rows) { if (r.type !== side) { if (r.type !== "movedFrom" && r.type !== (side === "added" ? "removed" : "added")) flush(); continue; } const b = blocks[(side === "added" ? r.a : r.b)[0]]; const startsNew = !group || (b.label && (isTopLabel(b.label + ".") || /^\d+(?:\.\d+)+$/.test(b.label)) && !group[group.length - 1].headOnly) || b.isHeading; if (startsNew && group && !(group.length === 1 && group[0].headOnly)) flush(); if (!group) group = []; r.headOnly = b.isHeading; group.push(r); } flush(); } items.push(...clauseItems); // One line per distinct change: the same old -> new value in several places is listed once. const byKey = new Map(); const merged = []; for (const it of items) { it.rows = it.rows || [it.row]; const k = it.key; if (byKey.has(k) && !k.startsWith("added|") && !k.startsWith("removed|")) { const m = byKey.get(k); m.rows.push(...it.rows.filter((x) => !m.rows.includes(x))); m.count++; continue; } it.count = 1; byKey.set(k, it); merged.push(it); } items = merged.sort((x, y) => x.row - y.row || CATEGORY_ORDER.indexOf(x.cat) - CATEGORY_ORDER.indexOf(y.cat)); items.forEach((it, n) => { it.n = n + 1; it.title = itemTitle(it); it.where = rows[it.row - 1].where; delete it.hunks; }); const count = (k) => rows.filter((r) => r.kind === k).length; const stats = { beforeBlocks: B.length, afterBlocks: A.length, beforeWords: B.reduce((s, b) => s + b.words.length, 0), afterWords: A.reduce((s, b) => s + b.words.length, 0), same: count("same"), changed: count("changed"), minor: count("minor"), added: count("added"), removed: count("removed"), moved: count("moved"), items: items.length, ms: Date.now() - t0, }; stats.places = new Set(items.flatMap((it) => it.rows)).size; stats.wordingOnly = rows.filter((r) => (r.kind === "changed" || r.kind === "minor") && !items.some((it) => it.rows.includes(r.id))).length; onProgress("Done", 1); const slimRows = rows.map((r) => ({ id: r.id, kind: r.kind, where: r.where, bRef: r.bRef, aRef: r.aRef, bSegs: r.bSegs || null, aSegs: r.aSegs || null, moveTo: r.target ? r.target.id : null, moveFrom: r.from ? r.from.id : null })); return { rows: slimRows, items, stats }; } /* ------------------------------------------------------------------ 13. Wording of each item, and export */ export function itemTitle(it) { const q = (s) => `\u201c${s}\u201d`; const L = it.label ? `${it.label}: ` : ""; const note = it.note ? ` ${it.note}` : ""; switch (it.cat) { case "Clause added": return it.sentence ? `New sentence: ${q(excerpt(it.after, 18))}` : `${it.label}: new clause, ${q(it.snippet)}`; case "Clause removed": return it.sentence ? `Sentence removed: ${q(excerpt(it.before, 18))}` : `${it.label}: clause removed, ${q(it.snippet)}`; case "Obligation": if (it.kind === "added") return `Obligation wording added: ${q(it.after)}`; if (it.kind === "removed") return `Obligation wording removed: ${q(it.before)}`; return `Obligation wording: ${q(it.before)} \u2192 ${q(it.after)}`; default: if (it.kind === "added") return `${L}${it.after} (added)${note}`; if (it.kind === "removed") return `${L}${it.before} (removed)${note}`; return `${L}${it.before} \u2192 ${it.after}${note}`; } } export const DISCLAIMER = "This list shows differences in wording found by an automatic comparison. It does not tell you whether a change is fair or legal. Check the full documents, and ask a qualified person before signing."; export function exportText(items, meta = {}, md = false) { const lines = []; const head = `What changed${meta.before || meta.after ? `: ${meta.before || "Before"} \u2192 ${meta.after || "After"}` : ""}`; lines.push(md ? `## ${head}` : head); if (meta.date) lines.push(md ? `_Compared on ${meta.date}_` : `Compared on ${meta.date}`); lines.push(""); lines.push(`${items.length} change${items.length === 1 ? "" : "s"} that matter${items.length === 1 ? "s" : ""}:`); lines.push(""); items.forEach((it, n) => { const where = it.where ? ` (${it.where}${it.count > 1 ? `, ${it.count} places` : ""})` : ""; const sn = it.snippet && !/^Clause/.test(it.cat) ? (md ? `\n > ${it.snippet.replace(/\n/g, " ")}` : `\n "${it.snippet.replace(/\n/g, " ")}"`) : ""; lines.push(md ? `${n + 1}. **${it.cat}**: ${mdEsc(it.title)}${where}${sn}` : `${n + 1}. [${it.cat}] ${it.title}${where}${sn}`); }); lines.push(""); lines.push(md ? `_${DISCLAIMER}_` : DISCLAIMER); return lines.join("\n"); } const mdEsc = (s) => String(s).replace(/([*_`|[\]])/g, "\\$1");