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:
+2
-1
@@ -554,9 +554,10 @@ describe('security and deep status', () => {
|
||||
}
|
||||
const status = await collectDoctorStatus(payload as never)
|
||||
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'twoFactorConfirm', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(Object.keys(status).sort()).toEqual(['growth', 'mail', 'media', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'twoFactorConfirm', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
expect(status.media).toBeNull() // no upload collection in this config
|
||||
})
|
||||
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
|
||||
const payload = {
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { collectGrowth } from '../src/modules/doctor/growth.js'
|
||||
import { folderBytes, GROWTH_DEFAULTS } from '../src/modules/doctor/rules/growth.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
import { resetNonceSweep, sweepExpiredNonces } from '../src/modules/email/relay/store.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { retentionMap, retentionOf, withRetention } from '../src/modules/shared/retention.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const packageRoot = path.resolve(import.meta.dirname, '..')
|
||||
let dirs: string[] = []
|
||||
afterEach(() => {
|
||||
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
|
||||
dirs = []
|
||||
})
|
||||
const project = (files: Record<string, string> = {}) => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'iapl-growth-'))
|
||||
dirs.push(root)
|
||||
for (const [rel, content] of Object.entries({ 'package.json': '{"name":"x-web"}', ...files })) {
|
||||
mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
|
||||
writeFileSync(path.join(root, rel), content)
|
||||
}
|
||||
return root
|
||||
}
|
||||
const growth = (over: object = {}) => ({ collections: [], kv: null, media: null, retention: {}, versions: [], ...over })
|
||||
const found = async (root: string, deep: null | object, config: object = {}) =>
|
||||
(await runDoctor({ config, deepStatus: deep ? ({ growth: deep } as never) : null, offline: true, only: ['growth'], packageRoot, root, today: '2026-12-01', writeSeen: false })).findings.map((f) => `${f.rule} ${f.severity}: ${f.message}`)
|
||||
|
||||
describe('doctor: growth rules', () => {
|
||||
test('nothing to say about a small, purged site', async () => {
|
||||
const deep = growth({
|
||||
collections: [{ slug: 'consent-records', bytes: 4096, docs: 20, oldest: '2026-11-30T10:00:00Z' }],
|
||||
kv: { expired: 0, total: 3 },
|
||||
media: { capped: false, checked: 30, orphaned: 0, total: 17 },
|
||||
retention: { 'consent-records': 1095 },
|
||||
versions: [{ slug: 'pages', docs: 15, kind: 'collection', max: 100, total: 300 }],
|
||||
})
|
||||
expect(await found(project(), deep)).toEqual([])
|
||||
})
|
||||
|
||||
test('size, unlimited versions, a purge that does not run, old submissions, expired KV, orphaned media', async () => {
|
||||
const deep = growth({
|
||||
collections: [
|
||||
{ slug: 'consent-records', bytes: 900 * 1024 * 1024, docs: 250_000, oldest: '2021-01-01T00:00:00Z' },
|
||||
{ slug: 'form-submissions', bytes: null, docs: 40, oldest: '2023-06-01T00:00:00Z' },
|
||||
],
|
||||
kv: { expired: 1500, total: 1600 },
|
||||
media: { capped: true, checked: 5000, orphaned: 30, total: 400 },
|
||||
retention: { 'consent-records': 1095 },
|
||||
versions: [{ slug: 'site-settings', docs: 1, kind: 'global', max: 0, total: 812 }, { slug: 'pages', docs: 900, kind: 'collection', max: 100, total: 60_000 }],
|
||||
})
|
||||
expect(await found(project(), deep)).toEqual([
|
||||
'growth-size warning: consent-records: 250000 documents, 900 MB with indexes, the oldest from 2021-01-01',
|
||||
'growth-versions warning: global site-settings keeps every version without a limit (812 now)',
|
||||
'growth-versions warning: collection pages: 60000 versions for 900 document(s)',
|
||||
'growth-retention warning: consent-records keeps records for 1095 days, but the oldest is 2160 days old',
|
||||
'growth-submissions warning: 40 form submissions kept without a retention, the oldest 1279 days old',
|
||||
'growth-kv warning: payload-kv holds 1600 entries, 1500 of them expired',
|
||||
'growth-media warning: 30 of 400 media files are not used by any document or global (from the first 5000 documents: may be fewer)',
|
||||
])
|
||||
})
|
||||
|
||||
test('thresholds from iapl-doctor.json; non-numbers keep the default; a retention silences the submissions rule', async () => {
|
||||
const deep = growth({ collections: [{ slug: 'form-submissions', bytes: null, docs: 40, oldest: '2023-06-01T00:00:00Z' }], media: { capped: false, checked: 9, orphaned: 3, total: 9 } })
|
||||
expect(await found(project(), deep, { growth: { orphanedMedia: 2, submissionDays: 'x' } })).toEqual([
|
||||
'growth-submissions warning: 40 form submissions kept without a retention, the oldest 1279 days old',
|
||||
'growth-media warning: 3 of 9 media files are not used by any document or global',
|
||||
])
|
||||
// with a retention the submissions rule is quiet — and the retention rule says the purge has not caught up yet
|
||||
expect(await found(project(), { ...deep, retention: { 'form-submissions': 365 } }, { growth: { submissionDays: 1000 } })).toEqual([
|
||||
'growth-retention warning: form-submissions keeps records for 365 days, but the oldest is 1279 days old',
|
||||
'growth-media info: 3 of 9 media files are not used by any document or global',
|
||||
])
|
||||
expect(GROWTH_DEFAULTS.maxDocs).toBe(200_000)
|
||||
})
|
||||
|
||||
test('growth-disk measures the image cache and the local upload folder on this machine', async () => {
|
||||
const root = project({ '.next/cache/images/a/b.webp': 'x'.repeat(3 * 1024 * 1024), 'media/a.jpg': 'y'.repeat(2048) })
|
||||
expect(folderBytes(path.join(root, '.next', 'cache', 'images'))).toBe(3 * 1024 * 1024)
|
||||
expect(await found(root, null, { growth: { imageCacheMB: 2, uploadsMB: 1 } })).toEqual([
|
||||
'growth-disk info: the image cache is 3 MB (no size cap in Next; each image × width × format)',
|
||||
])
|
||||
expect(folderBytes(path.join(root, 'missing'))).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deep collector', () => {
|
||||
test('counts, oldest, versions, expired KV entries and media nobody points at — values never leave it', async () => {
|
||||
const kv = new Map<string, unknown>([
|
||||
['iapl:2fa-verify:users:1', { count: 0, resetAt: Date.now() + 60_000 }],
|
||||
['iapl:mail-relay:nonce:a', { expiresAt: Date.now() - 1000 }],
|
||||
['other', 'plain'],
|
||||
])
|
||||
const docs: Record<string, object[]> = {
|
||||
media: [{ id: 'm1' }, { id: 'm2' }, { id: 'm3' }],
|
||||
pages: [{ id: 'p1', layout: [{ blockType: 'hero', media: 'm1' }], richText: { root: { children: [{ type: 'upload', value: 'm2' }] } } }],
|
||||
}
|
||||
const payload = {
|
||||
config: {
|
||||
collections: [{ slug: 'pages', versions: { maxPerDoc: 0 } }, { slug: 'media', upload: true }],
|
||||
custom: {},
|
||||
globals: [{ slug: 'site-settings', versions: { max: 20 } }],
|
||||
},
|
||||
count: async ({ collection }: { collection: string }) => ({ totalDocs: docs[collection]?.length ?? 0 }),
|
||||
countGlobalVersions: async () => ({ totalDocs: 7 }),
|
||||
countVersions: async () => ({ totalDocs: 42 }),
|
||||
db: { name: 'drizzle' },
|
||||
find: async ({ collection, select }: { collection: string; select?: object }) => ({ docs: select && 'createdAt' in select ? [{ createdAt: '2026-01-01T00:00:00Z' }] : (docs[collection] ?? []) }),
|
||||
findGlobal: async () => ({ logo: 'm3' }),
|
||||
kv: { get: async (k: string) => kv.get(k) ?? null, keys: async () => [...kv.keys()] },
|
||||
}
|
||||
const g = await collectGrowth(payload as never)
|
||||
expect(g.collections).toEqual([
|
||||
{ slug: 'pages', bytes: null, docs: 1, oldest: '2026-01-01T00:00:00Z' },
|
||||
{ slug: 'media', bytes: null, docs: 3, oldest: '2026-01-01T00:00:00Z' },
|
||||
])
|
||||
expect(g.versions).toEqual([
|
||||
{ slug: 'pages', docs: 1, kind: 'collection', max: 0, total: 42 },
|
||||
{ slug: 'site-settings', docs: 1, kind: 'global', max: 20, total: 7 },
|
||||
])
|
||||
expect(g.kv).toEqual({ expired: 1, total: 3 })
|
||||
expect(g.media).toEqual({ capped: false, checked: 1, orphaned: 0, total: 3 })
|
||||
expect(JSON.stringify(g)).not.toContain('hero')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mail service: expired nonces are swept', () => {
|
||||
test('only nonces past their expiry, at most once a day; the 2FA counters and live nonces stay', async () => {
|
||||
resetNonceSweep()
|
||||
const now = Date.now()
|
||||
const store = new Map<string, unknown>([
|
||||
['iapl:2fa-verify:users:1', { count: 3, resetAt: now - 1 }],
|
||||
['iapl:mail-relay:nonce:live', { expiresAt: now + 60_000 }],
|
||||
['iapl:mail-relay:nonce:old', { expiresAt: now - 1 }],
|
||||
])
|
||||
const kv = { delete: async (k: string) => void store.delete(k), get: async (k: string) => store.get(k) ?? null, keys: async () => [...store.keys()], set: async (k: string, v: unknown) => void store.set(k, v) }
|
||||
const payload = { config: {}, kv } as never
|
||||
expect(await sweepExpiredNonces(payload, now)).toBe(1)
|
||||
expect([...store.keys()].sort()).toEqual(['iapl:2fa-verify:users:1', 'iapl:mail-relay:nonce:live'])
|
||||
store.set('iapl:mail-relay:nonce:old2', { expiresAt: now - 1 })
|
||||
expect(await sweepExpiredNonces(payload, now + 1000)).toBe(0) // not again the same day
|
||||
expect(await sweepExpiredNonces(payload, now + 86_400_001)).toBe(2) // a day on: old2 and the one that was live
|
||||
})
|
||||
})
|
||||
|
||||
describe('retention', () => {
|
||||
test('recorded per collection in the config; invalid values ignored', () => {
|
||||
const config = withRetention(withRetention({ custom: { iapl: { mail: {} } } } as never, 'consent-records', 1095), 'form-submissions', 0)
|
||||
expect(retentionMap({ config } as never)).toEqual({ 'consent-records': 1095 })
|
||||
expect((config.custom as { iapl: { mail: object } }).iapl.mail).toEqual({}) // the rest kept
|
||||
expect(retentionOf({ config } as never, 'form-submissions')).toBeUndefined()
|
||||
})
|
||||
|
||||
test('forms.submissionRetentionDays: old submissions deleted after a new one (once a day); without it nothing is deleted', async () => {
|
||||
const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'company', blockType: 'text' }] } } })
|
||||
const deleteMany = vi.fn(async () => {})
|
||||
Object.assign(payload, { config: {}, db: { deleteMany } })
|
||||
await submitForm({ data: { company: 'Acme' }, formId: 'f', maxPerMinute: 0, payload })
|
||||
expect(deleteMany).not.toHaveBeenCalled()
|
||||
Object.assign(payload, { config: withRetention({} as never, 'form-submissions', 365) })
|
||||
await submitForm({ data: { company: 'Acme' }, formId: 'f', maxPerMinute: 0, payload })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(deleteMany).toHaveBeenCalledWith(expect.objectContaining({ collection: 'form-submissions', where: { createdAt: { less_than: expect.any(String) } } }))
|
||||
})
|
||||
})
|
||||
@@ -304,10 +304,11 @@ describe('commands and skills', () => {
|
||||
expect(pkg.bin['ipal-kit']).toBe('bin/iapl.mjs')
|
||||
})
|
||||
|
||||
test('the package ships the 16 skills as iapl-*, and none under the old names', () => {
|
||||
test('the package ships the 16 skills as iapl-* (plus those new since, never with an old name), and none under the old names', () => {
|
||||
const shipped = readdirSync(path.join(packageRoot, 'docs/agent/skills'))
|
||||
const since117 = ['iapl-performance'] // 1.18.0
|
||||
expect(shipped.filter((n) => n.startsWith('ipal-'))).toEqual([])
|
||||
expect(shipped.filter((n) => n.startsWith('iapl-')).sort()).toEqual(LEGACY_SKILL_NAMES.map((n) => n.replace('ipal-', 'iapl-')).sort())
|
||||
expect(shipped.filter((n) => n.startsWith('iapl-')).sort()).toEqual([...LEGACY_SKILL_NAMES.map((n) => n.replace('ipal-', 'iapl-')), ...since117].sort())
|
||||
})
|
||||
|
||||
test('the installer and the doctor remove the same fixed list of old names', () => {
|
||||
@@ -331,7 +332,7 @@ describe('commands and skills', () => {
|
||||
const first = run('iapl-skills.mjs')
|
||||
expect(first.status, first.stderr).toBe(0)
|
||||
const skills = readdirSync(path.join(dir, '.agents/skills')).sort()
|
||||
expect(skills.filter((n) => n.startsWith('iapl-'))).toHaveLength(16)
|
||||
expect(skills.filter((n) => n.startsWith('iapl-'))).toHaveLength(17) // the 16 renamed + iapl-performance (1.18.0)
|
||||
expect(skills.filter((n) => n.startsWith('ipal-'))).toEqual(['ipal-custom'])
|
||||
expect(readFileSync(path.join(dir, '.agents/skills/ipal-custom/SKILL.md'), 'utf8')).toBe(own)
|
||||
expect(skills).toContain('our-skill')
|
||||
|
||||
@@ -107,6 +107,19 @@ describe('lightbox helpers', () => {
|
||||
})
|
||||
|
||||
describe('lightbox behaviour', () => {
|
||||
test('the viewer is loaded on the first open (a separate chunk since 1.18.0), then opens at once', async () => {
|
||||
render(gallery())
|
||||
click(triggers()[0])
|
||||
expect(dialog()).toBeNull() // the first open waits for the viewer's code
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
})
|
||||
expect(dialog()).not.toBeNull()
|
||||
click(dialog()!.querySelector('[data-ipal="lightbox-close"]'))
|
||||
click(triggers()[1])
|
||||
expect(dialog()).not.toBeNull() // loaded: every later open is immediate
|
||||
})
|
||||
|
||||
test('nothing in the DOM until opened; triggers are labelled buttons', () => {
|
||||
render(gallery())
|
||||
expect(dialog()).toBeNull()
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
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: [] } }',
|
||||
'playwright.config.ts': 'export default {}',
|
||||
'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'])
|
||||
})
|
||||
})
|
||||
|
||||
test('perf-budgets: only for a project that already runs Playwright', async () => {
|
||||
const files = { 'next.config.ts': 'buildImagesConfig()' }
|
||||
expect(await found(project(files), ['perf-budgets'])).toEqual([])
|
||||
expect(await found(project({ ...files, 'playwright.config.ts': '' }), ['perf-budgets'])).toHaveLength(1)
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user