Files
portfolio-photo/scripts/check-seo.mjs
T

321 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PUBLIC = path.join(ROOT, 'public');
const requested = new Set(process.argv.slice(2));
const wants = (suite) => requested.size === 0 || requested.has('all') || requested.has(suite);
const failures = [];
function read(relativePath) {
return readFileSync(path.join(ROOT, relativePath), 'utf8');
}
function visibleText(html) {
return html
.replace(/<head\b[\s\S]*?<\/head>/gi, ' ')
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<noscript[\s\S]*?<\/noscript>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&[a-z0-9#]+;/gi, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function visibleWordCount(html) {
const text = visibleText(html);
return text ? text.split(' ').length : 0;
}
function pageHtml(file) {
return read(`public/${file}`);
}
function loadConfig() {
const context = { window: {} };
vm.createContext(context);
vm.runInContext(read('public/custom/seo-config.js'), context);
return context.window.SEO_CONFIG;
}
function count(text, pattern) {
return (text.match(pattern) || []).length;
}
function htmlEscape(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
function check(name, fn) {
try {
fn();
console.log(`PASS ${name}`);
} catch (error) {
failures.push(`${name}: ${error.message}`);
console.error(`FAIL ${name}: ${error.message}`);
}
}
function bakeSeo() {
return execFileSync(process.execPath, ['scripts/bake-seo.mjs'], {
cwd: ROOT,
encoding: 'utf8',
stdio: 'pipe'
});
}
function snapshotTopLevelHtml() {
return readdirSync(PUBLIC)
.filter((name) => name.endsWith('.html'))
.sort()
.map((name) => [name, readFileSync(path.join(PUBLIC, name), 'utf8')]);
}
if (wants('core')) {
const config = loadConfig();
const cities = ['Hamburg', 'Hannover', 'Wolfsburg', 'Uelzen', 'Celle', 'Lüneburg'];
check('Geschäftsort ist Ebstorf', () => {
assert.equal(config.BUSINESS.addressLocality, 'Ebstorf');
});
check('alle sechs Sportregionen sind zentral gepflegt', () => {
assert.deepEqual(Array.from(config.BUSINESS.areaServed), cities);
});
check('Sportseite hat seitenspezifische Service-Daten', () => {
const page = config.PAGES['/sportfotografie'];
assert.equal(page.service.serviceType, 'Sportfotografie');
assert.deepEqual(
Array.from(page.service.areaServed, (place) => place.name),
cities
);
assert.ok(page.jsonld.includes('service'));
});
check('Eventseite hat Hamburg und Deutschland als Einsatzgebiet', () => {
const page = config.PAGES['/eventfotografie'];
assert.deepEqual(
JSON.parse(JSON.stringify(page.service.areaServed)),
[
{ type: 'City', name: 'Hamburg' },
{ type: 'Country', name: 'Deutschland' }
]
);
assert.ok(page.jsonld.includes('service'));
});
check('gebackener Event-Head entspricht der Konfiguration', () => {
const page = config.PAGES['/eventfotografie'];
const html = read('public/eventfotografie.html');
assert.equal(count(html, /<title>/g), 1);
assert.equal(count(html, /<meta name="description"/g), 1);
assert.ok(html.includes(`<title>${htmlEscape(page.title)}</title>`));
assert.ok(html.includes(`content="${htmlEscape(page.desc)}"`));
assert.ok(html.includes('"serviceType":"Eventfotografie"'));
assert.ok(html.includes('"@type":"Country","name":"Deutschland"'));
});
check('erneutes SEO-Backen verändert keine Top-Level-HTML-Seite', () => {
const before = snapshotTopLevelHtml();
bakeSeo();
assert.deepEqual(snapshotTopLevelHtml(), before);
});
check('SEO-Bake meldet übersprungene HTML-Seiten als Fehler', () => {
const file = path.join(PUBLIC, 'blog.html');
const original = readFileSync(file, 'utf8');
let failure;
try {
writeFileSync(file, original.replace('</head>', ''));
try {
bakeSeo();
} catch (error) {
failure = error;
}
} finally {
writeFileSync(file, original);
}
assert.ok(failure, 'das Backen muss bei übersprungenen HTML-Seiten fehlschlagen');
assert.match(String(failure.stderr), /kein <\/head> in blog\.html/);
});
}
if (wants('sport')) {
check('Sportseite hat eindeutigen H1 und Canonical', () => {
const html = pageHtml('sportfotografie.html');
assert.equal(count(html, /<h1\b/g), 1);
assert.ok(html.includes('<h1 class="hero-title">Sportfotograf für Hamburg und Norddeutschland</h1>'));
assert.ok(html.includes('<link rel="canonical" href="https://leon-tonhaeuser.de/sportfotografie">'));
});
check('Sportseite besitzt substanziellen Inhalt', () => {
const words = visibleWordCount(pageHtml('sportfotografie.html'));
assert.ok(words >= 500 && words <= 800, `Wortzahl ${words} liegt außerhalb 500–800`);
});
check('Sportseite belegt Regionen mit vorhandenen Referenzen', () => {
const html = pageHtml('sportfotografie.html');
for (const href of [
'./portfolio-hamburger-sv',
'./portfolio-fc-st-pauli',
'./portfolio-hannover-96',
'./portfolio-svg-lueneburg',
'./portfolio-nfv-pokalfinale-2026'
]) {
assert.ok(html.includes(`href="${href}"`), `${href} fehlt`);
}
for (const city of ['Hamburg', 'Hannover', 'Wolfsburg', 'Uelzen', 'Celle', 'Lüneburg']) {
assert.ok(html.includes(city), `${city} fehlt`);
}
});
check('Sportseite hat Service-Schema und Kontakt-CTA', () => {
const html = pageHtml('sportfotografie.html');
assert.ok(html.includes('"serviceType":"Sportfotografie"'));
assert.ok(html.includes('href="./kontakt"'));
});
}
if (wants('event')) {
check('Event-Nutzen und Referenzen können nicht nur in Metadaten stehen', () => {
const metadataOnly = pageHtml('eventfotografie.html')
.replace(/<main\b[\s\S]*?<\/main>/i, '<main>Ohne die geforderten Begriffe.</main>');
const visible = visibleText(metadataOnly);
for (const term of ['Hamburg', 'deutschlandweit', 'PR', 'Social Media', 'YES!CON 2026', 'OMR x yes!wecancer']) {
assert.ok(!visible.includes(term), `${term} darf nicht aus Metadaten als sichtbarer Inhalt gelten`);
}
});
check('Eventseite hat eindeutigen H1 und substanziellen Inhalt', () => {
const html = pageHtml('eventfotografie.html');
assert.equal(count(html, /<h1\b/g), 1);
assert.ok(html.includes('<h1 class="hero-title">Eventfotograf für Hamburg und deutschlandweite Veranstaltungen</h1>'));
const words = visibleWordCount(html);
assert.ok(words >= 500 && words <= 800, `Wortzahl ${words} liegt außerhalb 500–800`);
});
check('Eventseite nennt Nutzen, Referenzen und Deutschland', () => {
const html = pageHtml('eventfotografie.html');
const visible = visibleText(html);
for (const term of ['Hamburg', 'deutschlandweit', 'PR', 'Social Media', 'YES!CON 2026', 'OMR x yes!wecancer']) {
assert.ok(visible.includes(term), `${term} fehlt im sichtbaren Inhalt`);
}
assert.ok(html.includes('"serviceType":"Eventfotografie"'));
assert.ok(html.includes('"@type":"Country","name":"Deutschland"'));
});
check('Startseite verlinkt beide Leistungsseiten', () => {
const html = pageHtml('index.html');
assert.ok(html.includes('href="./sportfotografie"'));
assert.ok(html.includes('href="./eventfotografie"'));
});
check('Leistungs-Hub verlinkt beide Leistungsseiten', () => {
const html = pageHtml('leistungen.html');
assert.ok(html.includes('href="./sportfotografie"'));
assert.ok(html.includes('href="./eventfotografie"'));
});
}
if (wants('links')) {
const sportPages = [
'portfolio-hamburger-sv.html',
'portfolio-fc-st-pauli.html',
'portfolio-hannover-96.html',
'portfolio-svg-lueneburg.html',
'portfolio-nfv-pokalfinale-2026.html'
];
const eventPages = [
'portfolio-yes-con-2026.html',
'portfolio-omr-yes-wecancer.html',
'portfolio-abiball.html'
];
check('Sportreferenzen verlinken die Sportseite', () => {
for (const file of sportPages) {
assert.ok(pageHtml(file).includes('href="./sportfotografie"'), `${file} fehlt`);
}
});
check('Eventreferenzen verlinken die Eventseite', () => {
for (const file of eventPages) {
assert.ok(pageHtml(file).includes('href="./eventfotografie"'), `${file} fehlt`);
}
});
check('Sitemap enthält die Sportseite und aktuelle Hub-Daten', () => {
const xml = read('public/sitemap.xml');
assert.equal(count(xml, /<loc>https:\/\/leon-tonhaeuser\.de\/sportfotografie<\/loc>/g), 1);
for (const url of ['/', '/leistungen', '/eventfotografie', '/sportfotografie']) {
const escaped = url === '/' ? '\\/' : url.replace(/\//g, '\\/');
const entry = new RegExp(`<loc>https:\\/\\/leon-tonhaeuser\\.de${escaped}<\\/loc><lastmod>2026-07-30<\\/lastmod>`);
assert.ok(entry.test(xml), `${url} hat kein lastmod 2026-07-30`);
}
});
check('alle konfigurierten Seiten haben genau einen statischen SEO-Block', () => {
const config = loadConfig();
for (const [urlPath, page] of Object.entries(config.PAGES)) {
const file = urlPath === '/' ? 'index.html' : `${urlPath.slice(1)}.html`;
const html = pageHtml(file);
assert.equal(count(html, /<!-- STATIC-SEO:/g), 1, `${file}: Startmarker`);
assert.equal(count(html, /<!-- \/STATIC-SEO -->/g), 1, `${file}: Endmarker`);
assert.equal(count(html, /<title>/g), 1, `${file}: Title`);
assert.equal(count(html, /<meta name="description"/g), 1, `${file}: Description`);
assert.ok(html.includes(`<title>${htmlEscape(page.title)}</title>`), `${file}: Title-Wert`);
}
});
check('alle relativen HTML-Links zeigen auf vorhandene Seiten', () => {
const files = readdirSync(PUBLIC).filter((file) => file.endsWith('.html'));
for (const file of files) {
const html = pageHtml(file);
const hrefs = Array.from(
html.matchAll(/<a\b[^>]*\shref="(\.\/[^"#?]*)/g),
(match) => match[1]
);
for (const href of hrefs) {
const clean = decodeURIComponent(href.slice(2));
const target = clean === '' ? 'index.html' : clean.endsWith('.html') ? clean : `${clean}.html`;
assert.ok(existsSync(path.join(PUBLIC, target)), `${file} → ${href}`);
}
}
});
}
if (wants('syntax')) {
check('alle ausführbaren Inline-Skripte der Top-Level-Seiten sind syntaktisch gültig', () => {
const files = readdirSync(PUBLIC).filter((file) => file.endsWith('.html')).sort();
for (const file of files) {
const html = pageHtml(file);
const scripts = Array.from(
html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi),
(match) => ({ attributes: match[1], source: match[2] })
);
for (const [index, script] of scripts.entries()) {
if (/\bsrc\s*=/i.test(script.attributes) || /\btype\s*=\s*["']application\/ld\+json["']/i.test(script.attributes)) {
continue;
}
new vm.Script(script.source, { filename: `${file} inline script ${index + 1}` });
}
}
});
}
if (failures.length) {
console.error(`\n${failures.length} Prüfung(en) fehlgeschlagen.`);
process.exit(1);
}
console.log('\nAlle angeforderten SEO-Prüfungen sind grün.');