feat(generation): select articles in three passes

This commit is contained in:
2026-11-24 00:38:02 +01:00
parent d22f84529f
commit 8022ee0547
27 changed files with 916 additions and 68 deletions

View File

@ -1,3 +1,4 @@
const { withPublicationDates } = require('./publication-date')
const express = require('express')
const cheerio = require('cheerio')
const puppeteer = require('puppeteer-extra')
@ -24,8 +25,8 @@ async function byparrRequest(body) {
return resp.json()
}
async function byparrFetch(url) {
console.log('[byparr] GET', url)
async function byparrFetch(url, quiet = false) {
if (!quiet) console.log('[byparr] GET', url)
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: 60000 })
const html = data.solution?.response
if (!html) throw new Error(`byparr returned no HTML for ${url}`)
@ -93,7 +94,7 @@ async function scrapeBloombergViaByparr(username, password) {
}
}
return articles
return withPublicationDates(articles, async url => (await byparrFetch(url, true)).html)
}
// ---------- Bloomberg scraping via Puppeteer (fallback, may be blocked) ----------
@ -246,7 +247,10 @@ async function scrapeBloombergViaPuppeteer(username, password) {
}
}
return articles
return await withPublicationDates(articles, async url => {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
return page.content()
})
} finally {
if (browser) await browser.close()
}

View File

@ -3,7 +3,8 @@
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
"start": "node index.js",
"test": "node --test tests/*.test.js"
},
"dependencies": {
"cheerio": "^1.0.0",

View File

@ -0,0 +1,71 @@
const cheerio = require('cheerio')
function reliableISO(value) {
if (typeof value !== 'string') return null
const m = value.trim().match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/)
if (!m) return null
const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number)
if (year < 1970 || month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) return null
const calendar = new Date(Date.UTC(year, month - 1, day))
if (calendar.getUTCMonth() !== month - 1 || calendar.getUTCDate() !== day) return null
if (m[7] !== 'Z') {
const [h, min] = m[7].slice(1).split(':').map(Number)
if (h > 14 || min > 59 || (h === 14 && min !== 0)) return null
}
const timestamp = Date.parse(value.trim())
return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null
}
function extractPublicationDate(html) {
const $ = cheerio.load(html)
for (const selector of ['meta[name="iso-8601-publish-date"]', 'time[datetime]']) {
for (const element of $(selector).toArray()) {
const date = reliableISO($(element).attr(selector.startsWith('meta') ? 'content' : 'datetime'))
if (date) return date
}
}
let visited = 0
function published(node, depth = 0) {
if (!node || typeof node !== 'object' || depth > 32 || ++visited > 2000) return null
if (!Array.isArray(node)) {
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]
if (types.some(type => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(type))) {
const date = reliableISO(node.datePublished)
if (date) return date
}
}
for (const child of Object.values(node)) {
const date = published(child, depth + 1)
if (date) return date
}
return null
}
for (const element of $('script[type="application/ld+json"]').toArray()) {
try {
const date = published(JSON.parse($(element).text()))
if (date) return date
} catch { /* Invalid metadata is absent; never log page content. */ }
}
return null
}
function isArticleURL(value) {
try {
const url = new URL(value)
return url.protocol === 'https:' && ['www.bloomberg.com', 'bloomberg.com'].includes(url.hostname) &&
!url.username && !url.password && !url.port &&
/^\/(news\/articles|news\/features|features)\//.test(url.pathname)
} catch { return false }
}
async function withPublicationDates(articles, loadHtml) {
const result = []
for (const article of articles) {
let published_at = null
try { if (isArticleURL(article.url)) published_at = extractPublicationDate(await loadHtml(article.url)) } catch { /* Date stays unknown. */ }
result.push({ ...article, published_at })
}
return result
}
module.exports = { extractPublicationDate, withPublicationDates }

View File

@ -0,0 +1,49 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const { extractPublicationDate, withPublicationDates } = require('../publication-date')
test('minimal metadata fixtures preserve genuine dates with explicit zones', () => {
assert.equal(extractPublicationDate('<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">'), '2026-01-02T03:04:05.000Z')
assert.equal(extractPublicationDate('<time datetime="2026-01-02T04:04:05+01:00"></time>'), '2026-01-02T03:04:05.000Z')
assert.equal(extractPublicationDate('<script type="application/ld+json">{"@graph":[{"@type":"NewsArticle","datePublished":"2026-01-02T03:04:05Z"}]}</script>'), '2026-01-02T03:04:05.000Z')
})
test('invalid or missing metadata never manufactures a collection date', () => {
for (const html of ['', '<time datetime="2026-01-02"></time>', '<time datetime="2026-02-30T03:04:05Z"></time>', '<time datetime="2026-01-02T03:04:05"></time>', '<script type="application/ld+json">bad</script>', '<script type="application/ld+json">{"@type":"WebSite","datePublished":"2026-01-02T03:04:05Z"}</script>']) {
assert.equal(extractPublicationDate(html), null)
}
})
test('metadata priority and failed hydration retain order and nullable dates', async () => {
const a = { title: 'fixture-a', url: 'https://www.bloomberg.com/news/articles/fixture-a' }
const b = { title: 'fixture-b', url: 'https://www.bloomberg.com/news/articles/fixture-b' }
const seen = []
const result = await withPublicationDates([a, b], async url => {
seen.push(url)
if (url === b.url) throw new Error('fixture only')
return '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><time datetime="2026-01-03T00:00:00Z"></time>'
})
assert.deepEqual(seen, [a.url, b.url])
assert.equal(result[0].published_at, '2026-01-02T03:04:05.000Z')
assert.equal(result[1].published_at, null)
assert.equal(a.published_at, undefined)
})
test('date hydration never fetches unrelated hosts or non-article URLs', async () => {
let calls = 0
const urls = ['http://127.0.0.1/news/articles/x', 'https://other.invalid/news/articles/x', 'https://www.bloomberg.com@other.invalid/news/articles/x', 'https://www.bloomberg.com:8443/news/articles/x', 'https://www.bloomberg.com/markets']
const result = await withPublicationDates(urls.map(url => ({ url })), async () => { calls++; return '' })
assert.equal(calls, 0)
assert.ok(result.every(item => item.published_at === null))
})
test('the three observed page shapes expose all publication metadata keys', () => {
// Attribute-only synthetic snippets: no source titles, URLs or page content.
for (const date of ['2026-01-02T03:04:05Z', '2026-02-03T04:05:06Z', '2026-03-04T05:06:07Z']) {
const html = `<meta name="iso-8601-publish-date" content="${date}"><time datetime="${date}"></time><script type="application/ld+json">{"@type":"NewsArticle","datePublished":"${date}"}</script>`
assert.equal(extractPublicationDate(html), new Date(date).toISOString())
}
})
test('invalid primary metadata falls through time then JSON-LD publication date', () => {
const json = '<script type="application/ld+json">{"@type":"NewsArticle","datePublished":"2026-01-02T03:04:05Z"}</script>'
assert.equal(extractPublicationDate('<meta name="iso-8601-publish-date" content="invalid"><time datetime="2026-02-03T04:05:06Z"></time>' + json), '2026-02-03T04:05:06.000Z')
assert.equal(extractPublicationDate('<meta name="iso-8601-publish-date" content="invalid"><time datetime="invalid"></time>' + json), '2026-01-02T03:04:05.000Z')
})