Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4c86933e2 | ||
|
|
5ab8626557 | ||
|
|
325fa2f61c | ||
|
|
8a17b42e60 | ||
|
|
3e922ca6f2 | ||
|
|
e50da02cfa | ||
|
|
632070a324 | ||
|
|
4b33448122 | ||
|
|
78c59a4850 | ||
|
|
5bb70d130d | ||
|
|
30bddfbef4 | ||
|
|
528b020989 | ||
|
|
b97b768057 | ||
|
|
fe9a19603c | ||
|
|
b23ca87102 | ||
|
|
dc1b6dd4f0 | ||
|
|
ded3c71ed6 | ||
|
|
c7329a7ea5 | ||
|
|
de19fb7e1a | ||
|
|
e43f04705a | ||
|
|
c61c19216c | ||
|
|
da539f33aa | ||
|
|
28a823dfbe | ||
|
|
5b069ee149 | ||
|
|
9e7bf236eb | ||
|
|
aa19492fe4 | ||
|
|
71e7697c29 | ||
|
|
657e1c3bde | ||
|
|
5fd457a75d | ||
|
|
5514f86dfa | ||
|
|
ee8405980c |
No files matched your search
+4
-4
@@ -2,11 +2,11 @@
|
||||
# Replace/add owners as needed per repository domain.
|
||||
|
||||
# CI and forge metadata
|
||||
/.gitea/ @tiago-neves @david-santos
|
||||
/.gitea/workflows/ @tiago-neves @david-santos
|
||||
/.gitea/ @devops-engineer @founding-engineer
|
||||
/.gitea/workflows/ @devops-engineer @founding-engineer
|
||||
|
||||
# Documentation
|
||||
/docs/ @david-santos @planner
|
||||
/docs/ @founding-engineer
|
||||
|
||||
# Catch-all
|
||||
* @david-santos
|
||||
* @founding-engineer
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: "24.22.1"
|
||||
cache: "npm"
|
||||
cache-dependency-path: writer-pipeline/package-lock.json
|
||||
- run: npm ci
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: "24.22.1"
|
||||
cache: "npm"
|
||||
cache-dependency-path: bridge/package-lock.json
|
||||
- run: npm ci
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: "24.22.1"
|
||||
cache: "npm"
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- run: npm install
|
||||
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [18, 20]
|
||||
node-version: ['24.22.1']
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
+4
-4
@@ -2,11 +2,11 @@
|
||||
# Replace/add owners as needed per repository domain.
|
||||
|
||||
# CI and forge metadata
|
||||
/.gitea/ @tiago-neves @david-santos
|
||||
/.gitea/workflows/ @tiago-neves @david-santos
|
||||
/.gitea/ @devops-engineer @founding-engineer
|
||||
/.gitea/workflows/ @devops-engineer @founding-engineer
|
||||
|
||||
# Documentation
|
||||
/docs/ @david-santos @planner
|
||||
/docs/ @founding-engineer
|
||||
|
||||
# Catch-all
|
||||
* @david-santos
|
||||
* @founding-engineer
|
||||
+5
-2
@@ -9,8 +9,8 @@
|
||||
"build": "tsc",
|
||||
"start": "node dist/server.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "npm run build && node --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/andeboltv.test.js dist/services/fpa-stream-match.test.js",
|
||||
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/andeboltv.test.js dist/services/fpa-stream-match.test.js"
|
||||
"test": "npm run build && node --test dist/lib/sanitize-html.test.js dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/andeboltv.test.js dist/services/fpa-stream-match.test.js dist/services/fpa-standings-url.test.js",
|
||||
"test:coverage": "npm run build && node --experimental-test-coverage --test dist/lib/sanitize-html.test.js dist/services/ranking.test.js dist/services/aggregator-mapper.test.js dist/services/andeboltv.test.js dist/services/fpa-stream-match.test.js dist/services/fpa-standings-url.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^9.0.1",
|
||||
@@ -23,5 +23,8 @@
|
||||
"pino-pretty": "^13.1.3",
|
||||
"tsx": "^4.15.0",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { sanitize_article_html } from '../lib/sanitize-html.js';
|
||||
|
||||
test('strips script tags from article content', () => {
|
||||
const input = '<p>Hello</p><script>alert("xss")</script><p>World</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Hello</p><p>World</p>');
|
||||
});
|
||||
|
||||
test('strips script tags with attributes', () => {
|
||||
const input = '<p>Text</p><script src="https://platform.twitter.com/widgets.js"></script><p>More</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p><p>More</p>');
|
||||
});
|
||||
|
||||
test('strips script tags with type attribute', () => {
|
||||
const input = '<p>Text</p><script type="text/javascript">console.log("hi")</script><p>More</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p><p>More</p>');
|
||||
});
|
||||
|
||||
test('strips multiple script tags', () => {
|
||||
const input = '<script>a()</script><p>A</p><script>b()</script><p>B</p><script>c()</script>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>A</p><p>B</p>');
|
||||
});
|
||||
|
||||
test('strips script with multiline content', () => {
|
||||
const input = '<p>Before</p><script>\nvar x = 1;\nvar y = 2;\n</script><p>After</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Before</p><p>After</p>');
|
||||
});
|
||||
|
||||
test('strips script with nested angle brackets (inline JSON)', () => {
|
||||
const input = '<script type="application/ld+json">{"@type":"Article","name":"Test"}</script><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('strips style tags from article content', () => {
|
||||
const input = '<p>Text</p><style>.embed{color:red}</style><p>More</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p><p>More</p>');
|
||||
});
|
||||
|
||||
test('strips style tags with attributes', () => {
|
||||
const input = '<style type="text/css">.wp-block{display:block}</style><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('strips link tags from article content', () => {
|
||||
const input = '<link rel="stylesheet" href="https://cdn.example.com/embed.css"><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('strips multiple link tags', () => {
|
||||
const input = '<link rel="stylesheet" href="a.css"><link rel="preconnect" href="https://example.com"><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('strips inline event handlers', () => {
|
||||
const input = '<div onload="track()" onclick="handle()">Text</div>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(!result.includes('onload'), `Expected no onload in: ${result}`);
|
||||
assert.ok(!result.includes('onclick'), `Expected no onclick in: ${result}`);
|
||||
assert.ok(result.includes('Text'), `Expected text preserved in: ${result}`);
|
||||
});
|
||||
|
||||
test('strips inline event handlers with single quotes', () => {
|
||||
const input = "<img src='test.jpg' onerror='alert(1)'>";
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(!result.includes('onerror'), `Expected no onerror in: ${result}`);
|
||||
});
|
||||
|
||||
test('strips inline event handlers with unquoted values', () => {
|
||||
const input = '<div onmouseover=alert(1)>Text</div>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(!result.includes('onmouseover'), `Expected no onmouseover in: ${result}`);
|
||||
});
|
||||
|
||||
test('replaces iframes with placeholders', () => {
|
||||
const input = '<iframe src="https://www.youtube.com/embed/abc123" width="560" height="315"></iframe>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('embed-placeholder'), `Expected placeholder div in: ${result}`);
|
||||
assert.ok(result.includes('data-embed-src'), `Expected data-embed-src in: ${result}`);
|
||||
assert.ok(!result.includes('<iframe'), `Expected no iframe in: ${result}`);
|
||||
});
|
||||
|
||||
test('preserves iframe title in placeholder aria-label', () => {
|
||||
const input = '<iframe src="https://www.youtube.com/embed/abc" title="Video player" width="560" height="315"></iframe>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('aria-label="Video player"'), `Expected aria-label in: ${result}`);
|
||||
assert.ok(result.includes('<span>Video player</span>'), `Expected title in button span in: ${result}`);
|
||||
});
|
||||
|
||||
test('placeholder uses aspect-ratio from width/height', () => {
|
||||
const input = '<iframe src="https://www.youtube.com/embed/abc" width="560" height="315"></iframe>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('aspect-ratio:560/315'), `Expected aspect-ratio in: ${result}`);
|
||||
});
|
||||
|
||||
test('handles WordPress Twitter embed blockquote', () => {
|
||||
const input = '<blockquote class="twitter-tweet"><p lang="pt">Some tweet text</p>— User (@user) <a href="https://twitter.com/user/status/123">August 1, 2026</a></blockquote><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(!result.includes('<script'), `Expected no scripts in: ${result}`);
|
||||
assert.ok(result.includes('<blockquote'), `Expected blockquote preserved in: ${result}`);
|
||||
});
|
||||
|
||||
test('handles WordPress Instagram embed iframe', () => {
|
||||
const input = '<iframe src="https://www.instagram.com/p/abc123/embed/" width="400" height="480"></iframe>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(!result.includes('<iframe'), `Expected no iframe in: ${result}`);
|
||||
assert.ok(result.includes('embed-placeholder'), `Expected placeholder in: ${result}`);
|
||||
});
|
||||
|
||||
test('handles combined sanitization', () => {
|
||||
const input = '<script src="https://platform.twitter.com/widgets.js"></script><p>Text</p><iframe src="https://www.youtube.com/embed/abc"></iframe>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(!result.includes('<script'), `Expected no scripts in: ${result}`);
|
||||
assert.ok(!result.includes('<iframe'), `Expected no iframes in: ${result}`);
|
||||
assert.ok(result.includes('<p>Text</p>'), `Expected paragraph preserved in: ${result}`);
|
||||
assert.ok(result.includes('embed-placeholder'), `Expected placeholder in: ${result}`);
|
||||
});
|
||||
|
||||
test('handles case-insensitive script tags', () => {
|
||||
const input = '<SCRIPT>alert(1)</SCRIPT><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('handles empty content', () => {
|
||||
const result = sanitize_article_html('');
|
||||
assert.equal(result, '');
|
||||
});
|
||||
|
||||
test('handles content with no scripts, styles, links, iframes, or event handlers', () => {
|
||||
const input = '<p>Hello world</p><h2>Heading</h2><ul><li>Item</li></ul>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, input);
|
||||
});
|
||||
|
||||
test('strips style tags with multiline CSS', () => {
|
||||
const input = '<style>\n.wp-block-embed {\n max-width: 100%;\n}\n</style><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('strips link with multiple attributes', () => {
|
||||
const input = '<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
test('handles iframe with no src gracefully', () => {
|
||||
const input = '<iframe width="560" height="315"></iframe><p>Text</p>';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('<p>Text</p>'), `Expected paragraph preserved in: ${result}`);
|
||||
});
|
||||
|
||||
test('adds loading=lazy and decoding=async to images without those attributes', () => {
|
||||
const input = '<img src="photo.jpg" alt="Photo">';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('loading="lazy"'), `Expected loading="lazy" in: ${result}`);
|
||||
assert.ok(result.includes('decoding="async"'), `Expected decoding="async" in: ${result}`);
|
||||
assert.ok(result.includes('alt="Photo"'), `Expected alt preserved in: ${result}`);
|
||||
});
|
||||
|
||||
test('does not add loading=lazy to images that already have it', () => {
|
||||
const input = '<img src="photo.jpg" loading="eager" alt="Photo">';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('loading="eager"'), `Expected loading="eager" preserved in: ${result}`);
|
||||
assert.ok(!result.includes('loading="lazy"'), `Did not expect loading="lazy" in: ${result}`);
|
||||
});
|
||||
|
||||
test('does not add decoding to images that already have it', () => {
|
||||
const input = '<img src="photo.jpg" decoding="sync" alt="Photo">';
|
||||
const result = sanitize_article_html(input);
|
||||
assert.ok(result.includes('decoding="sync"'), `Expected decoding="sync" preserved in: ${result}`);
|
||||
assert.ok(!result.includes('decoding="async"'), `Did not expect decoding="async" in: ${result}`);
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Sanitize WordPress article HTML to reduce client-side main-thread blocking.
|
||||
*
|
||||
* Primary targets:
|
||||
* - <script> tags (WordPress embed JS for Twitter, Instagram, etc.)
|
||||
* - <style> and <link> tags injected by oEmbed embeds
|
||||
* - Inline event handlers (onclick, onload, onerror, etc.)
|
||||
* - <iframe> elements (converted to lazy placeholders)
|
||||
*
|
||||
* WordPress oEmbed auto-embeds inject <script> tags, <iframe> elements,
|
||||
* <style> blocks, and inline event handlers that block the main thread
|
||||
* during HTML parsing. Since the news platform renders article content
|
||||
* server-side via set:html, these elements execute synchronously and
|
||||
* inflate Total Blocking Time (TBT) on article pages.
|
||||
*
|
||||
* This sanitizer runs in the bridge normalizer so sanitized content is
|
||||
* cached in Redis — all downstream consumers get clean HTML.
|
||||
*
|
||||
* Related: BIT-28145 (article TBT 7416ms → target Lighthouse Perf ≥ 90).
|
||||
*/
|
||||
|
||||
function strip_scripts(html: string): string {
|
||||
return html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '');
|
||||
}
|
||||
|
||||
function strip_styles(html: string): string {
|
||||
return html.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '');
|
||||
}
|
||||
|
||||
function strip_links(html: string): string {
|
||||
return html.replace(/<link\b[^>]*>/gi, '');
|
||||
}
|
||||
|
||||
function strip_inline_event_handlers(html: string): string {
|
||||
return html.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
|
||||
}
|
||||
|
||||
function lazy_load_images(html: string): string {
|
||||
return html.replace(
|
||||
/<img\b([^>]*)>/gi,
|
||||
(match, attrs: string) => {
|
||||
let new_attrs = attrs;
|
||||
if (!/\bloading\s*=/i.test(new_attrs)) {
|
||||
new_attrs += ' loading="lazy"';
|
||||
}
|
||||
if (!/\bdecoding\s*=/i.test(new_attrs)) {
|
||||
new_attrs += ' decoding="async"';
|
||||
}
|
||||
return `<img${new_attrs}>`;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const IFRAME_RE = /<iframe\b([^>]*)>([\s\S]*?<\/iframe>)?/gi;
|
||||
|
||||
function replace_iframes_with_placeholders(html: string): string {
|
||||
return html.replace(IFRAME_RE, (_match, attrs: string) => {
|
||||
const src_match = attrs.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const src = src_match?.[1] ?? src_match?.[2] ?? '';
|
||||
if (!src) return '';
|
||||
|
||||
const title_match = attrs.match(/\btitle\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const title = title_match?.[1] ?? title_match?.[2] ?? '';
|
||||
|
||||
const width_match = attrs.match(/\bwidth\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const width = width_match?.[1] ?? width_match?.[2] ?? '';
|
||||
|
||||
const height_match = attrs.match(/\bheight\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const height = height_match?.[1] ?? height_match?.[2] ?? '';
|
||||
|
||||
const escaped_src = src.replace(/&/g, '&').replace(/"/g, '"');
|
||||
const style_parts: string[] = ['display:block', 'max-width:100%'];
|
||||
if (width) style_parts.push(`width:${width}px`);
|
||||
if (height) style_parts.push(`aspect-ratio:${width}/${height}`);
|
||||
|
||||
return (
|
||||
`<div class="embed-placeholder" style="${style_parts.join(';')}" ` +
|
||||
`data-embed-src="${escaped_src}" ` +
|
||||
`data-embed-type="iframe" ` +
|
||||
`role="button" ` +
|
||||
`tabindex="0" ` +
|
||||
`aria-label="${title || 'Load embedded content'}">` +
|
||||
`<button class="embed-placeholder__btn" type="button" ` +
|
||||
`data-embed-src="${escaped_src}" ` +
|
||||
`data-embed-width="${width}" ` +
|
||||
`data-embed-height="${height}">` +
|
||||
`<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="2" y="3" width="20" height="14" rx="2"/><polygon points="10 8 16 10.5 10 13"/></svg>` +
|
||||
`<span>${title || 'Load embedded content'}</span></button></div>`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function sanitize_article_html(html: string): string {
|
||||
let result = html;
|
||||
result = strip_scripts(result);
|
||||
result = strip_styles(result);
|
||||
result = strip_links(result);
|
||||
result = strip_inline_event_handlers(result);
|
||||
result = replace_iframes_with_placeholders(result);
|
||||
result = lazy_load_images(result);
|
||||
return result;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ type SlugParams = {
|
||||
|
||||
type RelatedQuery = {
|
||||
limit?: string;
|
||||
category_id?: string;
|
||||
};
|
||||
|
||||
async function resolve_category_id(
|
||||
@@ -92,6 +93,8 @@ export async function articles_routes(app: FastifyInstance): Promise<void> {
|
||||
);
|
||||
|
||||
// GET /articles/:slug/related — related articles (same category, excluding current)
|
||||
// If ?category_id= is provided, skip the article fetch and use it directly.
|
||||
// This avoids a redundant WP API call when the caller already has the article.
|
||||
app.get(
|
||||
'/articles/:slug/related',
|
||||
async (req: FastifyRequest<{ Params: SlugParams; Querystring: RelatedQuery }>, reply) => {
|
||||
@@ -101,16 +104,22 @@ export async function articles_routes(app: FastifyInstance): Promise<void> {
|
||||
const { slug } = req.params;
|
||||
const limit = Math.min(parseInt(req.query.limit ?? '4', 10), 10);
|
||||
|
||||
// Fetch the article first to get its category
|
||||
const article = await swr_fetch(
|
||||
`${host}:wp:post:${slug}`,
|
||||
() => client.get_post_by_slug(slug),
|
||||
);
|
||||
let category_id: number;
|
||||
|
||||
if (req.query.category_id) {
|
||||
category_id = parseInt(req.query.category_id, 10);
|
||||
} else {
|
||||
const article = await swr_fetch(
|
||||
`${host}:wp:post:${slug}`,
|
||||
() => client.get_post_by_slug(slug),
|
||||
);
|
||||
category_id = article.category.id;
|
||||
}
|
||||
|
||||
const related = await swr_fetch<ArticleListItem[]>(
|
||||
`${host}:wp:related:${slug}:${limit}`,
|
||||
async () => {
|
||||
const posts = await client.get_posts_by_category_id(article.category.id, limit + 1);
|
||||
const posts = await client.get_posts_by_category_id(category_id, limit + 1);
|
||||
return posts.filter(p => p.slug !== slug).slice(0, limit);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AndebolTvStreamEvent } from '../services/andeboltv.js';
|
||||
import { fetch_andeboltv_stream_events } from '../services/andeboltv.js';
|
||||
import { get_fpa_agenda_from_store } from '../services/fpa-agenda.js';
|
||||
import { enrich_fpa_agenda_with_streams } from '../services/fpa-stream-match.js';
|
||||
import { enrich_fpa_agenda_with_standings_urls } from '../services/fpa-standings-url.js';
|
||||
|
||||
// Number of articles per section
|
||||
const HERO_COUNT = 3;
|
||||
@@ -151,7 +152,8 @@ export async function homepage_routes(app: FastifyInstance): Promise<void> {
|
||||
}
|
||||
}),
|
||||
]);
|
||||
return enrich_fpa_agenda_with_streams(games, streams);
|
||||
const with_streams = enrich_fpa_agenda_with_streams(games, streams);
|
||||
return enrich_fpa_agenda_with_standings_urls(with_streams);
|
||||
} catch (err) {
|
||||
app.log.warn({ err, host }, 'FPA agenda fetch failed');
|
||||
return [];
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
enrich_fpa_agenda_with_standings_urls,
|
||||
extract_fpa_competition_code,
|
||||
FPA_STANDINGS_FALLBACK_URL,
|
||||
resolve_fpa_standings_url,
|
||||
} from './fpa-standings-url.js';
|
||||
|
||||
test('extract_fpa_competition_code reads leading PO codes', () => {
|
||||
assert.equal(extract_fpa_competition_code('PO01 - Campeonato Betclic Masculino'), 'PO01');
|
||||
assert.equal(extract_fpa_competition_code('PO01A - Divisao de Honra Masculina'), 'PO01A');
|
||||
assert.equal(extract_fpa_competition_code('PO09 - Campeonato Betclic Feminino'), 'PO09');
|
||||
assert.equal(extract_fpa_competition_code('PARTICULARES SELECOES NACIONAIS'), null);
|
||||
});
|
||||
|
||||
test('resolve_fpa_standings_url maps Betclic leagues to Flashscore tables', () => {
|
||||
assert.match(
|
||||
resolve_fpa_standings_url('PO01 - Campeonato Betclic Masculino'),
|
||||
/campeonato-betclic-masculino\/classificacao\/$/,
|
||||
);
|
||||
assert.match(
|
||||
resolve_fpa_standings_url('PO09 - Campeonato Betclic Feminino'),
|
||||
/campeonato-betclic-feminino\/classificacao\/$/,
|
||||
);
|
||||
});
|
||||
|
||||
test('resolve_fpa_standings_url falls back by gender then national hub', () => {
|
||||
assert.match(
|
||||
resolve_fpa_standings_url('PO02 - Campeonato Nacional 2a Divisao Masculina'),
|
||||
/competicoes-nacionais-andebol-masculino\/$/,
|
||||
);
|
||||
assert.match(
|
||||
resolve_fpa_standings_url('PO10 - Campeonato Nacional 2a Divisao Feminina'),
|
||||
/competicoes-nacionais-andebol-feminino\/$/,
|
||||
);
|
||||
assert.equal(resolve_fpa_standings_url('PARTICULARES SELECOES NACIONAIS'), FPA_STANDINGS_FALLBACK_URL);
|
||||
});
|
||||
|
||||
test('enrich_fpa_agenda_with_standings_urls always sets standings_url', () => {
|
||||
const games: Array<{ competition: string; standings_url?: string | null }> = [
|
||||
{ competition: 'PO01 - Campeonato Betclic Masculino' },
|
||||
{ competition: 'Unknown cup', standings_url: null },
|
||||
];
|
||||
const enriched = enrich_fpa_agenda_with_standings_urls(games);
|
||||
assert.ok(enriched[0]?.standings_url.startsWith('https://'));
|
||||
assert.equal(enriched[1]?.standings_url, FPA_STANDINGS_FALLBACK_URL);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Resolve a public standings (classificação) URL for an FPA agenda competition name.
|
||||
*
|
||||
* Agenda rows only expose `PROVA` as a free-text label (e.g. "PO01 - Campeonato Betclic
|
||||
* Masculino"). There is no competition id in the feed. We map known competition codes to
|
||||
* public standings pages (Flashscore for top leagues that publish tables; FPA portal hubs
|
||||
* otherwise), with a national competitions fallback.
|
||||
*/
|
||||
|
||||
const FLASHSCORE_PT = 'https://www.flashscore.pt/andebol/portugal';
|
||||
const PORTAL_FPA = 'https://portal.fpa.pt';
|
||||
|
||||
/** General FPA national competitions hub (final fallback). */
|
||||
export const FPA_STANDINGS_FALLBACK_URL = `${PORTAL_FPA}/competicoes-nacionais/`;
|
||||
|
||||
const PORTAL_MASCULINO = `${PORTAL_FPA}/competicoes-nacionais-andebol-masculino/`;
|
||||
const PORTAL_FEMININO = `${PORTAL_FPA}/competicoes-nacionais-andebol-feminino/`;
|
||||
|
||||
/**
|
||||
* Competition code (from PROVA prefix) → public standings page.
|
||||
* Prefer pages that actually render a league table when available.
|
||||
*/
|
||||
const STANDINGS_BY_CODE: Record<string, string> = {
|
||||
PO01: `${FLASHSCORE_PT}/campeonato-betclic-masculino/classificacao/`,
|
||||
PO01A: PORTAL_MASCULINO,
|
||||
PO02: PORTAL_MASCULINO,
|
||||
PO03: PORTAL_MASCULINO,
|
||||
PO06: PORTAL_MASCULINO,
|
||||
PO09: `${FLASHSCORE_PT}/campeonato-betclic-feminino/classificacao/`,
|
||||
PO09A: PORTAL_FEMININO,
|
||||
PO10: PORTAL_FEMININO,
|
||||
PO12: PORTAL_FEMININO,
|
||||
PO20: `${FLASHSCORE_PT}/taca-de-portugal/`,
|
||||
PO23: PORTAL_FEMININO,
|
||||
};
|
||||
|
||||
/** Extract leading competition code such as PO01 / PO01A / PO09A from a PROVA label. */
|
||||
export function extract_fpa_competition_code(competition: string): string | null {
|
||||
const m = competition.trim().match(/^([A-Z]{1,3}\d{1,3}[A-Z]?)\b/i);
|
||||
return m?.[1] ? m[1].toUpperCase() : null;
|
||||
}
|
||||
|
||||
function gender_hub_url(competition: string): string | null {
|
||||
const lower = competition.toLowerCase();
|
||||
if (/\bfemin/i.test(lower)) {
|
||||
return PORTAL_FEMININO;
|
||||
}
|
||||
if (/\bmascul/i.test(lower)) {
|
||||
return PORTAL_MASCULINO;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Always returns a URL suitable for an external "Classificação" link.
|
||||
*/
|
||||
export function resolve_fpa_standings_url(competition: string): string {
|
||||
const code = extract_fpa_competition_code(competition);
|
||||
if (code && STANDINGS_BY_CODE[code]) {
|
||||
return STANDINGS_BY_CODE[code]!;
|
||||
}
|
||||
|
||||
return gender_hub_url(competition) ?? FPA_STANDINGS_FALLBACK_URL;
|
||||
}
|
||||
|
||||
/** Attach `standings_url` to each agenda game (idempotent). */
|
||||
export function enrich_fpa_agenda_with_standings_urls<T extends { competition: string; standings_url?: string | null }>(
|
||||
games: T[],
|
||||
): Array<T & { standings_url: string }> {
|
||||
return games.map((game) => ({
|
||||
...game,
|
||||
standings_url: game.standings_url || resolve_fpa_standings_url(game.competition),
|
||||
}));
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
WpTerm,
|
||||
WpUser,
|
||||
} from '../types.js';
|
||||
import { sanitize_article_html } from '../lib/sanitize-html.js';
|
||||
|
||||
const EMBED_VALUE = 'wp:featuredmedia,author,wp:term';
|
||||
|
||||
@@ -97,7 +98,7 @@ function normalize_post(post: WpPost): Article {
|
||||
|
||||
return {
|
||||
...list_item,
|
||||
content: post.content.rendered,
|
||||
content: sanitize_article_html(post.content.rendered),
|
||||
updated_at: post.modified,
|
||||
tags,
|
||||
};
|
||||
|
||||
@@ -40,6 +40,11 @@ export interface FpaAgendaGame {
|
||||
stream_status?: 'live' | 'upcoming' | null;
|
||||
/** Convenience flag when `stream_status === 'live'`. */
|
||||
is_live?: boolean;
|
||||
/**
|
||||
* Public standings (classificação) page for this competition.
|
||||
* Resolved from the PROVA label (code map + gender hub + FPA national fallback).
|
||||
*/
|
||||
standings_url?: string | null;
|
||||
}
|
||||
|
||||
export interface CategoryConfig {
|
||||
|
||||
@@ -92,6 +92,67 @@ Supporting figures: andebol.net home Total Blocking Time 5874 ms, main-thread wo
|
||||
- [BIT-28144](/BIT/issues/BIT-28144) — `andebol.net` (home + article) LCP ~8s / Performance ~30: render-path/CSS or third-party investigation (May TTFB was comparable to newsproject; not a network-floor issue alone).
|
||||
- [BIT-28145](/BIT/issues/BIT-28145) — `newsproject.bitreport.pt` article template TBT 7.4s (score 60, LCP still fine): main-thread profiling on article pages (likely heavy embed/widget).
|
||||
|
||||
## Root Cause & Fix — BIT-28145 — Article TBT 7416ms
|
||||
|
||||
**Date:** 2026-08-04
|
||||
**Auditor:** Miguel Teixeira (Database Engineer Agent)
|
||||
|
||||
### Root Cause
|
||||
|
||||
The article page (`/article/[slug]`) uses `set:html={sanitizeArticleHtml(article.content)}` to render WordPress CMS content. The ~100× TBT regression (7416ms vs 73ms on home) was caused by WordPress oEmbed HTML injected into article body:
|
||||
|
||||
1. **`<script>` tags** from Twitter, Instagram, YouTube embeds — already stripped by both bridge and frontend sanitizers.
|
||||
2. **`<style>` blocks** injected by WordPress oEmbed — **NOT** stripped. These cause synchronous style recalculation during HTML parsing.
|
||||
3. **`<link>` elements** injected by oEmbed (e.g. stylesheet links) — **NOT** stripped. These block rendering while external CSS is fetched and parsed.
|
||||
4. **Inline event handlers** (`onclick`, `onload`, `onerror`, etc.) — **NOT** stripped. These create long tasks during parsing.
|
||||
5. **`<iframe>` elements** for YouTube, Instagram embeds — previously lazy-loaded but still trigger expensive main-thread work (HTML parsing of embed documents, layout calculation). Even with `loading="lazy"`, the iframe document parse is heavy.
|
||||
6. **`<img>` tags without `loading="lazy"`** in WordPress body content — no lazy loading or async decoding.
|
||||
7. **`.article-body` div** had no `content-visibility: auto`, so the entire article body was rendered synchronously even when below the fold.
|
||||
|
||||
### Fix (deployed to both bridge and frontend sanitizers + CSS)
|
||||
|
||||
| Change | Files |
|
||||
|--------|-------|
|
||||
| Strip `<style>` blocks from article HTML | `bridge/src/lib/sanitize-html.ts`, `frontend/src/lib/sanitize-html.ts` |
|
||||
| Strip `<link>` elements from article HTML | both sanitizers |
|
||||
| Strip inline event handlers (`on*` attributes) | both sanitizers |
|
||||
| Replace `<iframe>` elements with click-to-load placeholders | both sanitizers, `frontend/src/styles/global.css` (placeholder styles), `frontend/src/pages/article/[slug].astro` (click handler script) |
|
||||
| Add `loading="lazy"` + `decoding="async"` to `<img>` tags in article body | both sanitizers |
|
||||
| Add `content-visibility: auto; contain-intrinsic-size: auto 5000px` to `.article-body` | `frontend/src/styles/global.css` |
|
||||
|
||||
### Expected Impact
|
||||
|
||||
- TBT should drop from ~7416ms to well under 600ms (conservative) on the same CPU-constrained host, as all synchronous script/style/link parsing and iframe document creation is eliminated.
|
||||
- Lighthouse Performance score should exceed 90 on article pages.
|
||||
- LCP remains unaffected (hero images already use `loading="eager"`).
|
||||
|
||||
### Deploy & Re-Verification — 2026-08-07
|
||||
|
||||
**Auditor:** Miguel Teixeira (Database Engineer Agent)
|
||||
|
||||
Fix merged to `main` via PR [#47](https://git.bitreport.pt/BitReport.pt/news-platform/pulls/47) on 2026-08-05 (3 approvals, CI green) and confirmed live on `newsproject.bitreport.pt`. An earlier deploy-verification confirmation was rejected on 2026-08-05 with reason "`https://newsproject.bitreport.pt/article/` 404" — that URL has no slug and is not a valid route; a real article URL returns `200`.
|
||||
|
||||
Lighthouse CLI 13.4.0 (Chrome for Testing 151.0.7922.71, headless, `--no-sandbox`), 5 runs against `newsproject.bitreport.pt/article/benfica-confirma-contratacao-do-guarda-redes-sueco-tobias-thulin`, plus a same-session home-page control (methodology per [[lighthouse-measurement-host-notes]] — host runs persistent background load, so multiple samples + a control page are required rather than trusting one run):
|
||||
|
||||
| Run | Performance | TBT | LCP |
|
||||
|---|---|---|---|
|
||||
| 1 | 86 | 348ms | 2769ms |
|
||||
| 2 | 99 | 0ms | 1894ms |
|
||||
| 3 | 99 | 0ms | 1886ms |
|
||||
| 4 | 99 | 0ms | 1910ms |
|
||||
| 5 | 99 | 0ms | 2051ms |
|
||||
| Home (control) | 83 | 0ms | 4669ms |
|
||||
|
||||
Median article Performance 99 (target ≥90), 4/5 runs ≥90; the one 86 run and the control's 83 both track back to LCP variance from host contention (TBT is 0ms across every run), not the TBT fix. **TBT regression is resolved**: 7416ms → 0-348ms.
|
||||
|
||||
Follow-up hardening committed under `fix/BIT-28145-tbt-followup` to widen the pass margin and close a test-coverage gap found during verification:
|
||||
- `bridge/package.json` `test`/`test:coverage` scripts did not actually run `sanitize-html.test.ts` (added in the original fix commit but never wired into the npm script) — the "28 bridge sanitizer tests pass" claim in PR #47 wasn't exercised by `npm test`. Fixed.
|
||||
- Deferred non-critical mobile-menu and share-button click handlers to `requestIdleCallback` (institutional/sports headers, `ArticleShareBar`) so they no longer compete with hydration-critical work.
|
||||
- Split the theme-flash-prevention script in `Base.astro` into a minimal inline `is:inline` snippet (runs before paint) and the click-handler logic (deferred), rather than one blocking script.
|
||||
- `bridge/src/routes/articles.ts` `/articles/:slug/related` accepts an optional `?category_id=` to skip a redundant WP post-by-slug fetch when the caller already has it.
|
||||
|
||||
Acceptance criteria for BIT-28145 are met: root cause documented, fix implemented and deployed, Lighthouse Performance ≥90 confirmed on live article pages (median 99).
|
||||
|
||||
---
|
||||
|
||||
## Root Cause, Fix & Deploy — BIT-28144 — andebol.net LCP ~8s / Performance ~26-38
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
22
|
||||
24.22.1
|
||||
@@ -4,7 +4,7 @@
|
||||
"version": "0.1.0",
|
||||
"description": "Astro SSR frontend for multi-domain sports news platform",
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
"node": ">=24.22.1"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
|
||||
@@ -61,17 +61,19 @@ const encoded_title = encodeURIComponent(title);
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.querySelectorAll('[data-share="copy"]').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const url = btn.getAttribute('data-url');
|
||||
if (!url) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
btn.classList.add('article-share__btn--copied');
|
||||
setTimeout(() => btn.classList.remove('article-share__btn--copied'), 2000);
|
||||
} catch {
|
||||
/* clipboard unavailable */
|
||||
}
|
||||
(typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout)(() => {
|
||||
document.querySelectorAll('[data-share="copy"]').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const url = btn.getAttribute('data-url');
|
||||
if (!url) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
btn.classList.add('article-share__btn--copied');
|
||||
setTimeout(() => btn.classList.remove('article-share__btn--copied'), 2000);
|
||||
} catch {
|
||||
/* clipboard unavailable */
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -114,6 +114,8 @@ const filtered_trending = trending.filter(t => t.slug !== article.slug).slice(0,
|
||||
border-radius: 10px;
|
||||
padding: var(--space-4);
|
||||
box-shadow: var(--shadow-sm);
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 200px;
|
||||
}
|
||||
|
||||
.article-sidebar__panel--muted {
|
||||
|
||||
@@ -72,6 +72,8 @@ const ui = getUiStrings(locale);
|
||||
margin-top: var(--space-12);
|
||||
padding-top: var(--space-8);
|
||||
border-top: 1px solid var(--color-border);
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 400px;
|
||||
}
|
||||
|
||||
.related-section__header {
|
||||
|
||||
@@ -12,7 +12,7 @@ interface Props {
|
||||
og_image?: string | null;
|
||||
og_type?: string;
|
||||
canonical?: string;
|
||||
schema?: object;
|
||||
schema?: object | object[];
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -92,13 +92,11 @@ const { Header, Footer } = getThemeComponents(config.theme);
|
||||
</main>
|
||||
<Footer config={config} />
|
||||
|
||||
<!-- Theme toggle script — no flash -->
|
||||
<!-- Theme toggle — critical: set theme immediately to prevent flash -->
|
||||
<script is:inline>
|
||||
(function(){var s=localStorage.getItem("theme");var p=window.matchMedia("(prefers-color-scheme:dark)").matches?"dark":"light";document.documentElement.setAttribute("data-theme",s||p)})();
|
||||
</script>
|
||||
<script>
|
||||
const saved = localStorage.getItem('theme');
|
||||
const preferred = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
const theme = saved ?? preferred;
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
const btn = (e.target as Element).closest('[data-theme-toggle]');
|
||||
if (!btn) return;
|
||||
|
||||
@@ -169,9 +169,14 @@ export class BridgeClient {
|
||||
);
|
||||
}
|
||||
|
||||
async getRelated(slug: string, limit = 4): Promise<ArticleListItem[]> {
|
||||
async getRelated(slug: string, limit = 4, categoryId?: number): Promise<ArticleListItem[]> {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('limit', String(limit));
|
||||
if (categoryId !== undefined) {
|
||||
qs.set('category_id', String(categoryId));
|
||||
}
|
||||
return fetchWithSWR<ArticleListItem[]>(
|
||||
`${this.base}/articles/${slug}/related?limit=${limit}`,
|
||||
`${this.base}/articles/${slug}/related?${qs.toString()}`,
|
||||
this.site_host,
|
||||
this.req_headers,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { sanitizeArticleHtml } from './sanitize-html.js';
|
||||
|
||||
describe('sanitizeArticleHtml', () => {
|
||||
it('strips script tags from article content', () => {
|
||||
const input = '<p>Hello</p><script>alert("xss")</script><p>World</p>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.equal(result, '<p>Hello</p><p>World</p>');
|
||||
});
|
||||
|
||||
it('strips script tags with src attribute', () => {
|
||||
const input = '<p>Text</p><script src="https://platform.twitter.com/widgets.js"></script><p>More</p>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.equal(result, '<p>Text</p><p>More</p>');
|
||||
});
|
||||
|
||||
it('strips style tags', () => {
|
||||
const input = '<style>.embed{color:red}</style><p>Text</p>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
it('strips link tags', () => {
|
||||
const input = '<link rel="stylesheet" href="https://cdn.example.com/embed.css"><p>Text</p>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.equal(result, '<p>Text</p>');
|
||||
});
|
||||
|
||||
it('strips inline event handlers', () => {
|
||||
const input = '<div onload="track()" onclick="handle()">Text</div>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(!result.includes('onload'));
|
||||
assert.ok(!result.includes('onclick'));
|
||||
assert.ok(result.includes('Text'));
|
||||
});
|
||||
|
||||
it('replaces iframes with click-to-load placeholders', () => {
|
||||
const input = '<iframe src="https://www.youtube.com/embed/abc123" width="560" height="315"></iframe>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(result.includes('embed-placeholder'));
|
||||
assert.ok(result.includes('data-embed-src'));
|
||||
assert.ok(!result.includes('<iframe'));
|
||||
});
|
||||
|
||||
it('preserves iframe title in placeholder aria-label', () => {
|
||||
const input = '<iframe src="https://www.youtube.com/embed/abc" title="Video player" width="560" height="315"></iframe>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(result.includes('aria-label="Video player"'));
|
||||
assert.ok(result.includes('<span>Video player</span>'));
|
||||
});
|
||||
|
||||
it('preserves non-script, non-iframe, non-style content unchanged', () => {
|
||||
const input = '<div><p>Hello</p><blockquote>Quote</blockquote></div>';
|
||||
assert.equal(sanitizeArticleHtml(input), input);
|
||||
});
|
||||
|
||||
it('handles WordPress Twitter embed', () => {
|
||||
const input = '<blockquote class="twitter-tweet"><p>Tweet text</p></blockquote><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(!result.includes('<script'));
|
||||
assert.ok(result.includes('<blockquote'));
|
||||
});
|
||||
|
||||
it('handles combined script strip and iframe placeholder', () => {
|
||||
const input = '<script src="https://platform.twitter.com/widgets.js"></script><p>Text</p><iframe src="https://www.youtube.com/embed/abc"></iframe>';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(!result.includes('<script'));
|
||||
assert.ok(result.includes('embed-placeholder'));
|
||||
assert.ok(result.includes('<p>Text</p>'));
|
||||
});
|
||||
|
||||
it('adds loading=lazy and decoding=async to images without those attributes', () => {
|
||||
const input = '<img src="photo.jpg" alt="Photo">';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(result.includes('loading="lazy"'));
|
||||
assert.ok(result.includes('decoding="async"'));
|
||||
assert.ok(result.includes('alt="Photo"'));
|
||||
});
|
||||
|
||||
it('does not add loading=lazy to images that already have it', () => {
|
||||
const input = '<img src="photo.jpg" loading="eager" alt="Photo">';
|
||||
const result = sanitizeArticleHtml(input);
|
||||
assert.ok(result.includes('loading="eager"'));
|
||||
assert.ok(!result.includes('loading="lazy"'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Sanitize WordPress article HTML to reduce client-side Total Blocking Time.
|
||||
*
|
||||
* WordPress oEmbed embeds (Twitter, Instagram, YouTube, etc.) inject <script>
|
||||
* tags, <iframe> elements, <style> blocks, <link> elements, and inline event
|
||||
* handlers that block the main thread during HTML parsing. This sanitizer
|
||||
* strips all of those and replaces iframes with click-to-load placeholders,
|
||||
* as a defense-in-depth measure alongside the bridge-side sanitizer in
|
||||
* bridge/src/lib/sanitize-html.ts.
|
||||
*
|
||||
* Related: BIT-28145 (article TBT 7416ms → target Lighthouse Perf ≥ 90).
|
||||
*/
|
||||
|
||||
function stripScripts(html: string): string {
|
||||
return html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '');
|
||||
}
|
||||
|
||||
function stripStyles(html: string): string {
|
||||
return html.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '');
|
||||
}
|
||||
|
||||
function stripLinks(html: string): string {
|
||||
return html.replace(/<link\b[^>]*>/gi, '');
|
||||
}
|
||||
|
||||
function stripInlineEventHandlers(html: string): string {
|
||||
return html.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
|
||||
}
|
||||
|
||||
function lazyLoadImages(html: string): string {
|
||||
return html.replace(
|
||||
/<img\b([^>]*)>/gi,
|
||||
(match: string, attrs: string) => {
|
||||
let newAttrs = attrs;
|
||||
if (!/\bloading\s*=/i.test(newAttrs)) {
|
||||
newAttrs += ' loading="lazy"';
|
||||
}
|
||||
if (!/\bdecoding\s*=/i.test(newAttrs)) {
|
||||
newAttrs += ' decoding="async"';
|
||||
}
|
||||
return `<img${newAttrs}>`;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const IFRAME_RE = /<iframe\b([^>]*)>([\s\S]*?<\/iframe>)?/gi;
|
||||
|
||||
function replaceIframesWithPlaceholders(html: string): string {
|
||||
return html.replace(IFRAME_RE, (_match: string, attrs: string) => {
|
||||
const srcMatch = attrs.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const src = srcMatch?.[1] ?? srcMatch?.[2] ?? '';
|
||||
if (!src) return '';
|
||||
|
||||
const titleMatch = attrs.match(/\btitle\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const title = titleMatch?.[1] ?? titleMatch?.[2] ?? '';
|
||||
|
||||
const widthMatch = attrs.match(/\bwidth\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const width = widthMatch?.[1] ?? widthMatch?.[2] ?? '';
|
||||
|
||||
const heightMatch = attrs.match(/\bheight\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
||||
const height = heightMatch?.[1] ?? heightMatch?.[2] ?? '';
|
||||
|
||||
const escapedSrc = src.replace(/&/g, '&').replace(/"/g, '"');
|
||||
const styleParts: string[] = ['display:block', 'max-width:100%'];
|
||||
if (width) styleParts.push(`width:${width}px`);
|
||||
if (height) styleParts.push(`aspect-ratio:${width}/${height}`);
|
||||
|
||||
return (
|
||||
`<div class="embed-placeholder" style="${styleParts.join(';')}" ` +
|
||||
`data-embed-src="${escapedSrc}" ` +
|
||||
`data-embed-type="iframe" ` +
|
||||
`role="button" ` +
|
||||
`tabindex="0" ` +
|
||||
`aria-label="${title || 'Load embedded content'}">` +
|
||||
`<button class="embed-placeholder__btn" type="button" ` +
|
||||
`data-embed-src="${escapedSrc}" ` +
|
||||
`data-embed-width="${width}" ` +
|
||||
`data-embed-height="${height}">` +
|
||||
`<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="2" y="3" width="20" height="14" rx="2"/><polygon points="10 8 16 10.5 10 13"/></svg>` +
|
||||
`<span>${title || 'Load embedded content'}</span></button></div>`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function sanitizeArticleHtml(html: string): string {
|
||||
let result = html;
|
||||
result = stripScripts(result);
|
||||
result = stripStyles(result);
|
||||
result = stripLinks(result);
|
||||
result = stripInlineEventHandlers(result);
|
||||
result = replaceIframesWithPlaceholders(result);
|
||||
result = lazyLoadImages(result);
|
||||
return result;
|
||||
}
|
||||
@@ -60,6 +60,7 @@ export type UiStrings = {
|
||||
fpa_status_live: string;
|
||||
fpa_watch_live: string;
|
||||
fpa_watch_stream: string;
|
||||
fpa_standings_link: string;
|
||||
fpa_games_on_date: (count: number) => string;
|
||||
/** News archive page title */
|
||||
news_archive_title: string;
|
||||
@@ -172,6 +173,7 @@ const en: UiStrings = {
|
||||
fpa_status_live: 'Live',
|
||||
fpa_watch_live: 'Watch live',
|
||||
fpa_watch_stream: 'Watch on AndebolTV',
|
||||
fpa_standings_link: 'Standings',
|
||||
fpa_games_on_date: count => (count === 1 ? '1 match' : `${count} matches`),
|
||||
news_archive_title: 'News',
|
||||
news_all_filter: 'All',
|
||||
@@ -268,6 +270,7 @@ const pt: UiStrings = {
|
||||
fpa_status_live: 'Em direto',
|
||||
fpa_watch_live: 'Ver em direto',
|
||||
fpa_watch_stream: 'Ver na AndebolTV',
|
||||
fpa_standings_link: 'Classificação',
|
||||
fpa_games_on_date: count => (count === 1 ? '1 jogo' : `${count} jogos`),
|
||||
news_archive_title: 'Notícias',
|
||||
news_all_filter: 'Todas',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
import type { ArticleListItem } from '../../types/index.js';
|
||||
import Base from '../../layouts/Base.astro';
|
||||
import ArticleHeader from '../../components/article/ArticleHeader.astro';
|
||||
import ArticleSidebar from '../../components/article/ArticleSidebar.astro';
|
||||
@@ -9,6 +10,7 @@ import { BridgeClient, resolveSsrBridge } from '../../lib/bridge.js';
|
||||
import { formatDate } from '../../lib/format.js';
|
||||
import { getPublicOrigin } from '../../lib/public-origin.js';
|
||||
import { getUiStrings } from '../../lib/ui-i18n.js';
|
||||
import { sanitizeArticleHtml } from '../../lib/sanitize-html.js';
|
||||
|
||||
const { slug } = Astro.params;
|
||||
if (!slug) return Astro.redirect('/');
|
||||
@@ -27,17 +29,23 @@ try {
|
||||
}
|
||||
|
||||
let article;
|
||||
let related;
|
||||
let trending;
|
||||
try {
|
||||
article = await bridge.getArticle(slug);
|
||||
} catch {
|
||||
return Astro.redirect('/');
|
||||
}
|
||||
|
||||
const category_id = article.category.id;
|
||||
|
||||
let related: ArticleListItem[] = [];
|
||||
let trending: ArticleListItem[] = [];
|
||||
|
||||
try {
|
||||
[article, related, trending] = await Promise.all([
|
||||
bridge.getArticle(slug),
|
||||
bridge.getRelated(slug, 4),
|
||||
[related, trending] = await Promise.all([
|
||||
bridge.getRelated(slug, 4, category_id),
|
||||
bridge.getTrending(6),
|
||||
]);
|
||||
} catch {
|
||||
return Astro.redirect('/');
|
||||
}
|
||||
|
||||
const public_origin = getPublicOrigin(Astro.request);
|
||||
@@ -92,9 +100,10 @@ const breadcrumb_schema = {
|
||||
og_image={article.featured_image}
|
||||
og_type="article"
|
||||
canonical={canonical}
|
||||
schema={news_article_schema}
|
||||
schema={[news_article_schema, breadcrumb_schema]}
|
||||
>
|
||||
<script type="application/ld+json" set:html={JSON.stringify(breadcrumb_schema)} slot="head" />
|
||||
<link rel="preconnect" href="https://secure.gravatar.com" slot="head" />
|
||||
<link rel="preconnect" href={new URL(article.featured_image ?? '').origin} slot="head" />
|
||||
|
||||
<article class:list={['article-page', is_institutional && 'article-page--inst']}>
|
||||
{is_institutional ? (
|
||||
@@ -184,7 +193,7 @@ const breadcrumb_schema = {
|
||||
<div class="ad-slot ad-slot--in-article" aria-label={ui.ad_slot_aria}>{ui.ad_slot_text}</div>
|
||||
)}
|
||||
|
||||
<div class="article-body" set:html={article.content} />
|
||||
<div class="article-body" set:html={sanitizeArticleHtml(article.content)} />
|
||||
|
||||
{article.tags.length > 0 && (
|
||||
<footer class="article-tags">
|
||||
@@ -242,11 +251,55 @@ const breadcrumb_schema = {
|
||||
</article>
|
||||
</Base>
|
||||
|
||||
<script>
|
||||
document.addEventListener('click', (e) => {
|
||||
const btn = (e.target as Element).closest('[data-embed-src]');
|
||||
if (!btn) return;
|
||||
const src = btn.getAttribute('data-embed-src');
|
||||
if (!src) return;
|
||||
const width = btn.getAttribute('data-embed-width');
|
||||
const height = btn.getAttribute('data-embed-height');
|
||||
const placeholder = btn.closest('.embed-placeholder');
|
||||
if (!placeholder) return;
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.src = src;
|
||||
iframe.loading = 'lazy';
|
||||
if (width) iframe.width = width;
|
||||
if (height) iframe.height = height;
|
||||
iframe.title = placeholder.getAttribute('aria-label') || '';
|
||||
iframe.style.cssText = 'width:100%;max-width:100%;border:0;display:block';
|
||||
placeholder.replaceWith(iframe);
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||
const target = e.target as Element;
|
||||
if (target.closest('.embed-placeholder')) {
|
||||
target.closest('.embed-placeholder')?.querySelector('[data-embed-src]')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.article-page {
|
||||
padding-bottom: var(--space-12);
|
||||
}
|
||||
|
||||
.related-section {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 400px;
|
||||
}
|
||||
|
||||
.article-byline-footer {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 100px;
|
||||
}
|
||||
|
||||
.article-tags {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 40px;
|
||||
}
|
||||
|
||||
.article-page--inst .article-layout {
|
||||
padding-top: var(--space-8);
|
||||
}
|
||||
|
||||
@@ -341,6 +341,8 @@ img {
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.85;
|
||||
color: var(--color-text);
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 5000px;
|
||||
}
|
||||
|
||||
.article-body > p:first-of-type::first-letter {
|
||||
@@ -485,3 +487,55 @@ img {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ---- Embed placeholder (click-to-load for oEmbed iframes) ---- */
|
||||
.embed-placeholder {
|
||||
background: var(--color-bg-secondary);
|
||||
border: 2px dashed var(--color-border);
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: var(--space-6) auto;
|
||||
max-width: 100%;
|
||||
min-height: 200px;
|
||||
cursor: pointer;
|
||||
transition: border-color var(--transition-fast), background var(--transition-fast);
|
||||
}
|
||||
|
||||
.embed-placeholder:hover,
|
||||
.embed-placeholder:focus-within {
|
||||
border-color: var(--color-primary);
|
||||
background: color-mix(in srgb, var(--color-primary) 6%, var(--color-bg-secondary));
|
||||
}
|
||||
|
||||
.embed-placeholder__btn {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 600;
|
||||
padding: var(--space-6);
|
||||
border-radius: 8px;
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.embed-placeholder__btn:hover,
|
||||
.embed-placeholder__btn:focus-visible {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.embed-placeholder__btn svg {
|
||||
opacity: 0.5;
|
||||
transition: opacity var(--transition-fast);
|
||||
}
|
||||
|
||||
.embed-placeholder__btn:hover svg,
|
||||
.embed-placeholder__btn:focus-visible svg {
|
||||
opacity: 0.8;
|
||||
}
|
||||
@@ -70,6 +70,7 @@ const date_groups = [...by_date.entries()];
|
||||
const finished = is_finished(g);
|
||||
const score = format_score(g);
|
||||
const has_stream = Boolean(g.stream_url);
|
||||
const standings_url = g.standings_url || 'https://portal.fpa.pt/competicoes-nacionais/';
|
||||
const is_live = Boolean(g.is_live);
|
||||
const status_label = finished
|
||||
? ui.fpa_status_finished
|
||||
@@ -173,6 +174,14 @@ const date_groups = [...by_date.entries()];
|
||||
<span>{g.venue}</span>
|
||||
</span>
|
||||
)}
|
||||
<a
|
||||
class="fpa-agenda__standings-link"
|
||||
href={standings_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{ui.fpa_standings_link}
|
||||
</a>
|
||||
{has_stream && (
|
||||
<a
|
||||
class="fpa-agenda__stream-link"
|
||||
@@ -603,15 +612,24 @@ const date_groups = [...by_date.entries()];
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.fpa-agenda__standings-link,
|
||||
.fpa-agenda__stream-link {
|
||||
margin-left: auto;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 700;
|
||||
color: #a20c17;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.fpa-agenda__standings-link {
|
||||
margin-left: auto;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.fpa-agenda__stream-link {
|
||||
color: #a20c17;
|
||||
}
|
||||
|
||||
.fpa-agenda__standings-link:hover,
|
||||
.fpa-agenda__stream-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@@ -609,15 +609,17 @@ const news_archive_active =
|
||||
</style>
|
||||
|
||||
<script>
|
||||
const btn = document.querySelector('.inst-header__menu-btn') as HTMLButtonElement | null;
|
||||
const menu = document.getElementById('inst-mobile-menu');
|
||||
const labelOpen = btn?.dataset.menuLabelOpen ?? 'Open menu';
|
||||
const labelClose = btn?.dataset.menuLabelClose ?? 'Close menu';
|
||||
(typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout)(() => {
|
||||
const btn = document.querySelector('.inst-header__menu-btn') as HTMLButtonElement | null;
|
||||
const menu = document.getElementById('inst-mobile-menu');
|
||||
const labelOpen = btn?.dataset.menuLabelOpen ?? 'Open menu';
|
||||
const labelClose = btn?.dataset.menuLabelClose ?? 'Close menu';
|
||||
|
||||
btn?.addEventListener('click', () => {
|
||||
const is_open = menu?.getAttribute('aria-hidden') === 'false';
|
||||
menu?.setAttribute('aria-hidden', is_open ? 'true' : 'false');
|
||||
btn.setAttribute('aria-expanded', is_open ? 'false' : 'true');
|
||||
btn.setAttribute('aria-label', is_open ? labelOpen : labelClose);
|
||||
btn?.addEventListener('click', () => {
|
||||
const is_open = menu?.getAttribute('aria-hidden') === 'false';
|
||||
menu?.setAttribute('aria-hidden', is_open ? 'true' : 'false');
|
||||
btn.setAttribute('aria-expanded', is_open ? 'false' : 'true');
|
||||
btn.setAttribute('aria-label', is_open ? labelOpen : labelClose);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -285,13 +285,15 @@ const auth_labels = show_auth ? authNavLabels(config) : null;
|
||||
</style>
|
||||
|
||||
<script>
|
||||
const btn = document.querySelector('.btn-menu') as HTMLButtonElement | null;
|
||||
const menu = document.getElementById('mobile-menu');
|
||||
(typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout)(() => {
|
||||
const btn = document.querySelector('.btn-menu') as HTMLButtonElement | null;
|
||||
const menu = document.getElementById('mobile-menu');
|
||||
|
||||
btn?.addEventListener('click', () => {
|
||||
const is_open = menu?.getAttribute('aria-hidden') === 'false';
|
||||
menu?.setAttribute('aria-hidden', is_open ? 'true' : 'false');
|
||||
btn.setAttribute('aria-expanded', is_open ? 'false' : 'true');
|
||||
btn.setAttribute('aria-label', is_open ? 'Open menu' : 'Close menu');
|
||||
btn?.addEventListener('click', () => {
|
||||
const is_open = menu?.getAttribute('aria-hidden') === 'false';
|
||||
menu?.setAttribute('aria-hidden', is_open ? 'true' : 'false');
|
||||
btn.setAttribute('aria-expanded', is_open ? 'false' : 'true');
|
||||
btn.setAttribute('aria-label', is_open ? 'Open menu' : 'Close menu');
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -55,6 +55,11 @@ export interface FpaAgendaGame {
|
||||
stream_status?: 'live' | 'upcoming' | null;
|
||||
/** Convenience flag when `stream_status === 'live'`. */
|
||||
is_live?: boolean;
|
||||
/**
|
||||
* Public standings (classificação) page for this competition.
|
||||
* Resolved from the PROVA label (code map + gender hub + FPA national fallback).
|
||||
*/
|
||||
standings_url?: string | null;
|
||||
}
|
||||
|
||||
export interface Article {
|
||||
|
||||
@@ -17,7 +17,7 @@ services:
|
||||
start_period: 90s
|
||||
|
||||
wordpress:
|
||||
image: wordpress:6-php8.3-fpm
|
||||
image: wordpress:6-php8.4-fpm
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
@@ -135,7 +135,7 @@ services:
|
||||
start_period: 90s
|
||||
|
||||
wordpress-andebol:
|
||||
image: wordpress:6-php8.3-fpm
|
||||
image: wordpress:6-php8.4-fpm
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db-andebol:
|
||||
|
||||
@@ -70,14 +70,14 @@
|
||||
{
|
||||
"id": "eurohandball_sitemap",
|
||||
"kind": "sitemap",
|
||||
"url": "https://www.eurohandball.com/sitemap.xml",
|
||||
"url": "https://www.eurohandball.com/google-news-sitemap.xml",
|
||||
"enabled": true,
|
||||
"topics": ["handball", "ehf"],
|
||||
"maxItems": 20,
|
||||
"pathIncludes": ["/news/", "/match-center/"],
|
||||
"timeoutMs": 25000,
|
||||
"pageTimeoutMs": 35000,
|
||||
"note": "EHF/Eurohandball: main sitemap is huge; path filter keeps news/match pages only (competition index URLs are heavy and not article content — BIT-25342)."
|
||||
"note": "EHF/Eurohandball: use google-news-sitemap (robots.txt) — main /sitemap.xml returns HTTP 500 (BIT-30741 / ERRSIG ca1ec5408f4a). Path filter keeps news/match pages (BIT-25342)."
|
||||
},
|
||||
{
|
||||
"id": "record_pt_main",
|
||||
|
||||
@@ -25,5 +25,8 @@
|
||||
"@types/node": "^20.14.0",
|
||||
"tsx": "^4.15.0",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
@@ -22,9 +22,28 @@ describe('cycleErrorMessageLevel', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps whole-source sitemap failures as error', () => {
|
||||
it('downgrades whole-source sitemap gateway blips to warning (BIT-30847)', () => {
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'sitemap eurohandball_sitemap (https://www.eurohandball.com/google-news-sitemap.xml): HTTP 502',
|
||||
),
|
||||
'warning',
|
||||
);
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel('sitemap eurohandball_sitemap (https://www.eurohandball.com/sitemap.xml): HTTP 503'),
|
||||
'warning',
|
||||
);
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'sitemap eurohandball_sitemap (https://www.eurohandball.com/google-news-sitemap.xml): HTTP 504',
|
||||
),
|
||||
'warning',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps whole-source sitemap HTTP 500 as error (actionable upstream/config)', () => {
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel('sitemap eurohandball_sitemap (https://www.eurohandball.com/sitemap.xml): HTTP 500'),
|
||||
'error',
|
||||
);
|
||||
});
|
||||
@@ -35,6 +54,34 @@ describe('cycleErrorMessageLevel', () => {
|
||||
'warning',
|
||||
);
|
||||
});
|
||||
|
||||
it('downgrades per-item draft undici fetch failed to warning (BIT-30583)', () => {
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'draft https://www.record.pt/modalidades/andebol/detalhe/benfica-bate-abc-e-comanda-o-campeonato-feminino?ref=Andebol_DestaquesPrincipais: fetch failed',
|
||||
),
|
||||
'warning',
|
||||
);
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'draft https://example.com/a: WP draft network error: fetch failed',
|
||||
),
|
||||
'warning',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps non-network draft failures as error', () => {
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel('draft https://example.com/a: WP draft failed 401: unauthorized'),
|
||||
'error',
|
||||
);
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'draft https://example.com/a: Mandatory featured image: no og:image for https://example.com/a',
|
||||
),
|
||||
'error',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reportCycleErrors', () => {
|
||||
|
||||
@@ -58,20 +58,52 @@ export async function fetchTextWithRetry(
|
||||
export async function fetchBinaryWithRetry(
|
||||
url: string,
|
||||
opts: FetchBinaryOptions = {},
|
||||
): Promise<Response> {
|
||||
return fetchResponseWithRetry(url, {
|
||||
method: 'GET',
|
||||
timeoutMs: opts.timeoutMs ?? 20_000,
|
||||
retries: opts.retries ?? 2,
|
||||
headers: {
|
||||
'User-Agent': opts.userAgent ?? DEFAULT_UA,
|
||||
...(opts.headers ?? {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface FetchResponseOptions {
|
||||
method?: string;
|
||||
timeoutMs?: number;
|
||||
retries?: number;
|
||||
headers?: Record<string, string>;
|
||||
body?: BodyInit | null;
|
||||
/** Retry on HTTP 5xx (default true). */
|
||||
retryOn5xx?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* fetch with bounded retries for transient network errors (and optional 5xx).
|
||||
* Used for WP REST POSTs that previously threw bare undici "fetch failed" (BIT-30583).
|
||||
*/
|
||||
export async function fetchResponseWithRetry(
|
||||
url: string,
|
||||
opts: FetchResponseOptions = {},
|
||||
): Promise<Response> {
|
||||
const timeoutMs = opts.timeoutMs ?? 20_000;
|
||||
const retries = Math.max(0, opts.retries ?? 2);
|
||||
const ua = opts.userAgent ?? DEFAULT_UA;
|
||||
const extraHeaders = opts.headers ?? {};
|
||||
const method = opts.method ?? 'GET';
|
||||
const headers = opts.headers ?? {};
|
||||
const retryOn5xx = opts.retryOn5xx !== false;
|
||||
let lastErr: unknown;
|
||||
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
redirect: 'follow',
|
||||
headers: { 'User-Agent': ua, ...extraHeaders },
|
||||
headers,
|
||||
body: opts.body ?? undefined,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (res.status >= 500 && attempt < retries) {
|
||||
if (retryOn5xx && res.status >= 500 && attempt < retries) {
|
||||
await sleep(400 * (attempt + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
titleFromArticleUrl,
|
||||
} from './html-listing.js';
|
||||
import {
|
||||
decodeJsonUnicodeEscapes,
|
||||
extractRevistaPdfUrls,
|
||||
isHandballRevistaLead,
|
||||
leadUrlForRevistaEntry,
|
||||
@@ -88,6 +89,21 @@ test('extractRevistaPdfUrls finds absolute and relative PDF hrefs', () => {
|
||||
assert.ok(urls[0].includes('18.06.2026'));
|
||||
});
|
||||
|
||||
test('decodeJsonUnicodeEscapes turns literal \\u2013 into en-dash (BIT-31118)', () => {
|
||||
assert.equal(decodeJsonUnicodeEscapes('Revista-de-Imprensa-\\u2013-12.10.2026.pdf'), 'Revista-de-Imprensa-\u2013-12.10.2026.pdf');
|
||||
});
|
||||
|
||||
test('extractRevistaPdfUrls decodes literal \\u2013 so URL is not /u2013 (BIT-31118)', () => {
|
||||
const html = `
|
||||
"pdf":"https://portal.fpa.pt/wp-content/uploads/2026/10/Revista-de-Imprensa-\\u2013-12.10.2026.pdf"
|
||||
`;
|
||||
const urls = extractRevistaPdfUrls(html, 'https://portal.fpa.pt/media/');
|
||||
assert.equal(urls.length, 1);
|
||||
assert.ok(!urls[0].includes('/u2013'), urls[0]);
|
||||
assert.ok(urls[0].includes('%E2%80%93') || urls[0].includes('\u2013'), urls[0]);
|
||||
assert.ok(urls[0].includes('12.10.2026'));
|
||||
});
|
||||
|
||||
test('publishedAtFromPtDate parses DD/MM/YYYY', () => {
|
||||
const iso = publishedAtFromPtDate('17/06/2026', '2026-01-01T00:00:00.000Z');
|
||||
assert.equal(iso.slice(0, 10), '2026-06-17');
|
||||
@@ -98,6 +114,18 @@ test('pdfDateFromRevistaUrl parses filename date', () => {
|
||||
pdfDateFromRevistaUrl('https://portal.fpa.pt/wp-content/uploads/2026/06/Revista-de-Imprensa-18.06.2026.pdf'),
|
||||
'2026-06-18',
|
||||
);
|
||||
assert.equal(
|
||||
pdfDateFromRevistaUrl(
|
||||
'https://portal.fpa.pt/wp-content/uploads/2026/10/Revista-de-Imprensa-%E2%80%93-12.10.2026.pdf',
|
||||
),
|
||||
'2026-10-12',
|
||||
);
|
||||
assert.equal(
|
||||
pdfDateFromRevistaUrl(
|
||||
'https://portal.fpa.pt/wp-content/uploads/2026/10/Revista-de-Imprensa-12.10.2026-9a3f277b.pdf',
|
||||
),
|
||||
'2026-10-12',
|
||||
);
|
||||
});
|
||||
|
||||
test('isHandballRevistaLead detects andebol keywords', () => {
|
||||
|
||||
@@ -2,10 +2,29 @@ import { reportError, reportMessage } from './errorReporter.js';
|
||||
|
||||
/** Map ingest cycle strings to hub severity (partial sitemap page failures are warnings, not loops). */
|
||||
export function cycleErrorMessageLevel(message: string): 'warning' | 'error' {
|
||||
// Per-item draft publish: undici transient network (BIT-30583 / ERRSIG f723b02cf00e).
|
||||
// Cycle still records the miss; Error Loop must not open high-sev tickets for one-off fetch blips.
|
||||
if (
|
||||
/^draft https?:\/\//i.test(message) &&
|
||||
/fetch failed|network error|aborted|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up/i.test(
|
||||
message,
|
||||
)
|
||||
) {
|
||||
return 'warning';
|
||||
}
|
||||
if (!message.startsWith('sitemap')) return 'error';
|
||||
if (message.includes('truncating')) return 'warning';
|
||||
// Per-URL HTML probe failed but other pages in the same source may have succeeded.
|
||||
if (/^sitemap .+ page \(https?:\/\//.test(message)) return 'warning';
|
||||
// Whole-source fetch already retries (http-retry); remaining gateway blips are upstream
|
||||
// noise (BIT-30847 / ERRSIG a92b3521aec8). Keep HTTP 500 as error — that flagged the
|
||||
// broken /sitemap.xml URL fixed in BIT-30741.
|
||||
if (
|
||||
/^sitemap .+ \(https?:\/\//.test(message) &&
|
||||
/: HTTP (502|503|504)\b/.test(message)
|
||||
) {
|
||||
return 'warning';
|
||||
}
|
||||
return 'error';
|
||||
}
|
||||
|
||||
|
||||
@@ -100,13 +100,25 @@ export function isHandballRevistaLead(title: string, source: string): boolean {
|
||||
return /andebol|handball|\behf\b|liga dos campeões de andebol|fpa\b/.test(hay);
|
||||
}
|
||||
|
||||
/**
|
||||
* FPA media JSON sometimes embeds PDF filenames with a *literal* `\u2013`
|
||||
* (en-dash) escape. `new URL` treats `\` as a path separator and turns that
|
||||
* into `/u2013`, which 404s. Decode JSON-style `\uXXXX` before URL parsing
|
||||
* (BIT-31118 / ERRSIG 97ac27c4c5df).
|
||||
*/
|
||||
export function decodeJsonUnicodeEscapes(raw: string): string {
|
||||
return raw.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex: string) =>
|
||||
String.fromCharCode(parseInt(hex, 16)),
|
||||
);
|
||||
}
|
||||
|
||||
export function extractRevistaPdfUrls(html: string, pageUrl: string): string[] {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
|
||||
const add = (raw: string) => {
|
||||
try {
|
||||
const href = new URL(raw, pageUrl).href;
|
||||
const href = new URL(decodeJsonUnicodeEscapes(raw), pageUrl).href;
|
||||
if (!seen.has(href)) {
|
||||
seen.add(href);
|
||||
out.push(href);
|
||||
@@ -134,7 +146,13 @@ export async function parseRevistaPdfBuffer(buffer: Buffer): Promise<RevistaEntr
|
||||
}
|
||||
|
||||
export function pdfDateFromRevistaUrl(pdfUrl: string): string | null {
|
||||
const m = pdfUrl.match(/Revista-de-Imprensa-(\d{2})\.(\d{2})\.(\d{4})\.pdf/i);
|
||||
// Accept hyphen or en-dash before the date, and optional WP hash suffix:
|
||||
// Revista-de-Imprensa-12.10.2026.pdf
|
||||
// Revista-de-Imprensa-–-12.10.2026.pdf
|
||||
// Revista-de-Imprensa-12.10.2026-9a3f277b.pdf
|
||||
const m = pdfUrl.match(
|
||||
/Revista-de-Imprensa-(?:(?:\u2013|%E2%80%93)-)?(\d{2})\.(\d{2})\.(\d{4})(?:-[a-f0-9]+)?\.pdf/i,
|
||||
);
|
||||
if (!m) return null;
|
||||
return `${m[3]}-${m[2]}-${m[1]}`;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import type { AggregatedItem } from './types.js';
|
||||
import { fetchArticleHtmlForMeta } from './legacy-fetch.js';
|
||||
import { fetchBinaryWithRetry } from './http-retry.js';
|
||||
import { fetchBinaryWithRetry, fetchResponseWithRetry } from './http-retry.js';
|
||||
import { absolutizeImageUrl, extractFeaturedImageFromHtml } from './html-meta.js';
|
||||
import {
|
||||
readWebDavArchiveFromEnv,
|
||||
@@ -198,6 +198,12 @@ export async function resolveFeaturedImageForDraft(item: AggregatedItem): Promis
|
||||
);
|
||||
}
|
||||
|
||||
function isTransientNetworkMessage(msg: string): boolean {
|
||||
return /fetch failed|aborted|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up/i.test(
|
||||
msg,
|
||||
);
|
||||
}
|
||||
|
||||
async function downloadBinaryImage(
|
||||
imageUrl: string,
|
||||
extraHeaders?: Record<string, string>,
|
||||
@@ -206,12 +212,21 @@ async function downloadBinaryImage(
|
||||
'User-Agent': 'BitReport-news-writer-pipeline/1.0 (media)',
|
||||
...(extraHeaders ?? {}),
|
||||
};
|
||||
const res = await fetchBinaryWithRetry(imageUrl, {
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
userAgent: headers['User-Agent'],
|
||||
headers,
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchBinaryWithRetry(imageUrl, {
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
userAgent: headers['User-Agent'],
|
||||
headers,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (isTransientNetworkMessage(msg)) {
|
||||
throw new Error(`Featured image network error for ${imageUrl}: ${msg}`);
|
||||
}
|
||||
throw e instanceof Error ? e : new Error(String(e));
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(`Featured image fetch failed ${res.status} for ${imageUrl}`);
|
||||
}
|
||||
@@ -255,12 +270,20 @@ async function uploadFeaturedMedia(
|
||||
const form = new FormData();
|
||||
form.append('file', blob, filename);
|
||||
|
||||
const res = await fetch(`${base}/wp/v2/media`, {
|
||||
method: 'POST',
|
||||
headers: mediaPostHeaders(cfg),
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchResponseWithRetry(`${base}/wp/v2/media`, {
|
||||
method: 'POST',
|
||||
headers: mediaPostHeaders(cfg),
|
||||
body: form,
|
||||
timeoutMs: 30_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP media upload network error: ${msg}`);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
@@ -272,15 +295,23 @@ async function uploadFeaturedMedia(
|
||||
if (!mediaId) throw new Error('WP media upload returned no id');
|
||||
|
||||
if (credit) {
|
||||
const patch = await fetch(`${base}/wp/v2/media/${mediaId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({
|
||||
alt_text: credit.slice(0, 500),
|
||||
caption: credit.slice(0, 2000),
|
||||
}),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
let patch: Response;
|
||||
try {
|
||||
patch = await fetchResponseWithRetry(`${base}/wp/v2/media/${mediaId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({
|
||||
alt_text: credit.slice(0, 500),
|
||||
caption: credit.slice(0, 2000),
|
||||
}),
|
||||
timeoutMs: 15_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP media caption/alt network error: ${msg}`);
|
||||
}
|
||||
if (!patch.ok) {
|
||||
const errText = await patch.text().catch(() => '');
|
||||
throw new Error(`WP media caption/alt failed ${patch.status}: ${errText.slice(0, 400)}`);
|
||||
@@ -321,12 +352,20 @@ export async function attachFeaturedImageToPost(
|
||||
): Promise<number> {
|
||||
const base = cfg.wpBase.replace(/\/$/, '');
|
||||
const mediaId = await uploadFeaturedMedia(cfg, base, imageUrl, credit, fetchHeaders);
|
||||
const res = await fetch(`${base}/wp/v2/posts/${postId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({ featured_media: mediaId }),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchResponseWithRetry(`${base}/wp/v2/posts/${postId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({ featured_media: mediaId }),
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP post featured_media patch network error: ${msg}`);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
throw new Error(`WP post featured_media patch failed ${res.status}: ${errText.slice(0, 500)}`);
|
||||
@@ -358,12 +397,20 @@ export async function createDraftFromAggregatedItem(
|
||||
if (mediaId) body.featured_media = mediaId;
|
||||
if (categoryId) body.categories = [categoryId];
|
||||
|
||||
const res = await fetch(`${base}/wp/v2/posts`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchResponseWithRetry(`${base}/wp/v2/posts`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify(body),
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP draft network error: ${msg}`);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
|
||||
Reference in new issue
Block a user