Merge claude/performance-2026-12-36a376: fewer queries per render, no 'use client' on the /client barrels, budgets, the doctor's performance and growth groups

Conflicts kept both sides: the doctor status (twoFactorConfirm with growth and media), its key test, e2e:built (the 2FA
enrolment spec and the performance budgets), the reference index (regenerated). Reference skill copies synced
(iapl-performance added, iapl-audit and iapl-reference updated).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 14:58:44 +01:00
co-authored by Claude Opus 5.5
77 changed files with 5841 additions and 80 deletions
+5
View File
@@ -20,6 +20,9 @@
* e2e/sign-in-answers.spec.ts (1.17.2: a locked staff account answers like a wrong password; the panel actions refuse
* another origin), e2e/two-factor-enrolment.spec.ts (1.18.0: the first 2FA set-up waits for the e-mailed link,
* read from the mail sink; the password alone no longer enrols a factor).
* 4. e2e/performance.spec.ts (1.18.0): the performance budgets — LCP, CLS, Total Blocking Time, the response to a tap,
* JS / CSS / font bytes, requests, render-blocking resources and third parties before consent for every page type,
* on a throttled phone and a desktop, and the MongoDB queries of one render (docs/performance.md).
*
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
@@ -98,6 +101,8 @@ for (const bundler of bundlers) {
}
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers and the own account`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', '--grep', '2FA enrolment|late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' })
// the budgets are the built site's own numbers: they hold for each bundler (docs/performance.md, docs/dev/perf/)
run(`${bundler}: performance budgets — every page type on a phone and a desktop, queries per render`, 'pnpm', ['exec', 'playwright', 'test', 'e2e/performance.spec'] /* a regex on the file path: a checkout path may hold "performance" */, site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
passed.push(bundler)
}
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env node
/**
* pnpm perf:measure — measures the BUILT reference site (reference/) and writes the numbers to a JSON file.
* The method behind docs/performance.md → "How the plugin is measured"; repeat it after a change and compare.
*
* Before: reference/.env filled (local seeded MongoDB, ALLOW_LOCAL_MEDIA=1), the plugin built, `pnpm build` in
* reference/ (webpack; `pnpm exec next build --turbopack` for Turbopack). The script starts `next start` itself.
*
* node scripts/perf-measure.mjs --label=webpack-before [--runs=3] [--port=3370] [--out=file.json] [--no-server]
*
* Server side: cold start (spawn → /api/health answers, → first page), memory (RSS of the server after the run),
* TTFB of a cached (ISR) page over 20 requests, and the cost of RENDERING each page once: the request carries
* Next's `x-prerender-revalidate` header (the on-demand revalidation Next uses itself), so the page is rendered
* now and not served from the ISR cache; MongoDB's profiler (level 2, the database in DATABASE_URI) counts every
* query that render made and their time. The profiler is switched off again at the end.
* Client side: e2e/perf-lab.mjs (Lighthouse's mobile and desktop profiles), the median of --runs runs per page.
*/
import { execFileSync, spawn } from 'node:child_process'
import { readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { launch, measureMedian } from '../reference/e2e/perf-lab.mjs'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const site = path.join(root, 'reference')
const arg = (name, fallback) => process.argv.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback
const label = arg('label', 'run')
const runs = Number(arg('runs', 3))
const env = Object.fromEntries(readFileSync(path.join(site, '.env'), 'utf8').split('\n').filter((l) => /^[A-Z0-9_]+=/.test(l)).map((l) => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)]))
const port = Number(arg('port', new URL(env.NEXT_PUBLIC_SERVER_URL ?? 'http://localhost:3370').port || 3370))
const base = `http://localhost:${port}`
const out = arg('out', path.join(root, 'docs', 'dev', 'perf', `${label}.json`))
/** The page types measured: one of each template the reference site has (AGENTS.md → Site map). */
export const PAGES = {
home: '/pl',
page: '/pl/o-nas',
archive: '/pl/blog',
post: '/pl/blog/zanim-kupisz-dzialke',
caseStudy: '/pl/realizacje/dom-pod-lasem',
form: '/pl/wycena',
showcase: '/pl/bloki',
notFound: '/pl/nie-ma-takiej-strony',
}
// --- MongoDB profiler (through the mongo container's shell when DATABASE_URI is local; else skipped) ---
const dbUri = process.env.DATABASE_URI ?? env.DATABASE_URI
const dbName = new URL(dbUri).pathname.slice(1)
const container = arg('mongo-container', process.env.PERF_MONGO_CONTAINER ?? '')
const mongo = (js) => {
if (!container) {return null}
return execFileSync('docker', ['exec', container, 'mongosh', '--quiet', dbName, '--eval', js], { encoding: 'utf8' }).trim()
}
const profileOn = () => mongo('db.setProfilingLevel(0); db.system.profile.drop(); db.setProfilingLevel(2); "ok"')
const profileOff = () => mongo('db.setProfilingLevel(0); "ok"')
const profileRead = () => {
const raw = mongo(`JSON.stringify(db.system.profile.find({ ns: { $not: /system\\.profile$/ }, op: { $in: ['query','command','getmore','insert','update','remove'] } }, { millis: 1, ns: 1, op: 1, 'command.find': 1, 'command.aggregate': 1, 'command.count': 1 }).toArray())`)
if (raw == null) {return null}
const rows = JSON.parse(raw).filter((r) => !r.command || r.command.find || r.command.aggregate || r.command.count || r.op !== 'command')
mongo('db.setProfilingLevel(0); db.system.profile.drop(); db.setProfilingLevel(2); "ok"')
const byCollection = {}
for (const r of rows) {const c = r.ns.split('.').slice(1).join('.'); byCollection[c] = (byCollection[c] ?? 0) + 1}
return { byCollection, count: rows.length, ms: rows.reduce((s, r) => s + (r.millis ?? 0), 0) }
}
const waitFor = async (url, timeoutMs = 60000) => {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
try {
if ((await fetch(url)).ok) {return Date.now() - start}
} catch {}
await new Promise((r) => setTimeout(r, 100))
}
throw new Error(`${url} did not answer in ${timeoutMs} ms`)
}
const timed = async (url, init) => {
const t = performance.now()
const res = await fetch(url, { redirect: 'manual', ...init })
await res.arrayBuffer()
return { ms: performance.now() - t, res }
}
const pct = (values, p) => {
const s = [...values].sort((a, b) => a - b)
return Math.round(s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))] * 10) / 10
}
const rssOf = (pid) => {
// the server is `node … next start` under pnpm: sum the process tree's RSS (KiB → MiB)
const tree = execFileSync('ps', ['-A', '-o', 'pid=,ppid=,rss='], { encoding: 'utf8' }).trim().split('\n').map((l) => l.trim().split(/\s+/).map(Number))
const ids = new Set([pid])
for (let changed = true; changed;) {
changed = false
for (const [p, pp] of tree) {if (ids.has(pp) && !ids.has(p)) {ids.add(p); changed = true}}
}
return Math.round(tree.filter(([p]) => ids.has(p)).reduce((s, [, , rss]) => s + rss, 0) / 1024)
}
const result = { client: {}, date: new Date().toISOString(), label, method: 'scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs', runs, server: {} }
let server = null
if (!process.argv.includes('--no-server')) {
// another server on the port would be measured instead of this build (and a stale .next answers 404 for assets)
if (await fetch(`${base}/api/health`).then(() => true, () => false)) {
console.error(`[perf] ${base} already answers: stop that server first (lsof -ti tcp:${port} | xargs kill) or pass --no-server`)
process.exit(2)
}
const t0 = Date.now()
server = spawn('pnpm', ['start'], { cwd: site, env: { ...process.env, PORT: String(port) }, detached: true, stdio: ['ignore', 'ignore', 'inherit'] })
result.server.coldStartHealthMs = await waitFor(`${base}/api/health`)
const first = await timed(`${base}${PAGES.home}`)
result.server.coldStartFirstPageMs = Date.now() - t0
result.server.firstPageMs = Math.round(first.ms)
}
try {
// TTFB of a cached page and of the dynamic routes the plugin serves
for (const [name, p] of Object.entries({ home: PAGES.home, md: '/md/pl', sitemap: '/sitemap.xml', llms: '/llms.txt' })) {
await timed(`${base}${p}`)
const times = []
for (let i = 0; i < 20; i++) {times.push((await timed(`${base}${p}`)).ms)}
result.server[`ttfb_${name}`] = { median: pct(times, 50), p95: pct(times, 95) }
}
// the cost of one render of each page (ISR bypassed), with the queries it made
const manifest = JSON.parse(readFileSync(path.join(site, '.next', 'prerender-manifest.json'), 'utf8'))
const previewModeId = manifest.preview?.previewModeId
result.server.render = {}
if (profileOn() == null) {result.server.queriesNote = 'no --mongo-container: query counts not measured'}
for (const [name, p] of Object.entries(PAGES)) {
profileRead()
const renders = []
for (let i = 0; i < 3; i++) {renders.push((await timed(`${base}${p}`, { headers: previewModeId ? { 'x-prerender-revalidate': previewModeId } : {} })).ms)}
const q = profileRead()
result.server.render[name] = { medianMs: pct(renders, 50), queries: q ? Math.round(q.count / 3) : null, queryMs: q ? Math.round(q.ms / 3) : null, byCollection: q?.byCollection }
}
for (const [name, p] of Object.entries({ md: '/md/pl', sitemap: '/sitemap.xml', llms: '/llms.txt', llmsFull: '/llms-full.txt' })) {
profileRead()
const { ms } = await timed(`${base}${p}`)
const q = profileRead()
result.server.render[name] = { medianMs: Math.round(ms), queries: q?.count ?? null, queryMs: q?.ms ?? null, byCollection: q?.byCollection }
}
profileOff()
const browser = await launch()
for (const profile of ['mobile', 'desktop']) {
result.client[profile] = {}
for (const [name, p] of Object.entries(PAGES)) {
result.client[profile][name] = await measureMedian(browser, `${base}${p}`, profile, runs)
const r = result.client[profile][name]
console.log(`[perf] ${profile.padEnd(7)} ${name.padEnd(9)} LCP ${r.lcp} CLS ${r.cls} TBT ${r.tbt} INP ${r.inp} JS ${r.bytes.js} CSS ${r.bytes.css} req ${r.requests}`)
}
}
result.client.admin = await measureMedian(browser, `${base}/admin/login`, 'desktop', runs, { interact: false })
await browser.close()
if (server) {result.server.rssMiB = rssOf(server.pid)}
} finally {
profileOff()
if (server) {
try { process.kill(-server.pid, 'SIGTERM') } catch {} // the whole process group: pnpm and next start
}
}
writeFileSync(out, `${JSON.stringify(result, null, 2)}\n`)
console.log(`[perf] written ${path.relative(root, out)}`)
console.log(JSON.stringify(result.server, null, 1))
process.exit(0)
+2
View File
@@ -68,6 +68,8 @@ export const DESCRIPTIONS = {
'e2e/late-staff.spec.ts': 'the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin\'s rule',
'e2e/global-setup.ts': 'Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order',
'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page',
'e2e/performance.spec.ts': 'the performance budgets (run by `pnpm e2e:built` in both bundlers): every page type on a throttled phone and a desktop — LCP, CLS, TBT, the response to a tap, JS / CSS / font bytes, requests, render-blocking, third parties before consent — and the MongoDB queries of one render (docs/performance.md)',
'e2e/perf-lab.mjs': 'the lab measurement of one page (Lighthouse\'s phone and desktop profiles, Web Vitals observers, bytes per type) — used by the performance spec and `pnpm perf:measure`; the iapl-performance skill ships the same file',
'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA',
'e2e/mail-relay-fixture.ts': 'test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service\'s client at the stand-in the spec starts; never in a real site (a real site names no address)',
'e2e/mail-relay-setup.ts': 'for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only)',