src / web / html.ts

import { load } from "cheerio";
import type { AnyNode } from "domhandler";

export interface HtmlBlock {
  id: number; kind: "post" | "section" | "table-row";
  start: number; end: number; startLine: number; endLine: number;
  headingPath: string[]; postNumber?: string; author?: string; date?: string; posterId?: string;
  replyTo: string[]; links: {label: string; url: string}[];
  tableHeaders?: string[];
}
export interface HtmlIndex { version: 1; title: string; url?: string; blocks: HtmlBlock[]; }
export interface HtmlText { text: string; html: HtmlIndex; }
export const escapeHtml = (text: string): string => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const clean = (text: string) => text.replace(/[\t\f\v ]+/g, " ").replace(/ *\n */g, "\n").replace(/\n{3,}/g, "\n\n").trim();

export function extractHtml(source: string, url?: string): HtmlText {
  const $ = load(source);
  const title = clean($("title").first().text()).slice(0, 500);
  $("script,style,noscript,template,nav,aside,form,button,[hidden],[aria-hidden='true'],.advertisement,.ads").remove();
  $("body > header,body > footer").remove();
  const blocks: HtmlBlock[] = [], pieces: string[] = [];
  let length = 0, nextLine = 1;
  const textOf = (element: AnyNode): string => {
    const copy = $(element).clone();
    copy.find("br").replaceWith("\n");
    copy.find("p,div,li,tr,blockquote").append("\n");
    return clean(copy.text());
  };
  const linksOf = (element: AnyNode) => {
    const links: HtmlBlock["links"] = [];
    let budget = 3500;
    const anchors = $(element).is("a[href]") ? $(element) : $(element).find("a[href]");
    anchors.each((_, anchor) => {
      if (links.length >= 20 || budget <= 0) return;
      const href = $(anchor).attr("href")?.trim() ?? "";
      if (!href || /^(?:javascript|data|file|vbscript):/i.test(href)) return;
      let target: string;
      try { const parsed = new URL(href, url); if (!/^https?:$/.test(parsed.protocol)) return; target = parsed.href; }
      catch { if (!/^(?:#|\/|\.\/|\.\.\/)/.test(href)) return; target = href; }
      if (target.length > 2048 || links.some(link => link.url === target)) return;
      const label = clean($(anchor).text()).slice(0, 160);
      if (target.length + label.length > budget) return;
      budget -= target.length + label.length;
      links.push({label, url: target});
    });
    return links;
  };
  const add = (body: string, info: Omit<HtmlBlock, "id" | "start" | "end" | "startLine" | "endLine" | "replyTo">) => {
    const text = clean(body);
    if (!text) return;
    if (blocks.length >= 20000) throw new Error("HTML exceeds 20,000 searchable blocks.");
    if (pieces.length) { pieces.push("\n\n"); length += 2; nextLine += 2; }
    const count = text.split("\n").length;
    blocks.push({...info, id: blocks.length, start: length, end: length + text.length,
      startLine: nextLine, endLine: nextLine + count - 1,
      replyTo: [...new Set([...text.matchAll(/(?:>>|>>)(\d{1,8}(?:-\d{1,8})?)/g)].map(match => match[1]))].slice(0, 50)});
    pieces.push(text); length += text.length; nextLine += count - 1;
  };
  const numberOf = (value: string) => {
    const match = /^(?:post[-_]?)?(\d{1,8})$/i.exec(value.trim());
    return match ? String(Number(match[1])) : undefined;
  };
  const modern = $("article.post,div.post,[data-post-id]").toArray().filter(node => !$(node).parents("article.post,div.post,[data-post-id]").length);
  if (modern.length) {
    for (const element of modern) {
      const post = $(element);
      const field = (selector: string) => clean(post.find(selector).first().text()).slice(0, 256) || undefined;
      const postNumber = numberOf(post.attr("data-post-id") ?? "") ?? numberOf(post.attr("id") ?? "")
        ?? numberOf(field(".number,.postid,.post-number") ?? "");
      const body = post.find(".message,.post-content,.postbody,.post-body").first();
      const author = field(".name,.username,.post-name"), date = field("time,.date,.post-date"), posterId = field(".uid,.poster-id,.post-uid");
      const header = [postNumber ? `[Post ${postNumber}]` : "", author, date, posterId].filter(Boolean).join(" ");
      add(`${header}${header ? "\n" : ""}${textOf((body.length ? body : post)[0])}`, {
        kind: "post", headingPath: [], postNumber, author, date, posterId, links: linksOf(element),
      });
    }
  } else {
    const classic = $("dl dt").toArray().filter(node => /^\s*\d{1,8}\s*[::]/.test($(node).text()) && $(node).next().is("dd"));
    if (classic.length) {
      for (const element of classic) {
        const header = textOf(element), body = $(element).next()[0];
        add(`${header}\n${textOf(body)}`, {kind: "post", headingPath: [],
          postNumber: numberOf(/^\s*(\d{1,8})/.exec(header)?.[1] ?? ""), author: clean($(element).find("b,.name").first().text()).slice(0, 256) || undefined,
          posterId: /\bID:([^\s]+)/.exec(header)?.[1]?.slice(0, 256),
          date: /\d{4}\/\d{1,2}\/\d{1,2}[^\n]*?(?=\sID:|$)/.exec(header)?.[0]?.slice(0, 256), links: linksOf(body)});
      }
    } else {
      const root = $("main").first().length ? $("main").first() : $("article").first().length ? $("article").first() : $("body");
      const headings: string[] = [];
      let pending = "", visited = 0;
      let pendingLinks: HtmlBlock["links"] = [];
      const flush = () => {
        while (pending.length) {
          // Split only at a paragraph boundary, never in the middle of a word.
          // A single long line remains one block and is read with pagination.
          let end = pending.length <= 6000 ? pending.length : pending.lastIndexOf("\n", 6000);
          if (end <= 0) { end = pending.indexOf("\n", 6000); if (end < 0) end = pending.length; }
          const part = pending.slice(0, end); pending = pending.slice(end).replace(/^\n+/, "");
          add(part, {kind: "section", headingPath: headings.filter(Boolean), links: pendingLinks});
        }
        pendingLinks = [];
      };
      const emit = (text: string) => { pending += text; if (pending.length > 12000) flush(); };
      const walk = (node: AnyNode): void => {
        if (++visited > 200000) throw new Error("HTML exceeds 200,000 DOM nodes.");
        if (node.type === "text") { emit(node.data.trim() ? node.data.replace(/\s+/g, " ") : " "); return; }
        if (!("name" in node) || !("children" in node)) return;
        const tag = node.name.toLowerCase();
        if (/^h[1-6]$/.test(tag)) {
          flush(); const depth = Number(tag[1]); headings.length = depth;
          headings[depth - 1] = textOf(node).slice(0, 500); emit(headings[depth - 1] + "\n"); return;
        }
        if (tag === "tr") {
          flush();
          const cells = $(node).children("th,td").toArray().map(textOf);
          const tableHeaders = $(node).closest("table").find("tr").first().children("th").toArray().slice(0,10).map(cell => textOf(cell).slice(0,100));
          add(cells.join(" | "), {kind: "table-row", headingPath: headings.filter(Boolean), links: linksOf(node), tableHeaders}); return;
        }
        if (tag === "pre") { emit("\n" + $(node).text() + "\n"); return; }
        if (tag === "br") { emit("\n"); return; }
        if (tag === "a" && pendingLinks.length < 20) {
          for (const link of linksOf(node)) {
            const cost = pendingLinks.reduce((sum,entry) => sum + entry.url.length + entry.label.length,0) + link.url.length + link.label.length;
            if (cost <= 3500 && !pendingLinks.some(entry => entry.url === link.url)) pendingLinks.push(link);
          }
        }
        const block = /^(?:p|div|li|section|article|blockquote|dt|dd)$/.test(tag);
        if (block && pending && !/\n\s*$/.test(pending)) emit("\n");
        for (const child of node.children ?? []) walk(child);
        if (block && !/\n\s*$/.test(pending)) emit("\n");
      };
      for (const element of root.contents().toArray()) walk(element);
      flush();
    }
  }
  return {text: pieces.join(""), html: {version: 1, title, url, blocks}};
}