feat(bloomberg): enrich article content for summaries (#36)

This commit is contained in:
2026-11-24 13:44:52 +01:00
parent 686f66a437
commit a53aec7947
22 changed files with 1148 additions and 127 deletions

View File

@ -0,0 +1,105 @@
const cheerio = require('cheerio')
const { extractPublicationDate } = require('./publication-date')
const MAX_CONTENT_BYTES = 16 * 1024
const MAX_HTML_BYTES = 16 * 1024 * 1024
const CONCURRENCY = 2
const ARTICLE_TIMEOUT_MS = 30000
const TOTAL_TIMEOUT_MS = 90000
function truncateUTF8 (value, maximum) {
const buffer = Buffer.from(value, 'utf8')
if (buffer.length <= maximum) return value
let end = maximum
while (end > 0 && (buffer[end] & 0xc0) === 0x80) end--
return buffer.subarray(0, end).toString('utf8')
}
function extractArticle (html, articleURL) {
const empty = { content: '', published_at: null, content_truncated: false }
if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES) return empty
const $ = cheerio.load(html)
const roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M')
const root = roots.length === 1 ? roots.first() : $()
const paragraphs = []
root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr').each((_, node) => {
const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], .placeholder, .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]'
if ($(node).parentsUntil(root).addBack().is(excluded)) return
const p = $(node).clone()
if (p.is('[hidden], [aria-hidden="true"], .disclaimer, [data-component="disclaimer"], [data-component="related-stories"]')) return
p.find(excluded).remove()
p.find('br').replaceWith(' ')
const text = p.text().normalize('NFC').replace(/\s+/gu, ' ').trim()
if (text) paragraphs.push(text)
})
const full = paragraphs.join('\n\n')
return { content: truncateUTF8(full, MAX_CONTENT_BYTES), published_at: extractPublicationDate(html, articleURL), content_truncated: Buffer.byteLength(full) > MAX_CONTENT_BYTES }
}
function canonicalURL (value) {
try {
if (typeof value !== 'string' || value.length > 4096) return null
const url = new URL(value)
if (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)) return null
url.search = ''; url.hash = ''
return url.href
} catch { return null }
}
async function enrichArticles (urls, loadHtml, options = {}) {
const concurrency = options.concurrency ?? CONCURRENCY
const articleTimeoutMs = options.articleTimeoutMs ?? ARTICLE_TIMEOUT_MS
const totalTimeoutMs = options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONCURRENCY || !(articleTimeoutMs > 0 && articleTimeoutMs <= ARTICLE_TIMEOUT_MS) || !(totalTimeoutMs > 0 && totalTimeoutMs <= TOTAL_TIMEOUT_MS)) throw new Error('invalid enrichment budget')
const empty = () => ({ content: '', published_at: null, content_truncated: false })
const keys = urls.map(canonicalURL)
const unique = [...new Set(keys.filter(Boolean))]
const results = new Map()
const controllers = new Set()
const deadline = Date.now() + totalTimeoutMs
// Reserve one wave for scheduling/cleanup. Every unique candidate gets a
// bounded opportunity within the remaining pool budget, even after login.
const poolArticleTimeoutMs = Math.max(1, Math.min(articleTimeoutMs,
Math.floor(totalTimeoutMs / (Math.ceil(unique.length / concurrency) + 1))))
let expired = false
let next = 0
let finishBudget
const budgetDone = new Promise(resolve => { finishBudget = resolve })
const expire = () => {
expired = true
for (const controller of controllers) controller.abort()
finishBudget()
}
const totalTimer = setTimeout(expire, totalTimeoutMs)
options.signal?.addEventListener('abort', expire, { once: true })
if (options.signal?.aborted) expire()
async function worker () {
while (next < unique.length && !expired && Date.now() < deadline) {
const key = unique[next++]
const controller = new AbortController()
controllers.add(controller)
const remaining = Math.max(1, Math.min(poolArticleTimeoutMs, deadline - Date.now()))
const articleDeadline = Date.now() + remaining
const timer = setTimeout(() => controller.abort(), remaining)
// A slot is not reused until the actual loader settles. If it ignores
// cancellation, the total budget ends the response without starting more
// work in that slot; underlying concurrency remains <=2.
const operation = Promise.resolve().then(() => {
if (expired || controller.signal.aborted || Date.now() >= deadline) throw new Error('enrichment expired')
return loadHtml(key, { signal: controller.signal, timeoutMs: remaining })
})
.then(html => {
if (!expired && !controller.signal.aborted && Date.now() < articleDeadline && Date.now() < deadline) {
const extracted = extractArticle(html, key)
if (Date.now() < articleDeadline && Date.now() < deadline) results.set(key, extracted)
}
}).catch(() => { /* Empty content, never log raw loader errors. */ })
.finally(() => { clearTimeout(timer); controllers.delete(controller) })
await Promise.race([operation, budgetDone])
}
}
try { await Promise.all(Array.from({ length: Math.min(concurrency, unique.length) }, worker)) } finally {
clearTimeout(totalTimer)
options.signal?.removeEventListener('abort', expire)
for (const controller of controllers) controller.abort()
}
return urls.map((url, i) => ({ url, ...(results.get(keys[i]) || empty()) }))
}
module.exports = { extractArticle, enrichArticles, canonicalURL, MAX_CONTENT_BYTES, ARTICLE_TIMEOUT_MS, TOTAL_TIMEOUT_MS }

View File

@ -1,3 +1,4 @@
const { enrichArticles, canonicalURL, TOTAL_TIMEOUT_MS } = require('./article-content')
const { withDatesFromLoadedHtml } = require('./publication-date')
const express = require('express')
const cheerio = require('cheerio')
@ -15,11 +16,12 @@ const BYPARR_URL = process.env.BYPARR_URL || ''
// ---------- Byparr helpers ----------
async function byparrRequest(body) {
async function byparrRequest(body, signal) {
const resp = await fetch(`${BYPARR_URL}/v1`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
})
if (!resp.ok) {
try { await resp.body?.cancel() } catch { /* Release without reading/logging the body. */ }
@ -28,9 +30,10 @@ async function byparrRequest(body) {
return resp.json()
}
async function byparrFetch(url, quiet = false) {
async function byparrFetch(url, quiet = false, options = {}) {
if (!quiet) console.log('[byparr] section request')
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: 60000 })
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: options.timeoutMs || 60000 }, options.signal)
if (options.signal && data.solution?.url && canonicalURL(data.solution.url) !== canonicalURL(url)) throw new Error('article association unavailable')
const html = data.solution?.response
if (!html) throw new Error('byparr returned no HTML')
return { html }
@ -142,84 +145,126 @@ async function tryType(page, selectors, text) {
return false
}
async function scrapeBloombergViaPuppeteer(username, password) {
async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
let browser
let abortBrowser
let loginTimer
try {
browser = await launchBrowser()
const page = await browser.newPage()
await page.setViewport({ width: 1920, height: 1080 })
const login = async () => {
browser = await launchBrowser()
if (enrichment) {
abortBrowser = () => { browser.close().catch(() => {}) }
enrichment.signal.addEventListener('abort', abortBrowser, { once: true })
if (enrichment.signal.aborted) { abortBrowser(); throw new Error('enrichment expired') }
}
const page = await browser.newPage()
await page.setViewport({ width: 1920, height: 1080 })
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined })
window.chrome = { runtime: {} }
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3] })
})
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined })
window.chrome = { runtime: {} }
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3] })
})
console.log('[bloomberg] navigating to login page')
await page.goto('https://www.bloomberg.com/account/signin', {
waitUntil: 'networkidle2',
timeout: 60000,
})
await new Promise(r => setTimeout(r, 2000))
console.log('[bloomberg] navigating to login page')
await page.goto('https://www.bloomberg.com/account/signin', {
waitUntil: 'networkidle2',
timeout: 60000,
})
await new Promise(r => setTimeout(r, 2000))
const pageInputs = await page.evaluate(() =>
Array.from(document.querySelectorAll('input')).map(i => ({
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
}))
)
console.log('[bloomberg] login input count:', pageInputs.length)
const emailOk = await tryType(page, [
'#email-form-input',
'input[id="email-form-input"]',
'input[type="email"]',
'input[name="text-input"]',
'input[placeholder*="email" i]',
], username)
if (!emailOk) throw new Error('could not find email input')
await new Promise(r => setTimeout(r, 800))
const submitted = await page.evaluate(() => {
const btn = Array.from(document.querySelectorAll('button')).find(b =>
b.type === 'submit' || /continue|next|sign.?in/i.test(b.textContent)
const pageInputs = await page.evaluate(() =>
Array.from(document.querySelectorAll('input')).map(i => ({
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
}))
)
if (btn) { btn.click(); return true }
const form = document.querySelector('form')
if (form) { form.submit(); return true }
return false
})
if (!submitted) await page.keyboard.press('Enter')
console.log('[bloomberg] login input count:', pageInputs.length)
try {
await page.waitForFunction(
() => document.querySelector('input[type="password"]') !== null,
{ timeout: 10000 }
)
} catch {
await new Promise(r => setTimeout(r, 3000))
const emailOk = await tryType(page, [
'#email-form-input',
'input[id="email-form-input"]',
'input[type="email"]',
'input[name="text-input"]',
'input[placeholder*="email" i]',
], username)
if (!emailOk) throw new Error('could not find email input')
await new Promise(r => setTimeout(r, 800))
const submitted = await page.evaluate(() => {
const btn = Array.from(document.querySelectorAll('button')).find(b =>
b.type === 'submit' || /continue|next|sign.?in/i.test(b.textContent)
)
if (btn) { btn.click(); return true }
const form = document.querySelector('form')
if (form) { form.submit(); return true }
return false
})
if (!submitted) await page.keyboard.press('Enter')
try {
await page.waitForFunction(
() => document.querySelector('input[type="password"]') !== null,
{ timeout: 10000 }
)
} catch {
await new Promise(r => setTimeout(r, 3000))
}
console.log('[bloomberg] email step completed')
const pwdOk = await tryType(page, [
'input[type="password"]',
'input[name="password"]',
'input[autocomplete="current-password"]',
'input[autocomplete="password"]',
], password)
if (!pwdOk) throw new Error('could not find password input')
await new Promise(r => setTimeout(r, 500))
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {}),
tryClick(page, ['button[type="submit"]', 'input[type="submit"]']),
])
const currentURL = page.url()
console.log('[bloomberg] login navigation completed')
if (currentURL.includes('/account/signin')) {
throw new Error('login did not redirect')
}
return page
}
console.log('[bloomberg] email step completed')
// Enrichment reserves at least 60s of its 90s total budget for pages.
// One login/session is shared; normal list collection keeps its deadlines.
const page = enrichment
? await Promise.race([login(), new Promise((resolve, reject) => {
loginTimer = setTimeout(() => {
abortBrowser?.()
reject(new Error('enrichment login expired'))
}, 30000)
})])
: await login()
if (enrichment) clearTimeout(loginTimer)
const pwdOk = await tryType(page, [
'input[type="password"]',
'input[name="password"]',
'input[autocomplete="current-password"]',
'input[autocomplete="password"]',
], password)
if (!pwdOk) throw new Error('could not find password input')
await new Promise(r => setTimeout(r, 500))
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 20000 }).catch(() => {}),
tryClick(page, ['button[type="submit"]', 'input[type="submit"]']),
])
const currentURL = page.url()
console.log('[bloomberg] login navigation completed')
if (currentURL.includes('/account/signin')) {
throw new Error('login did not redirect')
if (enrichment) {
const remaining = enrichment.deadline - Date.now()
if (remaining <= 0 || enrichment.signal.aborted) throw new Error('enrichment expired')
return await enrichArticles(enrichment.urls, async (url, options) => {
if (options.signal.aborted) throw new Error('article expired')
const articlePage = await browser.newPage()
const close = () => { articlePage.close().catch(() => {}) }
options.signal.addEventListener('abort', close, { once: true })
try {
if (options.signal.aborted) throw new Error('article expired')
await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs })
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) throw new Error('article association unavailable')
return await articlePage.content()
} finally {
options.signal.removeEventListener('abort', close)
await articlePage.close().catch(() => {})
}
}, { concurrency: 2, totalTimeoutMs: remaining, signal: enrichment.signal })
}
const targetPages = [
@ -257,6 +302,8 @@ async function scrapeBloombergViaPuppeteer(username, password) {
return articles
} finally {
if (enrichment) clearTimeout(loginTimer)
if (enrichment && abortBrowser) enrichment.signal.removeEventListener('abort', abortBrowser)
if (browser) await browser.close()
}
}
@ -289,4 +336,32 @@ app.post('/bloomberg/scrape', async (req, res) => {
}
})
// Enrichment is a separate RPC: the backend has already applied ArticleLimit.
app.post('/bloomberg/enrich', async (req, res) => {
const { username, password, urls } = req.body || {}
if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' })
if (!urls.length) return res.json({ articles: [] })
const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false }))
if (!urls.some(url => canonicalURL(url))) return res.json({ articles: empty() })
const controller = new AbortController()
const deadline = Date.now() + TOTAL_TIMEOUT_MS
let finish
const expired = new Promise(resolve => { finish = resolve })
const stop = () => { controller.abort(); finish(empty()) }
const timer = setTimeout(stop, TOTAL_TIMEOUT_MS)
const onClose = () => { if (!res.writableEnded) stop() }
res.once?.('close', onClose)
try {
const operation = BYPARR_URL
? enrichArticles(urls, async (url, options) => (await byparrFetch(url, true, options)).html, { signal: controller.signal })
: scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline })
const articles = await Promise.race([operation.catch(empty), expired])
if (!res.destroyed) res.json({ articles })
} finally {
clearTimeout(timer)
controller.abort()
res.removeListener?.('close', onClose)
}
})
app.listen(PORT, () => console.log(`scraper-service listening on :${PORT}`))

View File

@ -16,7 +16,7 @@ function reliableISO(value) {
return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null
}
function extractPublicationDate(html) {
function extractPublicationDate(html, expectedURL) {
const $ = cheerio.load(html)
for (const selector of ['meta[name="iso-8601-publish-date"]', 'time[datetime]']) {
for (const element of $(selector).toArray()) {
@ -30,7 +30,19 @@ function extractPublicationDate(html) {
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)
let associated = !expectedURL
if (expectedURL) {
const identity = node.url || node.mainEntityOfPage || node['@id']
const value = typeof identity === 'string' ? identity : identity?.['@id']
try {
if (typeof value === 'string') {
const actual = new URL(value, expectedURL); actual.search = ''; actual.hash = ''
const expected = new URL(expectedURL); expected.search = ''; expected.hash = ''
associated = isArticleURL(actual.href) && actual.href === expected.href
}
} catch { /* No trustworthy article identity. */ }
}
const date = associated ? reliableISO(node.datePublished) : null
if (date) return date
}
}
@ -75,7 +87,7 @@ function withDatesFromLoadedHtml(articles, html, loadedURL, parsed) {
const wanted = new Set(articles.map(article => key(article.url)).filter(Boolean))
const pageKey = key(loadedURL)
if (pageKey && wanted.has(pageKey)) {
const date = extractPublicationDate(html)
const date = extractPublicationDate(html, pageKey)
if (date) dates.set(pageKey, date)
}
for (const anchor of $('a[data-component="story-link"]').toArray()) {

View File

@ -0,0 +1,92 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const { extractArticle, enrichArticles, MAX_CONTENT_BYTES } = require('../article-content')
const paragraph = 'ArticleBodyText_articleBodyContent__17wqE typography_articleBody___5jDr'
const basic = text => `<article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="${paragraph}">${text}</p><div class="placeholder"><p class="${paragraph}">excluded placeholder</p></div></div></article>`
test('observed basic and feature layouts extract only editorial paragraphs within the observed root', () => {
for (const html of [basic(' First <em>synthetic</em> paragraph. '), `<article><div class="FeatureContent_body__NTf8M"><p class="${paragraph}"> First <em>synthetic</em> paragraph. </p></div></article>`]) {
const result = extractArticle(`<nav>excluded navigation</nav><meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">${html}`)
assert.equal(result.content, 'First synthetic paragraph.')
assert.equal(result.published_at, '2026-01-02T03:04:05.000Z')
}
})
test('no broad article/main or JSON-LD content fallback; paragraph normalization', () => {
assert.equal(extractArticle('<main><article><p>excluded generic body</p></article></main><script type="application/ld+json">bad</script>').content, '')
assert.equal(extractArticle('<script type="application/ld+json">{"@type":"NewsArticle","articleBody":"excluded"}</script>').content, '')
assert.equal(extractArticle(basic('one&nbsp; two<script>excluded</script>') .replace('</div></article>', `<p class="${paragraph}"> three\n four </p></div></article>`)).content, 'one two\n\nthree four')
})
test('oversized non-ASCII content is deterministically bounded on UTF-8 boundaries', () => {
const html = basic('é漢🙂'.repeat(MAX_CONTENT_BYTES))
const first = extractArticle(html)
assert.equal(first.content, extractArticle(html).content)
assert.ok(Buffer.byteLength(first.content) <= MAX_CONTENT_BYTES)
assert.ok(!first.content.includes('\ufffd'))
assert.equal(first.content_truncated, true)
})
test('enrichment deduplicates loads, bounds concurrency and preserves input order', async () => {
const urls = ['a', 'b', 'a', 'c'].map(id => `https://www.bloomberg.com/news/articles/${id}`)
const calls = []; let active = 0; let peak = 0
const result = await enrichArticles(urls, async url => {
calls.push(url); active++; peak = Math.max(peak, active)
await new Promise(resolve => setTimeout(resolve, url.endsWith('/a') ? 10 : 1))
active--; return basic('synthetic ' + url.slice(-1))
}, { concurrency: 2, articleTimeoutMs: 100, totalTimeoutMs: 200 })
assert.equal(calls.length, 3); assert.equal(peak, 2)
assert.deepEqual(result.map(v => v.url), urls)
assert.deepEqual(result.map(v => v.content), ['synthetic a', 'synthetic b', 'synthetic a', 'synthetic c'])
})
test('failure and ignored cancellation stay bounded without reusing occupied slots', async () => {
const urls = ['a', 'b', 'c'].map(id => `https://www.bloomberg.com/news/articles/${id}`)
let calls = 0
const result = await enrichArticles(urls, async () => { calls++; return new Promise(() => {}) }, { concurrency: 2, articleTimeoutMs: 5, totalTimeoutMs: 20 })
assert.equal(calls, 2); assert.ok(result.every(v => v.content === '' && v.published_at === null))
const failed = await enrichArticles(urls, async () => { throw new Error('private') }, { articleTimeoutMs: 10, totalTimeoutMs: 50 })
assert.ok(failed.every(v => v.content === '' && v.published_at === null))
})
test('JSON-LD belonging to another article cannot supply this article date', () => {
const html = basic('synthetic paragraph') + '<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/other","datePublished":"2026-01-02T03:04:05Z"}</script>'
const result = extractArticle(html, 'https://www.bloomberg.com/news/articles/current')
assert.equal(result.content, 'synthetic paragraph')
assert.equal(result.published_at, null)
})
test('sanitized structural fixtures exclude placeholders, recommendations and disclaimers', () => {
const fs = require('node:fs'); const path = require('node:path')
const load = name => fs.readFileSync(path.join(__dirname, 'fixtures', name), 'utf8')
assert.equal(extractArticle(load('content-basic.html')).content, 'Synthetic first paragraph.\n\nSynthetic second paragraph.')
assert.equal(extractArticle(load('content-feature.html')).content, 'Synthetic feature paragraph.')
})
test('aborted enrichment and invalid URLs never invoke a loader', async () => {
let calls = 0; const controller = new AbortController(); controller.abort()
const urls = ['https://www.bloomberg.com/news/articles/a']
const result = await enrichArticles(urls, async () => { calls++; return basic('unused') }, { signal: controller.signal })
assert.equal(calls, 0); assert.equal(result[0].content, '')
await enrichArticles(['http://127.0.0.1/news/articles/a', 'https://other.invalid/news/articles/a'], async () => { calls++; return '' })
assert.equal(calls, 0)
})
test('remaining pool budget gives every candidate a bounded attempt with an offline clock', async t => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
const urls = Array.from({ length: 30 }, (_, i) => `https://www.bloomberg.com/news/articles/pool-${i}`)
let active = 0; let peak = 0; let calls = 0; const slices = []
let done = false
const operation = enrichArticles(urls, async (_url, options) => {
calls++; active++; peak = Math.max(peak, active); slices.push(options.timeoutMs)
try { await new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('private')), { once: true })) } finally { active-- }
}, { concurrency: 2, articleTimeoutMs: 100, totalTimeoutMs: 1000 }).then(result => { done = true; return result })
for (let i = 0; i < 20 && !done; i++) {
await new Promise(resolve => setImmediate(resolve))
t.mock.timers.tick(62)
}
const result = await operation
assert.equal(calls, 30); assert.equal(peak, 2); assert.equal(active, 0)
assert.ok(slices.every(ms => ms <= 62))
assert.deepEqual(result.map(a => a.url), urls)
assert.ok(result.every(a => a.content === '' && a.published_at === null))
})
test('editorial descendants preserve document order and exclude non-editorial ancestors', () => {
const html = `<article><div class="FeatureContent_body__NTf8M"><div><section><p class="${paragraph}">one</p></section></div><aside><div><p class="${paragraph}">excluded</p></div></aside><div hidden><p class="${paragraph}">excluded</p></div><div data-component="related-stories"><p class="${paragraph}">excluded</p></div><div><div><p class="${paragraph}">two</p></div></div></div></article>`
assert.equal(extractArticle(html).content,'one\n\ntwo')
})

View File

@ -0,0 +1,81 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const { createRequire } = require('node:module')
const html = '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic editorial paragraph.</p></div></article>'
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false) {
const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0
const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} }
const express = () => app; express.json = () => () => {}
function page (auth) {
let url = ''; let evals = 0
return {
async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type () {}, async waitForFunction () {},
async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate () { return evals++ === 0 ? [] : true },
async $ () { return null }, keyboard: { async press () {} },
async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active-- } }, url () { return url },
async content () { return html }, async close () {}
}
}
const browser = { async newPage () { return page(pages++ === 0) }, async close () { closed = true } }
const index = path.resolve(__dirname, '../index.js'); const localRequire = createRequire(index)
vm.runInNewContext(fs.readFileSync(index, 'utf8'), {
require (name) {
if (name === 'express') return express
if (name === 'puppeteer-extra') return { use () {}, async launch () { return browser } }
if (name === 'puppeteer-extra-plugin-stealth') return () => ({})
return localRequire(name)
},
process: { env: { BYPARR_URL: byparr ? 'http://fixture.invalid' : '' } }, AbortController,
setTimeout (fn, ms) { timers.push(ms); if (authTimeout && ms === 30000) { queueMicrotask(fn); return undefined }; if ([2000, 800, 500, 3000].includes(ms)) { queueMicrotask(fn); return undefined }; return setTimeout(fn, ms) }, clearTimeout,
console: { log (...values) { logs.push(values.join(' ')) }, error (...values) { logs.push(values.join(' ')) } },
async fetch (_url, options) {
const body = JSON.parse(options.body); loads.push(body.url); active++; peak = Math.max(peak, active)
assert.ok(body.maxTimeout <= 30000); assert.ok(options.signal)
await new Promise(resolve => setTimeout(resolve, 1)); active--
if (failOne && body.url.endsWith('/b')) throw new Error('PRIVATE_BODY http://private.invalid')
return { ok: true, async json () { return { solution: { url: body.url, response: html } } } }
}
})
const urls = (poolSize === 2 ? ['a', 'b', 'a'] : Array.from({ length: poolSize }, (_, i) => `pool-${i}`)).map(id => `https://www.bloomberg.com/news/articles/${id}`)
let result
await routes['/bloomberg/enrich']({ body: { username: 'PRIVATE_USER', password: 'PRIVATE_SECRET', urls } }, { json (value) { result = value }, status () { return this } })
assert.deepEqual(result.articles.map(a => a.url), urls)
assert.equal(loads.length, authTimeout ? 0 : poolSize)
assert.ok(logs.every(line => !line.includes('PRIVATE') && !line.includes('http') && !line.includes('Synthetic editorial')))
return { result, pages, peak, closed, timers }
}
test('Byparr enrichment endpoint returns content and date from each unique HTML load', async () => {
const { result, peak } = await request(true)
assert.equal(peak, 2)
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.' && a.published_at === '2026-01-02T03:04:05.000Z'))
})
test('one fetch failure is empty and does not lose successful candidates', async () => {
const { result } = await request(true, true)
assert.equal(result.articles[0].content, 'Synthetic editorial paragraph.')
assert.equal(result.articles[1].content, ''); assert.equal(result.articles[1].published_at, null)
})
test('Puppeteer reuses the existing login flow and closes all enrichment resources', async () => {
const { result, pages, closed, peak } = await request(false)
assert.equal(peak, 2)
assert.equal(pages, 3); assert.equal(closed, true)
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.'))
})
test('Puppeteer loads a full pool with two pages and one shared authenticated session', async () => {
const {result,pages,peak,closed,timers} = await request(false,false,30)
assert.ok(timers.includes(30000), "login must reserve article-pool time with a 30s deadline")
assert.equal(pages,31); assert.equal(peak,2); assert.equal(closed,true)
assert.equal(result.articles.length,30)
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.'))
})
test('Puppeteer login deadline returns safe empty results and closes the shared session', async () => {
const {result,closed,timers} = await request(false,false,30,true)
assert.equal(closed,true);assert.ok(timers.includes(30000))
assert.equal(result.articles.length,30)
assert.ok(result.articles.every(a => a.content === '' && a.published_at === null))
})

View File

@ -0,0 +1,11 @@
<nav>excluded navigation</nav>
<article class="articleLayout_basic__gcpQk">
<header>excluded heading</header>
<div class="body-content">
<div class="editorial-wrapper"><div><p class="ArticleBodyText_articleBodyContent__17wqE typography_articleBody___5jDr">Synthetic <em>first</em> paragraph.</p></div></div>
<div class="placeholder"><p class="ArticleBodyText_articleBodyContent__17wqE">excluded placeholder</p></div>
<p class="typography_articleBody___5jDr">Synthetic&nbsp;second<br>paragraph.</p>
<p class="typography_articleBody___5jDr" data-component="disclaimer">excluded disclaimer</p>
</div>
<aside>excluded recommendations</aside>
</article>

View File

@ -0,0 +1,7 @@
<article>
<div class="FeatureContent_body__NTf8M">
<div><div class="editorial-wrapper"><p class="ArticleBodyText_articleBodyContent__17wqE typography_articleBody___5jDr">Synthetic feature paragraph.</p></div></div>
<div data-component="related-stories"><p class="typography_articleBody___5jDr">excluded recommendation</p></div>
</div>
<footer>excluded footer</footer>
</article>