Budgets and checks: PERF_BUDGETS / perfBudgets / overBudget, the reference gate (both bundlers), the doctor's performance group (static, live, deep)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 13:51:43 +01:00
co-authored by Claude Opus 5.5
parent 21073d98d0
commit 801b897ea0
10 changed files with 674 additions and 6 deletions
+221
View File
@@ -0,0 +1,221 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createServer, type Server } from 'node:http'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { gzipSync } from 'node:zlib'
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest'
import { runDoctor } from '../src/modules/doctor/run.js'
import { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets } from '../src/modules/performance/budgets.js'
const packageRoot = path.resolve(import.meta.dirname, '..')
const read = (rel: string) => readFileSync(path.join(packageRoot, rel), 'utf8')
let dirs: string[] = []
afterEach(() => {
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
dirs = []
})
function project(files: Record<string, string>): string {
const root = mkdtempSync(path.join(tmpdir(), 'iapl-perf-'))
dirs.push(root)
const all: Record<string, string> = {
'node_modules/@intecion/ipal-kit/package.json': JSON.stringify({ name: '@intecion/ipal-kit', version: '1.18.0' }),
'package.json': JSON.stringify({ name: 'examplepl-web', dependencies: { '@intecion/ipal-kit': '^1.18.0', next: '16.4.6' } }),
...files,
}
for (const [rel, content] of Object.entries(all)) {
mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
writeFileSync(path.join(root, rel), content)
}
return root
}
const doctor = (root: string, only: string[], extra: { deepStatus?: object; url?: string } = {}) =>
runDoctor({ offline: true, only, packageRoot, root, today: '2026-12-01', writeSeen: false, ...extra })
/** Each line starts with the expected text, in order. */
const startWith = (lines: string[], expected: string[]) => {
expect(lines).toHaveLength(expected.length)
expected.forEach((text, i) => expect(lines[i].startsWith(text), `${lines[i]}\n should start with: ${text}`).toBe(true))
}
const found = async (root: string, only: string[], extra = {}) => (await doctor(root, only, extra)).findings.map((f) => `${f.rule}: ${f.message}`)
describe('doctor: performance group (static)', () => {
test('a clean site has no findings', async () => {
const root = project({
'e2e/performance.spec.ts': 'perfBudgets({})',
'next.config.ts': 'images: buildImagesConfig()',
'src/app/(frontend)/[locale]/layout.tsx': "import { Inter } from 'next/font/google'\nconst body = Inter({ display: 'swap' })\n<script type=\"application/ld+json\" />",
'src/app/(frontend)/styles.css': '@import "@intecion/ipal-kit/tokens.css";\n.card { transition: transform 150ms, opacity 150ms }',
})
expect(await found(root, ['performance'])).toEqual([])
})
test('images config, fonts, render-blocking, embeds, animations and a missing budget test are reported', async () => {
const root = project({
'next.config.ts': 'export default { images: { remotePatterns: [] } }',
'src/app/(frontend)/[locale]/layout.tsx': [
"import { Fraunces, Inter, Lora } from 'next/font/google'",
"const a = Inter({ display: 'block' })",
'<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter" />',
'<script src="https://widget.example/chat.js"></script>',
'<script async src="https://ok.example/a.js"></script>',
].join('\n'),
'src/app/(frontend)/styles.css': '@import url("https://cdn.example/x.css");\n@font-face { font-family: X; src: url(x.woff2) }\n.menu { transition: height 200ms }\n@keyframes spin { to { transform: rotate(1turn) } }',
'src/components/Map.tsx': '<iframe src="https://www.google.com/maps/embed?pb=1" />\n<iframe loading="lazy" src="https://maps.example" />\n<iframe src="https://youtube.com/embed/x" />',
'src/components/Sticky.tsx': "window.addEventListener('scroll', onScroll)\n<div className=\"transition-all\" />",
})
const out = await found(root, ['performance'])
const by = (rule: string) => out.filter((l) => l.startsWith(`${rule}:`))
expect(by('perf-images-config')).toHaveLength(1)
startWith(by('perf-fonts'), [
'perf-fonts: a font is loaded from a third-party host',
'perf-fonts: font-display: block hides the text until',
'perf-fonts: @font-face without font-display',
'perf-fonts: 3 font families on the site (Fraunces, Inter, Lora)',
])
// the sync <script src>, the Google Fonts stylesheet <link> (also a font finding) and the remote @import
expect(by('perf-render-blocking')).toHaveLength(3)
expect(by('perf-embeds')).toHaveLength(1) // the map; the lazy one is fine, YouTube is iapl-audit's
startWith(by('perf-animations'), [
'perf-animations: a transition of a layout property',
'perf-animations: transition-all or a transition',
'perf-animations: a scroll listener runs on every scroll event',
'perf-animations: the site animates (@keyframes',
])
expect(by('perf-budgets')).toHaveLength(1)
// every finding is a warning (info for the budget test) in 1.18.0: reported, never failing CI
const report = await doctor(root, ['performance'])
expect(new Set(report.findings.map((f) => f.severity))).toEqual(new Set(['info', 'warning']))
})
test('a remote stylesheet <link> is reported as render-blocking', async () => {
const root = project({ 'e2e/perf.spec.ts': '', 'next.config.ts': 'buildImagesConfig()', 'src/app/layout.tsx': '<link href="https://cdn.example/a.css" rel="stylesheet" />' })
expect(await found(root, ['perf-render-blocking'])).toEqual(['perf-render-blocking: a stylesheet from another host blocks the first paint on an extra connection'])
})
})
describe('doctor: performance group (deep and live)', () => {
test('perf-images: stored images over the limits', async () => {
const root = project({})
expect(await found(root, ['perf-images'], { deepStatus: { media: { images: 40, oversized: 3, tooWide: 1 } } })).toEqual([
`perf-images: of 40 images, 3 are over ${(IMAGE_RULES.maxBytes / 1048576).toFixed(1)} MB and 1 wider than 2560 px`,
])
expect(await found(root, ['perf-images'], { deepStatus: { media: { images: 40, oversized: 0, tooWide: 0 } } })).toEqual([])
})
let server: Server
let url = ''
let html = ''
let compress = true
beforeAll(async () => {
server = createServer((_req, res) => {
if (compress) {res.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'text/html' }).end(gzipSync(html))}
else {res.writeHead(200, { 'content-type': 'text/html' }).end(html)}
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
url = `http://127.0.0.1:${(server.address() as { port: number }).port}`
})
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))
test('perf-live: compression, blocking scripts, font preloads, a lazy first image, HTML size', async () => {
const root = project({})
html = '<html><head><script src="/_next/a.js" async=""></script><script src="/_next/p.js" noModule=""></script></head><body><main><img loading="eager" fetchpriority="high" src="/h.webp"></main></body></html>'
expect(await found(root, ['perf-live'], { url })).toEqual([])
compress = false
const fonts = '<link rel="preload" href="/f.woff2" as="font" crossorigin="">'.repeat(5)
html = `<html><head>${fonts}<script src="/legacy.js"></script></head><body><main><img loading="lazy" src="/h.webp"></main>${'x'.repeat(160 * 1024)}</body></html>`
const out = await found(root, ['perf-live'], { url })
compress = true
startWith(out, [
'perf-live: the HTML came back uncompressed',
'perf-live: render-blocking scripts in <head>: /legacy.js',
'perf-live: 5 font files preloaded',
'perf-live: the first image of the page is lazy-loaded',
'perf-live: the home page HTML is 160 KB (budget 150 KB)',
])
})
})
describe('Site integrations: one read for callers that start together', () => {
test('two reads in flight share one query; the next read queries again', async () => {
const { getSiteIntegrations } = await import('../src/modules/payload/getSiteIntegrations.js')
let calls = 0
const payload = { findGlobal: async () => { calls++; await new Promise((r) => setTimeout(r, 5)); return { gtmContainerId: 'GTM-X' } } } as never
const [a, b] = await Promise.all([getSiteIntegrations(payload), getSiteIntegrations(payload)])
expect(a).toEqual({ gtmContainerId: 'GTM-X' })
expect(b).toBe(a)
expect(calls).toBe(1)
await getSiteIntegrations(payload)
expect(calls).toBe(2) // nothing kept after the read: a save in the panel is seen by the next request
await getSiteIntegrations(payload, { depth: 0 })
expect(calls).toBe(3) // reads with options are never shared
})
})
describe('budgets', () => {
const measured = { bytes: { css: 11_000, font: 209_000, js: 188_000 }, cls: 0.03, inp: 40, lcp: 800, renderBlocking: ['/a.css'], requests: 26, tbt: 20, thirdParty: [] as string[] }
test('the defaults are Core Web Vitals "good"; a site within them passes', () => {
expect(PERF_BUDGETS.mobile).toMatchObject({ cls: 0.1, inp: 200, lcp: 2500 })
expect(overBudget(measured, PERF_BUDGETS.mobile)).toEqual([])
})
test('a project tightens or loosens any number; every broken budget is named', () => {
const tight = perfBudgets({ mobile: { jsBytes: 150_000, lcp: 700, thirdParty: ['https://challenges.cloudflare.com'] } }).mobile
expect(tight.cls).toBe(0.1)
expect(overBudget({ ...measured, renderBlocking: ['/a.css', '/b.js', '/c.js'], thirdParty: ['https://challenges.cloudflare.com', 'https://www.googletagmanager.com'] }, tight)).toEqual([
'LCP 800 ms > 700 ms',
'JS 188000 B > 150000 B',
'render-blocking 3 > 2: /a.css, /b.js, /c.js',
'third-party requests before consent: https://www.googletagmanager.com',
])
// the defaults are not changed by an override
expect(PERF_BUDGETS.mobile.jsBytes).toBe(250_000)
})
})
describe('what 1.18.0 changed for speed (source checks; measured in docs/performance.md)', () => {
test('the /client barrels carry no "use client": a page ships only the components it uses', () => {
for (const file of ['src/exports/client.ts', ...['accessibility', 'analytics', 'consent', 'lightbox', 'stats', 'turnstile'].map((m) => `src/modules/${m}/client.ts`)]) {
expect(read(file), file).not.toMatch(/^\s*['"]use client['"]/m)
}
})
test('the lightbox viewer is loaded on first open, not with the page', () => {
const provider = read('src/modules/lightbox/LightboxProvider.tsx')
expect(provider).toMatch(/lazy\(\(\) => import\('\.\/LightboxDialog\.js'\)/)
expect(provider).not.toMatch(/^import \{ LightboxDialog \}/m)
})
test('route and metadata reads are cached per request by value, not by array identity', () => {
const helpers = read('src/modules/frontend/createContentHelpers.ts')
expect(helpers).toMatch(/resolveRouteCached\(locale, JSON\.stringify\(segments \?\? \[\]\), page\)/)
expect(helpers).toMatch(/pageMetadataCached = cache\(/)
})
test('reads that need one field select it', () => {
expect(read('src/modules/seo/slugsAcrossLocales.ts')).toMatch(/select: \{ slug: true \}/)
expect(read('src/modules/seo/readSiteMetaConfig.ts')).toMatch(/select: \{ slug: true \}/)
expect(read('src/modules/consent/getConsentTexts.ts')).toMatch(/select: \{ privacyPolicy: true \}/)
})
test('reduced motion: the banner and the cookie button stop their transitions', () => {
expect(read('src/modules/consent/CookieBanner.tsx').match(/motion-reduce:transition-none/g)).toHaveLength(3)
expect(read('src/modules/consent/CookieButton.tsx')).toContain('motion-reduce:transition-none')
})
test('the perf-lab helper the skill hands out is the one the reference gate runs', () => {
expect(read('docs/agent/skills/iapl-performance/resources/perf-lab.mjs')).toBe(read('reference/e2e/perf-lab.mjs'))
})
})
describe('deep status: images over the limits (counts only)', () => {
test('counted per upload collection with the plugin\'s limits; a collection without the upload fields is skipped', async () => {
const { countHeavyMedia } = await import('../src/modules/doctor/status.js')
const calls: unknown[] = []
const payload = {
count: async ({ collection, where }: { collection: string; where: { and?: Array<Record<string, unknown>> } }) => {
calls.push(where)
if (collection === 'broken') {throw new Error('no width field')}
const filter = JSON.stringify(where)
return { totalDocs: filter.includes('filesize') ? 2 : filter.includes('width') ? 1 : 30 }
},
}
expect(await countHeavyMedia(payload as never, [{ slug: 'pages' }, { slug: 'media', upload: true }, { slug: 'broken', upload: {} }])).toEqual({ images: 30, oversized: 2, tooWide: 1 })
expect(JSON.stringify(calls)).toContain(`"greater_than":${IMAGE_RULES.maxBytes}`)
expect(await countHeavyMedia(payload as never, [{ slug: 'pages' }])).toBeNull()
})
})