Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Document Assistant v0.3.0 · generic

Archive SHA-256 084f2065dfcd8f2b9402eace1c9e0d03e5eee1dd7d78a54f1dbe7ca5bd99adb2 · 39.1 KB · built Dec 2, 2026

src/text.js

// Markdown / plain-text analysis helpers for document-assistant. Pure functions; no I/O.
// Document content is untrusted data: it is tokenised and compared, never executed or followed.

export function normalize(text) {
  return String(text ?? "").replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
}

// ---------------------------------------------------------------------------------------------
// Structure: front matter, fenced code, headings
// ---------------------------------------------------------------------------------------------
export function frontMatter(lines) {
  if (lines[0]?.trim() !== "---") return { end: 0, data: {} };
  for (let i = 1; i < Math.min(lines.length, 300); i++) {
    if (/^(---|\.\.\.)\s*$/.test(lines[i])) {
      const data = {};
      for (const l of lines.slice(1, i)) {
        const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(l);
        if (m) data[m[1].toLowerCase()] = m[2].trim().replace(/^(["'])(.*)\1$/, "$2");
      }
      return { end: i + 1, data };
    }
  }
  return { end: 0, data: {} };
}

// Marks lines that are inside fenced code blocks (``` or ~~~) or front matter.
export function classifyLines(lines) {
  const fm = frontMatter(lines);
  const kind = new Array(lines.length).fill("text");
  for (let i = 0; i < fm.end; i++) kind[i] = "front_matter";
  let fence = null;
  for (let i = fm.end; i < lines.length; i++) {
    const m = /^ {0,3}(`{3,}|~{3,})/.exec(lines[i]);
    if (fence) {
      kind[i] = "code";
      const close = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(lines[i]);
      if (close && close[1][0] === fence[0] && close[1].length >= fence.length) fence = null;
      continue;
    }
    if (m) { fence = m[1]; kind[i] = "code"; }
  }
  return { kind, frontMatter: fm };
}

export function stripInline(s) {
  return s
    .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
    .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
    .replace(/\[([^\]]+)\]\[[^\]]*\]/g, "$1")
    .replace(/\[\^[^\]]+\]/g, "")
    .replace(/<(https?:\/\/[^>\s]+)>/g, "$1")
    .replace(/<\/?[A-Za-z][^>]*>/g, "")
    .replace(/`([^`]*)`/g, "$1")
    .replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, "$2")
    .replace(/(^|[^\w*])\*(?=\S)([^*]*?\S)\*(?!\w)/g, "$1$2")
    .replace(/(^|[^\w])_(?=\S)([^_]*?\S)_(?!\w)/g, "$1$2")
    .replace(/~~(?=\S)([\s\S]*?\S)~~/g, "$1")
    .replace(/\\([\\`*_{}[\]()#+\-.!>])/g, "$1")
    .trim();
}

const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;

function isPlainHeading(lines, i) {
  const l = lines[i].trim();
  if (!l || l.length > 80 || /[.,;:!?]$/.test(l)) return 0;
  const blankBefore = i === 0 || lines[i - 1].trim() === "";
  const blankAfter = i === lines.length - 1 || lines[i + 1].trim() === "";
  if (!blankBefore || !blankAfter) return 0;
  const num = /^(\d+(?:\.\d+)*)\.?\s+\S/.exec(l);
  if (num) return Math.min(6, num[1].split(".").length);
  if (/\p{L}/u.test(l) && l === l.toUpperCase() && /\p{Lu}{2,}/u.test(l)) return 1;
  return 0;
}

// Returns [{level, text, line}] (line is 1-based). format: "markdown" | "text" | "auto".
export function headings(text, format = "auto") {
  const lines = normalize(text).split("\n");
  const { kind } = classifyLines(lines);
  const md = [];
  for (let i = 0; i < lines.length; i++) {
    if (kind[i] !== "text") continue;
    const atx = ATX.exec(lines[i]);
    if (atx) {
      const t = stripInline(atx[2] ?? "");
      if (t) md.push({ level: atx[1].length, text: t, line: i + 1 });
      continue;
    }
    const next = lines[i + 1];
    if (next !== undefined && kind[i + 1] === "text" && lines[i].trim() && !/^\s{0,3}([-*+]|\d+[.)])\s/.test(lines[i]) && !ATX.test(lines[i]) && !/^\s*>/.test(lines[i])) {
      const prevBlank = i === 0 || lines[i - 1].trim() === "" || kind[i - 1] !== "text";
      if (prevBlank && /^ {0,3}=+\s*$/.test(next)) { md.push({ level: 1, text: stripInline(lines[i].trim()), line: i + 1 }); i++; continue; }
      if (prevBlank && /^ {0,3}-+\s*$/.test(next)) { md.push({ level: 2, text: stripInline(lines[i].trim()), line: i + 1 }); i++; continue; }
    }
  }
  if (format === "markdown" || (format === "auto" && md.length)) return md;
  const plain = [];
  for (let i = 0; i < lines.length; i++) {
    if (kind[i] !== "text") continue;
    const level = isPlainHeading(lines, i);
    if (level) plain.push({ level, text: lines[i].trim(), line: i + 1 });
  }
  return plain;
}

export function outlineStrings(hs) {
  if (!hs.length) return [];
  const min = Math.min(...hs.map((h) => h.level));
  return hs.map((h) => `${"  ".repeat(h.level - min)}${h.text}`);
}

const WORD = /[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu;

export function wordCount(text) {
  const lines = normalize(text).split("\n");
  const { kind } = classifyLines(lines);
  let n = 0;
  for (let i = 0; i < lines.length; i++) {
    if (kind[i] === "front_matter" || (kind[i] === "code" && /^ {0,3}(`{3,}|~{3,})/.test(lines[i]))) continue;
    const l = kind[i] === "code" ? lines[i] : stripInline(lines[i].replace(/^ {0,3}#{1,6}\s+/, "").replace(/^\s*>\s?/, "").replace(/^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/, ""));
    n += (l.match(WORD) ?? []).length;
  }
  return n;
}

export function titleOf(text, hs) {
  const lines = normalize(text).split("\n");
  const { kind, frontMatter: fm } = classifyLines(lines);
  if (fm.data.title) return fm.data.title;
  const h1 = hs.find((h) => h.level === 1) ?? hs[0];
  if (h1) return h1.text;
  for (let i = 0; i < lines.length; i++) {
    if (kind[i] !== "text") continue;
    const t = stripInline(lines[i].replace(/^\s*([-*+>]|\d+[.)])\s+/, ""));
    if (t) return t.length > 120 ? `${t.slice(0, 119)}…` : t;
  }
  return "";
}

// ---------------------------------------------------------------------------------------------
// Extractive summary
// ---------------------------------------------------------------------------------------------
const STOP = new Set(("a about above after again against all also am an and any are as at be because been before being below between both but by can could did do does doing down during each few for from further had has have having he her here hers herself him himself his how i if in into is it its itself just let me more most my myself no nor not now of off on once only or other our ours ourselves out over own same she should so some such than that the their theirs them themselves then there these they this those through to too under until up very was we were what when where which while who whom why will with would you your yours yourself yourselves may might must shall also however thus therefore").split(" "));
const ABBREV = new Set(["mr", "mrs", "ms", "dr", "prof", "sr", "jr", "st", "vs", "etc", "e.g", "i.e", "eg", "ie", "inc", "ltd", "co", "corp", "fig", "no", "vol", "approx", "dept", "est", "al", "cf", "jan", "feb", "mar", "apr", "jun", "jul", "aug", "sep", "sept", "oct", "nov", "dec"]);

export function tokens(s) {
  return (s.toLowerCase().match(WORD) ?? [])
    .map((w) => w.replace(/['’]s$/, ""))
    .filter((w) => w.length > 1 && !STOP.has(w) && !/^\d+$/.test(w))
    .map((w) => (w.length > 4 && w.endsWith("ies") ? `${w.slice(0, -3)}y` : w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w));
}

// Splits text into sentences, returning [{text, start}] with start offsets into `s`.
export function splitSentences(s) {
  const out = [];
  let start = 0;
  const re = /[.!?]+["'”’)\]]*(?=\s+["'“‘(\[]?[\p{Lu}\p{N}])/gu;
  for (const m of s.matchAll(re)) {
    const end = m.index + m[0].length;
    if (m[0][0] === ".") {
      const word = (/([\p{L}.]+)$/u.exec(s.slice(start, m.index))?.[1] ?? "").toLowerCase().replace(/\.$/, "");
      if (ABBREV.has(word) || /^\p{L}$/u.test(word)) continue;
    }
    pushSentence(out, s, start, end);
    start = end;
  }
  pushSentence(out, s, start, s.length);
  return out;
}

function pushSentence(out, s, start, end) {
  const raw = s.slice(start, end);
  const lead = raw.length - raw.trimStart().length;
  const text = raw.trim();
  if (text) out.push({ text, start: start + lead });
}

// Builds prose blocks (paragraphs and list items) with line mapping. Headings, code, tables are excluded.
export function blocks(text) {
  const lines = normalize(text).split("\n");
  const { kind } = classifyLines(lines);
  const hs = headings(text, "auto");
  const headingLines = new Set();
  for (const h of hs) {
    headingLines.add(h.line);
    if (/^ {0,3}(=+|-+)\s*$/.test(lines[h.line] ?? "") && !ATX.test(lines[h.line - 1])) headingLines.add(h.line + 1);
  }
  const out = [];
  let cur = null;
  let section = 0;
  const flush = () => { if (cur) out.push(cur); cur = null; };
  for (let i = 0; i < lines.length; i++) {
    const raw = lines[i];
    if (headingLines.has(i + 1)) { flush(); if (hs.some((h) => h.line === i + 1)) section++; continue; }
    if (kind[i] !== "text" || !raw.trim() || /^\s*\|/.test(raw) || /^ {0,3}([-*_])(\s*\1){2,}\s*$/.test(raw) || /^\s*<\/?[A-Za-z][^>]*>\s*$/.test(raw)) { flush(); continue; }
    const item = /^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?/.exec(raw);
    const content = stripInline(raw.replace(/^\s*>\s?/, "").replace(item?.[0] ?? "", ""));
    if (item) flush();
    if (!content) continue;
    if (!cur) cur = { text: "", lineStarts: [], section, list: Boolean(item) };
    cur.lineStarts.push({ offset: cur.text ? cur.text.length + 1 : 0, line: i + 1 });
    cur.text = cur.text ? `${cur.text} ${content}` : content;
  }
  flush();
  return out;
}

function lineFor(block, offset) {
  let line = block.lineStarts[0].line;
  for (const ls of block.lineStarts) if (ls.offset <= offset) line = ls.line;
  return line;
}

export const COVERED_FACTOR = 0.3;
export const SECTION_DECAY = 0.8;

export function summarize(text, maxSentences) {
  const hs = headings(text, "auto");
  const bl = blocks(text);
  const sents = [];
  for (const [bi, b] of bl.entries()) {
    for (const [si, s] of splitSentences(b.text).entries()) {
      sents.push({ text: s.text, line: lineFor(b, s.start), block: bi, section: b.section, firstInBlock: si === 0, toks: tokens(s.text) });
    }
  }
  if (!sents.length) return { sentences: [], count: 0 };

  // TF over the whole document, IDF over blocks (paragraphs / list items): ln(1 + N / df).
  const tf = new Map();
  let total = 0;
  const df = new Map();
  const blockTerms = bl.map(() => new Set());
  for (const s of sents) {
    for (const t of s.toks) { tf.set(t, (tf.get(t) ?? 0) + 1); total++; blockTerms[s.block].add(t); }
  }
  for (const set of blockTerms) for (const t of set) df.set(t, (df.get(t) ?? 0) + 1);
  const N = bl.length;
  const headingTerms = new Set(hs.flatMap((h) => tokens(h.text)));
  const weight = (t) => ((tf.get(t) ?? 0) / Math.max(1, total)) * Math.log(1 + N / (df.get(t) ?? 1)) * (headingTerms.has(t) ? 1.5 : 1);

  const minWords = sents.filter((s) => s.text.split(/\s+/).length >= 5).length >= maxSentences ? 5 : 1;
  const scored = sents.map((s, i) => {
    const uniq = [...new Set(s.toks)];
    const mult = (i === 0 ? 1.15 : s.firstInBlock && sents[i - 1].section !== s.section ? 1.05 : 1) / Math.sqrt(Math.max(1, s.toks.length));
    const score = uniq.reduce((acc, t) => acc + weight(t), 0) * mult;
    return { ...s, i, uniq, mult, score: Math.round(score * 1e6) / 1e6 };
  });
  const pool = scored.filter((s) => s.text.split(/\s+/).length >= minWords && s.toks.length > 0).map((s) => ({ ...s, set: new Set(s.toks) }));
  // Greedy coverage-based selection (in the spirit of SumBasic / maximal marginal relevance): once a
  // sentence is chosen, its terms count only COVERED_FACTOR as much for the remaining candidates, and
  // each sentence already chosen from the same section multiplies a candidate by SECTION_DECAY. The
  // summary therefore covers the document instead of repeating its most frequent topic.
  // Near-duplicates (term Jaccard similarity > 0.8 with a chosen sentence) are never chosen.
  const jaccard = (a, b) => {
    let inter = 0;
    for (const t of a) if (b.has(t)) inter++;
    return inter / (a.size + b.size - inter || 1);
  };
  const covered = new Set();
  const chosen = [];
  while (chosen.length < maxSentences && pool.length) {
    let best = -1;
    let bestAdj = -Infinity;
    for (let k = 0; k < pool.length; k++) {
      const c = pool[k];
      if (chosen.some((x) => jaccard(c.set, x.set) > 0.8)) continue;
      const same = chosen.filter((x) => x.section === c.section).length;
      const adj = c.uniq.reduce((acc, t) => acc + weight(t) * (covered.has(t) ? COVERED_FACTOR : 1), 0) * c.mult * SECTION_DECAY ** same;
      if (adj > bestAdj || (adj === bestAdj && c.i < pool[best].i)) { best = k; bestAdj = adj; }
    }
    if (best < 0) break;
    for (const t of pool[best].uniq) covered.add(t);
    chosen.push(pool[best]);
    pool.splice(best, 1);
  }
  chosen.sort((a, b) => a.i - b.i);
  return { sentences: chosen.map((c) => ({ text: c.text, line: c.line, score: c.score })), count: sents.length };
}

// ---------------------------------------------------------------------------------------------
// Find
// ---------------------------------------------------------------------------------------------
export function parseQuery(q) {
  const terms = [];
  for (const m of q.matchAll(/"([^"]+)"|(\S+)/g)) {
    const t = (m[1] ?? m[2]).trim();
    if (t && !terms.includes(t)) terms.push(t);
  }
  return terms;
}

export function escapeRe(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// ---------------------------------------------------------------------------------------------
// Diff (Myers O(ND), with common prefix/suffix trimming)
// ---------------------------------------------------------------------------------------------
export function myers(a, b, maxD) {
  const n = a.length;
  const m = b.length;
  const max = n + m;
  if (max === 0) return [];
  const off = max + 1;
  const v = new Int32Array(2 * max + 3).fill(-1);
  v[off + 1] = 0;
  const trace = [];
  let done = false;
  for (let d = 0; d <= max && !done; d++) {
    if (d > maxD) return null;
    for (let k = -d; k <= d; k += 2) {
      let x = k === -d || (k !== d && v[off + k - 1] < v[off + k + 1]) ? v[off + k + 1] : v[off + k - 1] + 1;
      let y = x - k;
      while (x < n && y < m && a[x] === b[y]) { x++; y++; }
      v[off + k] = x;
      if (x >= n && y >= m) { done = true; break; }
    }
    trace.push(v.slice(off - d - 1, off + d + 2));
  }
  const ops = [];
  let x = n;
  let y = m;
  for (let d = trace.length - 1; d > 0; d--) {
    const prev = trace[d - 1];
    const at = (kk) => prev[kk + d];
    const k = x - y;
    const prevK = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1;
    const prevX = at(prevK);
    const prevY = prevX - prevK;
    while (x > prevX && y > prevY) { ops.push(["eq", x - 1, y - 1]); x--; y--; }
    if (x === prevX) ops.push(["ins", -1, y - 1]);
    else ops.push(["del", x - 1, -1]);
    x = prevX;
    y = prevY;
  }
  while (x > 0 && y > 0) { ops.push(["eq", x - 1, y - 1]); x--; y--; }
  return ops.reverse();
}

// Word-level changes between two versions of one line: runs of removed/added words, merged.
// Returns null when the lines are too different to pair meaningfully (under 40% words in common).
export function wordChanges(beforeLine, afterLine, { maxWords = 2000, maxChanges = 50 } = {}) {
  const a = beforeLine.split(/\s+/).filter(Boolean);
  const b = afterLine.split(/\s+/).filter(Boolean);
  if (!a.length || !b.length || a.length > maxWords || b.length > maxWords) return null;
  const ids = new Map();
  const intern = (w) => { if (!ids.has(w)) ids.set(w, ids.size); return ids.get(w); };
  const ops = myers(a.map(intern), b.map(intern), 400);
  if (!ops) return null;
  const same = ops.filter((o) => o[0] === "eq").length;
  if ((2 * same) / (a.length + b.length) < 0.4) return null;
  const changes = [];
  let cur = null;
  for (const [t, i, j] of ops) {
    if (t === "eq") { if (cur) changes.push(cur); cur = null; continue; }
    cur ??= { removed: [], added: [] };
    if (t === "del") cur.removed.push(a[i]);
    else cur.added.push(b[j]);
  }
  if (cur) changes.push(cur);
  return changes.slice(0, maxChanges).map((c) => ({ removed: c.removed.join(" "), added: c.added.join(" ") }));
}

export function diffLines(before, after, { ignoreWhitespace = false, maxD = 2500 } = {}) {
  const key = (l) => (ignoreWhitespace ? l.trim().replace(/\s+/g, " ") : l);
  const ids = new Map();
  const intern = (l) => { const k = key(l); if (!ids.has(k)) ids.set(k, ids.size); return ids.get(k); };
  const a = before.map(intern);
  const b = after.map(intern);
  let pre = 0;
  while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
  let suf = 0;
  while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++;
  const midA = a.slice(pre, a.length - suf);
  const midB = b.slice(pre, b.length - suf);
  let mid = myers(midA, midB, maxD);
  let approximate = false;
  if (mid === null) {
    approximate = true;
    mid = [...midA.map((_, i) => ["del", i, -1]), ...midB.map((_, j) => ["ins", -1, j])];
  }
  const ops = [];
  for (let i = 0; i < pre; i++) ops.push(["eq", i, i]);
  for (const [t, i, j] of mid) ops.push([t, i < 0 ? -1 : i + pre, j < 0 ? -1 : j + pre]);
  for (let s = suf; s > 0; s--) ops.push(["eq", a.length - s, b.length - s]);
  return { ops, approximate };
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).