113 lines
6.5 KiB
TypeScript
113 lines
6.5 KiB
TypeScript
import type { Browser } from '@playwright/test'
|
||
|
||
import { overBudget, perfBudgets, SERVER_BUDGET } from '@intecion/ipal-kit/doctor'
|
||
import { chromium, expect, test } from '@playwright/test'
|
||
import { readFileSync } from 'node:fs'
|
||
import { createRequire } from 'node:module'
|
||
import path from 'node:path'
|
||
|
||
// a plain ES module (JSDoc types), shared with scripts/perf-measure.mjs
|
||
import { measureMedian } from './perf-lab.mjs'
|
||
|
||
/**
|
||
* Performance budgets — a BINDING gate (docs/performance.md): every page type, a phone on Slow 4G with a 4× slower CPU
|
||
* and a desktop, first visit. The numbers are this site's own, measured on 2026-12-01 (docs/dev/perf/*-after.json)
|
||
* with headroom for lab noise: a change that makes a page heavier or slower fails here, in `pnpm e2e:built`, with both
|
||
* bundlers. Loosen a number only with a reason in the comment next to it.
|
||
* PERF_RUNS (default 1) runs per page; the gate takes the median. Third-party requests are recorded (none may come
|
||
* before consent) and aborted, so an external host's speed cannot fail or hang the gate.
|
||
*/
|
||
const runs = Number(process.env.PERF_RUNS ?? 1)
|
||
|
||
const budgets = perfBudgets({
|
||
// measured 1.18.0: JS 184–188 kB, CSS 11–12 kB, fonts 209.5 kB (Inter + Fraunces, latin + latin-ext — four
|
||
// preloaded files: see "fonts" in docs/performance.md), LCP 0.8 s on the phone, 0.3 s on the desktop
|
||
desktop: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 200_000, lcp: 800, renderBlocking: 1, requests: 36, tbt: 50 },
|
||
mobile: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 200_000, lcp: 1500, renderBlocking: 1, requests: 30, tbt: 100 },
|
||
})
|
||
|
||
/** One of each template (AGENTS.md → Site map), with what differs for that page. */
|
||
type Budget = Partial<typeof budgets.mobile>
|
||
const PAGES: Array<{ budget?: { desktop?: Budget; mobile?: Budget }; name: string; path: string; why?: string }> = [
|
||
{ name: 'home', path: '/pl' },
|
||
{ name: 'page', path: '/pl/o-nas' },
|
||
{ name: 'archive', path: '/pl/blog' },
|
||
{ name: 'post', path: '/pl/blog/zanim-kupisz-dzialke' },
|
||
{ name: 'case study', path: '/pl/realizacje/dom-pod-lasem' },
|
||
{ name: 'form', path: '/pl/wycena' },
|
||
// every block × variant on one page, the contact form's Turnstile included (a necessary service, before consent)
|
||
{ budget: { desktop: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] }, mobile: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] } }, name: 'showcase', path: '/pl/bloki' },
|
||
// The 404 content loads after hydration (createNotFoundPage `load`, so it is not in every page's payload): it
|
||
// arrives late and moves the footer — measured CLS 0.32 and LCP 2.5 s on the phone. An owner decision in
|
||
// docs/performance.md; until then the gate holds it where it is (no worse).
|
||
{ budget: { mobile: { cls: 0.35, lcp: 3000 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'lazy 404 (owner decision pending)' },
|
||
]
|
||
|
||
let browser: Browser
|
||
test.beforeAll(async () => {
|
||
browser = await chromium.launch()
|
||
})
|
||
test.afterAll(async () => {
|
||
await browser?.close()
|
||
})
|
||
|
||
test.describe('performance budgets', () => {
|
||
test.describe.configure({ timeout: 180_000 })
|
||
for (const page of PAGES) {
|
||
for (const profile of ['mobile', 'desktop'] as const) {
|
||
test(`${page.name} (${profile}) stays within its budget`, async ({ baseURL }) => {
|
||
const budget = { ...budgets[profile], ...page.budget?.[profile] }
|
||
const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs, { blockThirdParty: true })
|
||
test.info().annotations.push({ description: JSON.stringify({ bytes: measured.bytes, cls: measured.cls, inp: measured.inp, lcp: measured.lcp, requests: measured.requests, tbt: measured.tbt }), type: 'measured' })
|
||
expect(overBudget(measured, budget), `${page.path} ${profile}${page.why ? ` (${page.why})` : ''}`).toEqual([])
|
||
// the LCP image is never lazy (web.dev/articles/lcp-lazy-loading)
|
||
if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, `${page.path}: the LCP image is lazy`).not.toBe('lazy')}
|
||
})
|
||
}
|
||
}
|
||
})
|
||
|
||
/**
|
||
* Database queries for ONE render of a page outside the ISR cache (Next's own on-demand revalidation header), counted
|
||
* by MongoDB's profiler. Measured 1.18.0: 19–27 per page (1.17.2: 30–43); each budget is that plus ~15 %. Skipped when the profiler cannot be
|
||
* switched on (not MongoDB, or a user without the right).
|
||
*/
|
||
test.describe('queries per render', () => {
|
||
const QUERY_BUDGET: Record<string, number> = { '/pl': 28, '/pl/bloki': 31, '/pl/blog/zanim-kupisz-dzialke': 30, '/pl/o-nas': 25, '/pl/wycena': 22 }
|
||
test('every page type stays within its query budget', async ({ baseURL }) => {
|
||
test.setTimeout(120_000)
|
||
const uri = process.env.DATABASE_URI
|
||
test.skip(!uri?.startsWith('mongodb'), 'not MongoDB')
|
||
const site = process.cwd() // Playwright runs in reference/
|
||
const requireFromAdapter = createRequire(createRequire(path.join(site, 'package.json')).resolve('@payloadcms/db-mongodb'))
|
||
const mongoose = requireFromAdapter('mongoose') as typeof import('mongoose')
|
||
const conn = await mongoose.createConnection(uri!).asPromise()
|
||
const db = conn.db!
|
||
try {
|
||
try {
|
||
await db.command({ profile: 0 })
|
||
} catch {
|
||
test.skip(true, 'the database user may not use the profiler')
|
||
}
|
||
const previewModeId = JSON.parse(readFileSync(path.join(site, '.next', 'prerender-manifest.json'), 'utf8')).preview?.previewModeId as string
|
||
const counts: Record<string, number> = {}
|
||
for (const [p, limit] of Object.entries(QUERY_BUDGET)) {
|
||
await fetch(`${baseURL}${p}`, { headers: { 'x-prerender-revalidate': previewModeId } }) // warm: the first render compiles
|
||
await db.command({ profile: 0 })
|
||
await db.collection('system.profile').drop().catch(() => {})
|
||
await db.command({ profile: 2 })
|
||
const res = await fetch(`${baseURL}${p}`, { headers: { 'x-prerender-revalidate': previewModeId } })
|
||
expect(res.status).toBe(200)
|
||
await db.command({ profile: 0 })
|
||
counts[p] = await db.collection('system.profile').countDocuments({ ns: { $not: /system\.profile$/ }, op: 'query' })
|
||
expect(counts[p], `${p}: no query counted — the profiler did not record this database`).toBeGreaterThan(0)
|
||
expect(counts[p], `${p}: ${counts[p]} queries (budget ${limit}, plugin default ${SERVER_BUDGET.queriesPerRender})`).toBeLessThanOrEqual(limit)
|
||
}
|
||
test.info().annotations.push({ description: JSON.stringify(counts), type: 'queries' })
|
||
} finally {
|
||
await db.command({ profile: 0 }).catch(() => {})
|
||
await conn.close()
|
||
}
|
||
})
|
||
})
|