feat(publisher): BIT-25574 sanitize tags and SEO meta from on-page text
ai-news-writer-ci / test (pull_request) Failing after 33s
ai-news-writer-ci / test (pull_request) Failing after 33s
Drop hallucinated athlete/team tags and derive Yoast fields only from published article content. Adds backfill tool for live andebol.net posts. Co-authored-by: Cursor <[email protected]>
This commit is contained in:
1 parent
478d82b070
commit
3027361259
9 files changed
+453
-13
No files matched your search
@@ -19,5 +19,6 @@
|
||||
},
|
||||
"status_default": "publish",
|
||||
"tags_auto": true,
|
||||
"tags_infer": "andebol",
|
||||
"lang": "pt"
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
"ops:check": "bash tools/ops-check.sh",
|
||||
"seed:smoke-verification": "node tools/seed-smoke-verification-article.js",
|
||||
"wp:backfill-categories": "node tools/backfill-wp-categories.js",
|
||||
"wp:backfill-meta": "node tools/backfill-wp-meta.js",
|
||||
"deploy:lxc": "bash tools/deploy-lxc.sh",
|
||||
"test": "c8 --reporter=text --reporter=html --reporter=lcov node --test --test-concurrency=1 $(find src -type f -name '*.test.js' | sort | tr '\\n' ' ')",
|
||||
"lint": "eslint src/",
|
||||
|
||||
@@ -5,6 +5,7 @@ const { metrics } = require('../monitoring/metrics');
|
||||
const { scoreArticleQuality } = require('./quality-scorer');
|
||||
const { verifyArticle } = require('../research');
|
||||
const { appendArticleRecord } = require('../store/article-log');
|
||||
const { sanitizeArticleMeta } = require('../publisher/article-meta');
|
||||
const { serializeVerificationReport } = require('../store/verification-report');
|
||||
|
||||
function getQualityThresholds() {
|
||||
@@ -31,8 +32,9 @@ function getQualityThresholds() {
|
||||
*/
|
||||
async function persistGeneratedArticle(article, site, mode, wp_link, voice = {}) {
|
||||
try {
|
||||
const normalized = sanitizeArticleMeta(article, site || {});
|
||||
const thresholds = getQualityThresholds();
|
||||
const quality = scoreArticleQuality(article, {
|
||||
const quality = scoreArticleQuality(normalized, {
|
||||
minWordCount: thresholds.minWordCount,
|
||||
maxReadabilityGrade: thresholds.maxReadabilityGrade
|
||||
});
|
||||
@@ -46,7 +48,7 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {})
|
||||
|
||||
let verification_report = null;
|
||||
try {
|
||||
const rawV = await verifyArticle(article);
|
||||
const rawV = await verifyArticle(normalized);
|
||||
verification_report = serializeVerificationReport(rawV);
|
||||
} catch (vErr) {
|
||||
logger.warn(`verification orchestration failed (non-fatal): ${vErr.message}`);
|
||||
@@ -59,12 +61,12 @@ async function persistGeneratedArticle(article, site, mode, wp_link, voice = {})
|
||||
}
|
||||
|
||||
appendArticleRecord({
|
||||
title: article.title,
|
||||
subtitle: article.subtitle,
|
||||
slug: article.slug,
|
||||
summary: article.summary,
|
||||
tags: article.tags,
|
||||
category: article.category || null,
|
||||
title: normalized.title,
|
||||
subtitle: normalized.subtitle,
|
||||
slug: normalized.slug,
|
||||
summary: normalized.summary,
|
||||
tags: normalized.tags,
|
||||
category: normalized.category || null,
|
||||
wp_link: wp_link || null,
|
||||
site_name: site?.name || 'default',
|
||||
mode,
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
'use strict';
|
||||
|
||||
const ANDEBOL_ENTITY_RULES = [
|
||||
{ tag: 'FC Porto', pattern: /\b(?:fc porto|f\.?\s*c\.?\s*porto)\b/i },
|
||||
{ tag: 'Benfica', pattern: /\b(?:sl benfica|benfica)\b/i },
|
||||
{ tag: 'Sporting CP', pattern: /\b(?:sporting cp|sporting)\b/i },
|
||||
{ tag: 'SC Braga', pattern: /\b(?:sc braga|vitória\s+sc)\b/i },
|
||||
{ tag: 'Seleção Nacional', pattern: /\bseleç(?:ão|ões)\s+nacionais?\b/i },
|
||||
{ tag: 'Portugal', pattern: /\bportugal\b/i },
|
||||
{ tag: 'Liga dos Campeões', pattern: /\bliga\s+dos\s+campeões\b/i },
|
||||
{ tag: 'Taça de Portugal', pattern: /\btaça\s+de\s+portugal\b/i },
|
||||
{ tag: 'Campeonato Nacional', pattern: /\bcampeonato\s+nacional\b/i },
|
||||
{ tag: 'EHF', pattern: /\behf\b/i },
|
||||
{ tag: 'IHF', pattern: /\bihf\b/i },
|
||||
{ tag: 'Andebol', pattern: /\bandebol\b/i }
|
||||
];
|
||||
|
||||
const SKIP_NAME_FRAGMENTS = new Set([
|
||||
'federação de', 'federação portuguesa', 'european portuguese', 'source material',
|
||||
'fonte original', 'fonte federação'
|
||||
]);
|
||||
|
||||
function foldAccents(value) {
|
||||
return String(value || '')
|
||||
.normalize('NFD')
|
||||
.replace(/\p{M}/gu, '');
|
||||
}
|
||||
|
||||
function plainTextFromHtml(html) {
|
||||
return String(html || '')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/\[[^\]]+\]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function articleCorpus(article) {
|
||||
return plainTextFromHtml([
|
||||
article?.title,
|
||||
article?.subtitle,
|
||||
article?.summary,
|
||||
article?.excerpt,
|
||||
article?.body,
|
||||
article?.content
|
||||
].filter(Boolean).join(' '));
|
||||
}
|
||||
|
||||
function tagMentionedInCorpus(tag, corpus) {
|
||||
const normalizedTag = foldAccents(tag).toLowerCase().trim();
|
||||
if (normalizedTag.length < 2) {
|
||||
return false;
|
||||
}
|
||||
const normalizedCorpus = foldAccents(corpus).toLowerCase();
|
||||
return normalizedCorpus.includes(normalizedTag);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep only tags that literally appear in the published article text.
|
||||
*
|
||||
* @param {string[]} tags
|
||||
* @param {string} corpus
|
||||
* @param {number} [maxTags]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function sanitizeTags(tags, corpus, maxTags = 8) {
|
||||
if (!Array.isArray(tags)) {
|
||||
return [];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const raw of tags) {
|
||||
const tag = String(raw || '').trim();
|
||||
if (!tag || tag.length > 60) {
|
||||
continue;
|
||||
}
|
||||
const key = foldAccents(tag).toLowerCase();
|
||||
if (seen.has(key)) {
|
||||
continue;
|
||||
}
|
||||
if (tagMentionedInCorpus(tag, corpus)) {
|
||||
seen.add(key);
|
||||
out.push(tag);
|
||||
}
|
||||
}
|
||||
return out.slice(0, maxTags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract editorial tags from article text (teams, competitions, people mentioned).
|
||||
*
|
||||
* @param {Object} article
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function inferAndebolTags(article) {
|
||||
const corpus = articleCorpus(article);
|
||||
if (!corpus) {
|
||||
return ['Andebol'];
|
||||
}
|
||||
|
||||
const seen = new Set();
|
||||
const tags = [];
|
||||
|
||||
function pushTag(tag) {
|
||||
const trimmed = String(tag || '').trim();
|
||||
if (!trimmed) {
|
||||
return;
|
||||
}
|
||||
const key = foldAccents(trimmed).toLowerCase();
|
||||
if (seen.has(key)) {
|
||||
return;
|
||||
}
|
||||
seen.add(key);
|
||||
tags.push(trimmed);
|
||||
}
|
||||
|
||||
for (const rule of ANDEBOL_ENTITY_RULES) {
|
||||
if (rule.pattern.test(corpus)) {
|
||||
pushTag(rule.tag);
|
||||
}
|
||||
}
|
||||
|
||||
const namePattern = /\b([A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+(?:\s+(?:de|da|do|dos|das|e)\s+)?(?:[A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+)+)\b/g;
|
||||
let match;
|
||||
while ((match = namePattern.exec(corpus)) !== null) {
|
||||
const candidate = match[1].trim();
|
||||
const lower = foldAccents(candidate).toLowerCase();
|
||||
if (candidate.split(/\s+/).length < 2 || candidate.length > 40) {
|
||||
continue;
|
||||
}
|
||||
if ([...SKIP_NAME_FRAGMENTS].some((frag) => lower.includes(frag))) {
|
||||
continue;
|
||||
}
|
||||
if (tagMentionedInCorpus(candidate, corpus)) {
|
||||
pushTag(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
if (tags.length === 0) {
|
||||
pushTag('Andebol');
|
||||
}
|
||||
|
||||
return tags.slice(0, 8);
|
||||
}
|
||||
|
||||
function truncateAtWord(text, maxLen) {
|
||||
const trimmed = String(text || '').trim();
|
||||
if (trimmed.length <= maxLen) {
|
||||
return trimmed;
|
||||
}
|
||||
const slice = trimmed.slice(0, maxLen);
|
||||
const lastSpace = slice.lastIndexOf(' ');
|
||||
if (lastSpace > maxLen * 0.6) {
|
||||
return `${slice.slice(0, lastSpace).trim()}…`;
|
||||
}
|
||||
return `${slice.trim()}…`;
|
||||
}
|
||||
|
||||
function deriveSeoTitle(article) {
|
||||
const title = plainTextFromHtml(article?.seo_title || article?.title || '');
|
||||
return truncateAtWord(title, 60);
|
||||
}
|
||||
|
||||
function seoDescriptionGrounded(text, corpus) {
|
||||
const plain = plainTextFromHtml(text);
|
||||
if (!plain) {
|
||||
return false;
|
||||
}
|
||||
const namePattern = /\b([A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+(?:\s+[A-ZÁÉÍÓÚÀÂÊÔÃÕÇ][a-záéíóúàâêôãõç]+)+)\b/g;
|
||||
let match;
|
||||
while ((match = namePattern.exec(plain)) !== null) {
|
||||
const candidate = match[1].trim();
|
||||
if (candidate.split(/\s+/).length >= 2 && !tagMentionedInCorpus(candidate, corpus)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function deriveSeoDescription(article) {
|
||||
const corpus = articleCorpus(article);
|
||||
const candidates = [
|
||||
article?.summary,
|
||||
article?.excerpt,
|
||||
plainTextFromHtml(article?.body || article?.content || '').slice(0, 220),
|
||||
article?.seo_description
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const text = plainTextFromHtml(candidate);
|
||||
if (!text || text.length < 40) {
|
||||
continue;
|
||||
}
|
||||
if (!seoDescriptionGrounded(text, corpus)) {
|
||||
continue;
|
||||
}
|
||||
return truncateAtWord(text, 155);
|
||||
}
|
||||
return truncateAtWord(corpus.slice(0, 155), 155);
|
||||
}
|
||||
|
||||
function deriveFocusKeyword(article) {
|
||||
const title = plainTextFromHtml(article?.title || '');
|
||||
const words = title
|
||||
.split(/\s+/)
|
||||
.map((w) => w.replace(/[^a-záéíóúàâêôãõç0-9-]/gi, ''))
|
||||
.filter((w) => w.length > 3);
|
||||
if (words.length === 0) {
|
||||
return 'andebol';
|
||||
}
|
||||
const corpus = articleCorpus(article);
|
||||
for (const word of words) {
|
||||
if (tagMentionedInCorpus(word, corpus)) {
|
||||
return word.toLowerCase();
|
||||
}
|
||||
}
|
||||
return words[0].toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize tags and SEO fields so meta-info only references on-page content.
|
||||
*
|
||||
* @param {Object} article
|
||||
* @param {{ tags_infer?: string }} [siteConfig]
|
||||
* @returns {Object} shallow copy with sanitized meta fields
|
||||
*/
|
||||
function sanitizeArticleMeta(article, siteConfig = {}) {
|
||||
const next = { ...article };
|
||||
const corpus = articleCorpus(article);
|
||||
const inferMode = siteConfig?.tags_infer || siteConfig?.category_infer;
|
||||
|
||||
let tags = sanitizeTags(next.tags, corpus);
|
||||
if (tags.length === 0 && (inferMode === 'andebol' || siteConfig?.tags_auto)) {
|
||||
tags = inferAndebolTags(next);
|
||||
}
|
||||
|
||||
next.tags = tags;
|
||||
next.seo_title = deriveSeoTitle(next);
|
||||
next.seo_description = deriveSeoDescription(next);
|
||||
next.focus_keyword = deriveFocusKeyword(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sanitizeArticleMeta,
|
||||
sanitizeTags,
|
||||
inferAndebolTags,
|
||||
deriveSeoTitle,
|
||||
deriveSeoDescription,
|
||||
deriveFocusKeyword,
|
||||
tagMentionedInCorpus,
|
||||
plainTextFromHtml,
|
||||
articleCorpus,
|
||||
ANDEBOL_ENTITY_RULES
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const test = require('node:test');
|
||||
const {
|
||||
sanitizeTags,
|
||||
inferAndebolTags,
|
||||
sanitizeArticleMeta,
|
||||
tagMentionedInCorpus
|
||||
} = require('./article-meta');
|
||||
|
||||
test('sanitizeTags drops tags not present in article body', () => {
|
||||
const corpus = 'O FC Porto venceu o Benfica por 28-25 na Liga dos Campeões.';
|
||||
const tags = sanitizeTags(['FC Porto', 'João Silva', 'Benfica', 'Cristiano Ronaldo'], corpus);
|
||||
assert.deepEqual(tags, ['FC Porto', 'Benfica']);
|
||||
});
|
||||
|
||||
test('inferAndebolTags extracts teams and competitions from text', () => {
|
||||
const tags = inferAndebolTags({
|
||||
title: 'FC Porto vence Benfica na Liga dos Campeões',
|
||||
body: '<p>O FC Porto confirmou a vitória sobre o Benfica na Liga dos Campeões.</p>'
|
||||
});
|
||||
assert.ok(tags.includes('FC Porto'));
|
||||
assert.ok(tags.includes('Benfica'));
|
||||
assert.ok(tags.includes('Liga dos Campeões'));
|
||||
});
|
||||
|
||||
test('sanitizeArticleMeta removes hallucinated player tags', () => {
|
||||
const result = sanitizeArticleMeta({
|
||||
title: 'Festa do Andebol regressa a Lagoa',
|
||||
body: '<p>A Festa do Andebol junta seleções regionais sub-14 em Lagoa.</p>',
|
||||
summary: 'Evento desportivo reunirá jovens atletas na região.',
|
||||
tags: ['Marta Costa', 'João Rodrigues', 'Andebol'],
|
||||
seo_description: 'Marta Costa brilhou na competição internacional'
|
||||
}, { tags_infer: 'andebol', tags_auto: true });
|
||||
|
||||
assert.ok(!result.tags.includes('Marta Costa'));
|
||||
assert.ok(!result.tags.includes('João Rodrigues'));
|
||||
assert.ok(result.tags.includes('Andebol'));
|
||||
assert.ok(!result.seo_description.includes('Marta Costa'));
|
||||
});
|
||||
|
||||
test('sanitizeArticleMeta keeps valid LLM tags', () => {
|
||||
const result = sanitizeArticleMeta({
|
||||
title: 'Carlos Ribeiro renova com Sporting CP',
|
||||
body: '<p>Carlos Ribeiro assinou renovação com o Sporting CP.</p>',
|
||||
tags: ['Carlos Ribeiro', 'Sporting CP', 'Pedro Santos']
|
||||
}, { tags_auto: true });
|
||||
|
||||
assert.ok(result.tags.includes('Carlos Ribeiro'));
|
||||
assert.ok(result.tags.includes('Sporting CP'));
|
||||
assert.equal(result.tags.includes('Pedro Santos'), false);
|
||||
});
|
||||
@@ -8,6 +8,7 @@ const { resolveWpTransport } = require('./wp-transport');
|
||||
const { publishArticleXmlRpc, testConnectionXmlRpc } = require('./xmlrpc-client');
|
||||
const { resolveWpStatus } = require('./wp-publish-hours');
|
||||
const { resolvePostCategoryIds } = require('./wp-categories');
|
||||
const { sanitizeArticleMeta } = require('./article-meta');
|
||||
const { metrics } = require('../monitoring/metrics');
|
||||
|
||||
function wpRestDraftFallbackEnabled() {
|
||||
@@ -35,10 +36,11 @@ function wpOriginForLogs(wp_url) {
|
||||
* @returns {Promise<Object>} WordPress post object on success
|
||||
*/
|
||||
async function publishToWordPress(article, site_config, publishHours) {
|
||||
const sanitized = sanitizeArticleMeta(article, site_config);
|
||||
if (resolveWpTransport(site_config) === 'xmlrpc') {
|
||||
return publishArticleXmlRpc(article, site_config, publishHours);
|
||||
return publishArticleXmlRpc(sanitized, site_config, publishHours);
|
||||
}
|
||||
return publishToWordPressRest(article, site_config, publishHours);
|
||||
return publishToWordPressRest(sanitized, site_config, publishHours);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,7 +73,8 @@ async function publishToWordPressRest(article, site_config, publishHours) {
|
||||
tags: [],
|
||||
meta: {
|
||||
_yoast_wpseo_title: article.seo_title,
|
||||
_yoast_wpseo_metadesc: article.seo_description
|
||||
_yoast_wpseo_metadesc: article.seo_description,
|
||||
_yoast_wpseo_focuskw: article.focus_keyword || undefined
|
||||
}
|
||||
};
|
||||
|
||||
@@ -209,4 +212,4 @@ async function testConnection(site_config) {
|
||||
return { ok: true, user_info: response.data };
|
||||
}
|
||||
|
||||
module.exports = { publishToWordPress, testConnection, resolveWpStatus };
|
||||
module.exports = { publishToWordPress, testConnection, resolveWpStatus, resolveTagIds };
|
||||
@@ -259,6 +259,9 @@ async function publishArticleXmlRpc(article, site_config, publishHours) {
|
||||
if (article.seo_description) {
|
||||
custom_fields.push({ key: '_yoast_wpseo_metadesc', value: String(article.seo_description) });
|
||||
}
|
||||
if (article.focus_keyword) {
|
||||
custom_fields.push({ key: '_yoast_wpseo_focuskw', value: String(article.focus_keyword) });
|
||||
}
|
||||
|
||||
const content = {
|
||||
post_type: 'post',
|
||||
|
||||
+6
-1
@@ -140,7 +140,12 @@ Return a JSON object with these exact keys:
|
||||
"tags": ["tag1", "tag2", "tag3"],
|
||||
"category": "${category}",
|
||||
"seo_title": "SEO optimized title (max 60 chars)",
|
||||
"seo_description": "meta description (max 155 chars)",
|
||||
"seo_description": "meta description (max 155 chars) — must summarize ONLY facts in the article body",
|
||||
|
||||
TAG RULES (critical):
|
||||
- Tags must be names, teams, or competitions that appear verbatim in your article title or body.
|
||||
- Do NOT tag athletes, clubs, or events that you did not mention in the article.
|
||||
- Prefer 3-6 short tags (teams, competitions, key people actually named in the text).
|
||||
"used_sources": [1, 2, 3] // Array of source indices (1-based) that were cited in the article
|
||||
}`;
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Backfill WordPress post tags and Yoast SEO meta on andebol.net.
|
||||
*
|
||||
* Usage:
|
||||
* node tools/backfill-wp-meta.js --site andebol.net.example.json --dry-run
|
||||
* node tools/backfill-wp-meta.js --site andebol.net.json --limit 50
|
||||
*/
|
||||
|
||||
require('dotenv').config();
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const axios = require('axios');
|
||||
const { sanitizeArticleMeta } = require('../src/publisher/article-meta');
|
||||
const { resolveTagIds } = require('../src/publisher/wordpress');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = { dryRun: false, limit: 100, siteFile: null };
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--dry-run') out.dryRun = true;
|
||||
else if (arg === '--limit' && argv[i + 1]) out.limit = parseInt(argv[++i], 10);
|
||||
else if (arg === '--site' && argv[i + 1]) out.siteFile = argv[++i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function loadSiteConfig(siteFile) {
|
||||
const sitesDir = path.join(ROOT, 'config', 'sites');
|
||||
const filename = siteFile.endsWith('.json') ? siteFile : `${siteFile}.json`;
|
||||
const fullPath = path.join(sitesDir, filename);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new Error(`Site config not found: ${fullPath}`);
|
||||
}
|
||||
return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (!args.siteFile) {
|
||||
console.error('Usage: node tools/backfill-wp-meta.js --site <file.json> [--dry-run] [--limit N]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const site = loadSiteConfig(args.siteFile);
|
||||
const wpUrl = site.wp_url || process.env.WP_URL;
|
||||
const user = site.user || process.env.WP_USER;
|
||||
const password = site.password || process.env.WP_PASSWORD;
|
||||
if (!wpUrl || !user || !password) {
|
||||
throw new Error('Missing wp_url/user/password in site config or env');
|
||||
}
|
||||
|
||||
const apiBase = `${wpUrl.replace(/\/$/, '').replace(/\/wp-json\/?$/, '')}/wp-json/wp/v2`;
|
||||
const credentials = Buffer.from(`${user}:${password}`).toString('base64');
|
||||
const siteDomain = site.site_domain || site.wp_site_domain;
|
||||
const headers = {
|
||||
Authorization: `Basic ${credentials}`,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
if (siteDomain) headers['X-Site-Domain'] = siteDomain;
|
||||
|
||||
const postsRes = await axios.get(`${apiBase}/posts`, {
|
||||
params: {
|
||||
per_page: Math.min(args.limit, 100),
|
||||
status: 'publish,draft',
|
||||
orderby: 'date',
|
||||
order: 'desc',
|
||||
_fields: 'id,title,content,excerpt,tags,meta,link'
|
||||
},
|
||||
headers,
|
||||
timeout: 20000
|
||||
});
|
||||
|
||||
const posts = Array.isArray(postsRes.data) ? postsRes.data : [];
|
||||
let patched = 0;
|
||||
let skipped = 0;
|
||||
|
||||
for (const post of posts) {
|
||||
const title = post.title?.rendered || post.title || '';
|
||||
const body = post.content?.rendered || post.content || '';
|
||||
const excerpt = post.excerpt?.rendered || post.excerpt || '';
|
||||
|
||||
const sanitized = sanitizeArticleMeta({
|
||||
title,
|
||||
body,
|
||||
summary: excerpt,
|
||||
tags: []
|
||||
}, site);
|
||||
|
||||
const tagIds = await resolveTagIds(sanitized.tags, apiBase, credentials);
|
||||
const payload = {
|
||||
tags: tagIds,
|
||||
meta: {
|
||||
_yoast_wpseo_title: sanitized.seo_title,
|
||||
_yoast_wpseo_metadesc: sanitized.seo_description,
|
||||
_yoast_wpseo_focuskw: sanitized.focus_keyword
|
||||
}
|
||||
};
|
||||
|
||||
console.log(`${args.dryRun ? '[dry-run]' : 'patch'} post ${post.id} tags=${sanitized.tags.join(', ')} focus=${sanitized.focus_keyword}`);
|
||||
if (!args.dryRun) {
|
||||
await axios.post(`${apiBase}/posts/${post.id}`, payload, { headers, timeout: 15000 });
|
||||
}
|
||||
patched += 1;
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ scanned: posts.length, patched, skipped, dryRun: args.dryRun }, null, 2));
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err.message || err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user