173 lines
11 KiB
JavaScript
173 lines
11 KiB
JavaScript
#!/usr/bin/env node
|
||
// ipal-seo-check — what Googlebot actually sees on a running site (Node 18+, no dependencies).
|
||
// node seo-check.mjs <baseUrl> [--max 20]
|
||
// node seo-check.mjs http://localhost:3000 # after `pnpm build && pnpm start`
|
||
// node seo-check.mjs https://klient.pl --max 40 # production
|
||
// Exit code: 0 = no errors (warnings allowed), 1 = errors, 2 = site unreachable.
|
||
|
||
const args = process.argv.slice(2)
|
||
if (!args[0] || args.includes('--help') || args.includes('-h')) {
|
||
console.log('Usage: seo-check.mjs <baseUrl> [--max N] (N = pages sampled from the sitemap, default 20)')
|
||
process.exit(args[0] ? 0 : 2)
|
||
}
|
||
const origin = args[0].replace(/\/$/, '')
|
||
const maxIdx = args.indexOf('--max')
|
||
const MAX = maxIdx >= 0 ? Number(args[maxIdx + 1]) || 20 : 20
|
||
const UA = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
|
||
|
||
let errors = 0
|
||
let warnings = 0
|
||
const findings = []
|
||
const report = (level, title, rule, items = []) => {
|
||
if (level === 'ERROR') errors += Math.max(items.length, 1)
|
||
else warnings += Math.max(items.length, 1)
|
||
findings.push({ level, title, rule, items })
|
||
}
|
||
const get = async (path, opts = {}) => {
|
||
const url = path.startsWith('http') ? path : origin + path
|
||
const res = await fetch(url, { redirect: opts.redirect ?? 'follow', headers: { 'user-agent': UA } })
|
||
return { res, text: opts.body === false ? '' : await res.text(), url }
|
||
}
|
||
const attr = (tag, name) => tag.match(new RegExp(`${name}\\s*=\\s*"([^"]*)"`, 'i'))?.[1]
|
||
const tags = (html, re) => [...html.matchAll(re)].map((m) => m[0])
|
||
const norm = (u) => (u || '').replace(/\/$/, '') || '/'
|
||
|
||
// --- 0. reachable ---------------------------------------------------------
|
||
let home
|
||
try {
|
||
home = await get('/', { redirect: 'manual', body: false })
|
||
} catch (e) {
|
||
console.error(`ipal-seo-check: ${origin} unreachable (${e.cause?.code ?? e.message}). Start the app first.`)
|
||
process.exit(2)
|
||
}
|
||
console.log(`ipal-seo-check — ${origin} (Googlebot UA)`)
|
||
|
||
// --- 1. root ----------------------------------------------------------------
|
||
const rootStatus = home.res.status
|
||
const rootLocation = home.res.headers.get('location')
|
||
if (![200, 301, 302, 307, 308].includes(rootStatus)) report('ERROR', `/ returns ${rootStatus}`, 'root must serve the home or redirect to /{locale}')
|
||
|
||
// --- 2. robots.txt --------------------------------------------------------
|
||
const robots = await get('/robots.txt')
|
||
if (robots.res.status !== 200) report('ERROR', `robots.txt → ${robots.res.status}`, 'export robots from lib/content (seo.md)')
|
||
else {
|
||
const txt = robots.text
|
||
const sm = txt.match(/^sitemap:\s*(\S+)/im)?.[1]
|
||
if (!sm) report('ERROR', 'robots.txt has no Sitemap line', 'buildRobots sitemap: true')
|
||
else if (!sm.startsWith('http')) report('ERROR', `Sitemap URL is relative: ${sm}`, 'set NEXT_PUBLIC_SERVER_URL / baseUrl')
|
||
const star = txt.split(/user-agent:\s*\*/i)[1]?.split(/user-agent:/i)[0] ?? ''
|
||
if (/^disallow:\s*\/\s*$/im.test(star)) report('ERROR', 'robots.txt blocks everything for *', 'Disallow: / — the site is invisible to search engines')
|
||
if (/localhost|127\.0\.0\.1/.test(txt) && !/localhost|127\.0\.0\.1/.test(origin)) report('ERROR', 'robots.txt points to localhost', 'NEXT_PUBLIC_SERVER_URL is not the production URL')
|
||
}
|
||
|
||
// --- 3. sitemap -----------------------------------------------------------
|
||
const sitemap = await get('/sitemap.xml')
|
||
let urls = []
|
||
let hasAlternates = false
|
||
if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemap from lib/content + force-dynamic')
|
||
else {
|
||
urls = [...new Set([...sitemap.text.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1]))]
|
||
hasAlternates = /hreflang=/.test(sitemap.text)
|
||
if (urls.length === 0) report('ERROR', 'sitemap.xml is empty', 'DB unreachable at build without force-dynamic, or no published pages')
|
||
const foreign = urls.filter((u) => !u.startsWith('http') || /localhost|127\.0\.0\.1/.test(u) !== /localhost|127\.0\.0\.1/.test(origin))
|
||
if (foreign.length) report('ERROR', 'sitemap URLs relative or on another host', 'NEXT_PUBLIC_SERVER_URL / baseUrl', foreign.slice(0, 5))
|
||
if (/(\/404|\/500|not-found)(\/|<|$)/.test(sitemap.text)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID')
|
||
}
|
||
|
||
// --- 4. sampled pages -----------------------------------------------------
|
||
const localeOf = (u) => new URL(u).pathname.split('/').filter(Boolean)[0] ?? ''
|
||
const byLocale = new Map()
|
||
for (const u of urls) {
|
||
const l = localeOf(u)
|
||
if (!byLocale.has(l)) byLocale.set(l, [])
|
||
byLocale.get(l).push(u)
|
||
}
|
||
const sample = []
|
||
for (let i = 0; sample.length < Math.min(MAX, urls.length); i++) {
|
||
for (const list of byLocale.values()) if (list[i] && sample.length < MAX) sample.push(list[i])
|
||
}
|
||
const multiLocale = hasAlternates || byLocale.size > 1
|
||
const urlSet = new Set(urls.map(norm))
|
||
const titles = new Map()
|
||
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [] }
|
||
|
||
for (const url of sample) {
|
||
let page
|
||
try { page = await get(url, { redirect: 'manual' }) } catch { issues.status.push(`${url} → unreachable`); continue }
|
||
if (page.res.status !== 200) { issues.status.push(`${url} → ${page.res.status}`); continue }
|
||
const html = page.text
|
||
const cut = html.search(/<\/head>/i)
|
||
if (cut < 0) { issues.noHead.push(url); continue }
|
||
const head = html.slice(0, cut)
|
||
const body = html.slice(cut)
|
||
|
||
// Next 16 streaming: metadata emitted into <body> is invisible to many crawlers
|
||
if (/<link[^>]+rel="canonical"/i.test(body) || /<title>/i.test(body)) issues.body.push(url)
|
||
|
||
const title = head.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]?.trim()
|
||
if (!title) issues.title.push(url)
|
||
else {
|
||
if (title.length > 65) issues.longTitle.push(`${url} (${title.length} chars)`)
|
||
titles.set(title, [...(titles.get(title) ?? []), url])
|
||
}
|
||
if (!/<meta[^>]+name="description"[^>]+content="[^"]+"/i.test(head)) issues.desc.push(url)
|
||
|
||
const canonTag = tags(head, /<link[^>]+rel="canonical"[^>]*>/gi)[0]
|
||
const canon = canonTag && attr(canonTag, 'href')
|
||
if (!canon) issues.canonical.push(url)
|
||
else if (norm(canon) !== norm(url)) issues.canonSelf.push(`${url} → canonical ${canon}`)
|
||
|
||
const robotsMeta = tags(head, /<meta[^>]+name="robots"[^>]*>/gi).map((t) => attr(t, 'content') ?? '').join(' ')
|
||
if (/noindex/i.test(robotsMeta)) issues.noindex.push(url)
|
||
|
||
if (!/<link[^>]+rel="(?:shortcut )?icon"/i.test(head)) issues.favicon.push(url)
|
||
|
||
if (multiLocale) {
|
||
const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }))
|
||
if (alts.length === 0) issues.hreflang.push(url)
|
||
else {
|
||
if (!alts.some((a) => a.lang === 'x-default')) issues.xdefault.push(url)
|
||
if (!alts.some((a) => norm(a.href) === norm(url))) issues.hreflang.push(`${url} (no self-reference)`)
|
||
for (const a of alts) if (a.lang !== 'x-default' && a.href && !urlSet.has(norm(a.href))) issues.reciprocal.push(`${url} → ${a.lang}: ${a.href}`)
|
||
}
|
||
}
|
||
}
|
||
|
||
const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([t, us]) => `"${t}" × ${us.length}`)
|
||
if (issues.status.length) report('ERROR', 'sitemap URLs not 200 (redirect / error)', 'sitemap must list final, live URLs', issues.status)
|
||
if (issues.noHead.length) report('ERROR', 'no </head> in HTML', 'broken document', issues.noHead)
|
||
if (issues.body.length) report('ERROR', 'metadata rendered in <body>', 'htmlLimitedBots, no explicit <head>, ISR + generateStaticParams (AGENT.md §4)', issues.body)
|
||
if (issues.title.length) report('ERROR', 'missing <title> in head', 'generatePageMetadata', issues.title)
|
||
if (issues.canonical.length) report('ERROR', 'missing canonical', 'generatePageMetadata + NEXT_PUBLIC_SERVER_URL', issues.canonical)
|
||
if (issues.canonSelf.length) report('ERROR', 'canonical not pointing to itself', 'canonical must be the page URL (or remove the page from the sitemap)', issues.canonSelf)
|
||
if (issues.noindex.length) report('ERROR', 'noindex pages listed in the sitemap', 'sitemap filters noindex — check buildNoindexField / stale build', issues.noindex)
|
||
if (issues.hreflang.length) report('ERROR', 'missing / non-self hreflang', 'createPageMetadata builds alternates from locale:"all" slugs', issues.hreflang)
|
||
if (issues.xdefault.length) report('WARNING', 'no x-default hreflang', 'buildHreflangAlternates adds x-default → defaultLocale', issues.xdefault)
|
||
if (issues.reciprocal.length) report('WARNING', 'hreflang alternates not in the sitemap', 'translation missing/unpublished or noindex in that locale', issues.reciprocal.slice(0, 15))
|
||
if (issues.desc.length) report('WARNING', 'missing meta description', 'fill SEO tab in the panel (or site description fallback)', issues.desc)
|
||
if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles)
|
||
if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle)
|
||
if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3))
|
||
|
||
// --- 5. 404 ---------------------------------------------------------------
|
||
const firstLocale = [...byLocale.keys()].find((l) => l && l.length <= 5) ?? ''
|
||
for (const path of [`/${firstLocale ? firstLocale + '/' : ''}ipal-seo-check-${Date.now()}`]) {
|
||
const r = await get(path.replace('//', '/'), { redirect: 'manual' })
|
||
if (r.res.status === 200) report('ERROR', `unknown URL returns 200 (soft 404): ${path}`, 'notFound() in the catch-all, not-found.tsx (pages.md)')
|
||
else if (r.res.status !== 404 && !(r.res.status >= 300 && r.res.status < 400)) report('WARNING', `unknown URL returns ${r.res.status}`, 'expected 404')
|
||
}
|
||
|
||
// --- 6. llms.txt (info-level) -------------------------------------------------
|
||
const llms = await get('/llms.txt', { body: false }).catch(() => null)
|
||
if (!llms || llms.res.status !== 200) report('WARNING', 'no /llms.txt', 'createLlmsTxtRoute (seo.md) — AI-readable site summary')
|
||
|
||
// --- output -------------------------------------------------------------
|
||
for (const f of findings) {
|
||
console.log(`\n[${f.level}] ${f.title}${f.items.length ? ` (${f.items.length})` : ''} — ${f.rule}`)
|
||
for (const i of f.items.slice(0, 10)) console.log(` ${i}`)
|
||
if (f.items.length > 10) console.log(` … and ${f.items.length - 10} more`)
|
||
}
|
||
console.log(`\nroot: ${rootStatus}${rootLocation ? ' → ' + rootLocation : ''} · sitemap: ${urls.length} URL(s), ${byLocale.size} locale group(s) · checked: ${sample.length} page(s)`)
|
||
console.log(`ipal-seo-check: ${errors} error(s), ${warnings} warning(s)`)
|
||
process.exit(errors ? 1 : 0)
|