/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/queue/frontier/seeds * * Seed ingestion for the crawl frontier: sitemaps (urlset + sitemapindex), * RSS 2.0 / RSS 1.0 and Atom feeds, and `Sitemap:` lines of robots.txt. * * Parsers are pure string functions (no DOM, no network) that tolerate CDATA, * comments, namespace prefixes, entities and arbitrary whitespace. Network * access and gzip decompression are delegated to the caller's `fetchText`. */ import type { AddRequestOptions, RequestQueue } from "../RequestQueue.ts"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface SitemapUrlEntry { loc: string; /** `lastmod` in ms since epoch, or null when absent/invalid. */ lastmod: number | null; changefreq: string | null; /** `priority` clamped to [0, 1], or null. */ priority: number | null; } export interface SitemapIndexEntry { loc: string; lastmod: number | null; } export interface ParsedSitemap { kind: "urlset" | "sitemapindex" | "unknown"; urls: SitemapUrlEntry[]; sitemaps: SitemapIndexEntry[]; } export interface FeedEntry { url: string; id: string | null; title: string | null; publishedAt: number | null; updatedAt: number | null; } export interface ParsedFeed { kind: "rss" | "atom" | "unknown"; title: string | null; entries: FeedEntry[]; } export interface SeedBoostOptions { now: number; /** Recency half-life. Default: 14 days. */ halfLifeMs?: number; /** Weight of the recency term. Default: 1. */ recencyWeight?: number; /** Weight of the sitemap priority term. Default: 1. */ priorityWeight?: number; /** Recency assumed when no date is known. Default: 0.25. */ unknownRecency?: number; } export interface IngestSeedsOptions { /** Fetch a document as text (decompress `.gz` sitemaps here). */ fetchText: (url: string) => Promise; /** Maximum sitemap / feed documents fetched. Default: 25. */ maxSitemaps?: number; /** Maximum URLs enqueued. Default: 50_000. */ maxUrls?: number; /** Recency half-life for `lastmod` / `pubDate`. Default: 14 days. */ halfLifeMs?: number; /** Reference time. Default: `Date.now()`. */ now?: number; /** Extra sitemap URLs (in addition to robots.txt discovery). */ sitemaps?: string[]; /** Feed URLs (RSS / Atom) to ingest. */ feeds?: string[]; /** Skip robots.txt discovery. Default: false. */ skipRobots?: boolean; /** Keep only URLs accepted by this predicate. */ filter?: (url: string) => boolean; /** Extra `userData` merged into every enqueued request. */ userData?: Record; /** Boost weights (see {@link seedBoost}). */ recencyWeight?: number; priorityWeight?: number; } export interface IngestSeedsResult { sitemapsFetched: number; feedsFetched: number; /** Unique URLs accepted by `filter` that were discovered (at most ~`maxUrls` per document). */ discovered: number; /** Newly inserted requests. */ enqueued: number; errors: string[]; } // --------------------------------------------------------------------------- // XML helpers // --------------------------------------------------------------------------- const CDATA_MARK = "\u0000"; interface ProtectedXml { text: string; cdata: string[]; } /** Replace CDATA sections by placeholders and drop comments / PIs / doctype. */ function protectXml(xml: string): ProtectedXml { const cdata: string[] = []; let text = xml.replace(//g, (_m, body: string) => { cdata.push(body); return `${CDATA_MARK}${cdata.length - 1}${CDATA_MARK}`; }); text = text .replace(//g, "") .replace(/<\?[\s\S]*?\?>/g, "") .replace(/[]*(?:\[[\s\S]*?\])?\s*>/gi, ""); return { text, cdata }; } const NAMED_ENTITIES: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00A0", }; export function decodeXmlEntities(value: string): string { return value.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (match, body: string) => { if (body[0] === "#") { const code = body[1] === "x" || body[1] === "X" ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10); if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) return match; try { return String.fromCodePoint(code); } catch { return match; } } return NAMED_ENTITIES[body.toLowerCase()] ?? match; }); } /** Text content of an element body: CDATA verbatim, entities decoded, tags stripped. */ function textOf(inner: string, cdata: string[]): string { let out = ""; const parts = inner.split(CDATA_MARK); for (let i = 0; i < parts.length; i++) { if (i % 2 === 1) { out += cdata[Number(parts[i])] ?? ""; } else { out += decodeXmlEntities(parts[i].replace(/<[^>]*>/g, "")); } } return out.trim(); } interface XmlElement { prefix: string; attrs: Map; /** Raw inner markup, or "" for self-closing elements. */ inner: string; start: number; end: number; } function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function parseAttributes(raw: string): Map { const attrs = new Map(); const re = /([A-Za-z_][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g; let m: RegExpExecArray | null; while ((m = re.exec(raw)) !== null) { attrs.set(m[1].toLowerCase(), decodeXmlEntities(m[2] ?? m[3] ?? "")); } return attrs; } /** * Iterate elements with a given local name (any namespace prefix, case * insensitive). Nested elements of the same name are not supported, which is * fine for sitemap / feed structures. */ function* elements(xml: string, localName: string): Generator { const open = new RegExp( `<(?:([A-Za-z_][\\w.-]*):)?${escapeRegExp(localName)}(?=[\\s/>])([^>]*)>`, "gi", ); let m: RegExpExecArray | null; while ((m = open.exec(xml)) !== null) { const prefix = m[1] ?? ""; let rawAttrs = m[2] ?? ""; const start = m.index; if (rawAttrs.endsWith("/")) { rawAttrs = rawAttrs.slice(0, -1); yield { prefix, attrs: parseAttributes(rawAttrs), inner: "", start, end: open.lastIndex }; continue; } const qname = prefix ? `${escapeRegExp(prefix)}:${escapeRegExp(localName)}` : escapeRegExp(localName); const close = new RegExp(``, "gi"); close.lastIndex = open.lastIndex; const c = close.exec(xml); const innerEnd = c ? c.index : xml.length; const end = c ? close.lastIndex : xml.length; yield { prefix, attrs: parseAttributes(rawAttrs), inner: xml.slice(open.lastIndex, innerEnd), start, end, }; open.lastIndex = end; } } /** First child element with a local name whose prefix is in `prefixes` (any when omitted). */ function child(inner: string, localName: string, prefixes?: readonly string[]): XmlElement | null { for (const el of elements(inner, localName)) { if (!prefixes || prefixes.includes(el.prefix)) return el; } return null; } function childText( inner: string, localName: string, cdata: string[], prefixes?: readonly string[], ): string | null { const el = child(inner, localName, prefixes); if (!el) return null; const text = textOf(el.inner, cdata); return text === "" ? null : text; } /** Prefix of the first root element among `names`, or null when absent. */ function rootPrefix(xml: string, names: readonly string[]): { name: string; prefix: string } | null { let best: { name: string; prefix: string; index: number } | null = null; for (const name of names) { const m = new RegExp(`<(?:([A-Za-z_][\\w.-]*):)?${name}(?=[\\s/>])`, "i").exec(xml); if (m && (!best || m.index < best.index)) { best = { name, prefix: m[1] ?? "", index: m.index }; } } return best ? { name: best.name, prefix: best.prefix } : null; } export function parseDate(value: string | null | undefined): number | null { if (!value) return null; const trimmed = value.trim(); if (trimmed === "") return null; let ms = Date.parse(trimmed); if (Number.isNaN(ms)) { // RFC 822 variants with named zones JS does not know ("CEST", "BST", ...). ms = Date.parse(trimmed.replace(/\s+[A-Z]{3,5}$/, " GMT")); } return Number.isNaN(ms) ? null : ms; } function resolveUrl(href: string | null | undefined, base?: string | null): string | null { if (!href) return null; const value = href.trim(); if (value === "") return null; try { if (/^[a-z][a-z0-9+.-]*:/i.test(value)) { return URL.canParse(value) ? value : null; } return base ? new URL(value, base).href : null; } catch { return null; } } function isHttpUrl(value: string | null): value is string { return value !== null && /^https?:\/\//i.test(value) && URL.canParse(value); } // --------------------------------------------------------------------------- // Sitemap // --------------------------------------------------------------------------- /** Parse a sitemap (``) or a sitemap index (``). */ export function parseSitemap(xml: string): ParsedSitemap { const { text, cdata } = protectXml(xml); const root = rootPrefix(text, ["urlset", "sitemapindex"]); const result: ParsedSitemap = { kind: "unknown", urls: [], sitemaps: [] }; if (!root) return result; const prefixes = [root.prefix]; if (root.name.toLowerCase() === "sitemapindex") { result.kind = "sitemapindex"; for (const el of elements(text, "sitemap")) { if (el.prefix !== root.prefix) continue; const loc = childText(el.inner, "loc", cdata, prefixes); if (!isHttpUrl(loc)) continue; result.sitemaps.push({ loc, lastmod: parseDate(childText(el.inner, "lastmod", cdata, prefixes)) }); } return result; } result.kind = "urlset"; for (const el of elements(text, "url")) { if (el.prefix !== root.prefix) continue; const loc = childText(el.inner, "loc", cdata, prefixes); if (!isHttpUrl(loc)) continue; const priorityText = childText(el.inner, "priority", cdata, prefixes); const priority = priorityText === null ? Number.NaN : Number.parseFloat(priorityText); const changefreq = childText(el.inner, "changefreq", cdata, prefixes); result.urls.push({ loc, lastmod: parseDate(childText(el.inner, "lastmod", cdata, prefixes)), changefreq: changefreq ? changefreq.toLowerCase() : null, priority: Number.isFinite(priority) ? Math.min(1, Math.max(0, priority)) : null, }); } return result; } // --------------------------------------------------------------------------- // RSS / Atom // --------------------------------------------------------------------------- const ATOM_SKIPPED_BLOCKS = /<(?:[A-Za-z_][\w.-]*:)?(source|author|contributor)(?=[\s>])[\s\S]*?<\/(?:[A-Za-z_][\w.-]*:)?\1\s*>/gi; function pickAtomLink(inner: string, prefix: string, base: string | null): string | null { let fallback: string | null = null; for (const link of elements(inner, "link")) { if (link.prefix !== prefix) continue; const rel = (link.attrs.get("rel") ?? "alternate").trim().toLowerCase(); if (rel !== "alternate") continue; const href = resolveUrl(link.attrs.get("href") ?? textOf(link.inner, []), base); if (!href) continue; const type = (link.attrs.get("type") ?? "").toLowerCase(); if (type === "" || type.includes("html")) return href; fallback ??= href; } return fallback; } /** * Parse an RSS 2.0 / RSS 1.0 (RDF) or Atom feed. Relative links are resolved * against `xml:base` or `baseUrl`. */ export function parseFeed(xml: string, baseUrl?: string): ParsedFeed { const { text, cdata } = protectXml(xml); const root = rootPrefix(text, ["rss", "RDF", "feed"]); const result: ParsedFeed = { kind: "unknown", title: null, entries: [] }; if (!root) return result; if (root.name === "feed") { result.kind = "atom"; const prefix = root.prefix; const feedEl = child(text, "feed", [prefix]); const feedBase = resolveUrl(feedEl?.attrs.get("xml:base"), baseUrl) ?? baseUrl ?? null; const head = feedEl ? feedEl.inner.split(/<(?:[A-Za-z_][\w.-]*:)?entry(?=[\s>])/i)[0] : ""; result.title = childText(head, "title", cdata, [prefix]); for (const entry of elements(text, "entry")) { if (entry.prefix !== prefix) continue; const entryBase = resolveUrl(entry.attrs.get("xml:base"), feedBase) ?? feedBase; const inner = entry.inner.replace(ATOM_SKIPPED_BLOCKS, ""); const id = childText(inner, "id", cdata, [prefix]); const url = pickAtomLink(inner, prefix, entryBase) ?? (isHttpUrl(id) ? id : null); if (!url) continue; result.entries.push({ url, id, title: childText(inner, "title", cdata, [prefix]), publishedAt: parseDate(childText(inner, "published", cdata, [prefix])), updatedAt: parseDate(childText(inner, "updated", cdata, [prefix])), }); } return result; } result.kind = "rss"; const channel = child(text, "channel"); if (channel) { const head = channel.inner.split(/<(?:[A-Za-z_][\w.-]*:)?item(?=[\s>])/i)[0]; result.title = childText(head, "title", cdata, [""]); } for (const item of elements(text, "item")) { const inner = item.inner; let url = resolveUrl(childText(inner, "link", cdata, [""]), baseUrl); const guidEl = child(inner, "guid", [""]); const guid = guidEl ? textOf(guidEl.inner, cdata) || null : null; if (!url && guid && guidEl?.attrs.get("ispermalink")?.trim().toLowerCase() !== "false") { const resolved = resolveUrl(guid, baseUrl); if (isHttpUrl(resolved)) url = resolved; } if (!url) { const atomHref = pickAtomLinkAnyPrefix(inner, baseUrl ?? null); url = atomHref ?? resolveUrl(item.attrs.get("rdf:about"), baseUrl); } if (!url) continue; const published = parseDate(childText(inner, "pubDate", cdata)) ?? parseDate(childText(inner, "date", cdata, ["dc"])) ?? parseDate(childText(inner, "published", cdata)); result.entries.push({ url, id: guid, title: childText(inner, "title", cdata, [""]), publishedAt: published, updatedAt: parseDate(childText(inner, "updated", cdata)) ?? published, }); } return result; } /** `` inside an RSS item. */ function pickAtomLinkAnyPrefix(inner: string, base: string | null): string | null { for (const link of elements(inner, "link")) { if (link.prefix === "") continue; const rel = (link.attrs.get("rel") ?? "alternate").trim().toLowerCase(); if (rel !== "alternate") continue; const href = resolveUrl(link.attrs.get("href"), base); if (href) return href; } return null; } // --------------------------------------------------------------------------- // robots.txt // --------------------------------------------------------------------------- /** `Sitemap:` URLs declared in a robots.txt (deduplicated, in order). */ export function discoverSitemaps(robotsTxt: string, baseUrl?: string): string[] { const out: string[] = []; const seen = new Set(); for (const rawLine of robotsTxt.replace(/^\uFEFF/, "").split(/\r\n|\r|\n/)) { const line = rawLine.replace(/(^|\s)#.*$/, "").trim(); const m = /^site-?map\s*:\s*(\S+)/i.exec(line); if (!m) continue; // Absolute URLs per the protocol; root-relative paths are tolerated. const url = m[1].startsWith("/") ? resolveUrl(m[1], baseUrl) : m[1]; if (!isHttpUrl(url) || seen.has(url)) continue; seen.add(url); out.push(url); } return out; } /** Plain-text sitemap: one absolute URL per line. */ function parseTextSitemap(text: string): string[] { const out: string[] = []; for (const line of text.split(/\r\n|\r|\n/)) { const value = line.trim(); if (isHttpUrl(value)) out.push(value); } return out; } // --------------------------------------------------------------------------- // Ingestion // --------------------------------------------------------------------------- const DAY_MS = 86_400_000; /** * Score prior of a seed: `recencyWeight · 0.5^(age / halfLife) + priorityWeight · priority` * (priority defaults to 0.5, unknown dates use `unknownRecency`). */ export function seedBoost( input: { lastmod: number | null; priority: number | null }, opts: SeedBoostOptions, ): number { const halfLife = opts.halfLifeMs && opts.halfLifeMs > 0 ? opts.halfLifeMs : 14 * DAY_MS; const recency = input.lastmod === null ? (opts.unknownRecency ?? 0.25) : 0.5 ** (Math.max(0, opts.now - input.lastmod) / halfLife); const priority = input.priority === null ? 0.5 : Math.min(1, Math.max(0, input.priority)); return (opts.recencyWeight ?? 1) * recency + (opts.priorityWeight ?? 1) * priority; } interface SeedCandidate { url: string; lastmod: number | null; priority: number | null; source: "sitemap" | "feed"; } /** * Discover seeds for `rootUrl` from robots.txt sitemaps (fallback * `/sitemap.xml`), explicit sitemaps and feeds, follow sitemap indexes * (bounded by `maxSitemaps`, freshest children first) and enqueue the URLs * with a `boost` derived from `lastmod` / `pubDate` recency and sitemap priority. */ export async function ingestSeeds( queue: RequestQueue, rootUrl: string, opts: IngestSeedsOptions, ): Promise { const maxSitemaps = opts.maxSitemaps ?? 25; const maxUrls = opts.maxUrls ?? 50_000; const now = opts.now ?? Date.now(); const result: IngestSeedsResult = { sitemapsFetched: 0, feedsFetched: 0, discovered: 0, enqueued: 0, errors: [], }; let origin: string; try { origin = new URL(rootUrl).origin; } catch { result.errors.push(`invalid root URL: ${rootUrl}`); return result; } const docs: string[] = []; const queued = new Set(); const pushDoc = (url: string | null) => { if (url && !queued.has(url)) { queued.add(url); docs.push(url); } }; for (const feed of opts.feeds ?? []) pushDoc(resolveUrl(feed, origin)); for (const sitemap of opts.sitemaps ?? []) pushDoc(resolveUrl(sitemap, origin)); if (!opts.skipRobots) { try { for (const sitemap of discoverSitemaps(await opts.fetchText(`${origin}/robots.txt`), origin)) { pushDoc(sitemap); } } catch (err) { result.errors.push(`robots.txt: ${err instanceof Error ? err.message : String(err)}`); } } if (docs.length === 0 || (opts.feeds?.length ?? 0) === docs.length) pushDoc(`${origin}/sitemap.xml`); const candidates = new Map(); const addCandidate = (candidate: SeedCandidate) => { if (opts.filter && !opts.filter(candidate.url)) return; const existing = candidates.get(candidate.url); if (!existing) { candidates.set(candidate.url, candidate); return; } if ((candidate.lastmod ?? -1) > (existing.lastmod ?? -1)) existing.lastmod = candidate.lastmod; if ((candidate.priority ?? -1) > (existing.priority ?? -1)) existing.priority = candidate.priority; }; let fetched = 0; while (docs.length > 0 && fetched < maxSitemaps && candidates.size < maxUrls) { const url = docs.shift() as string; let body: string; try { fetched++; body = await opts.fetchText(url); } catch (err) { result.errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`); continue; } if (body.charCodeAt(0) === 0x1f && body.charCodeAt(1) === 0x8b) { result.errors.push(`${url}: gzip payload (decompress in fetchText)`); continue; } const head = body.slice(0, 2048); if (/<(?:[A-Za-z_][\w.-]*:)?(?:rss|RDF|feed)(?=[\s>])/i.test(head) && !/<(?:[A-Za-z_][\w.-]*:)?(?:urlset|sitemapindex)(?=[\s>])/i.test(head)) { result.feedsFetched++; for (const entry of parseFeed(body, url).entries) { addCandidate({ url: entry.url, lastmod: entry.updatedAt ?? entry.publishedAt, priority: null, source: "feed", }); } continue; } result.sitemapsFetched++; const sitemap = parseSitemap(body); if (sitemap.kind === "sitemapindex") { const children = [...sitemap.sitemaps].sort((a, b) => (b.lastmod ?? 0) - (a.lastmod ?? 0)); for (const childMap of children) pushDoc(childMap.loc); } else if (sitemap.kind === "urlset") { for (const entry of sitemap.urls) { addCandidate({ url: entry.loc, lastmod: entry.lastmod, priority: entry.priority, source: "sitemap" }); } } else { for (const line of parseTextSitemap(body)) { addCandidate({ url: line, lastmod: null, priority: null, source: "sitemap" }); } } } result.discovered = candidates.size; const items: Array<{ url: string; opts: AddRequestOptions }> = []; for (const candidate of candidates.values()) { if (items.length >= maxUrls) break; items.push({ url: candidate.url, opts: { depth: 0, boost: seedBoost(candidate, { now, halfLifeMs: opts.halfLifeMs, recencyWeight: opts.recencyWeight, priorityWeight: opts.priorityWeight, }), userData: { ...opts.userData, depth: 0, seedSource: candidate.source, ...(candidate.lastmod !== null ? { lastmod: candidate.lastmod } : {}), }, }, }); } result.enqueued = items.length > 0 ? queue.addRequests(items) : 0; return result; }