feat: scaffold Journal layer with configurable post route and git-install check

- journal module registers the Journal pages at journal.routes paths
- typed anonymous-GET client, html gate, SSR x-forwarded-for forwarding
- fixture API, built-server SSR smoke and git-tag install check
This commit is contained in:
2026-10-09 17:31:45 +02:00
commit 6f6792f51c
34 changed files with 12893 additions and 0 deletions

9
testing/expect-acme.txt Normal file
View File

@@ -0,0 +1,9 @@
# SSR expectations against the acme fixtures (testing/fixtures/acme).
# Grammar: STATUS PATH [contains=TEXT] [notcontains=TEXT] [type=PREFIX]
# The consumer enables en (default, no prefix) and pl (/pl prefix).
# Single post
200 /blog/hello-acme contains=Hello Acme
404 /blog/missing-post
200 /blog/unsafe-sample contains=journal-post-body--blocked notcontains=alert(
404 /blog/draft-note

247
testing/fixture-api.mjs Normal file
View File

@@ -0,0 +1,247 @@
// A small node:http stand-in for the anonymous Journal API
// (/_journal/api/v1), answering from JSON fixtures. It follows the Go
// handlers' query rules (page, per_page clamp, sort allow-list, category with
// nested children, tag, search, include_empty) and the author routes, and it
// records every request so a smoke run can assert header forwarding.
//
// Plain .mjs with JSDoc types: Node does not strip TypeScript under
// node_modules, and consuming apps import this file from there.
import { createServer } from 'node:http'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
const PREFIX = '/_journal/api/v1'
const DEFAULT_PER_PAGE = 9
const MAX_PER_PAGE = 30
const SORT_COLUMNS = new Set(['published_at', 'created_at', 'updated_at', 'title', 'id'])
/**
* @typedef {{ method: string, url: string, xff: string | null }} FixtureRequest
* @typedef {{ url: string, requests: FixtureRequest[], close: () => Promise<void> }} FixtureApi
*/
/** @param {string} dir @param {string} name @param {any} fallback */
function readJson(dir, name, fallback) {
try {
return JSON.parse(readFileSync(join(dir, name), 'utf8'))
} catch (err) {
if (/** @type {any} */ (err).code === 'ENOENT') return fallback
throw err
}
}
/** @param {any} post */
function isPublished(post) {
return post.published === true && !!post.published_at && Date.parse(post.published_at) <= Date.now()
}
/** @param {string | null} raw */
function parsePage(raw) {
const n = Number.parseInt(raw ?? '', 10)
return Number.isFinite(n) && n > 0 ? n : 1
}
/** @param {string | null} raw */
function parsePerPage(raw) {
if (raw === null || raw.trim() === '') return DEFAULT_PER_PAGE
const n = Number.parseInt(raw, 10)
if (!Number.isFinite(n)) return DEFAULT_PER_PAGE
return Math.min(MAX_PER_PAGE, Math.max(1, n))
}
/** @param {string | null} raw @returns {[string, 'asc' | 'desc']} */
function parseSort(raw) {
const [col, dir] = (raw ?? '').trim().split(/\s+/)
if (col && SORT_COLUMNS.has(col)) return [col, dir === 'asc' ? 'asc' : 'desc']
return ['published_at', 'desc']
}
/** @param {any[]} rows @param {[string, 'asc' | 'desc']} sort */
function sortRows(rows, [col, dir]) {
const sign = dir === 'asc' ? 1 : -1
return [...rows].sort((a, b) => {
const av = a[col]
const bv = b[col]
if (av === bv) return (a.id - b.id) * sign
return (av < bv ? -1 : 1) * sign
})
}
/** @param {any[]} tree @returns {any[]} */
function flatten(tree) {
/** @type {any[]} */
const out = []
const walk = (/** @type {any[]} */ nodes) => {
for (const n of nodes ?? []) {
out.push(n)
walk(n.children)
}
}
walk(tree)
return out
}
/** @param {any[]} tree @param {boolean} includeEmpty @returns {any[]} */
function filterTree(tree, includeEmpty) {
/** @type {any[]} */
const out = []
for (const node of tree ?? []) {
const children = filterTree(node.children ?? [], includeEmpty)
if (!includeEmpty && node.post_count === 0 && children.length === 0) continue
const { children: _drop, ...row } = node
if (children.length > 0) row.children = children
out.push(row)
}
return out
}
/** @param {any[]} rows @param {number} page @param {number} perPage */
function paginate(rows, page, perPage) {
const total = rows.length
const lastPage = Math.max(1, Math.ceil(total / perPage))
return {
data: rows.slice((page - 1) * perPage, page * perPage),
meta: { current_page: page, last_page: lastPage, per_page: perPage, total },
}
}
/** @param {any} post */
function sibling(post) {
return post ? { id: post.id, title: post.title, slug: post.slug } : null
}
/**
* Starts the fixture API on 127.0.0.1.
* @param {{ dir: string, port?: number }} opts
* @returns {Promise<FixtureApi>}
*/
export function startFixtureApi({ dir, port = 0 }) {
/** @type {any[]} */
const posts = readJson(dir, 'posts.json', [])
/** @type {any[]} */
const categories = readJson(dir, 'categories.json', [])
/** @type {any[]} */
const tags = readJson(dir, 'tags.json', [])
/** @type {any[]} */
const authors = readJson(dir, 'authors.json', [])
let rss = ''
try {
rss = readFileSync(join(dir, 'rss.xml'), 'utf8')
} catch {
rss = '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel></channel></rss>'
}
/** @type {FixtureRequest[]} */
const requests = []
const published = () => posts.filter(isPublished)
/** @param {string} value */
const resolveAuthor = (value) => {
const bySlug = authors.find((a) => a.slug === value)
if (bySlug) return bySlug
const byLogin = authors.find((a) => a.login === value)
if (byLogin && published().some((p) => p.author && p.author.id === byLogin.id)) return byLogin
return null
}
/** @param {URLSearchParams} q */
const listPosts = (q, base = published()) => {
let rows = base
const category = q.get('category')
if (category) {
const flat = flatten(categories)
const root = flat.find((c) => c.slug === category || String(c.id) === category)
const ids = new Set(root ? flatten([root]).map((c) => c.id) : [])
rows = rows.filter((p) => p.categories.some((/** @type {any} */ c) => ids.has(c.id)))
}
const tag = q.get('tag')
if (tag) rows = rows.filter((p) => p.tags.some((/** @type {any} */ t) => t.slug === tag))
const search = (q.get('search') ?? '').trim()
if (search.length >= 3) {
const s = search.toLowerCase()
rows = rows.filter((p) => p.title.toLowerCase().includes(s))
}
rows = sortRows(rows, parseSort(q.get('sort')))
return paginate(rows, parsePage(q.get('page')), parsePerPage(q.get('per_page')))
}
/**
* @param {import('node:http').IncomingMessage} req
* @returns {{ status: number, body: string, type: string }}
*/
const route = (req) => {
const url = new URL(req.url ?? '/', 'http://fixture.local')
const json = (/** @type {number} */ status, /** @type {any} */ value) => ({
status,
body: JSON.stringify(value),
type: 'application/json',
})
if (!url.pathname.startsWith(PREFIX + '/')) return json(404, { error: 'Not found' })
if (req.method !== 'GET' && req.method !== 'HEAD') return json(405, { error: 'Method not allowed' })
const path = decodeURIComponent(url.pathname.slice(PREFIX.length))
const q = url.searchParams
if (path === '/posts') return json(200, listPosts(q))
if (path.startsWith('/posts/')) {
const slug = path.slice('/posts/'.length)
const live = sortRows(published(), ['published_at', 'desc'])
const post = live.find((p) => p.slug === slug || String(p.id) === slug)
if (!post) return json(404, { error: 'Post not found' })
const idx = live.indexOf(post)
const catIds = new Set(post.categories.map((/** @type {any} */ c) => c.id))
const related =
catIds.size === 0
? []
: live
.filter((p) => p.id !== post.id && p.categories.some((/** @type {any} */ c) => catIds.has(c.id)))
.slice(0, 3)
return json(200, {
data: { ...post, previous_post: sibling(live[idx + 1]), next_post: sibling(live[idx - 1]), related_posts: related },
})
}
if (path === '/categories') {
const includeEmpty = ['1', 'true'].includes(q.get('include_empty') ?? '')
return json(200, { data: filterTree(categories, includeEmpty) })
}
if (path === '/tags') return json(200, { data: tags })
if (path === '/rss') return { status: 200, body: rss, type: 'application/rss+xml; charset=utf-8' }
const author = /^\/authors\/([^/]+)(\/posts)?$/.exec(path)
if (author) {
const row = resolveAuthor(author[1].trim())
if (!row) return json(404, { error: 'Author not found' })
if (!author[2]) {
return json(200, { data: { id: row.id, slug: row.slug, first_name: row.first_name, last_name: row.last_name } })
}
const mine = published().filter((p) => p.author && p.author.id === row.id)
return json(200, listPosts(new URLSearchParams({ page: q.get('page') ?? '', per_page: q.get('per_page') ?? '', sort: q.get('sort') ?? '' }), mine))
}
return json(404, { error: 'Not found' })
}
const server = createServer((req, res) => {
const xff = req.headers['x-forwarded-for']
requests.push({ method: req.method ?? 'GET', url: req.url ?? '/', xff: Array.isArray(xff) ? xff.join(', ') : (xff ?? null) })
let out
try {
out = route(req)
} catch (err) {
out = { status: 500, body: JSON.stringify({ error: String(err) }), type: 'application/json' }
}
res.writeHead(out.status, { 'content-type': out.type })
res.end(req.method === 'HEAD' ? undefined : out.body)
})
return new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, '127.0.0.1', () => {
const addr = /** @type {import('node:net').AddressInfo} */ (server.address())
resolve({
url: `http://127.0.0.1:${addr.port}`,
requests,
close: () => new Promise((done) => server.close(() => done())),
})
})
})
}

View File

@@ -0,0 +1,9 @@
[
{
"id": 1,
"slug": "jane-doe",
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
}
]

View File

@@ -0,0 +1,22 @@
[
{
"id": 1,
"name": "News",
"slug": "news",
"description": "Company news from Acme.",
"content": "<h2>About Acme news</h2>\n<p>Acme news marker: every launch, recall and anvil delivery.</p>\n",
"parent_id": null,
"nest_depth": 0,
"post_count": 12
},
{
"id": 2,
"name": "Quiet",
"slug": "quiet",
"description": "A category with no posts yet.",
"content": null,
"parent_id": null,
"nest_depth": 0,
"post_count": 0
}
]

View File

@@ -0,0 +1,466 @@
[
{
"id": 1,
"title": "Hello Acme",
"slug": "hello-acme",
"excerpt": "Acme says hello and introduces its blog.",
"content": "## Welcome to Acme\n\nAcme builds anvils, rockets and very fast roller skates.\n",
"content_html": "<h2>Welcome to Acme</h2>\n<p>Acme builds anvils, rockets and very fast roller skates.</p>\n",
"reading_time": 1,
"published": true,
"published_at": "2026-01-14T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [
{
"id": 1,
"name": "Release",
"slug": "release"
}
],
"featured_images": [
{
"id": 1,
"url": "/storage/app/uploads/public/acme/hello.png",
"file_name": "hello.png",
"file_size": 1024
}
],
"featured_image_url": "/storage/app/uploads/public/acme/hello.png",
"translations": {},
"created_at": "2026-01-14T09:00:00+00:00",
"updated_at": "2026-02-01T10:00:00+00:00"
},
{
"id": 2,
"title": "Unsafe Sample",
"slug": "unsafe-sample",
"excerpt": "Unsafe Sample: a short summary.",
"content": "Before",
"content_html": "<p>Before</p><script>alert(1)</script><p>After</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-13T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-13T09:00:00+00:00",
"updated_at": "2026-01-13T09:00:00+00:00"
},
{
"id": 3,
"title": "Acme Note 03",
"slug": "acme-note-03",
"excerpt": "Acme Note 03: a short summary.",
"content": "Acme Note 03 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 03 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-12T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-12T09:00:00+00:00",
"updated_at": "2026-01-12T09:00:00+00:00"
},
{
"id": 4,
"title": "Acme Note 04",
"slug": "acme-note-04",
"excerpt": "Acme Note 04: a short summary.",
"content": "Acme Note 04 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 04 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-11T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-11T09:00:00+00:00",
"updated_at": "2026-01-11T09:00:00+00:00"
},
{
"id": 5,
"title": "Acme Note 05",
"slug": "acme-note-05",
"excerpt": "Acme Note 05: a short summary.",
"content": "Acme Note 05 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 05 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-10T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-10T09:00:00+00:00",
"updated_at": "2026-01-10T09:00:00+00:00"
},
{
"id": 6,
"title": "Acme Note 06",
"slug": "acme-note-06",
"excerpt": "Acme Note 06: a short summary.",
"content": "Acme Note 06 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 06 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-09T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-09T09:00:00+00:00",
"updated_at": "2026-01-09T09:00:00+00:00"
},
{
"id": 7,
"title": "Acme Note 07",
"slug": "acme-note-07",
"excerpt": "Acme Note 07: a short summary.",
"content": "Acme Note 07 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 07 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-08T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-08T09:00:00+00:00",
"updated_at": "2026-01-08T09:00:00+00:00"
},
{
"id": 8,
"title": "Acme Note 08",
"slug": "acme-note-08",
"excerpt": "Acme Note 08: a short summary.",
"content": "Acme Note 08 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 08 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-07T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-07T09:00:00+00:00",
"updated_at": "2026-01-07T09:00:00+00:00"
},
{
"id": 9,
"title": "Acme Note 09",
"slug": "acme-note-09",
"excerpt": "Acme Note 09: a short summary.",
"content": "Acme Note 09 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 09 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-06T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-06T09:00:00+00:00",
"updated_at": "2026-01-06T09:00:00+00:00"
},
{
"id": 10,
"title": "Acme Note 10",
"slug": "acme-note-10",
"excerpt": "Acme Note 10: a short summary.",
"content": "Acme Note 10 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 10 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-05T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-05T09:00:00+00:00",
"updated_at": "2026-01-05T09:00:00+00:00"
},
{
"id": 11,
"title": "Acme Note 11",
"slug": "acme-note-11",
"excerpt": "Acme Note 11: a short summary.",
"content": "Acme Note 11 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 11 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-04T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-04T09:00:00+00:00",
"updated_at": "2026-01-04T09:00:00+00:00"
},
{
"id": 12,
"title": "Acme Note 12",
"slug": "acme-note-12",
"excerpt": "Acme Note 12: a short summary.",
"content": "Acme Note 12 is a sample post for the Acme blog.",
"content_html": "<p>Acme Note 12 is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-03T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-03T09:00:00+00:00",
"updated_at": "2026-01-03T09:00:00+00:00"
},
{
"id": 13,
"title": "Uncategorised Note",
"slug": "uncategorised-note",
"excerpt": "Uncategorised Note: a short summary.",
"content": "Uncategorised Note is a sample post for the Acme blog.",
"content_html": "<p>Uncategorised Note is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": true,
"published_at": "2026-01-02T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": null,
"categories": [],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-02T09:00:00+00:00",
"updated_at": "2026-01-02T09:00:00+00:00"
},
{
"id": 14,
"title": "Draft Note",
"slug": "draft-note",
"excerpt": "Draft Note: a short summary.",
"content": "Draft Note is a sample post for the Acme blog.",
"content_html": "<p>Draft Note is a sample post for the Acme blog.</p>",
"reading_time": 1,
"published": false,
"published_at": "2026-01-20T09:00:00+00:00",
"is_pinned": false,
"metadata": null,
"sources": null,
"author": {
"id": 1,
"first_name": "Jane",
"last_name": "Doe",
"login": "jdoe"
},
"categories": [
{
"id": 1,
"name": "News",
"slug": "news"
}
],
"tags": [],
"featured_images": [],
"featured_image_url": null,
"translations": {},
"created_at": "2026-01-20T09:00:00+00:00",
"updated_at": "2026-01-20T09:00:00+00:00"
}
]

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Acme Blog</title>
<link>http://acme.test</link>
<description>News from Acme</description>
<item>
<title>Hello Acme</title>
<link>http://acme.test/blog/hello-acme</link>
<guid>http://acme.test/blog/hello-acme</guid>
<pubDate>Wed, 14 Jan 2026 09:00:00 +0000</pubDate>
<description>Acme says hello and introduces its blog.</description>
</item>
</channel>
</rss>

View File

@@ -0,0 +1,8 @@
[
{
"id": 1,
"name": "Release",
"slug": "release",
"post_count": 1
}
]

71
testing/nuxt-server.mjs Normal file
View File

@@ -0,0 +1,71 @@
// Boots a built Nuxt server (`<outputDir>/server/index.mjs`) on 127.0.0.1
// against a given Journal API base and waits until it answers HTTP.
// Plain .mjs with JSDoc types so it runs from node_modules unchanged.
import { spawn } from 'node:child_process'
import { createServer } from 'node:net'
import { existsSync } from 'node:fs'
import { join, resolve } from 'node:path'
/** @returns {Promise<number>} */
function freePort() {
return new Promise((done, fail) => {
const srv = createServer()
srv.once('error', fail)
srv.listen(0, '127.0.0.1', () => {
const { port } = /** @type {import('node:net').AddressInfo} */ (srv.address())
srv.close(() => done(port))
})
})
}
/**
* @param {{ outputDir: string, apiBase: string, port?: number, env?: Record<string, string>, timeoutMs?: number }} opts
* @returns {Promise<{ url: string, close: () => Promise<void> }>}
*/
export async function startNuxtServer({ outputDir, apiBase, port = 0, env = {}, timeoutMs = 30000 }) {
const entry = join(resolve(outputDir), 'server', 'index.mjs')
if (!existsSync(entry)) throw new Error(`nuxt-server: ${entry} does not exist; build first`)
const listenPort = port || (await freePort())
const url = `http://127.0.0.1:${listenPort}`
const child = spawn(process.execPath, [entry], {
env: {
...process.env,
NODE_ENV: 'production',
NITRO_HOST: '127.0.0.1',
NITRO_PORT: String(listenPort),
NUXT_JOURNAL_API_BASE: apiBase,
...env,
},
stdio: ['ignore', 'pipe', 'pipe'],
})
let log = ''
child.stdout.on('data', (b) => (log += b))
child.stderr.on('data', (b) => (log += b))
let exited = false
child.once('exit', () => (exited = true))
const close = () =>
new Promise((/** @type {(v?: void) => void} */ done) => {
if (exited) return done()
child.once('exit', () => done())
child.kill('SIGTERM')
setTimeout(() => {
if (!exited) child.kill('SIGKILL')
}, 5000).unref()
})
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (exited) throw new Error(`nuxt-server: server exited before answering\n${log}`)
try {
await fetch(url + '/', { redirect: 'manual', signal: AbortSignal.timeout(2000) })
return { url, close }
} catch {
await new Promise((r) => setTimeout(r, 200))
}
}
await close()
throw new Error(`nuxt-server: no answer on ${url} within ${timeoutMs} ms\n${log}`)
}

132
testing/smoke-ssr.mjs Executable file
View File

@@ -0,0 +1,132 @@
#!/usr/bin/env node
// SSR smoke check: boots the fixture Journal 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] [type=PREFIX]
// A value runs until the next ` contains=`, ` notcontains=`, ` type=` or the
// end of the line, so it may contain spaces. 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).
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)
}
/**
* @param {string} line
* @returns {{ status: number, path: string, contains?: string, notcontains?: string, type?: string }}
*/
export function parseExpectLine(line) {
const m = /^(\d{3})\s+(\S+)(.*)$/.exec(line.trim())
if (!m) throw new Error('expected "STATUS PATH [options]"')
/** @type {{ status: number, path: string, contains?: string, notcontains?: string, type?: string }} */
const check = { status: Number(m[1]), path: m[2] }
const rest = m[3]
const re = /\s(contains|notcontains|type)=/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()}"`)
}
/** @type {Record<string, string>} */
const options = {}
marks.forEach((mark, i) => {
const end = i + 1 < marks.length ? marks[i + 1].start : rest.length
options[mark.key] = rest.slice(mark.valueStart, end).trim()
})
return { ...check, ...options }
}
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: args.env })
for (const line of lines) {
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()
const type = res.headers.get('content-type') ?? ''
if (res.status !== check.status) failures.push(`${line}: status ${res.status}, want ${check.status}`)
else if (check.contains !== undefined && !body.includes(check.contains)) failures.push(`${line}: body lacks "${check.contains}"`)
else if (check.notcontains !== undefined && body.includes(check.notcontains)) failures.push(`${line}: body contains "${check.notcontains}"`)
else if (check.type !== undefined && !type.startsWith(check.type)) failures.push(`${line}: content-type "${type}", want prefix "${check.type}"`)
}
if (!api.requests.some((r) => (r.xff ?? '').includes(VISITOR_IP))) {
failures.push('x-forwarded-for: x-forwarded-for not forwarded')
}
} 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)
})