src/feed.js
// Minimal, bounded XML reader and RSS 2.0 / RSS 1.0 (RDF) / Atom 1.0 item extractor.
// Feed content is untrusted data: entities other than the XML built-ins (and a few common HTML
// names) are never expanded, DTDs that declare entities are rejected, and size/depth are capped.
import { ToolError } from "./errors.js";
const MAX_NODES = 200000;
const MAX_DEPTH = 64;
const NAMED = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'", nbsp: " ", mdash: "—", ndash: "–", hellip: "…", rsquo: "’", lsquo: "‘", ldquo: "“", rdquo: "”", copy: "©", reg: "®", trade: "™" };
export function decodeEntities(s) {
return String(s).replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (m, body) => {
if (body[0] === "#") {
const cp = body[1] === "x" || body[1] === "X" ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10);
if (!Number.isFinite(cp) || cp <= 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) return "";
return String.fromCodePoint(cp);
}
return NAMED[body.toLowerCase()] ?? m;
});
}
function parseAttrs(s) {
const attrs = {};
const re = /([^\s=/]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
let m;
while ((m = re.exec(s))) attrs[m[1]] = decodeEntities(m[3] ?? m[4] ?? "");
return attrs;
}
/** Parses XML into {name, attrs, children} elements; text children are strings. Tolerant of minor errors. */
export function parseXml(src) {
const s = String(src);
const root = { name: "#document", attrs: {}, children: [] };
const stack = [root];
let nodes = 0;
let i = 0;
const addText = (t) => {
if (t) stack[stack.length - 1].children.push(t);
};
while (i < s.length) {
const lt = s.indexOf("<", i);
if (lt < 0) {
addText(decodeEntities(s.slice(i)));
break;
}
if (lt > i) addText(decodeEntities(s.slice(i, lt)));
if (s.startsWith("<!--", lt)) {
const e = s.indexOf("-->", lt + 4);
i = e < 0 ? s.length : e + 3;
continue;
}
if (s.startsWith("<![CDATA[", lt)) {
const e = s.indexOf("]]>", lt + 9);
addText(s.slice(lt + 9, e < 0 ? s.length : e));
i = e < 0 ? s.length : e + 3;
continue;
}
if (s.startsWith("<?", lt)) {
const e = s.indexOf("?>", lt + 2);
i = e < 0 ? s.length : e + 2;
continue;
}
if (s.startsWith("<!", lt)) {
let e = s.indexOf(">", lt);
const br = s.indexOf("[", lt);
if (br >= 0 && (e < 0 || br < e)) {
const close = s.indexOf("]", br);
e = close < 0 ? -1 : s.indexOf(">", close);
}
const decl = s.slice(lt, e < 0 ? s.length : e + 1);
if (/<!ENTITY/i.test(decl)) throw new ToolError("unsafe_xml", "Feed declares XML entities in a DTD; refusing to parse it (entity expansion attacks).");
i = e < 0 ? s.length : e + 1;
continue;
}
if (s[lt + 1] === "/") {
const e = s.indexOf(">", lt);
const name = s.slice(lt + 2, e < 0 ? s.length : e).trim();
for (let k = stack.length - 1; k > 0; k--) {
if (stack[k].name === name) {
stack.length = k;
break;
}
}
i = e < 0 ? s.length : e + 1;
continue;
}
let j = lt + 1;
let quote = null;
for (; j < s.length; j++) {
const c = s[j];
if (quote) {
if (c === quote) quote = null;
} else if (c === '"' || c === "'") quote = c;
else if (c === ">") break;
}
const inner = s.slice(lt + 1, j);
const selfClose = inner.endsWith("/");
const body = selfClose ? inner.slice(0, -1) : inner;
const nm = /^([A-Za-z_][\w.:-]*)/.exec(body);
if (!nm) {
addText("<");
i = lt + 1;
continue;
}
if (++nodes > MAX_NODES) throw new ToolError("too_large", `Feed has more than ${MAX_NODES} XML elements.`);
const el = { name: nm[1], attrs: parseAttrs(body.slice(nm[1].length)), children: [] };
stack[stack.length - 1].children.push(el);
if (!selfClose) {
stack.push(el);
if (stack.length > MAX_DEPTH) throw new ToolError("too_large", "Feed XML is nested too deeply.");
}
i = j + 1;
}
return root;
}
const local = (name) => name.slice(name.lastIndexOf(":") + 1).toLowerCase();
const elements = (el) => el.children.filter((c) => typeof c === "object");
const child = (el, n) => elements(el).find((c) => local(c.name) === n);
const childrenNamed = (el, n) => elements(el).filter((c) => local(c.name) === n);
export function textOf(el) {
if (!el) return "";
return el.children.map((c) => (typeof c === "string" ? c : textOf(c))).join("");
}
export function stripHtml(html) {
return decodeEntities(
String(html)
.replace(/<(script|style)[\s\S]*?<\/\1\s*>/gi, " ")
.replace(/<br\s*\/?>/gi, " ")
.replace(/<\/(p|div|li|h[1-6])>/gi, ". ")
.replace(/<[^>]*>/g, " "),
)
.replace(/\s+/g, " ")
.replace(/(\.\s*){2,}/g, ". ")
.trim();
}
// Titles are plain text in RSS but often carry a few inline HTML tags; strip only those, so a
// literal title such as "Rust <edition> notes" survives.
const INLINE_TAG_RE = /<\/?(?:a|b|i|em|strong|span|code|sup|sub|br|p|div|mark|small|u|s|abbr|cite|q|time|font)(?=[\s/>])[^>]*>/gi;
export function stripTitleHtml(s) {
return decodeEntities(String(s).replace(INLINE_TAG_RE, ""))
.replace(/\s+/g, " ")
.trim();
}
function clipText(s, n) {
if (s.length <= n) return s;
const cut = s.slice(0, n);
const sp = cut.lastIndexOf(" ");
return `${cut.slice(0, sp > n * 0.6 ? sp : n)}…`;
}
export function safeHttpUrl(raw, base) {
if (typeof raw !== "string" || !raw.trim()) return null;
try {
const u = base ? new URL(raw.trim(), base) : new URL(raw.trim());
if (u.protocol !== "https:" && u.protocol !== "http:") return null;
if (u.username || u.password) return null;
return u.toString();
} catch {
return null;
}
}
function isoDate(raw) {
const t = String(raw ?? "").trim();
if (!t) return null;
const ms = Date.parse(t);
return Number.isNaN(ms) ? null : new Date(ms).toISOString();
}
/**
* Extracts source_list items from feed XML. Returns { format, title, items, skipped }.
* Throws not_a_feed when the document is HTML or not RSS/Atom.
*/
export function parseFeed(xml, { feedUrl, maxItems = 500, excerptChars = 600 } = {}) {
const head = String(xml).slice(0, 2000).toLowerCase();
if (/<!doctype html|<html[\s>]/.test(head)) throw new ToolError("not_a_feed", "This is an HTML page, not an RSS/Atom feed. HTML pages are not scraped.");
const doc = parseXml(xml);
const top = elements(doc)[0];
if (!top) throw new ToolError("not_a_feed", "No XML root element found.");
const rootName = local(top.name);
let format;
let feedTitle = "";
let entries;
if (rootName === "rss") {
format = "rss2";
const channel = child(top, "channel") ?? top;
feedTitle = textOf(child(channel, "title")).trim();
entries = [...childrenNamed(channel, "item"), ...childrenNamed(top, "item")];
} else if (rootName === "rdf") {
format = "rss1";
feedTitle = textOf(child(child(top, "channel") ?? top, "title")).trim();
entries = childrenNamed(top, "item");
} else if (rootName === "feed") {
format = "atom";
feedTitle = textOf(child(top, "title")).trim();
entries = childrenNamed(top, "entry");
} else {
throw new ToolError("not_a_feed", `Root element <${top.name.slice(0, 40)}> is not rss, rdf:RDF or feed.`);
}
const items = [];
let skipped = 0;
for (const e of entries.slice(0, maxItems)) {
let url = null;
let published = null;
let excerptRaw = "";
const title = stripTitleHtml(textOf(child(e, "title"))).slice(0, 500);
if (format === "atom") {
const links = childrenNamed(e, "link");
const alt = links.find((l) => !l.attrs.rel || l.attrs.rel === "alternate") ?? links[0];
url = safeHttpUrl(alt?.attrs.href, feedUrl) ?? safeHttpUrl(textOf(child(e, "id")).trim());
published = isoDate(textOf(child(e, "published"))) ?? isoDate(textOf(child(e, "updated")));
excerptRaw = textOf(child(e, "summary")) || textOf(child(e, "content"));
} else {
const plainLink = elements(e).find((c) => c.name.toLowerCase() === "link");
url = safeHttpUrl(textOf(plainLink).trim(), feedUrl);
if (!url) {
const guid = child(e, "guid");
if (guid && guid.attrs.isPermaLink !== "false") url = safeHttpUrl(textOf(guid).trim(), feedUrl);
}
if (!url) url = safeHttpUrl(childrenNamed(e, "link").find((l) => l.attrs.href)?.attrs.href, feedUrl);
published = isoDate(textOf(child(e, "pubdate"))) ?? isoDate(textOf(child(e, "date"))) ?? isoDate(textOf(child(e, "published")));
excerptRaw = textOf(child(e, "description")) || textOf(child(e, "encoded")) || textOf(child(e, "summary"));
}
if (!url) {
skipped++;
continue;
}
const item = { url, title: title || url };
if (published) item.published_at = published;
const excerpt = clipText(stripHtml(excerptRaw), excerptChars);
if (excerpt) item.excerpt = excerpt;
if (feedTitle) item.source_name = stripHtml(feedTitle).slice(0, 200);
if (feedUrl) item.feed_url = feedUrl;
items.push(item);
}
if (entries.length > maxItems) skipped += entries.length - maxItems;
return { format, title: feedTitle, items, skipped };
}