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, expectedURL) { 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))) { 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 } } 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 } } // Only associate metadata with an article identified in this already-loaded // document. Section-level publication dates must never be copied onto its links. function withDatesFromLoadedHtml(articles, html, loadedURL, parsed) { const $ = parsed || cheerio.load(html) const dates = new Map() function key(value) { try { if (typeof value !== 'string' || !value.trim()) return null const url = new URL(value, loadedURL) url.search = '' url.hash = '' return isArticleURL(url.href) ? url.href : null } catch { return null } } 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, pageKey) if (date) dates.set(pageKey, date) } for (const anchor of $('a[data-component="story-link"]').toArray()) { const articleKey = key($(anchor).attr('href')) if (!articleKey || !wanted.has(articleKey) || dates.has(articleKey)) continue let scope = $(anchor) const card = scope.closest('article') if (card.length) { const links = new Set(card.find('a[data-component="story-link"]').toArray() .map(link => key($(link).attr('href'))).filter(Boolean)) if (links.size === 1 && links.has(articleKey)) scope = card } for (const [selector, attribute] of [['meta[name="iso-8601-publish-date"]', 'content'], ['time[datetime]', 'datetime']]) { for (const element of scope.find(selector).toArray()) { const date = reliableISO($(element).attr(attribute)) if (date) { dates.set(articleKey, date); break } } if (dates.has(articleKey)) break } } let visited = 0 function collect(node, depth = 0) { if (!node || typeof node !== 'object' || depth > 32 || ++visited > 2000) return const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']] if (types.some(type => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(type))) { const identity = node.url || node.mainEntityOfPage const articleKey = key(typeof identity === 'string' ? identity : identity?.['@id']) const date = reliableISO(node.datePublished) if (articleKey && wanted.has(articleKey) && !dates.has(articleKey) && date) dates.set(articleKey, date) } for (const child of Object.values(node)) collect(child, depth + 1) } for (const script of $('script[type="application/ld+json"]').toArray()) { try { collect(JSON.parse($(script).text())) } catch { /* Unknown date, no raw metadata logging. */ } } return articles.map(article => ({ ...article, published_at: dates.get(key(article.url)) || null })) } module.exports = { extractPublicationDate, withDatesFromLoadedHtml }