feat(writer-pipeline): multi-source ingest (RSS, sitemap, HTML) for BIT-711
- Add ingest-sources with retries, sitemap index/urlset parsing, and HTML meta extraction - Preserve original article URLs in store; dedupe ids via canonical URL hash - Extend andebol.net.sources.json: FPA, IHF RSS, Handball Planet, Eurohandball sitemap (filtered) - Optional shortlist ?topic= query; strip common tracking query params in canonicalUrl - Add npm test (node:test) for sitemap and html-meta helpers Paperclip-Agent: Tiago Neves (urlKey tiago-neves; id 5d084b36-f38f-42a5-a92a-520005afda4f) Paperclip-Issue: BIT-711 Paperclip-Run: 83b79f64-d6b6-4efd-ab06-c5cc7d687169 Made-with: Cursor
This commit is contained in:
1 parent
f18e1f9fed
commit
512ab3bca6
13 files changed
+598
-104
No files matched your search
@@ -1,11 +1,39 @@
|
||||
{
|
||||
"site": "andebol.net",
|
||||
"feeds": [
|
||||
"sources": [
|
||||
{
|
||||
"id": "fpa_portal_main",
|
||||
"kind": "rss",
|
||||
"url": "https://portal.fpa.pt/feed/",
|
||||
"enabled": true,
|
||||
"note": "FPA portal WordPress main feed (category /noticias/feed is empty). Add more feeds as needed; failures are skipped per source."
|
||||
"topics": ["handball", "pt", "fpa"],
|
||||
"note": "FPA portal WordPress main feed."
|
||||
},
|
||||
{
|
||||
"id": "ihf_rss",
|
||||
"kind": "rss",
|
||||
"url": "https://www.ihf.info/rss.xml",
|
||||
"enabled": true,
|
||||
"topics": ["handball", "ihf", "international"],
|
||||
"note": "IHF official RSS (verified 200)."
|
||||
},
|
||||
{
|
||||
"id": "handball_planet",
|
||||
"kind": "rss",
|
||||
"url": "https://www.handball-planet.com/feed/",
|
||||
"enabled": true,
|
||||
"topics": ["handball", "media"],
|
||||
"note": "Handball Planet WordPress feed (use www host — redirect stable)."
|
||||
},
|
||||
{
|
||||
"id": "eurohandball_sitemap",
|
||||
"kind": "sitemap",
|
||||
"url": "https://www.eurohandball.com/sitemap.xml",
|
||||
"enabled": true,
|
||||
"topics": ["handball", "ehf"],
|
||||
"maxItems": 25,
|
||||
"pathIncludes": ["/competitions/", "/news/", "/calendar/", "/match-center/"],
|
||||
"note": "EHF/Eurohandball: main sitemap is huge; path filter skips /club/ noise; pages fetched for title/summary (no LLM)."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "npm run build && node --test dist/*.test.js",
|
||||
"aggregator": "node dist/aggregator-server.js",
|
||||
"aggregator:dev": "tsx src/aggregator-server.ts",
|
||||
"cycle": "node dist/run-cycle.js",
|
||||
|
||||
@@ -20,13 +20,14 @@ async function buildServer() {
|
||||
app.get('/health', async () => ({ ok: true, storePath }));
|
||||
|
||||
app.get<{
|
||||
Querystring: { site?: string; limit?: string };
|
||||
Querystring: { site?: string; limit?: string; topic?: string };
|
||||
}>('/shortlist', async (req) => {
|
||||
const site = req.query.site ?? 'andebol.net';
|
||||
const limit = Math.min(50, Math.max(1, parseInt(req.query.limit ?? '10', 10)));
|
||||
const topic = req.query.topic?.trim() || undefined;
|
||||
const store = await loadStore(storePath);
|
||||
const items = shortlist(store, site, limit);
|
||||
return { site, limit, count: items.length, items };
|
||||
const items = shortlist(store, site, limit, topic);
|
||||
return { site, limit, topic: topic ?? null, count: items.length, items };
|
||||
});
|
||||
|
||||
app.post<{
|
||||
|
||||
@@ -4,8 +4,11 @@ import type { SiteSourcesConfig } from './types.js';
|
||||
export async function readSourcesConfig(filePath: string): Promise<SiteSourcesConfig> {
|
||||
const raw = await readFile(filePath, 'utf8');
|
||||
const data = JSON.parse(raw) as SiteSourcesConfig;
|
||||
if (!data?.site || !Array.isArray(data.feeds)) {
|
||||
throw new Error(`Invalid sources config: ${filePath}`);
|
||||
if (!data?.site) throw new Error(`Invalid sources config (missing site): ${filePath}`);
|
||||
const hasSources = Array.isArray(data.sources) && data.sources.length > 0;
|
||||
const hasFeeds = Array.isArray(data.feeds) && data.feeds.length > 0;
|
||||
if (!hasSources && !hasFeeds) {
|
||||
throw new Error(`Invalid sources config: need non-empty sources or feeds (${filePath})`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractTitleAndSummary } from './html-meta.js';
|
||||
|
||||
test('extractTitleAndSummary prefers og tags', () => {
|
||||
const html = `<!doctype html><html><head>
|
||||
<meta property="og:title" content="OG & Title" />
|
||||
<meta property="og:description" content="Hello world" />
|
||||
<title>Ignore me</title>
|
||||
</head></html>`;
|
||||
const r = extractTitleAndSummary(html);
|
||||
assert.equal(r.title, 'OG & Title');
|
||||
assert.ok(r.summary.includes('Hello world'));
|
||||
});
|
||||
|
||||
test('extractTitleAndSummary falls back to title and meta description', () => {
|
||||
const html = `<html><head>
|
||||
<title>Plain title</title>
|
||||
<meta name="description" content="Desc here" />
|
||||
</head></html>`;
|
||||
const r = extractTitleAndSummary(html);
|
||||
assert.equal(r.title, 'Plain title');
|
||||
assert.ok(r.summary.includes('Desc here'));
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Lightweight title/description extraction (no DOM / cheerio).
|
||||
*/
|
||||
export function extractTitleAndSummary(html: string): { title: string; summary: string } {
|
||||
const ogTitle = matchOne(
|
||||
html,
|
||||
/<meta\s+[^>]*property=["']og:title["'][^>]*content=["']([^"']*)["']/i,
|
||||
);
|
||||
const ogDesc = matchOne(
|
||||
html,
|
||||
/<meta\s+[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i,
|
||||
);
|
||||
const metaDesc = matchOne(
|
||||
html,
|
||||
/<meta\s+[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i,
|
||||
);
|
||||
const titleTag = matchOne(html, /<title[^>]*>([\s\S]*?)<\/title>/i);
|
||||
const title = decodeEntities(stripTags(ogTitle || titleTag || '')).trim() || 'Sem título';
|
||||
const summary = decodeEntities(stripTags(ogDesc || metaDesc || ''))
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 2000);
|
||||
return { title, summary };
|
||||
}
|
||||
|
||||
function matchOne(html: string, re: RegExp): string {
|
||||
const m = re.exec(html);
|
||||
return m?.[1] ? m[1] : '';
|
||||
}
|
||||
|
||||
function stripTags(s: string): string {
|
||||
return s.replace(/<[^>]+>/g, ' ');
|
||||
}
|
||||
|
||||
function decodeEntities(s: string): string {
|
||||
return s
|
||||
.replace(/ /gi, ' ')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
const DEFAULT_UA = 'BitReport-news-writer-pipeline/1.0';
|
||||
|
||||
export interface FetchTextOptions {
|
||||
timeoutMs?: number;
|
||||
retries?: number;
|
||||
userAgent?: string;
|
||||
accept?: string;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* GET url as text with bounded retries (transient network / 5xx).
|
||||
*/
|
||||
export async function fetchTextWithRetry(
|
||||
url: string,
|
||||
opts: FetchTextOptions = {},
|
||||
): Promise<string> {
|
||||
const timeoutMs = opts.timeoutMs ?? 15000;
|
||||
const retries = Math.max(0, opts.retries ?? 2);
|
||||
const ua = opts.userAgent ?? DEFAULT_UA;
|
||||
const accept = opts.accept ?? '*/*';
|
||||
let lastErr: unknown;
|
||||
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
redirect: 'follow',
|
||||
headers: { 'User-Agent': ua, Accept: accept },
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (res.status >= 500 && attempt < retries) {
|
||||
await sleep(400 * (attempt + 1));
|
||||
continue;
|
||||
}
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return await res.text();
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
if (attempt < retries) await sleep(500 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import Parser from 'rss-parser';
|
||||
import type { AggregatedItem, IngestSource, SiteSourcesConfig, SourceKind, StoreFile } from './types.js';
|
||||
import { canonicalUrl, itemId, upsertItem } from './store.js';
|
||||
import { fetchTextWithRetry } from './http-retry.js';
|
||||
import { extractTitleAndSummary } from './html-meta.js';
|
||||
import {
|
||||
isSitemapIndexXml,
|
||||
parseLooseLocs,
|
||||
parseSitemapIndexLocs,
|
||||
parseUrlsetEntries,
|
||||
type SitemapUrlEntry,
|
||||
} from './sitemap-parse.js';
|
||||
|
||||
const parser = new Parser();
|
||||
|
||||
const SITEMAP_MAX_CHILD_SITEMAPS = 10;
|
||||
const SITEMAP_LOOSE_CAP = 250;
|
||||
|
||||
export interface IngestResult {
|
||||
store: StoreFile;
|
||||
attempted: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
newItems: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/** Resolve config path for a site key (e.g. andebol.net). */
|
||||
export function sourcesConfigPath(site: string, configDir: string): string {
|
||||
return `${configDir}/${site}.sources.json`;
|
||||
}
|
||||
|
||||
function normalizeSources(config: SiteSourcesConfig): IngestSource[] {
|
||||
if (config.sources?.length) return config.sources;
|
||||
const feeds = config.feeds ?? [];
|
||||
return feeds.map((f) => ({
|
||||
id: f.id,
|
||||
kind: 'rss' as const,
|
||||
url: f.url,
|
||||
enabled: f.enabled,
|
||||
note: f.note,
|
||||
}));
|
||||
}
|
||||
|
||||
function pickSummary(entry: { contentSnippet?: string; content?: string; summary?: string }): string {
|
||||
const s = entry.contentSnippet || entry.summary || '';
|
||||
if (s) return s.replace(/\s+/g, ' ').trim().slice(0, 2000);
|
||||
const c = entry.content || '';
|
||||
return c.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 2000);
|
||||
}
|
||||
|
||||
function publishedFromLastmod(lastmod: string | undefined, fallback: string): string {
|
||||
if (!lastmod) return fallback;
|
||||
const d = new Date(lastmod);
|
||||
if (Number.isNaN(d.getTime())) return fallback;
|
||||
return d.toISOString();
|
||||
}
|
||||
|
||||
async function parseFeedUrl(url: string, timeoutMs: number, retries: number) {
|
||||
const xml = await fetchTextWithRetry(url, {
|
||||
timeoutMs,
|
||||
retries,
|
||||
accept: 'application/rss+xml, application/xml, text/xml, */*',
|
||||
});
|
||||
return parser.parseString(xml);
|
||||
}
|
||||
|
||||
function filterByPath(entries: SitemapUrlEntry[], pathIncludes?: string[]): SitemapUrlEntry[] {
|
||||
if (!pathIncludes?.length) return entries;
|
||||
return entries.filter((e) => {
|
||||
try {
|
||||
const p = new URL(e.loc).pathname;
|
||||
return pathIncludes.some((frag) => p.includes(frag));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function sortByLastmodDesc(entries: SitemapUrlEntry[]): SitemapUrlEntry[] {
|
||||
return [...entries].sort((a, b) => {
|
||||
const ta = a.lastmod ? Date.parse(a.lastmod) : 0;
|
||||
const tb = b.lastmod ? Date.parse(b.lastmod) : 0;
|
||||
return tb - ta;
|
||||
});
|
||||
}
|
||||
|
||||
async function collectSitemapEntries(rootUrl: string, source: IngestSource): Promise<SitemapUrlEntry[]> {
|
||||
const timeoutMs = source.timeoutMs ?? 20000;
|
||||
const retries = source.retries ?? 2;
|
||||
const xml = await fetchTextWithRetry(rootUrl, {
|
||||
timeoutMs,
|
||||
retries,
|
||||
accept: 'application/xml, text/xml, */*',
|
||||
});
|
||||
|
||||
if (isSitemapIndexXml(xml)) {
|
||||
const children = parseSitemapIndexLocs(xml).slice(0, SITEMAP_MAX_CHILD_SITEMAPS);
|
||||
const merged: SitemapUrlEntry[] = [];
|
||||
for (const childUrl of children) {
|
||||
try {
|
||||
const childXml = await fetchTextWithRetry(childUrl, {
|
||||
timeoutMs,
|
||||
retries,
|
||||
accept: 'application/xml, text/xml, */*',
|
||||
});
|
||||
let entries = parseUrlsetEntries(childXml);
|
||||
if (!entries.length) {
|
||||
const loose = parseLooseLocs(childXml);
|
||||
entries = loose.map((loc) => ({ loc }));
|
||||
}
|
||||
merged.push(...entries);
|
||||
} catch {
|
||||
/* child failure: continue */
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
let entries = parseUrlsetEntries(xml);
|
||||
if (!entries.length) {
|
||||
const loose = parseLooseLocs(xml);
|
||||
entries = loose.slice(0, SITEMAP_LOOSE_CAP).map((loc) => ({ loc }));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function buildItem(
|
||||
storeSite: string,
|
||||
source: IngestSource,
|
||||
originalUrl: string,
|
||||
title: string,
|
||||
summary: string,
|
||||
publishedAt: string,
|
||||
now: string,
|
||||
kind: SourceKind,
|
||||
): AggregatedItem {
|
||||
const trimmed = originalUrl.trim();
|
||||
const id = itemId(canonicalUrl(trimmed));
|
||||
return {
|
||||
id,
|
||||
site: storeSite,
|
||||
sourceFeedId: source.id,
|
||||
url: trimmed,
|
||||
sourceKind: kind,
|
||||
topics: source.topics?.length ? [...source.topics] : undefined,
|
||||
title,
|
||||
summary,
|
||||
publishedAt,
|
||||
ingestedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
export async function ingestAllSources(
|
||||
store: StoreFile,
|
||||
config: SiteSourcesConfig,
|
||||
): Promise<IngestResult> {
|
||||
const errors: string[] = [];
|
||||
let current = store;
|
||||
let attempted = 0;
|
||||
let succeeded = 0;
|
||||
let failed = 0;
|
||||
let newItems = 0;
|
||||
const now = new Date().toISOString();
|
||||
const sources = normalizeSources(config);
|
||||
|
||||
for (const source of sources) {
|
||||
if (!source.enabled) continue;
|
||||
const kind = source.kind;
|
||||
const timeoutMs = source.timeoutMs ?? (kind === 'sitemap' ? 20000 : 15000);
|
||||
const retries = source.retries ?? 2;
|
||||
|
||||
if (kind === 'rss') {
|
||||
attempted += 1;
|
||||
try {
|
||||
const parsed = await parseFeedUrl(source.url, timeoutMs, retries);
|
||||
succeeded += 1;
|
||||
const items = parsed.items ?? [];
|
||||
for (const entry of items) {
|
||||
const link = entry.link?.trim();
|
||||
if (!link) continue;
|
||||
const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim();
|
||||
const summary = pickSummary(entry);
|
||||
const publishedAt = entry.isoDate || entry.pubDate || entry.date || now;
|
||||
const item = buildItem(
|
||||
config.site,
|
||||
source,
|
||||
link,
|
||||
title,
|
||||
summary,
|
||||
publishedAt,
|
||||
now,
|
||||
'rss',
|
||||
);
|
||||
const { store: next, isNew } = upsertItem(current, item);
|
||||
current = next;
|
||||
if (isNew) newItems += 1;
|
||||
}
|
||||
} catch (e) {
|
||||
failed += 1;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(`rss ${source.id} (${source.url}): ${msg}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (kind === 'html_fetch') {
|
||||
attempted += 1;
|
||||
try {
|
||||
const html = await fetchTextWithRetry(source.url, {
|
||||
timeoutMs,
|
||||
retries,
|
||||
accept: 'text/html, application/xhtml+xml, */*',
|
||||
});
|
||||
succeeded += 1;
|
||||
const { title, summary } = extractTitleAndSummary(html);
|
||||
const item = buildItem(
|
||||
config.site,
|
||||
source,
|
||||
source.url,
|
||||
title,
|
||||
summary || '(sem resumo)',
|
||||
now,
|
||||
now,
|
||||
'html_fetch',
|
||||
);
|
||||
const { store: next, isNew } = upsertItem(current, item);
|
||||
current = next;
|
||||
if (isNew) newItems += 1;
|
||||
} catch (e) {
|
||||
failed += 1;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(`html_fetch ${source.id} (${source.url}): ${msg}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (kind === 'sitemap') {
|
||||
attempted += 1;
|
||||
try {
|
||||
let entries = await collectSitemapEntries(source.url, source);
|
||||
entries = filterByPath(entries, source.pathIncludes);
|
||||
entries = sortByLastmodDesc(entries);
|
||||
const maxItems = source.maxItems ?? 30;
|
||||
if (!source.pathIncludes?.length && entries.length > 200) {
|
||||
errors.push(
|
||||
`sitemap ${source.id}: no pathIncludes and ${entries.length} URLs — truncating to 200 before maxItems`,
|
||||
);
|
||||
entries = entries.slice(0, 200);
|
||||
}
|
||||
const slice = entries.slice(0, maxItems);
|
||||
if (!slice.length) {
|
||||
succeeded += 1;
|
||||
errors.push(`sitemap ${source.id}: no URLs after filters`);
|
||||
continue;
|
||||
}
|
||||
let ok = 0;
|
||||
for (const entry of slice) {
|
||||
try {
|
||||
const html = await fetchTextWithRetry(entry.loc, {
|
||||
timeoutMs,
|
||||
retries,
|
||||
accept: 'text/html, application/xhtml+xml, */*',
|
||||
});
|
||||
const { title, summary } = extractTitleAndSummary(html);
|
||||
const publishedAt = publishedFromLastmod(entry.lastmod, now);
|
||||
const item = buildItem(
|
||||
config.site,
|
||||
source,
|
||||
entry.loc,
|
||||
title,
|
||||
summary || '(sem resumo)',
|
||||
publishedAt,
|
||||
now,
|
||||
'sitemap',
|
||||
);
|
||||
const { store: next, isNew } = upsertItem(current, item);
|
||||
current = next;
|
||||
if (isNew) newItems += 1;
|
||||
ok += 1;
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(`sitemap ${source.id} page (${entry.loc}): ${msg}`);
|
||||
}
|
||||
}
|
||||
if (ok > 0) succeeded += 1;
|
||||
else failed += 1;
|
||||
} catch (e) {
|
||||
failed += 1;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(`sitemap ${source.id} (${source.url}): ${msg}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { store: current, attempted, succeeded, failed, newItems, errors };
|
||||
}
|
||||
|
||||
/** @deprecated Use ingestAllSources */
|
||||
export async function ingestSiteFeeds(
|
||||
store: StoreFile,
|
||||
config: SiteSourcesConfig,
|
||||
): Promise<IngestResult> {
|
||||
return ingestAllSources(store, config);
|
||||
}
|
||||
@@ -1,93 +1,9 @@
|
||||
import Parser from 'rss-parser';
|
||||
import type { AggregatedItem, SiteSourcesConfig, StoreFile } from './types.js';
|
||||
import { canonicalUrl, itemId, upsertItem } from './store.js';
|
||||
|
||||
const parser = new Parser();
|
||||
|
||||
async function parseFeedUrl(url: string) {
|
||||
const res = await fetch(url, {
|
||||
redirect: 'follow',
|
||||
headers: {
|
||||
'User-Agent': 'BitReport-news-writer-pipeline/1.0',
|
||||
Accept: 'application/rss+xml, application/xml, text/xml, */*',
|
||||
},
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const xml = await res.text();
|
||||
return parser.parseString(xml);
|
||||
}
|
||||
|
||||
function pickSummary(entry: { contentSnippet?: string; content?: string; summary?: string }): string {
|
||||
const s = entry.contentSnippet || entry.summary || '';
|
||||
if (s) return s.replace(/\s+/g, ' ').trim().slice(0, 2000);
|
||||
const c = entry.content || '';
|
||||
return c.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 2000);
|
||||
}
|
||||
|
||||
export interface IngestResult {
|
||||
store: StoreFile;
|
||||
attempted: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
newItems: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export async function ingestSiteFeeds(
|
||||
store: StoreFile,
|
||||
config: SiteSourcesConfig,
|
||||
): Promise<IngestResult> {
|
||||
const errors: string[] = [];
|
||||
let current = store;
|
||||
let attempted = 0;
|
||||
let succeeded = 0;
|
||||
let failed = 0;
|
||||
let newItems = 0;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
for (const feed of config.feeds) {
|
||||
if (!feed.enabled) continue;
|
||||
attempted += 1;
|
||||
try {
|
||||
const parsed = await parseFeedUrl(feed.url);
|
||||
succeeded += 1;
|
||||
const items = parsed.items ?? [];
|
||||
for (const entry of items) {
|
||||
const link = entry.link?.trim();
|
||||
if (!link) continue;
|
||||
const url = canonicalUrl(link);
|
||||
const id = itemId(url);
|
||||
const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim();
|
||||
const summary = pickSummary(entry);
|
||||
const publishedAt =
|
||||
entry.isoDate || entry.pubDate || entry.date || now;
|
||||
|
||||
const agg: AggregatedItem = {
|
||||
id,
|
||||
site: config.site,
|
||||
sourceFeedId: feed.id,
|
||||
url,
|
||||
title,
|
||||
summary,
|
||||
publishedAt,
|
||||
ingestedAt: now,
|
||||
};
|
||||
const { store: next, isNew } = upsertItem(current, agg);
|
||||
current = next;
|
||||
if (isNew) newItems += 1;
|
||||
}
|
||||
} catch (e) {
|
||||
failed += 1;
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(`feed ${feed.id} (${feed.url}): ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { store: current, attempted, succeeded, failed, newItems, errors };
|
||||
}
|
||||
|
||||
/** Resolve config path for a site key (e.g. andebol.net). */
|
||||
export function sourcesConfigPath(site: string, configDir: string): string {
|
||||
return `${configDir}/${site}.sources.json`;
|
||||
}
|
||||
/**
|
||||
* Compatibility re-exports — implementation lives in ingest-sources.ts (BIT-711).
|
||||
*/
|
||||
export {
|
||||
ingestAllSources,
|
||||
ingestSiteFeeds,
|
||||
sourcesConfigPath,
|
||||
} from './ingest-sources.js';
|
||||
export type { IngestResult } from './ingest-sources.js';
|
||||
@@ -0,0 +1,38 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
isSitemapIndexXml,
|
||||
parseSitemapIndexLocs,
|
||||
parseUrlsetEntries,
|
||||
parseLooseLocs,
|
||||
} from './sitemap-parse.js';
|
||||
|
||||
test('parseUrlsetEntries pairs loc and lastmod', () => {
|
||||
const xml = `<?xml version="1.0"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>https://ex.com/a</loc><lastmod>2026-01-02</lastmod></url>
|
||||
<url><loc>https://ex.com/b</loc></url>
|
||||
</urlset>`;
|
||||
const e = parseUrlsetEntries(xml);
|
||||
assert.equal(e.length, 2);
|
||||
assert.equal(e[0].loc, 'https://ex.com/a');
|
||||
assert.equal(e[0].lastmod, '2026-01-02');
|
||||
assert.equal(e[1].loc, 'https://ex.com/b');
|
||||
assert.equal(e[1].lastmod, undefined);
|
||||
});
|
||||
|
||||
test('isSitemapIndexXml detects index', () => {
|
||||
assert.equal(isSitemapIndexXml('<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'), true);
|
||||
assert.equal(isSitemapIndexXml('<urlset>'), false);
|
||||
});
|
||||
|
||||
test('parseSitemapIndexLocs reads child sitemaps', () => {
|
||||
const xml = `<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<sitemap><loc>https://ex.com/news.xml</loc></sitemap>
|
||||
</sitemapindex>`;
|
||||
assert.deepEqual(parseSitemapIndexLocs(xml), ['https://ex.com/news.xml']);
|
||||
});
|
||||
|
||||
test('parseLooseLocs finds bare loc tags', () => {
|
||||
const xml = `<foo><loc>https://ex.com/x</loc></foo>`;
|
||||
assert.deepEqual(parseLooseLocs(xml), ['https://ex.com/x']);
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
export interface SitemapUrlEntry {
|
||||
loc: string;
|
||||
lastmod?: string;
|
||||
}
|
||||
|
||||
export function isSitemapIndexXml(xml: string): boolean {
|
||||
return /<sitemapindex\b/i.test(xml);
|
||||
}
|
||||
|
||||
/** Child sitemap URLs from a sitemap index document. */
|
||||
export function parseSitemapIndexLocs(xml: string): string[] {
|
||||
const out: string[] = [];
|
||||
const blockRe = /<sitemap\b[^>]*>([\s\S]*?)<\/sitemap>/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = blockRe.exec(xml)) !== null) {
|
||||
const locM = /<loc>\s*([^<\s]+)\s*<\/loc>/i.exec(m[1]);
|
||||
if (locM?.[1]) out.push(locM[1].trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** <url> blocks from a urlset sitemap. */
|
||||
export function parseUrlsetEntries(xml: string): SitemapUrlEntry[] {
|
||||
const out: SitemapUrlEntry[] = [];
|
||||
const blockRe = /<url\b[^>]*>([\s\S]*?)<\/url>/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = blockRe.exec(xml)) !== null) {
|
||||
const block = m[1];
|
||||
const locM = /<loc>\s*([^<\s]+)\s*<\/loc>/i.exec(block);
|
||||
if (!locM?.[1]) continue;
|
||||
const lastmodM = /<lastmod>\s*([^<]+?)\s*<\/lastmod>/i.exec(block);
|
||||
out.push({
|
||||
loc: locM[1].trim(),
|
||||
lastmod: lastmodM?.[1]?.trim(),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Fallback when there are <loc> tags but no <url> wrappers. */
|
||||
export function parseLooseLocs(xml: string): string[] {
|
||||
const out: string[] = [];
|
||||
const re = /<loc>\s*([^<\s]+)\s*<\/loc>/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(xml)) !== null) {
|
||||
if (m[1]) out.push(m[1].trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -7,11 +7,23 @@ import type { AggregatedItem, StoreFile } from './types.js';
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const DEFAULT_STORE_PATH = path.resolve(__dirname, '../var/aggregated-items.json');
|
||||
|
||||
const TRACKING_QUERY_KEYS = new Set([
|
||||
'fbclid',
|
||||
'gclid',
|
||||
'msclkid',
|
||||
'mc_cid',
|
||||
'mc_eid',
|
||||
'twclid',
|
||||
]);
|
||||
|
||||
export function canonicalUrl(raw: string): string {
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
for (const key of [...u.searchParams.keys()]) {
|
||||
if (key.toLowerCase().startsWith('utm_')) u.searchParams.delete(key);
|
||||
u.hash = '';
|
||||
const keys = [...u.searchParams.keys()];
|
||||
for (const key of keys) {
|
||||
const lower = key.toLowerCase();
|
||||
if (lower.startsWith('utm_') || TRACKING_QUERY_KEYS.has(lower)) u.searchParams.delete(key);
|
||||
}
|
||||
return u.toString();
|
||||
} catch {
|
||||
@@ -65,9 +77,14 @@ export function shortlist(
|
||||
store: StoreFile,
|
||||
site: string,
|
||||
limit: number,
|
||||
topic?: string,
|
||||
): AggregatedItem[] {
|
||||
return store.items
|
||||
.filter((i) => i.site === site && !i.wpDraftId && !i.skippedReason)
|
||||
.filter((i) => {
|
||||
if (i.site !== site || i.wpDraftId || i.skippedReason) return false;
|
||||
if (!topic) return true;
|
||||
return i.topics?.includes(topic) ?? false;
|
||||
})
|
||||
.sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0))
|
||||
.slice(0, limit);
|
||||
}
|
||||
@@ -1,3 +1,21 @@
|
||||
export type SourceKind = 'rss' | 'sitemap' | 'html_fetch';
|
||||
|
||||
export interface IngestSource {
|
||||
id: string;
|
||||
kind: SourceKind;
|
||||
url: string;
|
||||
enabled: boolean;
|
||||
topics?: string[];
|
||||
note?: string;
|
||||
/** Cap per-source items (sitemap URLs processed, or single html page). Default: 30 sitemap, 1 html_fetch */
|
||||
maxItems?: number;
|
||||
/** For sitemap: keep URLs whose path includes any of these substrings */
|
||||
pathIncludes?: string[];
|
||||
retries?: number;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
/** @deprecated Use IngestSource with kind rss — kept for legacy JSON configs */
|
||||
export interface FeedSource {
|
||||
id: string;
|
||||
url: string;
|
||||
@@ -7,14 +25,20 @@ export interface FeedSource {
|
||||
|
||||
export interface SiteSourcesConfig {
|
||||
site: string;
|
||||
feeds: FeedSource[];
|
||||
/** Unified multi-source config (RSS, sitemap, HTML fetch) */
|
||||
sources?: IngestSource[];
|
||||
/** Legacy: treated as RSS sources when `sources` is absent */
|
||||
feeds?: FeedSource[];
|
||||
}
|
||||
|
||||
export interface AggregatedItem {
|
||||
id: string;
|
||||
site: string;
|
||||
sourceFeedId: string;
|
||||
/** Original article URL from the source (preserved verbatim aside from trim) */
|
||||
url: string;
|
||||
sourceKind?: SourceKind;
|
||||
topics?: string[];
|
||||
title: string;
|
||||
summary: string;
|
||||
publishedAt: string;
|
||||
|
||||
Reference in new issue
Block a user