- extend vue-seo-layer (link dependency during development) and drop
@nuxtjs/seo: the page head, canonical and the one JSON-LD graph come
from the CMS resolve answer; the post's own title, excerpt and image
apply only while there is no CMS answer
- remove the journal sitemap source and the copied shared purge route,
library and plugin (the SEO layer serves POST /api/__site__/cache/purge);
the deprecated POST /api/__journal__/cache/purge keeps working
- post title is h1 while the Journal API reports content_h1_to_h2 on
(or absent) and p.journal-post__title while off; journal.postTitleTag
('auto' | 'h1' | 'p') overrides it; body h1 headings are demoted to h2
while the setting is on (gateJournalHtml/sanitizeJournalHtml demoteH1)
- journal.breadcrumbs option and post-title CSS tokens
- smoke harness: count=, header=, noheader= and resolves lines; the
fixture API also answers the SEO resolve and site endpoints
BREAKING CHANGE: the layer no longer installs @nuxtjs/seo (no
nuxt-site-config, nuxt-schema-org, robots or sitemap module, no
/api/__sitemap__/journal source, no useSiteConfig()); apps take their
head, sitemaps and robots from the SEO plugin through vue-seo-layer.
207 lines
8.5 KiB
JavaScript
Executable File
207 lines
8.5 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
// SSR smoke check: boots the fixture Journal and SEO API and a built Nuxt
|
|
// server, then checks each line of an expectations file.
|
|
//
|
|
// node smoke-ssr.mjs --output <.output dir> --fixtures <dir> --expect <file> [--env KEY=VALUE]...
|
|
//
|
|
// Expectation grammar, one check per line ('#' starts a comment line):
|
|
// STATUS PATH [contains=TEXT] [notcontains=TEXT] [count=TEXT:N] [type=PREFIX]
|
|
// [header=NAME: VALUE] [noheader=NAME]
|
|
// resolves PATH N the fixture SEO API has seen exactly N resolve calls for
|
|
// PATH so far (PATH * counts every resolve call)
|
|
// A value runs until the next ` contains=`, ` notcontains=`, ` count=`,
|
|
// ` type=`, ` header=`, ` noheader=` or the end of the line, so it may
|
|
// contain spaces. Every option may repeat on a line and every occurrence
|
|
// applies. count= wants exactly N occurrences of TEXT in the body (N is the
|
|
// number after the last colon); header= wants the response header NAME to
|
|
// equal VALUE (both trimmed); noheader= wants it absent. The same grammar
|
|
// as vue-seo-layer's testing/smoke-ssr.mjs. Requests are plain GETs that do
|
|
// not follow redirects and carry `X-Forwarded-For: 203.0.113.7`. After the
|
|
// lines, at least one fixture API request must have carried that address
|
|
// (the SSR fetches forward the visitor's x-forwarded-for), and every
|
|
// categories request must have carried include_empty=1.
|
|
//
|
|
// The server gets the fixture API as NUXT_JOURNAL_API_BASE and, for the
|
|
// vue-seo-layer resolve calls, NUXT_SEO_API_BASE (<fixtures>/seo/resolve.json
|
|
// and site.json); --env overrides either.
|
|
|
|
import { readFileSync } from 'node:fs'
|
|
import { resolve } from 'node:path'
|
|
import { startFixtureApi } from './fixture-api.mjs'
|
|
import { startNuxtServer } from './nuxt-server.mjs'
|
|
|
|
const VISITOR_IP = '203.0.113.7'
|
|
|
|
/** @param {string[]} argv */
|
|
function parseArgs(argv) {
|
|
/** @type {{ output?: string, fixtures?: string, expect?: string, env: Record<string, string> }} */
|
|
const out = { env: {} }
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const arg = argv[i]
|
|
const next = () => {
|
|
const v = argv[++i]
|
|
if (v === undefined) throw new Error(`${arg} needs a value`)
|
|
return v
|
|
}
|
|
if (arg === '--output') out.output = next()
|
|
else if (arg === '--fixtures') out.fixtures = next()
|
|
else if (arg === '--expect') out.expect = next()
|
|
else if (arg === '--env') {
|
|
const kv = next()
|
|
const eq = kv.indexOf('=')
|
|
if (eq < 1) throw new Error(`--env expects KEY=VALUE, got ${kv}`)
|
|
out.env[kv.slice(0, eq)] = kv.slice(eq + 1)
|
|
} else throw new Error(`unknown argument ${arg}`)
|
|
}
|
|
if (!out.output || !out.fixtures || !out.expect) throw new Error('--output, --fixtures and --expect are required')
|
|
return /** @type {{ output: string, fixtures: string, expect: string, env: Record<string, string> }} */ (out)
|
|
}
|
|
|
|
const OPTION_KEYS = ['contains', 'notcontains', 'count', 'type', 'header', 'noheader']
|
|
|
|
/**
|
|
* @typedef {{ status: number, path: string, options: Array<{ key: string, value: string }> }} ExpectCheck
|
|
*/
|
|
|
|
/**
|
|
* @param {string} line
|
|
* @returns {ExpectCheck}
|
|
*/
|
|
export function parseExpectLine(line) {
|
|
const m = /^(\d{3})\s+(\S+)(.*)$/.exec(line.trim())
|
|
if (!m) throw new Error('expected "STATUS PATH [options]"')
|
|
const rest = m[3]
|
|
const re = new RegExp(`\\s(${OPTION_KEYS.join('|')})=`, 'g')
|
|
/** @type {Array<{ key: string, start: number, valueStart: number }>} */
|
|
const marks = []
|
|
let hit
|
|
while ((hit = re.exec(rest)) !== null) marks.push({ key: hit[1], start: hit.index, valueStart: re.lastIndex })
|
|
if (marks.length === 0 && rest.trim() !== '') throw new Error(`unknown option text "${rest.trim()}"`)
|
|
if (marks.length > 0 && rest.slice(0, marks[0].start).trim() !== '') {
|
|
throw new Error(`unknown option text "${rest.slice(0, marks[0].start).trim()}"`)
|
|
}
|
|
const options = marks.map((mark, i) => {
|
|
const end = i + 1 < marks.length ? marks[i + 1].start : rest.length
|
|
return { key: mark.key, value: rest.slice(mark.valueStart, end).trim() }
|
|
})
|
|
return { status: Number(m[1]), path: m[2], options }
|
|
}
|
|
|
|
/** @param {string} body @param {string} text */
|
|
function occurrences(body, text) {
|
|
if (text === '') return 0
|
|
let n = 0
|
|
for (let at = body.indexOf(text); at !== -1; at = body.indexOf(text, at + text.length)) n++
|
|
return n
|
|
}
|
|
|
|
/**
|
|
* The failures of one response against its check.
|
|
* @param {ExpectCheck} check @param {{ status: number, headers: Headers, body: string }} res
|
|
* @returns {string[]}
|
|
*/
|
|
export function checkResponse(check, res) {
|
|
if (res.status !== check.status) return [`status ${res.status}, want ${check.status}`]
|
|
/** @type {string[]} */
|
|
const out = []
|
|
const type = res.headers.get('content-type') ?? ''
|
|
for (const { key, value } of check.options) {
|
|
if (key === 'contains' && !res.body.includes(value)) out.push(`body lacks "${value}"`)
|
|
else if (key === 'notcontains' && res.body.includes(value)) out.push(`body contains "${value}"`)
|
|
else if (key === 'count') {
|
|
const colon = value.lastIndexOf(':')
|
|
const want = colon > 0 ? Number(value.slice(colon + 1)) : NaN
|
|
if (!Number.isInteger(want)) {
|
|
out.push(`count=${value}: want TEXT:N`)
|
|
continue
|
|
}
|
|
const text = value.slice(0, colon)
|
|
const got = occurrences(res.body, text)
|
|
if (got !== want) out.push(`body has ${got} of "${text}", want ${want}`)
|
|
} else if (key === 'type' && !type.startsWith(value)) out.push(`content-type "${type}", want prefix "${value}"`)
|
|
else if (key === 'header') {
|
|
const colon = value.indexOf(':')
|
|
const name = colon > 0 ? value.slice(0, colon).trim() : value.trim()
|
|
const want = colon > 0 ? value.slice(colon + 1).trim() : ''
|
|
const got = res.headers.get(name)
|
|
if (got === null || got.trim() !== want) out.push(`header ${name} is ${JSON.stringify(got)}, want "${want}"`)
|
|
} else if (key === 'noheader') {
|
|
const got = res.headers.get(value)
|
|
if (got !== null) out.push(`header ${value} is ${JSON.stringify(got)}, want none`)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
async function main() {
|
|
const args = parseArgs(process.argv.slice(2))
|
|
const lines = readFileSync(resolve(args.expect), 'utf8')
|
|
.split('\n')
|
|
.map((l) => l.trim())
|
|
.filter((l) => l !== '' && !l.startsWith('#'))
|
|
|
|
const api = await startFixtureApi({ dir: resolve(args.fixtures) })
|
|
/** @type {{ url: string, close: () => Promise<void> } | null} */
|
|
let nuxt = null
|
|
const failures = /** @type {string[]} */ ([])
|
|
try {
|
|
nuxt = await startNuxtServer({
|
|
outputDir: args.output,
|
|
apiBase: `${api.url}/_journal/api/v1`,
|
|
env: { NUXT_SEO_API_BASE: `${api.url}/_seo/api/v1`, ...args.env },
|
|
})
|
|
for (const line of lines) {
|
|
const resolves = /^resolves\s+(\S+)\s+(\d+)$/.exec(line)
|
|
if (resolves) {
|
|
const got = api.resolveCount(resolves[1] === '*' ? undefined : resolves[1])
|
|
if (got !== Number(resolves[2])) failures.push(`${line}: the API saw ${got} resolve calls`)
|
|
continue
|
|
}
|
|
let check
|
|
try {
|
|
check = parseExpectLine(line)
|
|
} catch (err) {
|
|
failures.push(`${line}: ${/** @type {Error} */ (err).message}`)
|
|
continue
|
|
}
|
|
let res
|
|
try {
|
|
res = await fetch(nuxt.url + check.path, {
|
|
redirect: 'manual',
|
|
headers: { 'X-Forwarded-For': VISITOR_IP },
|
|
signal: AbortSignal.timeout(20000),
|
|
})
|
|
} catch (err) {
|
|
failures.push(`${line}: request failed: ${/** @type {Error} */ (err).message}`)
|
|
continue
|
|
}
|
|
const body = await res.text()
|
|
for (const f of checkResponse(check, { status: res.status, headers: res.headers, body })) failures.push(`${line}: ${f}`)
|
|
}
|
|
if (!api.requests.some((r) => (r.xff ?? '').includes(VISITOR_IP))) {
|
|
failures.push('x-forwarded-for: x-forwarded-for not forwarded')
|
|
}
|
|
// Categories are always requested with include_empty=1, so empty ones resolve.
|
|
for (const r of api.requests) {
|
|
const u = new URL(r.url, 'http://fixture.local')
|
|
if (u.pathname.endsWith('/categories') && u.searchParams.get('include_empty') !== '1') {
|
|
failures.push(`include_empty: ${r.url} requested without include_empty=1`)
|
|
}
|
|
}
|
|
} finally {
|
|
if (nuxt) await nuxt.close()
|
|
await api.close()
|
|
}
|
|
|
|
if (failures.length > 0) {
|
|
for (const f of failures) console.error(`smoke-ssr: FAIL ${f}`)
|
|
process.exit(1)
|
|
}
|
|
console.log(`smoke-ssr: ok (${lines.length} checks)`)
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(`smoke-ssr: FAIL setup: ${err instanceof Error ? err.message : String(err)}`)
|
|
process.exit(1)
|
|
})
|