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
+1
View File
@@ -50,6 +50,7 @@ API details — one file per module:
| Rich text, table of contents | [richtext.md](./richtext.md) |
| Headers, CSP, 2FA | [security.md](./security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
| Speed: what the plugin does, what the project does, budgets, measuring, the doctor's performance group | [performance.md](./performance.md) |
| Stats in the admin panel (no cookies; visitor history with consent) | [stats.md](./stats.md) |
| Auto-slug | [slug.md](./slug.md) |
| Light / dark theme, switcher | [theme.md](./theme.md) |
+22 -10
View File
@@ -1041,22 +1041,30 @@ Example `styles.css`: [section-code.md](./skills/iapl-block/resources/section-co
125 % and 150 % zoom at 1366 (common on Windows). No horizontal scroll, no clipped text,
the menu works, the hero CTA is visible.
### 6.11b Speed (Core Web Vitals)
### 6.11b Speed (Core Web Vitals) — the handbook is [performance.md](../performance.md), the skill `iapl-performance`
| What | How | Forbidden |
|---|---|---|
| LCP image (the first visible one, usually the hero) | `<Media priority>` — exactly one per page | `priority` on many images, the hero as a CSS `background-image` |
| every other image | `<Media sizes={MEDIA_SIZES.third}>` — `sizes` = the width on screen | no `sizes` (downloads the full width), `<img>` |
| LCP image (the first visible one, usually the hero) | `<Media priority>` — exactly one per page (preload + `fetchpriority="high"`) | `priority` on many images, the hero as a CSS `background-image`, a lazy hero |
| above the fold, not the LCP (header logo) | `<Media eager>` — loads at once, no high priority, no preload | `priority` on the logo (it competes with the hero) |
| every other image | `<Media sizes={MEDIA_SIZES.third}>` — `sizes` = the width on screen; lazy by default | no `sizes` (downloads the full width), `<img>` |
| placeholder | `buildMediaPlaceholderHook` + a field in Media (blur + color) | empty boxes that "jump in" while loading |
| uploads | `buildOptimizeUploadHook` (stops images over 1.5 MB / 2560 px, converts on request); `iapl-doctor --deep` counts stored images over the limits | 8 MB phone photos in the library |
| background video | `videoMode="background"`, MP4 H.264 ≤ 20 MB, no sound, with a poster | a video as the hero without a poster, `autoplay` with sound |
| video with content | `videoMode="player"` (loads after a click) | `preload="auto"` |
| YouTube | `<YouTubeEmbed>` from `/client` (the iframe only after a click) | a bare `<iframe src="youtube.com/embed…">` |
| next.config | `images: { ...buildImagesConfig() }` (AVIF/WebP, R2) | no `remotePatterns` → images from R2 without optimization |
| fonts | `next/font`, max 2 families × 2–3 weights, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'` | a `<link>` to Google Fonts, 6 weights "just in case" |
| third-party scripts | `Analytics` (via `SiteProviders`, `analytics={{ defer: true }}`) / `ConsentScript` from the plugin | chat/map widgets loaded at start |
| client components | small, interaction only (§6.9) | a whole section `'use client'` |
| YouTube, maps, widgets | `<YouTubeEmbed>` from `/client` (the iframe only after a click); a map behind a click (a picture + a button) | a bare `<iframe>` that loads with the page |
| next.config | `images: buildImagesConfig()` (AVIF/WebP, R2, 31-day cache) | no `remotePatterns` → images from R2 without optimization |
| fonts | `next/font`, max 2 families, variable, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'` | a `<link>` to Google Fonts, `display: 'block'`, 6 weights "just in case" |
| third-party scripts | `Analytics` (via `SiteProviders`, `analytics={{ defer: true }}`) / `ConsentScript` from the plugin; `next/script` for anything else | `<script src>` without `async` in the layout, chat/map widgets loaded at start |
| animations | `transform` / `opacity` only, the token durations (`duration-fast`, reduced motion built in) or `motion-reduce:`; IntersectionObserver for "is it on screen" | animating `height` / `top` / `margin`, `transition-all`, a `scroll` listener doing work per event |
| client components | small, interaction only (§6.9); import from `@intecion/ipal-kit/client` freely — a page ships only what it renders (1.18.0) | a whole section `'use client'` |
| data | the cached helpers of `lib/content` (`getSettings`, `resolveRoute`, `getSiteShell`…), `depth` as low as the page needs, `select` when you need one field, `cache()` around your own getters | `findGlobal` in a component without `cache()`, `depth: 2` "to be safe", a query per list item |
| what grows | logs with a retention (consent log 1095 days, statistics 90; `forms: { submissionRetentionDays }` on the client's decision), `versions: { maxPerDoc: 20 }` where you turn versions on, unused media reviewed; `iapl-doctor --deep --only growth` ([performance.md](../performance.md) §6) | `maxPerDoc: 0`, submissions kept forever without a decision, a persistent volume on `.next` |
| budgets | `e2e/performance.spec.ts` from the `iapl-performance` skill (`perfBudgets()` from `/doctor`): fails when a page gets slower | "it felt fast on my machine" |
Target on the built site (mobile, Lighthouse/PageSpeed): LCP < 2.5 s, CLS < 0.1, INP < 200 ms.
Checks: `iapl-audit` (img/video outside Media, many `priority`, `h-screen`, fixed widths,
Target on the built site (mobile, Lighthouse/PageSpeed): LCP < 2.5 s, CLS < 0.1, INP < 200 ms — the plugin's default
budgets (`PERF_BUDGETS`). Checks: `iapl-doctor --only performance` (images config, fonts, render-blocking, embeds,
animations, a budget test; `--url`: compression, blocking scripts, preloads, a lazy first image, HTML size; `--deep`:
stored images over the limits), `iapl-audit` (img/video outside Media, many `priority`, `h-screen`, fixed widths,
YouTube `<iframe>`) and `iapl-seo-check` (images without dimensions, LCP image without priority).
### 6.12 Exports and imports
@@ -1561,6 +1569,8 @@ block library — [doctor.md](../doctor.md)):
bash .agents/skills/iapl-audit/scripts/audit.sh
pnpm exec iapl-doctor # + --deep --url http://localhost:3000 on the built site
node .agents/skills/iapl-seo-check/scripts/seo-check.mjs http://localhost:3000
pnpm test:e2e e2e/performance.spec # the budget gate (iapl-performance) on the built site
pnpm exec iapl-doctor --deep --only growth # what grows: sizes, versions, retention, old submissions, unused media
pnpm generate:types && pnpm tsc --noEmit
pnpm build # --webpack in the script; locally, not only dev
# hardcoding and the field zoo in blocks
@@ -1621,6 +1631,7 @@ Anything that needs a developer → move it to the panel.
| Rich text | [richtext.md](../richtext.md) |
| Headers, CSP, 2FA, panel path | [security.md](../security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](../seo.md) |
| Speed: what the plugin does, what the project does, budgets, measuring, the doctor's performance group | [performance.md](../performance.md) |
| Auto-slug | [slug.md](../slug.md) |
| Media: collection, file names, optimization, placeholders | [media.md](../media.md) |
| Image lightbox (enlarge, galleries, rich text images) | [lightbox.md](../lightbox.md) |
@@ -1702,6 +1713,7 @@ the task matches — manually: `/<name>`.
| `iapl-debug` | anything does not work — procedure + a symptom → cause → fix table |
| `iapl-audit` | before every "done" — the §0b set + the §11 checks + panel (§6.5a) + hardcoding in JSX + tsc + build |
| `iapl-seo-check` | the running site through the eyes of Googlebot and AI agents (head, canonical, hreflang, sitemap, 404, JSON-LD, llms, Markdown, MCP) |
| `iapl-performance` | speed: the doctor's performance group, measuring the built site (phone and desktop), the budget gate `e2e/performance.spec.ts` (`resources/`), reading LCP / CLS / INP / bytes / queries — when building pages or blocks, before handing over, whenever "slow" or PageSpeed comes up |
| `iapl-consent-check` | browser: no tracking pixels or cookies before consent; the Google tag may load before consent only in Consent Mode `advanced` (all signals `denied`) — a client who wants zero requests gets `consentMode: 'basic'` |
| `iapl-doctor` | the whole site against the team standard in one command (`pnpm exec iapl-doctor`): versions, Node 22, layout, database names, env, headers, CSP, 2FA, cookie scanner, adminMeta, AGENTS.md, skills, seeds, block library, pnpm audit; `--url` / `--deep` for the running site and the database; `--strict` in the CI of a new site |
| `iapl-plugin-gap` | IAPL has a bug or is missing a feature — report to the owner, wait for the decision; a marked workaround only after approval |
+3 -1
View File
@@ -374,7 +374,7 @@ export const Pages: CollectionConfig = {
{ name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 },
buildSummaryField(), // aiSummary — GEO (llms.txt, MCP)
buildNoindexField(),
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } },
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text', index: true }], labels: { plural: 'Old addresses', singular: 'Old address' } },
],
hooks: {
afterChange: [revalidate.afterChange],
@@ -1138,6 +1138,8 @@ Rules: AGENT.md §8a.
| `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) (below) |
| `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives |
| `e2e/own-account.spec.ts` | built-site test (pnpm e2e:built, 1.18.0): the account page asks for the current password before a new e-mail is saved (accounts.confirmOwnChanges); five failed staff sign-ins from one place answer 429 there, not elsewhere (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin) |
| `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/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/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with |
| `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) |
| `e2e/sign-in-answers.spec.ts` | built-site test (pnpm e2e:built, 1.17.2): a locked staff account gets the wrong-password answer over REST and GraphQL (accounts.lockedAnswer); the plugin's panel actions refuse another origin and take the site's own (adminSameOrigin) |
+7
View File
@@ -42,6 +42,13 @@ classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warnin
next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and
`iapl-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error.
## Speed (AGENT.md §6.11b, docs/performance.md)
The full run (not `--quick`) lists the doctor's `performance` group as warnings: `next.config` without
`buildImagesConfig()`, fonts from Google or with `display: 'block'`, more than two families, a blocking `<script src>`
or a remote stylesheet, an `<iframe>` that loads with the page, transitions of layout properties, `transition-all`,
`scroll` listeners, animations with nothing for reduced motion. The `iapl-performance` skill measures the built site and
adds the budget test.
## iapl-audit and iapl-doctor
`iapl-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec iapl-doctor` checks the **site**
against the team standard: it runs this script (`--quick`) from the installed package, reports its findings under its
@@ -362,6 +362,14 @@ if [ -n "$UI" ]; then
done
fi
# --- Speed (§6.11b, performance.md) — the doctor's performance group: images config, fonts, render-blocking,
# embeds, animations, a budget test. Full mode only: the doctor itself runs this audit with --quick.
if [ "$QUICK" -eq 0 ] && [ -x node_modules/.bin/iapl-doctor ]; then
PERF=$(node_modules/.bin/iapl-doctor --only performance --offline --json 2>/dev/null \
| node -e 'let s="";process.stdin.on("data",(d)=>(s+=d)).on("end",()=>{try{for(const f of JSON.parse(s).findings){if(!f.silenced&&f.severity!=="info"){console.log(`${f.file??"(site)"} [${f.rule}] ${f.message}`)}}}catch{}})')
report WARNING "speed (iapl-doctor --only performance)" "§6.11b / performance.md — each line names the rule; iapl-performance skill" "$PERF"
fi
# --- Compile & build ---
if [ "$QUICK" -eq 0 ]; then
echo
@@ -0,0 +1,66 @@
---
name: iapl-performance
description: Makes and keeps an IAPL site fast — page loading (LCP image, fonts, nothing render-blocking, static rendering), elements (lazy below the fold, reserved space, click-to-load embeds), animations (transform/opacity, reduced motion, no scroll handlers), resources (only the JS a page uses, compression, no third-party request before consent), images (AVIF/WebP, sizes, upload limits) and the server (queries per render, depth, select, caching); what grows in the database and on disk over the years (logs and their retention, form submissions, versions, KV, unused media, the image cache). Measures the built site, runs the doctor's performance group, and adds the budget gate that fails when a change makes the site slower. Use when building pages or blocks, before handing over, after an IAPL upgrade, and whenever "slow", PageSpeed, Lighthouse, Core Web Vitals, LCP, CLS, INP, a growing database or disk come up.
---
# iapl-performance
The handbook is `node_modules/@intecion/ipal-kit/docs/performance.md`: what the plugin does for you, what the project
must do, how to measure, how to read the findings. This skill is the order of work.
## 1. Check what the plugin cannot do for you (code)
```bash
pnpm exec iapl-doctor --only performance # images config, fonts, render-blocking, embeds, animations, budget test
bash .agents/skills/iapl-audit/scripts/audit.sh --quick # <img>/<video> outside Media, priority outside the hero, YouTube iframe, h-screen
```
Fix every warning — each names the file, the fix and the doc. The rules that matter most:
| Area | Do | Never |
|---|---|---|
| LCP image | `<Media priority>` on the first image of the page — **one** per page; a header logo gets `eager` | `priority` on many images; a lazy hero; the hero as a CSS background |
| other images | `<Media sizes={MEDIA_SIZES.third}>` — the width on screen; lazy by default | no `sizes`; a plain `<img>` |
| fonts | `next/font` (self-hosted), ≤ 2 families, variable, `display: 'swap'` | a `<link>` to Google Fonts; `display: 'block'` |
| scripts | the plugin's `Analytics` / `ConsentScript`; `next/script` for anything else | a `<script src>` without `async` in the layout |
| embeds | `<YouTubeEmbed>`; a map or widget behind a click (a picture + a button) | an `<iframe>` that loads with the page |
| animations | `transform` / `opacity` only; the token durations (`duration-fast`) or `motion-reduce:` | animating `height`, `top`, `margin`; `transition-all`; a `scroll` listener (use IntersectionObserver) |
| client code | small `'use client'` leaves; server components by default | a whole section `'use client'` |
| server | the plugin's cached helpers (`lib/content`), `depth` as low as the page needs, `select` for one field | `findGlobal` without `cache()`; `depth: 2` "to be safe"; a query per list item |
## 2. Measure the built site
```bash
pnpm build && pnpm start # dev numbers mean nothing
pnpm exec iapl-doctor --url http://localhost:3000 --only perf-live # compression, blocking scripts, preloads, lazy hero, HTML size
pnpm exec iapl-doctor --deep --only perf-images # stored images over 1.5 MB / 2560 px
```
Lab numbers per page (phone on Slow 4G with a 4× slower CPU, and desktop): copy `resources/perf-lab.mjs` and
`resources/performance.spec.template.ts` (→ `e2e/performance.spec.ts`), list one page of each template, run
`pnpm test:e2e e2e/performance.spec`, then set each budget to what you measured plus ~20 %. From then on the test fails when
a change makes a page slower. PageSpeed Insights on the deployed site shows the field data (real visitors).
## 3. Read the result
- **LCP** > 2.5 s on the phone: the LCP element is named in the measurement (`lcpElement`). An image → `priority`,
`sizes`, a smaller upload; text → a font that arrives late (fewer preloaded files).
- **CLS** > 0.1: an image without dimensions (use `Media`), content that arrives after hydration (the lazy 404 —
`createNotFoundPage({ load, placeholder })`), a font swap (next/font sets fallback metrics).
- **TBT / INP**: long tasks — a big client component, a scroll handler, a third-party widget at start.
- **JS bytes**: what the page ships; import client components from `@intecion/ipal-kit/client` freely — since
1.18.0 a page carries only the ones it renders.
- **Queries per render** (the reference gate counts them): over 30 for an ordinary page → a missing `cache()`, a
`depth` too high, or a loop of `findByID`.
## 4. What grows (performance.md §6)
```bash
pnpm exec iapl-doctor --deep --only growth # counts and sizes per collection, oldest records, versions, expired KV, unused media, disk
```
- Logs purge themselves (consent log 1095 days, statistics 90). Form submissions are kept unless
`iapl({ forms: { submissionRetentionDays } })` — ask the client (personal data) and record it in AGENTS.md.
- Versions: where you turn them on, `versions: { maxPerDoc: 20 }` (globals `max`); never `0`.
- Unused media (`growth-media`): list them for the client; the plugin never deletes media or submissions by itself.
- Coolify: no persistent volume on `.next` (the image cache starts empty on each deploy); database backups on the
MongoDB resource.
- Thresholds of the findings: `iapl-doctor.json` → `growth`.
## 5. Before "done"
`iapl-doctor --only performance` without warnings (or each one silenced with a reason in `iapl-doctor.json`),
the budget test green, and the numbers in `AGENTS.md` → "Project decisions" when the client accepted an exception
(a heavy font, a third-party widget).
@@ -0,0 +1,175 @@
/**
* Lab measurements of one page in Chromium (Playwright + the DevTools protocol) — used by `pnpm perf:measure`
* (scripts/perf-measure.mjs, numbers for docs/performance.md) and by the budget gate (e2e/performance.spec.ts).
*
* Profiles follow Lighthouse's defaults so the numbers compare with PageSpeed Insights' lab data:
* - mobile: 412×823 at DPR 1.75, "Slow 4G" (150 ms RTT, 1.6 Mbit/s down, 750 kbit/s up), CPU 4× slower;
* - desktop: 1350×940, 40 ms RTT, 10 Mbit/s, CPU 1×.
* Every run is a fresh browser context (empty HTTP cache, no cookies): a first visit, the worst ordinary case.
*
* What is measured (all from the browser itself, web.dev/articles/vitals):
* ttfb, fcp, lcp (+ the LCP element: tag, src, loading, fetchpriority), cls (session windows, as web-vitals does),
* tbt (sum of long-task time over 50 ms between FCP and the end of the run: the lab stand-in for INP),
* inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button),
* scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type
* (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to
* another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are
* counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run.
* Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host
* cannot hold the page's load event, and the numbers are the site's own.
*/
import { chromium } from '@playwright/test'
export const PROFILES = {
desktop: { cpu: 1, network: { downloadThroughput: (10 * 1024 * 1024) / 8, latency: 40, uploadThroughput: (10 * 1024 * 1024) / 8 }, viewport: { deviceScaleFactor: 1, height: 940, isMobile: false, width: 1350 } },
mobile: { cpu: 4, network: { downloadThroughput: (1.6 * 1024 * 1024) / 8, latency: 150, uploadThroughput: (750 * 1024) / 8 }, viewport: { deviceScaleFactor: 1.75, hasTouch: true, height: 823, isMobile: true, width: 412 } },
}
const OBSERVERS = `(() => {
const v = (window.__perf = { cls: 0, events: [], lcp: null, longTasks: [] })
let win = 0, winStart = 0, winLast = 0
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
const el = e.element
v.lcp = { at: e.startTime, size: e.size, tag: el ? el.tagName.toLowerCase() : null, src: e.url || null,
loading: el && el.getAttribute ? el.getAttribute('loading') : null,
fetchpriority: el && el.getAttribute ? el.getAttribute('fetchpriority') : null }
} }).observe({ buffered: true, type: 'largest-contentful-paint' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
if (e.hadRecentInput) continue
if (win && e.startTime - winLast < 1000 && e.startTime - winStart < 5000) { win += e.value } else { win = e.value; winStart = e.startTime }
winLast = e.startTime
v.cls = Math.max(v.cls, win)
} }).observe({ buffered: true, type: 'layout-shift' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.longTasks.push([e.startTime, e.duration]) }).observe({ buffered: true, type: 'longtask' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.events.push({ d: e.duration, n: e.name }) }).observe({ buffered: true, durationThreshold: 16, type: 'event' })
})()`
/**
* @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number,
* fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number,
* lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string },
* load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number,
* status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement
*/
const typeOf = (resourceType, mime = '') => {
if (resourceType === 'Document') {return 'html'}
if (resourceType === 'Script') {return 'js'}
if (resourceType === 'Stylesheet') {return 'css'}
if (resourceType === 'Font') {return 'font'}
if (resourceType === 'Image' || mime.startsWith('image/')) {return 'image'}
return 'other'
}
/**
* @param {import('@playwright/test').Browser} browser
* @param {string} url
* @param {'mobile'|'desktop'} profileName
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
* @returns {Promise<PageMeasurement>}
*/
export async function measurePage(browser, url, profileName, options = {}) {
const profile = PROFILES[profileName]
const context = await browser.newContext({ ...profile.viewport, viewport: { height: profile.viewport.height, width: profile.viewport.width } })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
await cdp.send('Network.enable')
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network })
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
await cdp.send('Performance.enable')
await page.addInitScript(OBSERVERS)
const origin = new URL(url).origin
if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())}
const requests = new Map()
let prefetches = 0
cdp.on('Network.requestWillBeSent', (e) => {
if (e.request.url.startsWith('data:')) {return}
if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return}
requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })
})
cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} })
cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} })
const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' })
await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {})
await page.waitForTimeout(options.settleMs ?? 1000)
let interaction = null
if (options.interact !== false) {
// INP stand-in: one click on the first visible button (menu toggle, cookie settings, theme): a real handler runs
const button = page.locator('button:visible').first()
if (await button.count()) {
interaction = (await button.getAttribute('aria-label')) ?? (await button.innerText()).slice(0, 40)
await button.click({ timeout: 5000 }).catch(() => { interaction = null })
await page.waitForTimeout(500)
}
}
const nav = await page.evaluate(() => {
const n = performance.getEntriesByType('navigation')[0]
const fcp = performance.getEntriesByName('first-contentful-paint')[0]
const blocking = performance.getEntriesByType('resource').filter((r) => r.renderBlockingStatus === 'blocking').map((r) => r.name)
return { blocking, domContentLoaded: n.domContentLoadedEventEnd, fcp: fcp ? fcp.startTime : null, load: n.loadEventEnd, ttfb: n.responseStart }
})
const vitals = await page.evaluate(() => window.__perf)
const { metrics } = await cdp.send('Performance.getMetrics')
const metric = (name) => metrics.find((m) => m.name === name)?.value ?? 0
await context.close()
const list = [...requests.values()]
const bytes = { css: 0, font: 0, html: 0, image: 0, js: 0, other: 0 }
for (const r of list) {bytes[r.type] += r.bytes}
const fcp = nav.fcp ?? 0
const tbt = vitals.longTasks.filter(([start]) => start >= fcp).reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0)
const round = (n) => (n == null ? null : Math.round(n))
return {
bytes: Object.fromEntries(Object.entries(bytes).map(([k, b]) => [k, Math.round(b)])),
cls: Math.round(vitals.cls * 1000) / 1000,
fcp: round(nav.fcp),
inp: vitals.events.length ? round(Math.max(...vitals.events.map((e) => e.d))) : interaction ? 0 : null,
interaction,
lcp: round(vitals.lcp?.at),
lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null,
load: round(nav.load),
prefetches,
profile: profileName,
renderBlocking: nav.blocking.map((u) => u.replace(origin, '')),
requests: list.length,
scriptMs: round(metric('ScriptDuration') * 1000),
status: response?.status() ?? null,
tbt: round(tbt),
thirdParty: [...new Set(list.filter((r) => !r.url.startsWith(origin)).map((r) => new URL(r.url).origin))],
ttfb: round(nav.ttfb),
url: url.replace(origin, ''),
}
}
export const median = (values) => {
const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b)
if (!sorted.length) {return null}
const mid = Math.floor(sorted.length / 2)
return sorted.length % 2 ? sorted[mid] : Math.round(((sorted[mid - 1] + sorted[mid]) / 2) * 1000) / 1000
}
/**
* The median of `runs` measurements for every number; the rest from the last run.
* @param {import('@playwright/test').Browser} browser
* @param {string} url
* @param {'mobile'|'desktop'} profileName
* @param {number} [runs]
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
* @returns {Promise<PageMeasurement>}
*/
export async function measureMedian(browser, url, profileName, runs = 3, options = {}) {
const all = []
for (let i = 0; i < runs; i++) {all.push(await measurePage(browser, url, profileName, options))}
const last = all.at(-1)
const out = { ...last, runs }
for (const key of ['cls', 'fcp', 'inp', 'lcp', 'load', 'requests', 'scriptMs', 'tbt', 'ttfb']) {out[key] = median(all.map((r) => r[key]))}
out.bytes = Object.fromEntries(Object.keys(last.bytes).map((k) => [k, median(all.map((r) => r.bytes[k]))]))
return out
}
export const launch = () => chromium.launch()
@@ -0,0 +1,48 @@
// e2e/performance.spec.ts — the project's performance budget gate (iapl-performance skill, docs/performance.md).
// Copy this file and perf-lab.mjs (same folder) to e2e/. Runs against the BUILT site: pnpm build && pnpm test:e2e.
// It fails when a page breaks a budget: the plugin's defaults (Core Web Vitals "good", bytes, requests), tightened
// below to what this site measured, so a change that makes it slower fails. Loosen a number only with a reason.
import type { Browser } from '@playwright/test'
import { overBudget, perfBudgets } from '@intecion/ipal-kit/doctor'
import { chromium, expect, test } from '@playwright/test'
// a plain ES module (JSDoc types) — perf-lab.mjs from the skill's resources
import { measureMedian } from './perf-lab.mjs'
const runs = Number(process.env.PERF_RUNS ?? 1)
// Start from the defaults; after the first run, set each number to what you measured plus ~20 % (the lab is noisy).
const budgets = perfBudgets({
desktop: {},
mobile: {},
})
// One page of each template the site has (AGENTS.md → Site map). `budget` changes a number for one page, with a reason.
const PAGES: Array<{ budget?: Partial<typeof budgets.mobile>; name: string; path: string }> = [
{ name: 'home', path: '/pl' },
// { name: 'page', path: '/pl/o-nas' },
// { name: 'post', path: '/pl/blog/<a-post>' },
// { name: 'form', path: '/pl/kontakt', budget: { thirdParty: ['https://challenges.cloudflare.com'] } }, // Turnstile
]
let browser: Browser
test.beforeAll(async () => {
browser = await chromium.launch()
})
test.afterAll(async () => {
await browser?.close()
})
for (const page of PAGES) {
for (const profile of ['mobile', 'desktop'] as const) {
test(`${page.name} (${profile}) stays within its performance budget`, async ({ baseURL }) => {
test.setTimeout(120_000)
// third-party requests are recorded, then aborted: an external host cannot fail or hang the test
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 }), type: 'measured' })
expect(overBudget(measured, { ...budgets[profile], ...page.budget }), `${page.path} ${profile}`).toEqual([])
if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, 'the LCP image is lazy').not.toBe('lazy')}
})
}
}
@@ -218,6 +218,7 @@ Mandatory set: AGENT.md §0b, skill **iapl-setup**; checks: **iapl-audit**, **ia
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → E-mail sending → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **iapl-form** |
| forms — retention | config (client decision) | `forms: { submissionRetentionDays: 365 }` (1.18.0; default: kept) | `iapl-doctor --deep --only growth-submissions` quiet; old submissions gone a day after the next submission | performance.md §6, forms.md |
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Spam protection or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
@@ -338,7 +338,7 @@ Opt-in with `iapl({ cookieScanner: true })`; the plugin wires the collection, en
|---|---|---|
| `createContentHelpers({ config, content?, i18n?, baseUrl?, … })` | `@intecion/ipal-kit` | factory for `src/lib/content.ts`: cached `getCachedPayload`, `getSettings`, `resolveRoute`, `getEntries`, `generatePageMetadata`, `getSiteShell`, `sitemap`, `robots`, `getRobots`, `isPathVisible`, `markdownRoute`, `healthRoute`, `mcpGET`/`mcpPOST`… — do not write these wrappers yourself |
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
| `createNotFoundPage(content, { load, placeholder? } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended; `placeholder` (1.18.0) reserves the 404 content's height until it arrives — no layout shift, performance.md) |
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); `nonce` (from `x-nonce`) goes on the theme script and the GA4/GTM tag; does not mount `AlternateLinksProvider` |
@@ -454,7 +454,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission (and, with `forms.submissionRetentionDays`, deletes older ones at most once a day); returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
@@ -532,7 +532,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `mediaImageProps(resource, { sizes?, priority?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>` |
| `mediaImageProps(resource, { sizes?, priority?, eager?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>`. `eager` (1.18.0): above the fold but not the LCP image (a logo) — eager without high priority or a preload |
| `videoProps(resource, { mode?, poster?, reducedMotion? })` | `@intecion/ipal-kit` | `<video>` attributes for a video upload (`'background'`: autoplay/muted/loop; `'player'`: controls, `preload="none"`) or `null` |
| `MEDIA_SIZES` | `@intecion/ipal-kit` | Ready constant `sizes` values: `full`, `half`, `third`, `quarter`, `thumb` |
| `normalizeFilename(filename)` | `@intecion/ipal-kit` | Slugifies a file name, keeping the extension (`"Zdjęcie 1.JPG"` → `"zdjecie-1.jpg"`) |
@@ -881,7 +881,10 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `iapl-doctor.json` wins. |
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `media` (images over `IMAGE_RULES`, 1.18.0), `plugin`, `node`. |
| `PERF_BUDGETS`, `SERVER_BUDGET`, `perfBudgets(overrides)`, `overBudget(measured, budget)`, `IMAGE_RULES` | `@intecion/ipal-kit/doctor` | Performance budgets (1.18.0, performance.md): the defaults per profile (`mobile`, `desktop`: `lcp`, `cls`, `inp`, `tbt`, `jsBytes`, `cssBytes`, `fontBytes`, `requests`, `renderBlocking`, `thirdParty`) and per render (`queriesPerRender`); a project's own on top; the broken budgets of one measurement as lines (empty = within budget); the image limits (1.5 MB, 2560 px, AVIF/WebP). Types `PerfBudget`, `PerfMeasurement`, `PerfProfile`, `ServerBudget`. The gate: `iapl-performance/resources/performance.spec.template.ts` + `perf-lab.mjs`. |
| `collectGrowth(payload)` → `GrowthStatus`, `growthRules`, `GROWTH_DEFAULTS`, `folderBytes(dir)` | `@intecion/ipal-kit/doctor` | What grows (1.18.0, performance.md §6): per collection documents, bytes (MongoDB) and the oldest record; versions per collection and global with their limit; `payload-kv` entries and expired ones; media no document points at (first 5000 documents) — counts only. The `growth` rules (`growth-size`, `-versions`, `-retention`, `-submissions`, `-kv`, `-media`, `-disk`) and their default thresholds (`iapl-doctor.json` → `growth`, type `GrowthThresholds`). |
| `performanceRules` | `@intecion/ipal-kit/doctor` | The doctor's `performance` group (`perf-images-config`, `perf-fonts`, `perf-render-blocking`, `perf-embeds`, `perf-animations`, `perf-budgets`, `perf-live`, `perf-images`) — part of `doctorRules`. |
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. |
| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. |
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
+185
View File
@@ -0,0 +1,185 @@
# Performance review 2026-12 — method, numbers, audit, decisions
The measurements and the audit behind [performance.md](../../performance.md) (1.18.0). Owner's brief (2026-12-01):
the site as light as possible, everything fast and optimised, good practice required, the audit and the doctor
check it, full documentation; page loading, elements, animations, resources, images.
## Method (repeatable)
```bash
docker run -d --rm --name iapl-perf-mongo -p 127.0.0.1:27277:27017 mongo:7 # any local MongoDB
# reference/.env: DATABASE_URI on that port, ALLOW_LOCAL_MEDIA=1, NEXT_PUBLIC_SERVER_URL=http://localhost:3370
pnpm build && (cd reference && pnpm install --ignore-workspace && pnpm seed && pnpm build)
pnpm perf:measure --label=webpack-after --mongo-container=iapl-perf-mongo # starts next start itself
(cd reference && pnpm exec next build --turbopack) && pnpm perf:measure --label=turbopack-after --mongo-container=iapl-perf-mongo
```
`scripts/perf-measure.mjs` + `reference/e2e/perf-lab.mjs`: Chromium (Playwright 1.65) with Lighthouse's profiles,
empty cache, median of 3 runs; eight page types × phone and desktop; `/admin/login`; cold start (spawn → `/api/health`),
RSS after the run, TTFB over 20 requests, and one render of each page with ISR bypassed (`x-prerender-revalidate`)
counted by MongoDB's profiler. Machine: Apple silicon, Node 22.23, MongoDB 7 in Docker, Next 16.4.6, Payload 3.94.1.
Raw results: `webpack-before.json`, `webpack-after.json`, `turbopack-before.json`, `turbopack-after.json` here.
"Before" = local main `ee241de` (1.17.2), "after" = this branch.
## Numbers
### Server: one render of a page (ISR bypassed), webpack build
| Page | Queries before → after (both bundlers) | Render ms webpack | Render ms Turbopack |
|---|---|---|---|
| home `/pl` | 43 → 24 | 95 → 51 | 57 → 41 |
| page `/pl/o-nas` | 34 → 21 | 54 → 34 | 41 → 38 |
| archive `/pl/blog` | 34 → 23 | 63 → 42 | 32 → 29 |
| post | 41 → 26 | 61 → 41 | 41 → 30 |
| case study | 37 → 22 | 33 → 31 | 33 → 24 |
| form `/pl/wycena` | 30 → 19 | 28 → 29 | 28 → 22 |
| showcase `/pl/bloki` | 42 → 27 | 68 → 62 | 73 → 50 |
| 404 | 25 → 20 | 29 → 26 | 27 → 19 |
| `/md/pl`, `/llms.txt`, `/llms-full.txt`, `/sitemap.xml` | 16, 22, 38, 0 — unchanged | — |
All query time on a local MongoDB is ≤ 1 ms per render: the count is what costs on a remote database (one round trip
each — on Coolify's Docker network ~0.2–0.5 ms, more on a managed database). A cached (ISR) page answers in
2.5–3.7 ms median, ≤ 5.4 ms p95, with 0 queries, before and after. Cold start (spawn → health) 1.0–1.6 s, no change.
Memory, measured on its own (`next start`, Turbopack build: boot → 100 cached requests → 40 renders): 1.17.2
282 → 295–318 → 417–421 MiB, this branch 282 → 295 → 394 MiB (two runs each). The RSS that `perf:measure` prints
after its whole run swings by ±100 MiB with garbage collection; do not compare it.
### Client: lab, median of 3, phone (Slow 4G, CPU 4×) / desktop
| | Before (webpack) | After (webpack) | Before (Turbopack) | After (Turbopack) |
|---|---|---|---|---|
| JS per page, compressed | 191.3 KB | 188.1 KB | 184.4 KB | 181.6 KB |
| JS, showcase (every block) | 219.6 KB | 216.4 KB | 212.7 KB | 209.9 KB |
| CSS | 11.0 KB | 11.0 KB | 12.0 KB | 12.0 KB |
| Fonts | 209.5 KB | 209.5 KB | 209.5 KB | 209.5 KB |
| HTML | 17.0–19.8 KB | 17.1–19.8 KB | 17.1–19.9 KB | 17.1–19.9 KB |
| Requests (home / page, phone) | 26 / 21 | 26 / 21 | 26 / 21 | 26 / 21 |
| LCP phone (pages) | 788–832 ms | 780–828 ms | 796–836 ms | 820–868 ms |
| LCP desktop | 284–316 ms | 288–300 ms | 284–300 ms | 288–304 ms |
| CLS | 0 (home 0.036) | 0 (home 0.036) | 0 (home 0.036) | 0 (home 0–0.036) |
| TBT phone | 22–25 ms | 16–23 ms | 6–13 ms | 1–7 ms |
| Tap response (INP proxy) | 32–40 ms | 32–48 ms | 32–48 ms | 32–40 ms |
| Script time (parse, run, hydrate), phone | 117–124 ms | 110–118 ms | 76–82 ms | 64–76 ms |
| Render-blocking | 1 (the stylesheet) | 1 | 1 | 1 |
| 404: LCP / CLS (phone) | 2.49 s / 0.319 | 2.50 s / 0.319 | 2.37 s / 0.319 | 2.31 s / 0.319 |
| `/admin/login` JS | 843 KB | 843 KB | — | — |
Lab numbers on localhost: LCP is the network profile plus render, so the differences between pages are small; the
budgets and the gate catch regressions, PageSpeed Insights shows the field.
On every page FCP = LCP: the first paint waits for the one stylesheet, which on the phone profile (1.6 Mbit/s) shares
the line with four preloaded font files (209 KB) and the async script chunks. With Turbopack the phone's first paint
came out 20–50 ms later after this branch (three runs on a quiet machine; webpack unchanged), although it ships 2.8 KB
less JS and nothing new blocks: Turbopack splits the client chunks differently once the barrels are no longer one
client boundary, and on that line the order of downloads moves the stylesheet a little. The fonts are the bigger
lever (decision 2 below: −36 to −52 ms).
## Audit — what the plugin does, file and line, and the gain of each fix
Sources: web.dev (vitals, optimize-lcp, cls, optimize-inp, font-best-practices, animations-guide,
prefers-reduced-motion, third-party-facades, render-blocking-resources, serve-images-avif-webp,
lcp-lazy-loading), nextjs.org/docs (caching, fonts, image, lazy-loading, package bundling), payloadcms.com/docs
(queries/depth, queries/select, database/indexes).
### Built in this branch (no change to how a site looks or how editors work)
| # | Finding (before) | Fix | Measured gain |
|---|---|---|---|
| S1 | `resolveRoute` was `cache()`d but called with `segments ?? []` — a new array each time, so React's identity comparison missed; the homepage was read in full at depth 2 (≈ 6 queries) four times per render (`src/modules/frontend/createContentHelpers.ts` resolveRoute; callers `pageRoute.tsx:123`, `createContentHelpers.ts` getPageJsonLd, `seo/createPageMetadata.ts:152`) | key by `JSON.stringify(segments ?? [])` | home 43 → 24 queries with S2–S4 |
| S2 | `generatePageMetadata` uncached: the page's metadata, the reference page's alternate links and `getPageJsonLd` each built it — three × (homepage + document read in every locale) | `cache()` keyed by value | −6 queries on every page |
| S3 | `slugsAcrossLocales` and `readSiteMetaConfig` read whole documents (layout in every locale) for the slug map (`seo/slugsAcrossLocales.ts:28`, `seo/readSiteMetaConfig.ts:78`) | `select: { slug: true }` | smaller reads (same count) |
| S4 | `getConsentTexts` → `readPrivacyPage` read Site settings at depth 1 in every locale, populating every system page, archive and allowed page in full (`consent/getConsentTexts.ts:138`) | `select: { privacyPolicy: true }` | fewer populated pages per render |
| S5 | analytics and Turnstile each read Site integrations in the same `Promise.all` (`frontend/createContentHelpers.ts` getSiteShell, `analytics/getAnalyticsConfig.ts:14`, `turnstile/config.ts:90`) | one in-flight read shared (`payload/getSiteIntegrations.ts`), nothing kept after it | −1 query per render (−2 with a form that has file blocks) |
| S6 | reference: `siteJsonLd` read the Company global again instead of the cached `getCompany` (`reference/src/lib/content.ts`) | the cached getter | −1 query per render |
| S7 | reference: `slugHistory.slug` without an index — queried on every unknown URL (`content/resolveRedirect.ts:96`) | `index: true` (reference `Pages.ts`, hooks.md) | a collection scan avoided per 404; nothing measurable at 30 pages |
| C1 | `src/exports/client.ts` and six module barrels carried `'use client'`: the barrel was one client boundary, so every page shipped every component behind it | the directive only on the leaf components | with C2: −3.2 KB compressed JS on every page |
| C2 | `LightboxProvider` imported the viewer statically (`lightbox/LightboxProvider.tsx:10`) | `lazy()` — loaded on the first open (7.3 KB raw chunk) | in C1 |
| C3 | `TableOfContents` measured every heading on every scroll event (`richtext/TableOfContents.tsx:38`) | at most once per frame (rAF) | fewer forced layouts while scrolling a long article (INP) |
| C4 | `Turnstile` polled every 300 ms for the life of the form (`turnstile/Turnstile.tsx:100`) | stop once rendered | no idle timer on form pages |
| C5 | the cookie banner's switches, its details chevron and the cookie button animated with no regard for reduced motion (`consent/CookieBanner.tsx:139,171,361`, `CookieButton.tsx:82`) | `motion-reduce:transition-none` | WCAG 2.3.3; no change without the setting |
| C6 | the reference header logo had `priority` — a second high-priority preload next to the hero (`reference/src/components/layout/Header.tsx:27`) | `Media eager` (new option: eager, no high priority, no preload) | the hero gets the first round trip (a site with a logo) |
| C7 | the lazy 404 could not reserve space | `createNotFoundPage({ load, placeholder })` (default unchanged) | CLS 0.32 → 0 when the project sets its 404 height |
### Already right (kept)
ISR for every page and 0 queries for a cached page; no `headers()` / `cookies()` in the layout; the consent banner
in the first paint (`docs/consent.md`); theme client hints only on `/admin`; `next/font` self-hosted with
`display: 'swap'`; one render-blocking stylesheet (11 KB); `mediaImageProps` sets dimensions, `sizes`, lazy and
the LCP `priority`; `buildImagesConfig` serves AVIF / WebP with a 31-day cache; upload limits with an opt-in
conversion (metadata dropped); `YouTubeEmbed` is a facade; Meta, LinkedIn, TikTok and Clarity wait for consent;
the proxy does no database work; the 434 KB cookie database is loaded only by a scan; the sitemap has `select` and a
300 s memo.
### For the owner — yes / no (gain and cost)
1. **Lazy 404 content (CLS 0.32, LCP 2.5 s on a phone).** The 404 is fetched by a server action after hydration
so that every page's payload does not carry it (pages.md). Options: (a) keep, and have the reference site set a
`placeholder` of its 404 height — CLS → 0, LCP unchanged, a number to keep in sync with the content; (b) render
the 404 eagerly — LCP and CLS as any page, but every page's HTML grows by the 404 content in every language
(pages.md: a two-language home page as the 404 made a page 195 KB gzip instead of 146 KB). Recommendation (a).
2. **Fonts: 209.5 KB, four preloaded files** (Inter + Fraunces, latin + latin-ext). Each variable family has two
subset files. Measured (Turbopack, phone, median of 5): Fraunces with `preload: false` → first paint and LCP
−36 to −52 ms on home, page and post; the same 209 KB still downloads (the headings use it), and the home page's
CLS goes from 0 to 0.036 (the headings swap, < 0.1). One family instead of two would save ~70 KB as well. A design
decision for the reference site and the starter default. Recommendation: `preload: false` on the heading font.
3. **Form code on every page (≈ 10 KB compressed).** The catch-all route renders any block, so the contact form's
client code (BuilderForm, Turnstile provider) is in every page's bundle. A `lazy()` wrapper would load it only on
pages with a form; SSR stays complete. Gain −10 KB on most pages; cost: a hydration wait on the form, test effort
with both bundlers. Recommendation: yes, next release.
4. **Background video and reduced motion.** `Media` (a server component) cannot know the visitor's setting, so a
background video autoplays for everyone (`block-library/ui/Media.tsx:29`). A small client wrapper pausing it with
`prefers-reduced-motion` adds ~1 KB to pages with a video. Recommendation: yes.
5. **Consent Mode `basic` as the default** (no request to Google before consent; already pending as a security
decision). Speed gain on a first visit with GA/GTM set: one third-party origin and ~100 KB of tag less until consent.
6. **Card hover animates `box-shadow`** (`block-library/ui/Card.tsx:6`, a paint per frame, cheap on cards). A
pseudo-element with `opacity` would be compositor-only; the hover looks the same. Low gain; yes if the block
library is touched anyway.
7. **Upload variants (`imageSizes`) and metadata on originals.** next/image already resizes and converts on request,
so stored variants mostly help the lightbox `srcSet` and R2 egress; originals under the 1.5 MB limit keep their
EXIF (camera, possibly GPS). Stripping metadata on every upload re-encodes the original. Recommendation: strip
metadata on upload for JPEG/PNG (privacy more than speed), variants no.
8. **Doctor performance rules: warnings now, errors later?** In 1.18.0 they warn (as asked); `perf-live`
uncompressed HTML and `perf-images` could become errors in 1.19.0.
## Growth review (owner's addition, 2026-12-01): what swells the site and its database
Measured on the reference site (MongoDB 7) after the full reference suite as traffic: 15 collections, the largest
`pages` (15 × 9 KB); consent record 185 B, form submission 647 B, KV entry 371 B on average, plus 2–6 indexes per
collection. `pnpm exec iapl-doctor --deep --only growth` on it: 2.6 s, two infos (3 submissions without a
retention; 1 of 17 media unused — `logo-example-studio-1.webp`, a duplicate logo a test uploaded).
| Store | Today (1.17.2 defaults) | file:line | 1.18.0 |
|---|---|---|---|
| consent-records | purged after 1095 days, once a day per process, only after a new record; one unbounded `deleteMany` | `consent/consentLog.ts:124,161`, `shared/purge.ts:16` | retention recorded for the doctor; `growth-retention` reports a purge that has not caught up |
| stats-visits (opt-in) | purged after 90 days, same mechanism | `stats/endpoint.ts:53,153` | same |
| form-submissions | **no retention, nothing deletes them**; files never stored | `forms/submitForm.ts:324` | opt-in `forms.submissionRetentionDays` (default: kept); `growth-submissions` |
| payload-kv: mail-service nonces | expiry checked only on read: a nonce whose call-back never came stayed for good | `email/relay/store.ts:174` | expired nonces swept (once a day, at the next enrolment) |
| payload-kv: 2FA counters, relay state | one per staff account / host; never deleted | `security/totp/verifyLimit.ts:84`, `relay/store.ts:114` | left alone: bounded; a sweep could race a live verify |
| versions | the plugin turns none on; Payload keeps 100 per document / global | `payload/dist/collections/config/sanitize.js:172` | `growth-versions` (0 = unlimited, or over 50 000) |
| cookie-review (opt-in) | upsert by name; `gone` rows kept | `consent/scanner/scan.ts:297` | documented |
| payload-preferences / locked-documents / jobs | Payload cleans them; the plugin queues no jobs | — | — |
| media | deleted with the document (disk and R2); nothing finds unused media | `storage/buildR2Storage.ts:140` | `growth-media` (counts, never deletes) |
| `.next/cache/images` | 31-day TTL, no size cap | `storage/buildImagesConfig.ts:56` | `growth-disk` (info); Coolify: no volume on `.next` |
| logs | the plugin writes no files | — | — |
Postgres / SQLite: the same purges through Drizzle's `deleteMany`; no TTL indexes; sizes not read (counts only).
### Growth — for the owner (yes / no)
9. **A default retention for form submissions** (e.g. 365 days) on every site, existing ones included. Deletes
data on live sites on their next submission. Recommendation: no default; the agent asks the client
(`submissionRetentionDays`) and the doctor reports sites without one — or yes with 730 days and a loud upgrade note.
10. **MongoDB TTL indexes** for the consent log and statistics (expire `createdAt` / `lastAt` after the retention),
so the purge runs even when no new record comes. Same records deleted as today, sooner on a quiet site; one index
build per site at start. Recommendation: yes for 1.19.0 (opt-out), Mongo only.
11. **Delete `gone` cookie-review rows after a year.** Deletes the scanner's history. Recommendation: no.
12. **A media clean-up action in the panel** (list the unused media, delete after confirmation). Recommendation:
yes, as a panel view — never automatic.
13. **`maxPerDoc: 20`** in the reference and the starter wherever versions get turned on (none today). Recommendation: yes (no data deleted until a document is saved again).
### Shared with IAWL
Proposed for both products (performance.md §7): the Core Web Vitals targets and the lab profile; JS ≤ 250 KB,
CSS ≤ 50 KB, fonts ≤ 250 KB and two families, ≤ 40 requests on the phone, one render-blocking stylesheet, no
third-party origin before consent; images ≤ 1.5 MB and ≤ 2560 px at upload, AVIF / WebP in the width the screen
needs, one high-priority LCP image, lazy below the fold. Not shared: the database budget (MongoDB queries per render
here, SQL queries per request in WordPress).
+753
View File
@@ -0,0 +1,753 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 19896,
"image": 9532,
"js": 181608,
"other": 24705
},
"cls": 0,
"fcp": 868,
"inp": 32,
"interaction": "PL",
"lcp": 868,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2457,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 26,
"scriptMs": 76,
"status": 200,
"tbt": 7,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 17127,
"image": 8451,
"js": 181608,
"other": 13038
},
"cls": 0,
"fcp": 820,
"inp": 32,
"interaction": "PL",
"lcp": 820,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2438,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 21,
"scriptMs": 65,
"status": 200,
"tbt": 2,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 16491,
"image": 5316,
"js": 181608,
"other": 18546
},
"cls": 0,
"fcp": 828,
"inp": 32,
"interaction": "PL",
"lcp": 828,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2431,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 22,
"scriptMs": 64,
"status": 200,
"tbt": 2,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 17082,
"image": 5316,
"js": 181608,
"other": 13038
},
"cls": 0,
"fcp": 828,
"inp": 32,
"interaction": "PL",
"lcp": 828,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2430,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 21,
"scriptMs": 64,
"status": 200,
"tbt": 2,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 16599,
"image": 4372,
"js": 181608,
"other": 13038
},
"cls": 0,
"fcp": 848,
"inp": 40,
"interaction": "PL",
"lcp": 848,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2418,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 20,
"scriptMs": 66,
"status": 200,
"tbt": 5,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 16323,
"image": 0,
"js": 181608,
"other": 13038
},
"cls": 0,
"fcp": 828,
"inp": 32,
"interaction": "PL",
"lcp": 828,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2387,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 18,
"scriptMs": 61,
"status": 200,
"tbt": 1,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 36962,
"image": 2016,
"js": 209854,
"other": 24820
},
"cls": 0,
"fcp": 860,
"inp": 32,
"interaction": "PL",
"lcp": 860,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2403,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 25,
"scriptMs": 125,
"status": 200,
"tbt": 3,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 7747,
"image": 0,
"js": 181608,
"other": 68180
},
"cls": 0.319,
"fcp": 2312,
"inp": 40,
"interaction": "PL",
"lcp": 2312,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2694,
"profile": "mobile",
"renderBlocking": [],
"requests": 27,
"scriptMs": 119,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 19896,
"image": 9274,
"js": 181608,
"other": 71353
},
"cls": 0.001,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 448,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 33,
"scriptMs": 25,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 17127,
"image": 10676,
"js": 181608,
"other": 47896
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary.webp&w=750&q=75",
"tag": "img"
},
"load": 466,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 28,
"scriptMs": 20,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 16491,
"image": 4809,
"js": 181608,
"other": 64655
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 458,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 30,
"scriptMs": 18,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 17082,
"image": 4809,
"js": 181608,
"other": 47896
},
"cls": 0,
"fcp": 296,
"inp": 48,
"interaction": "PL",
"lcp": 296,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 470,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 27,
"scriptMs": 20,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 16599,
"image": 9278,
"js": 181608,
"other": 47896
},
"cls": 0,
"fcp": 308,
"inp": 40,
"interaction": "PL",
"lcp": 308,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 462,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 28,
"scriptMs": 19,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 16323,
"image": 0,
"js": 181608,
"other": 47896
},
"cls": 0,
"fcp": 300,
"inp": 40,
"interaction": "PL",
"lcp": 300,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 465,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 24,
"scriptMs": 20,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 36962,
"image": 5263,
"js": 209911,
"other": 47896
},
"cls": 0,
"fcp": 304,
"inp": 40,
"interaction": "PL",
"lcp": 304,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 457,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1g084kp2cldky.css"
],
"requests": 30,
"scriptMs": 39,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 12044,
"font": 209501,
"html": 7747,
"image": 0,
"js": 181608,
"other": 84467
},
"cls": 0,
"fcp": 512,
"inp": 40,
"interaction": "PL",
"lcp": 572,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 507,
"profile": "desktop",
"renderBlocking": [],
"requests": 31,
"scriptMs": 40,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98914,
"font": 0,
"html": 23019,
"image": 0,
"js": 876243,
"other": 1690
},
"cls": 0,
"fcp": 1036,
"inp": null,
"interaction": null,
"lcp": 1036,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 957,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3ebvnk7qs9043.css",
"/_next/static/chunks/1l9apu4iesvci.css",
"/_next/static/chunks/3c_6gydv624zb.css",
"/_next/static/chunks/2h0ajyj_brp--.css",
"/_next/static/chunks/3k6de-uhqm-in.css",
"/_next/static/chunks/1z_mbvpkjhpd5.css",
"/_next/static/chunks/2do7kfo662xwp.css"
],
"requests": 23,
"scriptMs": 413,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 92,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T12:54:41.262Z",
"label": "turbopack-after",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1020,
"coldStartFirstPageMs": 1040,
"firstPageMs": 19,
"ttfb_home": {
"median": 3.3,
"p95": 4.6
},
"ttfb_md": {
"median": 19.5,
"p95": 31
},
"ttfb_sitemap": {
"median": 1.1,
"p95": 1.5
},
"ttfb_llms": {
"median": 28.6,
"p95": 38.8
},
"render": {
"home": {
"medianMs": 36.9,
"queries": 24,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 33,
"media": 9,
"forms": 3
}
},
"page": {
"medianMs": 25.2,
"queries": 21,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3
}
},
"archive": {
"medianMs": 29.1,
"queries": 23,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3,
"posts": 6
}
},
"post": {
"medianMs": 29,
"queries": 26,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 9,
"posts": 15,
"forms": 3
}
},
"caseStudy": {
"medianMs": 25,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 21,
"media": 6,
"casestudies": 9,
"forms": 3
}
},
"form": {
"medianMs": 21,
"queries": 19,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 3,
"forms": 3
}
},
"showcase": {
"medianMs": 48.7,
"queries": 27,
"queryMs": 0,
"byCollection": {
"globals": 24,
"pages": 33,
"media": 12,
"forms": 6,
"posts": 6
}
},
"notFound": {
"medianMs": 19.9,
"queries": 20,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 6,
"pages": 27
}
},
"md": {
"medianMs": 30,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 4,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 42,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 74,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 468
}
}
+753
View File
@@ -0,0 +1,753 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 19872,
"image": 9532,
"js": 184428,
"other": 24705
},
"cls": 0.036,
"fcp": 816,
"inp": 40,
"interaction": "PL",
"lcp": 816,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2440,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 26,
"scriptMs": 76,
"status": 200,
"tbt": 6,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 17099,
"image": 8451,
"js": 184428,
"other": 13035
},
"cls": 0,
"fcp": 800,
"inp": 32,
"interaction": "PL",
"lcp": 800,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2451,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 21,
"scriptMs": 82,
"status": 200,
"tbt": 7,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 16468,
"image": 5316,
"js": 184428,
"other": 18548
},
"cls": 0,
"fcp": 796,
"inp": 32,
"interaction": "PL",
"lcp": 796,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2443,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 22,
"scriptMs": 74,
"status": 200,
"tbt": 6,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 17059,
"image": 5316,
"js": 184428,
"other": 13035
},
"cls": 0,
"fcp": 796,
"inp": 32,
"interaction": "PL",
"lcp": 796,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2450,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 21,
"scriptMs": 77,
"status": 200,
"tbt": 13,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 16558,
"image": 4372,
"js": 184428,
"other": 13035
},
"cls": 0,
"fcp": 816,
"inp": 32,
"interaction": "PL",
"lcp": 816,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2436,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 20,
"scriptMs": 82,
"status": 200,
"tbt": 12,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 16307,
"image": 0,
"js": 184428,
"other": 13035
},
"cls": 0,
"fcp": 808,
"inp": 32,
"interaction": "PL",
"lcp": 808,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2401,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 18,
"scriptMs": 77,
"status": 200,
"tbt": 7,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 36928,
"image": 2016,
"js": 212731,
"other": 24821
},
"cls": 0,
"fcp": 836,
"inp": 40,
"interaction": "PL",
"lcp": 836,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2424,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 25,
"scriptMs": 148,
"status": 200,
"tbt": 9,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 7733,
"image": 0,
"js": 184428,
"other": 68188
},
"cls": 0.319,
"fcp": 2372,
"inp": 32,
"interaction": "PL",
"lcp": 2372,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2531,
"profile": "mobile",
"renderBlocking": [],
"requests": 27,
"scriptMs": 124,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 19872,
"image": 9274,
"js": 184428,
"other": 71365
},
"cls": 0.001,
"fcp": 292,
"inp": 32,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 454,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 33,
"scriptMs": 26,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 17099,
"image": 10676,
"js": 184428,
"other": 47905
},
"cls": 0,
"fcp": 284,
"inp": 32,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary.webp&w=750&q=75",
"tag": "img"
},
"load": 456,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 28,
"scriptMs": 17,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 16468,
"image": 4809,
"js": 184428,
"other": 64679
},
"cls": 0,
"fcp": 284,
"inp": 32,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 459,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 30,
"scriptMs": 17,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 17059,
"image": 4809,
"js": 184428,
"other": 47905
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 459,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 27,
"scriptMs": 18,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 16558,
"image": 9278,
"js": 184428,
"other": 47905
},
"cls": 0,
"fcp": 300,
"inp": 40,
"interaction": "PL",
"lcp": 300,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 460,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 28,
"scriptMs": 19,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 16307,
"image": 0,
"js": 184428,
"other": 47905
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 454,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 24,
"scriptMs": 18,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 36928,
"image": 5263,
"js": 212674,
"other": 47905
},
"cls": 0,
"fcp": 296,
"inp": 40,
"interaction": "PL",
"lcp": 296,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 458,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/05jza-3-ce5bf.css"
],
"requests": 30,
"scriptMs": 41,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 12004,
"font": 209501,
"html": 7733,
"image": 0,
"js": 184428,
"other": 84492
},
"cls": 0,
"fcp": 516,
"inp": 40,
"interaction": "PL",
"lcp": 576,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 513,
"profile": "desktop",
"renderBlocking": [],
"requests": 31,
"scriptMs": 29,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98914,
"font": 0,
"html": 23023,
"image": 0,
"js": 876243,
"other": 1690
},
"cls": 0,
"fcp": 1052,
"inp": null,
"interaction": null,
"lcp": 1052,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 975,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/1l9apu4iesvci.css",
"/_next/static/chunks/3c_6gydv624zb.css",
"/_next/static/chunks/3ebvnk7qs9043.css",
"/_next/static/chunks/2h0ajyj_brp--.css",
"/_next/static/chunks/3k6de-uhqm-in.css",
"/_next/static/chunks/1z_mbvpkjhpd5.css",
"/_next/static/chunks/2do7kfo662xwp.css"
],
"requests": 23,
"scriptMs": 410,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 90,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T12:14:21.329Z",
"label": "turbopack-before",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1455,
"coldStartFirstPageMs": 1478,
"firstPageMs": 22,
"ttfb_home": {
"median": 3.9,
"p95": 6.2
},
"ttfb_md": {
"median": 21,
"p95": 42.4
},
"ttfb_sitemap": {
"median": 0.9,
"p95": 1.5
},
"ttfb_llms": {
"median": 28.5,
"p95": 34
},
"render": {
"home": {
"medianMs": 56.6,
"queries": 43,
"queryMs": 0,
"byCollection": {
"globals": 39,
"media": 24,
"pages": 57,
"forms": 9
}
},
"page": {
"medianMs": 40.5,
"queries": 34,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 48,
"media": 12,
"forms": 6
}
},
"archive": {
"medianMs": 31.7,
"queries": 34,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 45,
"media": 9,
"forms": 6,
"posts": 6
}
},
"post": {
"medianMs": 40.9,
"queries": 41,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 39,
"media": 15,
"posts": 27,
"forms": 6
}
},
"caseStudy": {
"medianMs": 32.5,
"queries": 37,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 36,
"media": 12,
"casestudies": 21,
"forms": 6
}
},
"form": {
"medianMs": 28.2,
"queries": 30,
"queryMs": 0,
"byCollection": {
"globals": 36,
"media": 6,
"pages": 42,
"forms": 6
}
},
"showcase": {
"medianMs": 72.7,
"queries": 42,
"queryMs": 0,
"byCollection": {
"globals": 30,
"pages": 57,
"media": 21,
"forms": 12,
"posts": 6
}
},
"notFound": {
"medianMs": 26.6,
"queries": 25,
"queryMs": 0,
"byCollection": {
"globals": 33,
"pages": 33,
"media": 9
}
},
"md": {
"medianMs": 29,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 2,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 33,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 55,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 308
}
}
+751
View File
@@ -0,0 +1,751 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 19849,
"image": 9532,
"js": 188111,
"other": 24978
},
"cls": 0.036,
"fcp": 800,
"inp": 40,
"interaction": "PL",
"lcp": 800,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2495,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 26,
"scriptMs": 118,
"status": 200,
"tbt": 18,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 17076,
"image": 8451,
"js": 188111,
"other": 13192
},
"cls": 0,
"fcp": 796,
"inp": 32,
"interaction": "PL",
"lcp": 796,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2502,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 21,
"scriptMs": 114,
"status": 200,
"tbt": 19,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 16537,
"image": 5316,
"js": 188111,
"other": 18767
},
"cls": 0,
"fcp": 780,
"inp": 32,
"interaction": "PL",
"lcp": 780,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2489,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 22,
"scriptMs": 116,
"status": 200,
"tbt": 18,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 17062,
"image": 5316,
"js": 188111,
"other": 13192
},
"cls": 0,
"fcp": 796,
"inp": 40,
"interaction": "PL",
"lcp": 796,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2488,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 21,
"scriptMs": 110,
"status": 200,
"tbt": 16,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 16546,
"image": 4372,
"js": 188111,
"other": 13192
},
"cls": 0,
"fcp": 792,
"inp": 40,
"interaction": "PL",
"lcp": 792,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2475,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 20,
"scriptMs": 116,
"status": 200,
"tbt": 20,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 16279,
"image": 0,
"js": 188111,
"other": 13192
},
"cls": 0,
"fcp": 792,
"inp": 32,
"interaction": "PL",
"lcp": 792,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2447,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 18,
"scriptMs": 119,
"status": 200,
"tbt": 23,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 36946,
"image": 2016,
"js": 216357,
"other": 25110
},
"cls": 0,
"fcp": 828,
"inp": 32,
"interaction": "PL",
"lcp": 828,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2464,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 25,
"scriptMs": 170,
"status": 200,
"tbt": 20,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 7694,
"image": 0,
"js": 188111,
"other": 68916
},
"cls": 0.319,
"fcp": 2504,
"inp": 40,
"interaction": "PL",
"lcp": 2504,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2587,
"profile": "mobile",
"renderBlocking": [],
"requests": 27,
"scriptMs": 194,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 19849,
"image": 9274,
"js": 188111,
"other": 72052
},
"cls": 0.001,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 482,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 33,
"scriptMs": 46,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 17076,
"image": 10676,
"js": 188111,
"other": 48402
},
"cls": 0,
"fcp": 292,
"inp": 32,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary.webp&w=750&q=75",
"tag": "img"
},
"load": 464,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 28,
"scriptMs": 28,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 16537,
"image": 4809,
"js": 188111,
"other": 65348
},
"cls": 0,
"fcp": 288,
"inp": 40,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 468,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 30,
"scriptMs": 32,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 17062,
"image": 4809,
"js": 188111,
"other": 48402
},
"cls": 0,
"fcp": 288,
"inp": 48,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 469,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 27,
"scriptMs": 32,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 16546,
"image": 9278,
"js": 188111,
"other": 48402
},
"cls": 0,
"fcp": 300,
"inp": 40,
"interaction": "PL",
"lcp": 300,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 468,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 28,
"scriptMs": 28,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 16279,
"image": 0,
"js": 188111,
"other": 48402
},
"cls": 0,
"fcp": 300,
"inp": 40,
"interaction": "PL",
"lcp": 300,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 475,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 24,
"scriptMs": 31,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 36946,
"image": 5263,
"js": 216414,
"other": 48402
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 457,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/3ca5a494a33af0a8.css"
],
"requests": 30,
"scriptMs": 50,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11042,
"font": 209501,
"html": 7694,
"image": 0,
"js": 188111,
"other": 85469
},
"cls": 0,
"fcp": 512,
"inp": 48,
"interaction": "PL",
"lcp": 576,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 505,
"profile": "desktop",
"renderBlocking": [],
"requests": 31,
"scriptMs": 44,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98168,
"font": 0,
"html": 23081,
"image": 0,
"js": 843270,
"other": 1690
},
"cls": 0,
"fcp": 1024,
"inp": null,
"interaction": null,
"lcp": 1024,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 950,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/de3d54fcc6ee5dc6.css",
"/_next/static/css/c1e0b959dd828ab8.css",
"/_next/static/css/e5d1b6185968e333.css",
"/_next/static/css/4858144d3215dfc6.css",
"/_next/static/css/dc48c3ee3f159f65.css"
],
"requests": 20,
"scriptMs": 350,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 93,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T12:39:24.391Z",
"label": "webpack-after",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1040,
"coldStartFirstPageMs": 1068,
"firstPageMs": 26,
"ttfb_home": {
"median": 3.7,
"p95": 5.4
},
"ttfb_md": {
"median": 26.7,
"p95": 31.9
},
"ttfb_sitemap": {
"median": 1.4,
"p95": 1.8
},
"ttfb_llms": {
"median": 36.4,
"p95": 53.7
},
"render": {
"home": {
"medianMs": 51,
"queries": 24,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 33,
"media": 9,
"forms": 3
}
},
"page": {
"medianMs": 33.8,
"queries": 21,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3
}
},
"archive": {
"medianMs": 42.1,
"queries": 23,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 6,
"pages": 27,
"forms": 3,
"posts": 6
}
},
"post": {
"medianMs": 40.6,
"queries": 26,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 9,
"posts": 15,
"forms": 3
}
},
"caseStudy": {
"medianMs": 30.8,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 21,
"media": 6,
"casestudies": 9,
"forms": 3
}
},
"form": {
"medianMs": 28.9,
"queries": 19,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 3,
"forms": 3
}
},
"showcase": {
"medianMs": 61.8,
"queries": 27,
"queryMs": 0,
"byCollection": {
"globals": 24,
"pages": 33,
"media": 12,
"forms": 6,
"posts": 6
}
},
"notFound": {
"medianMs": 26.4,
"queries": 20,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6
}
},
"md": {
"medianMs": 30,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 3,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 41,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 65,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 440
}
}
+751
View File
@@ -0,0 +1,751 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 19829,
"image": 9532,
"js": 191323,
"other": 24973
},
"cls": 0.036,
"fcp": 800,
"inp": 32,
"interaction": "PL",
"lcp": 800,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2492,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 26,
"scriptMs": 124,
"status": 200,
"tbt": 24,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 17074,
"image": 8451,
"js": 191323,
"other": 13185
},
"cls": 0,
"fcp": 788,
"inp": 40,
"interaction": "PL",
"lcp": 788,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2508,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 21,
"scriptMs": 117,
"status": 200,
"tbt": 22,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 16520,
"image": 5316,
"js": 191323,
"other": 18759
},
"cls": 0,
"fcp": 796,
"inp": 32,
"interaction": "PL",
"lcp": 796,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2495,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 22,
"scriptMs": 118,
"status": 200,
"tbt": 22,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 17019,
"image": 5316,
"js": 191323,
"other": 13185
},
"cls": 0,
"fcp": 788,
"inp": 32,
"interaction": "PL",
"lcp": 788,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2502,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 21,
"scriptMs": 122,
"status": 200,
"tbt": 22,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 16514,
"image": 4372,
"js": 191323,
"other": 13185
},
"cls": 0,
"fcp": 792,
"inp": 32,
"interaction": "PL",
"lcp": 792,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2487,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 20,
"scriptMs": 121,
"status": 200,
"tbt": 24,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 16262,
"image": 0,
"js": 191323,
"other": 13185
},
"cls": 0,
"fcp": 792,
"inp": 32,
"interaction": "PL",
"lcp": 792,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2453,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 18,
"scriptMs": 118,
"status": 200,
"tbt": 23,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 36904,
"image": 2016,
"js": 219569,
"other": 25103
},
"cls": 0,
"fcp": 832,
"inp": 40,
"interaction": "PL",
"lcp": 832,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3",
"tag": "img"
},
"load": 2474,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 25,
"scriptMs": 185,
"status": 200,
"tbt": 25,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 7675,
"image": 0,
"js": 191323,
"other": 68911
},
"cls": 0.319,
"fcp": 2488,
"inp": 32,
"interaction": "PL",
"lcp": 2488,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2400,
"profile": "mobile",
"renderBlocking": [],
"requests": 27,
"scriptMs": 195,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 19829,
"image": 9274,
"js": 191323,
"other": 72045
},
"cls": 0.001,
"fcp": 288,
"inp": 32,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 471,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 33,
"scriptMs": 40,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 17074,
"image": 10676,
"js": 191323,
"other": 48398
},
"cls": 0,
"fcp": 316,
"inp": 40,
"interaction": "PL",
"lcp": 316,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary.webp&w=750&q=75",
"tag": "img"
},
"load": 488,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 28,
"scriptMs": 32,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 16520,
"image": 4809,
"js": 191323,
"other": 65341
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 472,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 30,
"scriptMs": 34,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 17019,
"image": 4809,
"js": 191323,
"other": 48398
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 471,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 27,
"scriptMs": 33,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 16514,
"image": 9278,
"js": 191323,
"other": 48398
},
"cls": 0,
"fcp": 304,
"inp": 40,
"interaction": "PL",
"lcp": 304,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 468,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 28,
"scriptMs": 31,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 16262,
"image": 0,
"js": 191323,
"other": 48398
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 470,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 24,
"scriptMs": 34,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 36904,
"image": 5263,
"js": 219626,
"other": 48398
},
"cls": 0,
"fcp": 300,
"inp": 40,
"interaction": "PL",
"lcp": 300,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 467,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/42cf443dc3526fb0.css"
],
"requests": 30,
"scriptMs": 44,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11023,
"font": 209501,
"html": 7675,
"image": 0,
"js": 191323,
"other": 85467
},
"cls": 0,
"fcp": 516,
"inp": 32,
"interaction": "PL",
"lcp": 580,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 509,
"profile": "desktop",
"renderBlocking": [],
"requests": 31,
"scriptMs": 44,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98168,
"font": 0,
"html": 23080,
"image": 0,
"js": 843253,
"other": 1690
},
"cls": 0,
"fcp": 1044,
"inp": null,
"interaction": null,
"lcp": 1044,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 963,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/de3d54fcc6ee5dc6.css",
"/_next/static/css/dc48c3ee3f159f65.css",
"/_next/static/css/c1e0b959dd828ab8.css",
"/_next/static/css/e5d1b6185968e333.css",
"/_next/static/css/4858144d3215dfc6.css"
],
"requests": 20,
"scriptMs": 349,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 87,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T11:54:21.044Z",
"label": "webpack-before",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1243,
"coldStartFirstPageMs": 1270,
"firstPageMs": 25,
"ttfb_home": {
"median": 3.5,
"p95": 5.3
},
"ttfb_md": {
"median": 30.4,
"p95": 40.8
},
"ttfb_sitemap": {
"median": 1.1,
"p95": 1.5
},
"ttfb_llms": {
"median": 26.8,
"p95": 39.6
},
"render": {
"home": {
"medianMs": 94.6,
"queries": 43,
"queryMs": 1,
"byCollection": {
"globals": 39,
"media": 24,
"pages": 57,
"forms": 9
}
},
"page": {
"medianMs": 54,
"queries": 34,
"queryMs": 1,
"byCollection": {
"globals": 36,
"pages": 48,
"media": 12,
"forms": 6
}
},
"archive": {
"medianMs": 62.8,
"queries": 34,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 45,
"media": 9,
"forms": 6,
"posts": 6
}
},
"post": {
"medianMs": 61.1,
"queries": 41,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 39,
"media": 15,
"posts": 27,
"forms": 6
}
},
"caseStudy": {
"medianMs": 32.6,
"queries": 37,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 36,
"media": 12,
"casestudies": 21,
"forms": 6
}
},
"form": {
"medianMs": 28.1,
"queries": 30,
"queryMs": 0,
"byCollection": {
"globals": 36,
"pages": 42,
"media": 6,
"forms": 6
}
},
"showcase": {
"medianMs": 68.3,
"queries": 42,
"queryMs": 0,
"byCollection": {
"globals": 30,
"pages": 57,
"media": 21,
"forms": 12,
"posts": 6
}
},
"notFound": {
"medianMs": 28.5,
"queries": 25,
"queryMs": 0,
"byCollection": {
"globals": 33,
"media": 9,
"pages": 33
}
},
"md": {
"medianMs": 24,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 2,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 36,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 63,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 340
}
}
+27 -2
View File
@@ -2,7 +2,8 @@
`iapl-doctor` checks a site against the team's rules and lists every gap with a fix hint and a doc link. It covers
what drifts between sites: versions, Node, the folder layout, database names, env rules, security headers, 2FA, the
cookie scanner, the admin preview, the agent guide, seeds, the block library, and the running site.
cookie scanner, the admin preview, the agent guide, seeds, the block library, speed (images, fonts, embeds,
render-blocking resources, animations, budgets), and the running site.
Related: [AGENT.md §11](./agent/AGENT.md), the `iapl-doctor` skill, [deployment.md](./deployment.md),
[seeding.md](./seeding.md), [security.md](./security.md), [blocks.md](./blocks.md).
@@ -66,9 +67,17 @@ Added by `iapl` and **off until the site has `IAPL_DOCTOR_TOKEN`** (at least 32
returns counts only — never names, e-mails or values:
```json
{ "mail": { "graphEnv": false, "relay": { "connected": true, "disconnected": false, "nameReplaced": false, "state": "active" }, "replyAddress": true, "status": null, "transport": "relay" }, "node": "v22.20.0", "openSignUp": [], "pendingCookies": 0, "plugin": "1.15.0", "staffOnOwnRoles": [], "staffOpenToOthers": [], "turnstile": null, "turnstileSecretFromEnv": false, "usersSetupClosed": 0, "usersWithout2fa": 0 }
{ "mail": { "graphEnv": false, "relay": { "connected": true, "disconnected": false, "nameReplaced": false, "state": "active" }, "replyAddress": true, "status": null, "transport": "relay" }, "media": { "images": 42, "oversized": 0, "tooWide": 0 }, "node": "v22.20.0", "openSignUp": [], "pendingCookies": 0, "plugin": "1.15.0", "staffOnOwnRoles": [], "staffOpenToOthers": [], "turnstile": null, "turnstileSecretFromEnv": false, "usersSetupClosed": 0, "usersWithout2fa": 0 }
```
`growth` (since 1.18.0): per collection its documents, its size with indexes (MongoDB; `null` elsewhere) and the date
of its oldest record; versions per versioned collection and global with their limit; `payload-kv` entries and how
many have expired; media no document points at (`checked` documents read, at most 5000); the retention in days of
each plugin log — counts, sizes and dates only.
`media` (since 1.18.0): how many images the upload collections hold and how many are over the plugin's limits
(1.5 MB, 2560 px) — counts only, `null` without an upload collection.
`mail` (since 1.17.0): the e-mail transport in effect, the recorded state of sending and the site's state with the
Intecion mail service — states and codes only, never a token, a password or an address; `relay` is `null` when the
mail service is switched off.
@@ -135,6 +144,21 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
| | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` |
| | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` |
| | `blocks-tokens` | error / warning | from `iapl-audit`: hex colours, the token standard not wired, `iapl-tokens --check` |
| performance | `perf-images-config` | warning | `next.config` uses `buildImagesConfig()` (AVIF / WebP, R2, long cache) — [performance.md](./performance.md) |
| | `perf-fonts` | warning | no font from Google / Typekit hosts, no `font-display: block`, every `@font-face` has `font-display`, at most two `next/font` families |
| | `perf-render-blocking` | warning | no `<script src>` without `async` / `defer`, no stylesheet `<link>` or CSS `@import` from another host |
| | `perf-embeds` | warning | no `<iframe>` (map, widget) that loads with the page — a click-to-load facade, or `loading="lazy"`; YouTube is `iapl-audit`'s |
| | `perf-animations` | warning | no transition of a layout property or `transition-all`, no `scroll` listener, something honours `prefers-reduced-motion` when the site animates |
| | `perf-budgets` | info | a project that runs Playwright has a performance budget test in `e2e/` (the `iapl-performance` skill's template) |
| | `perf-live` | warning | (live) the home HTML is compressed, has no blocking `<script>` in `<head>`, preloads at most four fonts, its first image in `<main>` is not lazy, and is at most 150 KB |
| | `perf-images` | warning | (deep) no stored image over 1.5 MB or 2560 px wide (`IMAGE_RULES`) |
| growth | `growth-size` | warning | (deep) no collection over `growth.maxDocs` (200 000) documents or `growth.maxMB` (512, data + indexes, MongoDB) — [performance.md](./performance.md) §6 |
| | `growth-versions` | warning | (deep) no collection or global keeps versions without a limit (`maxPerDoc` / `max`: 0), none over `growth.maxVersions` (50 000) |
| | `growth-retention` | warning | (deep) a log with a retention (consent log, statistics, form submissions with `submissionRetentionDays`) holds no record older than it — its purge runs |
| | `growth-submissions` | info / warning | (deep) form submissions kept without a retention; a warning when the oldest is over `growth.submissionDays` (730) |
| | `growth-kv` | warning | (deep) at most `growth.expiredKv` (1000) expired entries in `payload-kv` |
| | `growth-media` | info / warning | (deep) media no document or global points at; a warning over `growth.orphanedMedia` (25). From the first 5000 documents |
| | `growth-disk` | info | `.next/cache/images` over `growth.imageCacheMB` (1024), the local `media/` over `growth.uploadsMB` (2048), on the machine the doctor runs on |
| audit | `i18n-literals` | error / warning | from `iapl-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `iapl-audit` skill) |
| | `audit:<title>` | as reported | every other `iapl-audit --quick` finding, one per file |
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `iapl-seo-check` error and warning |
@@ -170,6 +194,7 @@ of the two exists, `iapl-doctor.json` when both do):
|---|---|
| `domain` | the production domain (dots allowed) — the base of the database names. Without it: a non-local `NEXT_PUBLIC_SERVER_URL`, else the folder name minus `-web` |
| `launched` | the site is live: seeds must then name their records. Also true when "Project decisions" has a line with "launch" and a date |
| `growth` | thresholds of the `growth` rules: `maxDocs`, `maxMB`, `maxVersions`, `submissionDays`, `expiredKv`, `orphanedMedia`, `imageCacheMB`, `uploadsMB` ([performance.md](./performance.md) §6) |
| `layout.allow` | more top-level `src/` entries the convention allows |
| `layout.frontend` | the folder that holds the site's pages, e.g. `src/app/(site)` — only for a layout the doctor cannot tell (two route groups with pages); the route group's name is otherwise free |
| `rules.<id>` | `off` (silence), `severity` (`error` / `warning` / `info`), `reason` (**required** — an entry without one is ignored and reported), `until` (ISO date; after it the entry stops applying and the report says so), `files` (globs: only findings in those files). The id is the rule (`csp`) or an audit finding (`audit:collections-present`); `audit` covers all audit findings |
+1
View File
@@ -60,6 +60,7 @@ iapl({
| `formOverrides` / `formSubmissionOverrides` | — | collection overrides (`fields` as a function + any collection settings) |
| `emailLayout` | `false` | nice emails + the Site settings → E-mails tab |
| `beforeEmail` | — | the form-builder's `beforeEmail` (after the layout, when `emailLayout`) |
| `submissionRetentionDays` | — (kept) | 1.18.0: delete submissions older than this many days (checked at most once a day, after a new submission). Submissions are personal data — set it on the client's decision (AGENTS.md → Project decisions); the doctor's `growth-submissions` reports a site without one ([performance.md](./performance.md) §6) |
| `consentFieldName` | `'consent'` | name of the GDPR consent field for `submitForm` / `createSubmitAction` (the call's argument wins) |
`payment` is always off — `fields: { payment: true }` does **not** turn it on (the value `true`
+1 -1
View File
@@ -163,7 +163,7 @@ export const Pages: CollectionConfig = {
fields: [
// ...
{ name: 'slugHistory', type: 'array', admin: { readOnly: true },
fields: [{ name: 'slug', type: 'text' }] },
fields: [{ name: 'slug', type: 'text', index: true }] }, // index: asked on every unknown URL (resolveRedirect)
],
hooks: { beforeChange: [trackSlugHistoryHook] },
}
+2 -1
View File
@@ -12,7 +12,8 @@ schema until you use it.
with a `srcSet` from every Payload image size.
- `RenderRichText lightbox` (`/rsc`) — click-to-enlarge for images in rich text.
- `useLightbox()` (`/client`) — open, close, next, previous for your own controls.
- `<LightboxDialog>` (`/client`) — the viewer itself, controlled, for full control.
- `<LightboxDialog>` (`/client`) — the viewer itself, controlled, for full control. Since 1.18.0 the provider loads it
the first time an image is opened (a separate chunk), so a page carries only the small provider and the triggers.
## What the visitor gets
+3 -1
View File
@@ -132,12 +132,14 @@ export function Media({ resource, priority, className }: Props) {
}
```
**`mediaImageProps(resource, { alt?, sizes?, priority?, placeholderColor? })`** → `next/image`
**`mediaImageProps(resource, { alt?, sizes?, priority?, eager?, placeholderColor? })`** → `next/image`
props or `null` (video, PDF, a bare id, no `width`/`height`):
- `width`/`height` from the document (no layout shift), `alt` from the document (override: `alt`, `''` for decoration);
- `sizes` defaults to `'100vw'` — give the real width (`MEDIA_SIZES`);
- `priority: true` (one LCP image per page) → `loading="eager"`, `fetchPriority="high"`, `preload`
(Next 16); otherwise `loading="lazy"`;
- `eager: true` (1.18.0; above the fold but not the LCP image — a header logo) → `loading="eager"` without
`fetchPriority` or a preload, so it does not compete with the one `priority` image; the library's `<Media eager>` too;
- focal point (≠ 50/50) → `style.objectPosition`;
- `placeholder.blurDataURL` → `placeholder="blur"`;
- `placeholder.color` → `style.backgroundColor` per `placeholderColor`: `'auto'` (default — JPEG only,
+5
View File
@@ -104,6 +104,11 @@ export default createNotFoundPage(content, { load: loadNotFoundView })
```
(`fallback` with JSX → file `notFoundView.tsx`.)
**Layout shift (1.18.0: `placeholder`).** The lazy content comes after hydration, so the footer moves when it arrives
(measured on the reference site: CLS 0.32 and LCP 2.5 s on a phone, [performance.md](./performance.md)). A block as tall
as your 404 content keeps the footer still: `createNotFoundPage(content, { load, placeholder: <div style={{ minHeight: '36rem' }} /> })`.
Default: nothing, as before. A fixed one-screen block is no fix: shorter content then pulls the footer up into view.
**Why lazy:** Next puts the layout's `not-found` tree into the RSC data (`self.__next_f`) of **every** page
under it — the router needs it for a client-side 404. The immediate variant renders the 404 page from the admin panel there
in every language, so every page carries it in its HTML (404 = home page with 2 languages: home page HTML
+195
View File
@@ -0,0 +1,195 @@
# Performance — a light, fast site by default
What the plugin does for speed without any project work, what a project must still do, the budgets every site is
held to, how to measure, and how to read the doctor's findings. The agent's short version is AGENT.md §6.11b and the
`iapl-performance` skill. The measurements and the audit behind this page: [dev/perf/README.md](./dev/perf/README.md).
Related: [media.md](./media.md), [frontend.md](./frontend.md), [consent.md](./consent.md), [doctor.md](./doctor.md),
[design-tokens.md](./design-tokens.md).
Targets on the built site, a phone on a slow connection (the numbers Google uses, [web.dev/articles/vitals](https://web.dev/articles/vitals)):
**LCP < 2.5 s, CLS < 0.1, INP < 200 ms.** The reference site measures LCP 0.8 s, CLS 0–0.04 and a 32–48 ms tap
response on that profile (the 404 page is the exception, below).
## 1. What the plugin does for you
| Area | Default | Change it |
|---|---|---|
| Static pages | `createPageRoute` + `generateStaticParams` + `revalidate`: every page is prerendered (ISR); nothing in the layout reads `headers()` or `cookies()`, so the HTML is cached and the server answers in ~4 ms | your own `render`; never call `headers()` in the layout ([nextjs.org/docs/app/guides/caching](https://nextjs.org/docs/app/guides/caching)) |
| Data per render | the `lib/content` helpers cache every read per request (`getSettings`, `resolveRoute`, `generatePageMetadata`, `getSiteShell`), keyed by value; Site settings at depth 1; one Site integrations read shared by analytics and Turnstile; reads that need one field `select` it | `createContentHelpers({ settingsDepth })`; your own getters with `cache()` |
| LCP image | `<Media priority>`: `fetchpriority="high"`, `loading="eager"` and a preload; everything else lazy with `sizes` | `priority` / `eager` / `sizes` per image (`MEDIA_SIZES`) |
| Image formats | `buildImagesConfig()`: AVIF and WebP, the width the screen needs, a 31-day cache, R2 allowed | `buildImagesConfig({ … })` ([media.md](./media.md)) |
| Upload limits | `buildOptimizeUploadHook()`: images over 1.5 MB or 2560 px wide are stopped; the editor may let the plugin shrink them (WebP, metadata dropped) | `maxImageBytes`, `maxImageWidth`, `quality` |
| No layout shift from images | width and height always from the document; a blur placeholder and the dominant colour (`buildMediaPlaceholderHook`) | `placeholderColor` |
| Embeds | `<YouTubeEmbed>`: a picture and a button; the iframe only after a click, from youtube-nocookie.com | `poster` |
| Client JavaScript | small client leaves; since 1.18.0 a page ships only the client components it renders (the `/client` barrels are no longer one client boundary) and the lightbox viewer loads on the first open | — |
| Third parties before consent | none besides Google's tag in Consent Mode `advanced` (all signals denied); Meta, LinkedIn, TikTok and Clarity wait for consent; Turnstile only on a form's last step | `analytics={{ consentMode: 'basic' }}` — no request to Google before consent; `analytics={{ defer: true }}` — the tag after the first interaction |
| Fonts | the reference layout uses `next/font` (self-hosted, `display: 'swap'`, fallback metrics against layout shift) | the project's own fonts |
| Motion | the token durations (`duration-fast`, `-base`, `-slow`) are 0 ms with `prefers-reduced-motion: reduce`; the cookie banner, its switches and the cookie button stop their transitions too | `motion-reduce:` classes |
| Admin only | Payload's colour-scheme client hints only on `/admin`, so a public page is requested once | `withSecurityConfig(…, { adminClientHints: false })` |
## 2. What a project must do
Every row is something the plugin cannot decide for you. `iapl-doctor --only performance` finds most of them.
**Page loading** ([web.dev/articles/optimize-lcp](https://web.dev/articles/optimize-lcp))
- Exactly one `<Media priority>` per page: the first image a visitor sees (the library's hero does this itself via
`leadsWithImage`). A header logo is `<Media eager>` — at once, but without competing with the hero.
- Nothing render-blocking but the one stylesheet: no `<script src>` without `async` in the layout (use `next/script`
or the plugin's `ConsentScript` / `Analytics`), no stylesheet or `@import` from another host
([web.dev/articles/render-blocking-resources](https://web.dev/articles/render-blocking-resources)).
- Keep the page static: no `headers()`, `cookies()` or `searchParams` in the layout or page tree.
**Elements** ([web.dev/articles/cls](https://web.dev/articles/cls))
- Images through `Media` (dimensions, `sizes`, lazy below the fold, never lazy for the LCP image —
[web.dev/articles/lcp-lazy-loading](https://web.dev/articles/lcp-lazy-loading)).
- Content that arrives after the first paint reserves its space. The lazy 404 is the plugin's own case:
`createNotFoundPage(content, { load, placeholder: <div style={{ minHeight: '36rem' }} /> })` with the height of your
404 content keeps the footer still.
- Maps, videos and widgets behind a click: a picture and a button ([web.dev/articles/third-party-facades](https://web.dev/articles/third-party-facades)).
**Fonts** ([web.dev/articles/font-best-practices](https://web.dev/articles/font-best-practices),
[nextjs.org/docs/app/getting-started/fonts](https://nextjs.org/docs/app/getting-started/fonts))
- `next/font` only, at most two families, variable fonts, `subsets: ['latin', 'latin-ext']` for Polish,
`display: 'swap'`. Every subset of every family is a preloaded file: two variable families with two subsets are
four files (the reference site: 209 KB). A third family or a second weight file is the first thing to cut.
**Animations** ([web.dev/articles/animations-guide](https://web.dev/articles/animations-guide),
[web.dev/articles/prefers-reduced-motion](https://web.dev/articles/prefers-reduced-motion))
- Only `transform` and `opacity`; never `height`, `top`, `margin`, `transition-all`.
- Reduced motion honoured: the token durations do it; anything else gets `motion-reduce:` or a media query.
- No work per `scroll` event: IntersectionObserver for "is it on screen", at most one update per frame
(`requestAnimationFrame`) for a reading position (the plugin's `TableOfContents` does this since 1.18.0).
**Resources** ([web.dev/articles/reduce-javascript-payloads-with-code-splitting](https://web.dev/articles/reduce-javascript-payloads-with-code-splitting))
- Server components by default; `'use client'` on the small interactive leaf, not the section.
- Compression on: Next compresses by itself; behind Coolify's proxy check that the HTML arrives with
`Content-Encoding` (`iapl-doctor --url` does). Next names its static files by content and serves them
`immutable` — nothing to do.
- No third-party request before consent (the consent rules, [consent.md](./consent.md)).
**Images** ([web.dev/articles/serve-images-avif-webp](https://web.dev/articles/serve-images-avif-webp),
[nextjs.org/docs/app/api-reference/components/image](https://nextjs.org/docs/app/api-reference/components/image))
- `images: buildImagesConfig()` in `next.config`; `buildOptimizeUploadHook()` and `buildMediaPlaceholderHook()` on the
media collection (the reference `Media.ts`).
- `sizes` = the width on screen (`MEDIA_SIZES.half`, `.third`, …): without it a phone downloads the full width.
- Images uploaded before the limits: `iapl-doctor --deep` counts those over 1.5 MB or 2560 px.
**Server** ([payloadcms.com/docs/queries/depth](https://payloadcms.com/docs/queries/depth),
[payloadcms.com/docs/queries/select](https://payloadcms.com/docs/queries/select))
- Read through `lib/content` (cached per request). Your own getters: `cache()` with primitive arguments — React
compares arguments by identity, so an array or an object argument never hits the cache.
- `depth` as low as the page needs; `select` when you need one field; no `findByID` in a loop.
- An index on fields you query: `index: true` on the slug (the plugin's `buildSlugField` does), on `slugHistory.slug`
(old addresses, asked on every unknown URL), on anything you filter a list by.
## 3. Budgets
The plugin's defaults (`PERF_BUDGETS` from `@intecion/ipal-kit/doctor`), per page, first visit:
| | Phone (Slow 4G, CPU 4×) | Desktop |
|---|---|---|
| LCP | 2500 ms | 1200 ms |
| CLS | 0.1 | 0.1 |
| INP (one scripted tap, Event Timing) | 200 ms | 100 ms |
| Total Blocking Time | 200 ms | 100 ms |
| JavaScript (compressed) | 250 KB | 250 KB |
| CSS (compressed) | 50 KB | 50 KB |
| Fonts | 250 KB | 250 KB |
| Requests | 40 | 50 |
| Render-blocking resources | 2 | 2 |
| Third-party origins before consent | none | none |
| Database queries per render (`SERVER_BUDGET`) | 40 | |
A project tightens them to what it measured (`perfBudgets({ mobile: { jsBytes: 200_000 } })`) in
`e2e/performance.spec.ts` (the `iapl-performance` skill's template): from then on the test fails when a change
makes a page slower. The reference site's gate (`reference/e2e/performance.spec.ts`, run by `pnpm e2e:built` with
both bundlers) holds each page type to its own numbers and counts the database queries of one render.
## 4. How to measure
- **The lab, per page** — `perf-lab.mjs` (the skill's `resources/`, the reference site's `e2e/`): Chromium with
Lighthouse's profiles (phone 412×823, Slow 4G — 150 ms, 1.6 Mbit/s — and a 4× slower CPU; desktop 1350×940,
40 ms, 10 Mbit/s), an empty cache, the median of several runs. It returns TTFB, FCP, LCP and the LCP element, CLS,
TBT, the response to one tap, script time, bytes per type, requests, render-blocking resources and third-party
origins.
- **The plugin repository** — `pnpm perf:measure --label=<name> --mongo-container=<docker name>` on the built
reference site: the lab numbers for eight page types on both profiles, the panel's sign-in page, cold start,
memory, TTFB, and the database queries of one render of each page (MongoDB's profiler; the render bypasses the ISR
cache with Next's own `x-prerender-revalidate` header). JSON in `docs/dev/perf/`.
- **The running site** — `pnpm exec iapl-doctor --url https://example.pl --only perf-live`, and PageSpeed Insights
for the field data of real visitors (28 days).
- Never measure `next dev`: it compiles on request and ships unminified code.
## 5. The doctor's findings
All in the `performance` group (`iapl-doctor --only performance`), warnings in 1.18.0 (`perf-budgets` is info):
| Rule | Source | It means | Fix |
|---|---|---|---|
| `perf-images-config` | static | `next.config` has no `buildImagesConfig()` | `images: buildImagesConfig()` |
| `perf-fonts` | static | a font from Google / Typekit, `font-display: block`, `@font-face` without `font-display`, more than two families | `next/font`, `display: 'swap'`, two families |
| `perf-render-blocking` | static | a `<script src>` without `async` / `defer`, a stylesheet or `@import` from another host | `next/script`, the plugin's script components, self-host |
| `perf-embeds` | static | an `<iframe>` (map, widget) that loads with the page (YouTube is `iapl-audit`'s) | a facade (picture + button), or `loading="lazy"` below the fold |
| `perf-animations` | static | a transition of a layout property, `transition-all`, a `scroll` listener, animations with nothing for reduced motion | `transform` / `opacity`, IntersectionObserver, `motion-reduce:` |
| `perf-budgets` | static | the project runs Playwright but has no performance budget test in `e2e/` | the skill's template |
| `perf-live` | `--url` | the HTML is not compressed; blocking scripts in `<head>`; more than four preloaded fonts; the first image in `<main>` is lazy; the home HTML over 150 KB | proxy compression; `async`; fewer font files; `priority`; less data to client components |
| `perf-images` | `--deep` | images stored over 1.5 MB or 2560 px wide | re-upload prepared, or tick "Optimise large image" |
Silence a finding with a reason in `iapl-doctor.json` like any other ([doctor.md](./doctor.md)).
## 6. What grows — keeping the site and its database small over the years
Measured on the reference site after a full test run (MongoDB; average record without indexes): a consent record
185 B, a form submission 647 B, a key-value entry 371 B, a page 9 KB. Every collection also carries 2–6 indexes.
| What | Grows with | What the plugin does (1.18.0) | What the project decides |
|---|---|---|---|
| Consent log (`consent-records`) | one record per banner choice | deleted after `retentionDays` (default 1095 — three years, the proof-of-consent period); the purge runs at most once a day, after a new record | `consentLog: { retentionDays }` |
| Statistics (`stats-visits`, opt-in) | one record per visit | deleted after `retentionDays` (default 90), same purge | `stats: { retentionDays }` |
| Form submissions | one per sent form (files are never stored: they go out by e-mail) | **kept** until deleted in the panel — unless `forms: { submissionRetentionDays }` is set (1.18.0), then deleted after that many days, once a day after a new submission | the retention: personal data, a client decision (AGENTS.md → Project decisions) |
| Versions and drafts | every save | the plugin turns versions on nowhere; Payload keeps 100 per document by default (`maxPerDoc`, `max` for globals) | a lower limit where you turn versions on: `versions: { maxPerDoc: 20 }`; never `0` (unlimited) |
| `payload-kv` | 2FA attempt counters (one per staff account), the mail service state (one per host), enrolment nonces | expired mail-service nonces are swept (at most once a day, when the next enrolment starts); counters and state are bounded by accounts and hosts | — |
| Cookie review (opt-in) | distinct cookie names | upserted by name; a cookie that disappears is marked `gone`, not deleted (the history of what the site set) | delete old `gone` rows in the panel when the client agrees |
| `payload-preferences`, `payload-locked-documents`, `payload-jobs` | panel users, open documents, queued jobs | Payload removes them with the user, on save, and on completion (`deleteJobOnComplete`); the plugin queues no jobs | — |
| Media | uploads | Payload deletes the files (and R2 objects) with the document; nothing deletes media nobody uses | review `growth-media` findings in the panel |
| `.next/cache/images` | each image × width × format (AVIF + WebP) | kept 31 days per variant (`minimumCacheTTL`); Next caps nothing by size | no persistent volume on `.next` in Coolify: every deploy starts empty |
| ISR output | pages × languages | rewritten in place on each revalidation | — |
| Logs | — | the plugin writes no files; it logs to stdout (Coolify keeps the container's log) | Coolify's log retention |
**Postgres and SQLite:** the same purges (one `DELETE … WHERE created_at < …`); no TTL indexes; the doctor reports
counts but not sizes. A consent log without its migration records nothing and so never purges.
**What a project schedules:** nothing for the plugin's own logs — the purges run inside the site. A site that gets
no new consent records (or submissions) for a long time keeps the old ones until the next one comes; the doctor's
`growth-retention` rule says so. Database backups are the hosting's job (Coolify → the MongoDB resource → Backups).
**How to check:** `pnpm exec iapl-doctor --deep --only growth` (or `--url` with `IAPL_DOCTOR_TOKEN`): document
counts, sizes (MongoDB), the oldest record, versions per collection and global, expired KV entries, media no
document points at; and on the machine it runs on, the image cache and the local upload folder. Thresholds in
`iapl-doctor.json`:
```json
{ "growth": { "maxDocs": 200000, "maxMB": 512, "maxVersions": 50000, "submissionDays": 730, "expiredKv": 1000, "orphanedMedia": 25, "imageCacheMB": 1024, "uploadsMB": 2048 } }
```
| Rule | Source | It means |
|---|---|---|
| `growth-size` | deep | a collection over `maxDocs` documents or `maxMB` (data + indexes, MongoDB) |
| `growth-versions` | deep | a collection or global keeps versions without a limit, or over `maxVersions` |
| `growth-retention` | deep | a log with a retention holds records older than it: its purge has not run |
| `growth-submissions` | deep | form submissions kept without a retention (info; a warning when the oldest is over `submissionDays`) |
| `growth-kv` | deep | more than `expiredKv` expired entries in `payload-kv` |
| `growth-media` | deep | media nothing points at (info; a warning over `orphanedMedia`). Counted from the first 5000 documents |
| `growth-disk` | static | `.next/cache/images` over `imageCacheMB`, the local `media/` folder over `uploadsMB` (info) |
None of these rules deletes anything; the plugin never deletes media or submissions by itself.
## 7. Shared with IAWL
IAWL (the WordPress line) holds its sites to the same numbers where the measurement is the same: the Core Web Vitals
targets and lab profile, JS ≤ 250 KB, CSS ≤ 50 KB, fonts ≤ 250 KB and two families, requests ≤ 40 on the phone,
one render-blocking stylesheet, no third-party origin before consent, and the image rules (`IMAGE_RULES`): uploads
≤ 1.5 MB and ≤ 2560 px, served as AVIF / WebP in the width the screen needs, metadata dropped on conversion, one
high-priority LCP image, lazy below the fold. The database budget is per product (Payload counts MongoDB queries per
render; WordPress counts SQL queries per request).
+3 -2
View File
@@ -118,15 +118,16 @@
"cookie-db:refresh": "node scripts/refresh-cookie-database.mjs",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
"dev": "next dev dev --turbo",
"e2e:built": "node scripts/e2e-built.mjs",
"legacy:site": "node scripts/legacy-site-check.mjs",
"dev:generate-importmap": "pnpm dev:payload generate:importmap",
"dev:generate-types": "pnpm dev:payload generate:types",
"dev:payload": "cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload",
"e2e:built": "node scripts/e2e-built.mjs",
"generate:importmap": "pnpm dev:generate-importmap",
"generate:types": "pnpm dev:generate-types",
"legacy:site": "node scripts/legacy-site-check.mjs",
"lint": "eslint ./src ./test",
"lint:fix": "eslint ./src ./test --fix",
"perf:measure": "node scripts/perf-measure.mjs",
"prepare": "pnpm build",
"prepublishOnly": "pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate",
"reference:index": "node scripts/reference-index.mjs",
@@ -42,6 +42,13 @@ classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warnin
next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and
`iapl-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error.
## Speed (AGENT.md §6.11b, docs/performance.md)
The full run (not `--quick`) lists the doctor's `performance` group as warnings: `next.config` without
`buildImagesConfig()`, fonts from Google or with `display: 'block'`, more than two families, a blocking `<script src>`
or a remote stylesheet, an `<iframe>` that loads with the page, transitions of layout properties, `transition-all`,
`scroll` listeners, animations with nothing for reduced motion. The `iapl-performance` skill measures the built site and
adds the budget test.
## iapl-audit and iapl-doctor
`iapl-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec iapl-doctor` checks the **site**
against the team standard: it runs this script (`--quick`) from the installed package, reports its findings under its
@@ -362,6 +362,14 @@ if [ -n "$UI" ]; then
done
fi
# --- Speed (§6.11b, performance.md) — the doctor's performance group: images config, fonts, render-blocking,
# embeds, animations, a budget test. Full mode only: the doctor itself runs this audit with --quick.
if [ "$QUICK" -eq 0 ] && [ -x node_modules/.bin/iapl-doctor ]; then
PERF=$(node_modules/.bin/iapl-doctor --only performance --offline --json 2>/dev/null \
| node -e 'let s="";process.stdin.on("data",(d)=>(s+=d)).on("end",()=>{try{for(const f of JSON.parse(s).findings){if(!f.silenced&&f.severity!=="info"){console.log(`${f.file??"(site)"} [${f.rule}] ${f.message}`)}}}catch{}})')
report WARNING "speed (iapl-doctor --only performance)" "§6.11b / performance.md — each line names the rule; iapl-performance skill" "$PERF"
fi
# --- Compile & build ---
if [ "$QUICK" -eq 0 ]; then
echo
@@ -0,0 +1,66 @@
---
name: iapl-performance
description: Makes and keeps an IAPL site fast — page loading (LCP image, fonts, nothing render-blocking, static rendering), elements (lazy below the fold, reserved space, click-to-load embeds), animations (transform/opacity, reduced motion, no scroll handlers), resources (only the JS a page uses, compression, no third-party request before consent), images (AVIF/WebP, sizes, upload limits) and the server (queries per render, depth, select, caching); what grows in the database and on disk over the years (logs and their retention, form submissions, versions, KV, unused media, the image cache). Measures the built site, runs the doctor's performance group, and adds the budget gate that fails when a change makes the site slower. Use when building pages or blocks, before handing over, after an IAPL upgrade, and whenever "slow", PageSpeed, Lighthouse, Core Web Vitals, LCP, CLS, INP, a growing database or disk come up.
---
# iapl-performance
The handbook is `node_modules/@intecion/ipal-kit/docs/performance.md`: what the plugin does for you, what the project
must do, how to measure, how to read the findings. This skill is the order of work.
## 1. Check what the plugin cannot do for you (code)
```bash
pnpm exec iapl-doctor --only performance # images config, fonts, render-blocking, embeds, animations, budget test
bash .agents/skills/iapl-audit/scripts/audit.sh --quick # <img>/<video> outside Media, priority outside the hero, YouTube iframe, h-screen
```
Fix every warning — each names the file, the fix and the doc. The rules that matter most:
| Area | Do | Never |
|---|---|---|
| LCP image | `<Media priority>` on the first image of the page — **one** per page; a header logo gets `eager` | `priority` on many images; a lazy hero; the hero as a CSS background |
| other images | `<Media sizes={MEDIA_SIZES.third}>` — the width on screen; lazy by default | no `sizes`; a plain `<img>` |
| fonts | `next/font` (self-hosted), ≤ 2 families, variable, `display: 'swap'` | a `<link>` to Google Fonts; `display: 'block'` |
| scripts | the plugin's `Analytics` / `ConsentScript`; `next/script` for anything else | a `<script src>` without `async` in the layout |
| embeds | `<YouTubeEmbed>`; a map or widget behind a click (a picture + a button) | an `<iframe>` that loads with the page |
| animations | `transform` / `opacity` only; the token durations (`duration-fast`) or `motion-reduce:` | animating `height`, `top`, `margin`; `transition-all`; a `scroll` listener (use IntersectionObserver) |
| client code | small `'use client'` leaves; server components by default | a whole section `'use client'` |
| server | the plugin's cached helpers (`lib/content`), `depth` as low as the page needs, `select` for one field | `findGlobal` without `cache()`; `depth: 2` "to be safe"; a query per list item |
## 2. Measure the built site
```bash
pnpm build && pnpm start # dev numbers mean nothing
pnpm exec iapl-doctor --url http://localhost:3000 --only perf-live # compression, blocking scripts, preloads, lazy hero, HTML size
pnpm exec iapl-doctor --deep --only perf-images # stored images over 1.5 MB / 2560 px
```
Lab numbers per page (phone on Slow 4G with a 4× slower CPU, and desktop): copy `resources/perf-lab.mjs` and
`resources/performance.spec.template.ts` (→ `e2e/performance.spec.ts`), list one page of each template, run
`pnpm test:e2e e2e/performance.spec`, then set each budget to what you measured plus ~20 %. From then on the test fails when
a change makes a page slower. PageSpeed Insights on the deployed site shows the field data (real visitors).
## 3. Read the result
- **LCP** > 2.5 s on the phone: the LCP element is named in the measurement (`lcpElement`). An image → `priority`,
`sizes`, a smaller upload; text → a font that arrives late (fewer preloaded files).
- **CLS** > 0.1: an image without dimensions (use `Media`), content that arrives after hydration (the lazy 404 —
`createNotFoundPage({ load, placeholder })`), a font swap (next/font sets fallback metrics).
- **TBT / INP**: long tasks — a big client component, a scroll handler, a third-party widget at start.
- **JS bytes**: what the page ships; import client components from `@intecion/ipal-kit/client` freely — since
1.18.0 a page carries only the ones it renders.
- **Queries per render** (the reference gate counts them): over 30 for an ordinary page → a missing `cache()`, a
`depth` too high, or a loop of `findByID`.
## 4. What grows (performance.md §6)
```bash
pnpm exec iapl-doctor --deep --only growth # counts and sizes per collection, oldest records, versions, expired KV, unused media, disk
```
- Logs purge themselves (consent log 1095 days, statistics 90). Form submissions are kept unless
`iapl({ forms: { submissionRetentionDays } })` — ask the client (personal data) and record it in AGENTS.md.
- Versions: where you turn them on, `versions: { maxPerDoc: 20 }` (globals `max`); never `0`.
- Unused media (`growth-media`): list them for the client; the plugin never deletes media or submissions by itself.
- Coolify: no persistent volume on `.next` (the image cache starts empty on each deploy); database backups on the
MongoDB resource.
- Thresholds of the findings: `iapl-doctor.json` → `growth`.
## 5. Before "done"
`iapl-doctor --only performance` without warnings (or each one silenced with a reason in `iapl-doctor.json`),
the budget test green, and the numbers in `AGENTS.md` → "Project decisions" when the client accepted an exception
(a heavy font, a third-party widget).
@@ -0,0 +1,175 @@
/**
* Lab measurements of one page in Chromium (Playwright + the DevTools protocol) — used by `pnpm perf:measure`
* (scripts/perf-measure.mjs, numbers for docs/performance.md) and by the budget gate (e2e/performance.spec.ts).
*
* Profiles follow Lighthouse's defaults so the numbers compare with PageSpeed Insights' lab data:
* - mobile: 412×823 at DPR 1.75, "Slow 4G" (150 ms RTT, 1.6 Mbit/s down, 750 kbit/s up), CPU 4× slower;
* - desktop: 1350×940, 40 ms RTT, 10 Mbit/s, CPU 1×.
* Every run is a fresh browser context (empty HTTP cache, no cookies): a first visit, the worst ordinary case.
*
* What is measured (all from the browser itself, web.dev/articles/vitals):
* ttfb, fcp, lcp (+ the LCP element: tag, src, loading, fetchpriority), cls (session windows, as web-vitals does),
* tbt (sum of long-task time over 50 ms between FCP and the end of the run: the lab stand-in for INP),
* inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button),
* scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type
* (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to
* another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are
* counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run.
* Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host
* cannot hold the page's load event, and the numbers are the site's own.
*/
import { chromium } from '@playwright/test'
export const PROFILES = {
desktop: { cpu: 1, network: { downloadThroughput: (10 * 1024 * 1024) / 8, latency: 40, uploadThroughput: (10 * 1024 * 1024) / 8 }, viewport: { deviceScaleFactor: 1, height: 940, isMobile: false, width: 1350 } },
mobile: { cpu: 4, network: { downloadThroughput: (1.6 * 1024 * 1024) / 8, latency: 150, uploadThroughput: (750 * 1024) / 8 }, viewport: { deviceScaleFactor: 1.75, hasTouch: true, height: 823, isMobile: true, width: 412 } },
}
const OBSERVERS = `(() => {
const v = (window.__perf = { cls: 0, events: [], lcp: null, longTasks: [] })
let win = 0, winStart = 0, winLast = 0
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
const el = e.element
v.lcp = { at: e.startTime, size: e.size, tag: el ? el.tagName.toLowerCase() : null, src: e.url || null,
loading: el && el.getAttribute ? el.getAttribute('loading') : null,
fetchpriority: el && el.getAttribute ? el.getAttribute('fetchpriority') : null }
} }).observe({ buffered: true, type: 'largest-contentful-paint' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
if (e.hadRecentInput) continue
if (win && e.startTime - winLast < 1000 && e.startTime - winStart < 5000) { win += e.value } else { win = e.value; winStart = e.startTime }
winLast = e.startTime
v.cls = Math.max(v.cls, win)
} }).observe({ buffered: true, type: 'layout-shift' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.longTasks.push([e.startTime, e.duration]) }).observe({ buffered: true, type: 'longtask' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.events.push({ d: e.duration, n: e.name }) }).observe({ buffered: true, durationThreshold: 16, type: 'event' })
})()`
/**
* @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number,
* fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number,
* lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string },
* load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number,
* status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement
*/
const typeOf = (resourceType, mime = '') => {
if (resourceType === 'Document') {return 'html'}
if (resourceType === 'Script') {return 'js'}
if (resourceType === 'Stylesheet') {return 'css'}
if (resourceType === 'Font') {return 'font'}
if (resourceType === 'Image' || mime.startsWith('image/')) {return 'image'}
return 'other'
}
/**
* @param {import('@playwright/test').Browser} browser
* @param {string} url
* @param {'mobile'|'desktop'} profileName
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
* @returns {Promise<PageMeasurement>}
*/
export async function measurePage(browser, url, profileName, options = {}) {
const profile = PROFILES[profileName]
const context = await browser.newContext({ ...profile.viewport, viewport: { height: profile.viewport.height, width: profile.viewport.width } })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
await cdp.send('Network.enable')
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network })
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
await cdp.send('Performance.enable')
await page.addInitScript(OBSERVERS)
const origin = new URL(url).origin
if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())}
const requests = new Map()
let prefetches = 0
cdp.on('Network.requestWillBeSent', (e) => {
if (e.request.url.startsWith('data:')) {return}
if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return}
requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })
})
cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} })
cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} })
const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' })
await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {})
await page.waitForTimeout(options.settleMs ?? 1000)
let interaction = null
if (options.interact !== false) {
// INP stand-in: one click on the first visible button (menu toggle, cookie settings, theme): a real handler runs
const button = page.locator('button:visible').first()
if (await button.count()) {
interaction = (await button.getAttribute('aria-label')) ?? (await button.innerText()).slice(0, 40)
await button.click({ timeout: 5000 }).catch(() => { interaction = null })
await page.waitForTimeout(500)
}
}
const nav = await page.evaluate(() => {
const n = performance.getEntriesByType('navigation')[0]
const fcp = performance.getEntriesByName('first-contentful-paint')[0]
const blocking = performance.getEntriesByType('resource').filter((r) => r.renderBlockingStatus === 'blocking').map((r) => r.name)
return { blocking, domContentLoaded: n.domContentLoadedEventEnd, fcp: fcp ? fcp.startTime : null, load: n.loadEventEnd, ttfb: n.responseStart }
})
const vitals = await page.evaluate(() => window.__perf)
const { metrics } = await cdp.send('Performance.getMetrics')
const metric = (name) => metrics.find((m) => m.name === name)?.value ?? 0
await context.close()
const list = [...requests.values()]
const bytes = { css: 0, font: 0, html: 0, image: 0, js: 0, other: 0 }
for (const r of list) {bytes[r.type] += r.bytes}
const fcp = nav.fcp ?? 0
const tbt = vitals.longTasks.filter(([start]) => start >= fcp).reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0)
const round = (n) => (n == null ? null : Math.round(n))
return {
bytes: Object.fromEntries(Object.entries(bytes).map(([k, b]) => [k, Math.round(b)])),
cls: Math.round(vitals.cls * 1000) / 1000,
fcp: round(nav.fcp),
inp: vitals.events.length ? round(Math.max(...vitals.events.map((e) => e.d))) : interaction ? 0 : null,
interaction,
lcp: round(vitals.lcp?.at),
lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null,
load: round(nav.load),
prefetches,
profile: profileName,
renderBlocking: nav.blocking.map((u) => u.replace(origin, '')),
requests: list.length,
scriptMs: round(metric('ScriptDuration') * 1000),
status: response?.status() ?? null,
tbt: round(tbt),
thirdParty: [...new Set(list.filter((r) => !r.url.startsWith(origin)).map((r) => new URL(r.url).origin))],
ttfb: round(nav.ttfb),
url: url.replace(origin, ''),
}
}
export const median = (values) => {
const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b)
if (!sorted.length) {return null}
const mid = Math.floor(sorted.length / 2)
return sorted.length % 2 ? sorted[mid] : Math.round(((sorted[mid - 1] + sorted[mid]) / 2) * 1000) / 1000
}
/**
* The median of `runs` measurements for every number; the rest from the last run.
* @param {import('@playwright/test').Browser} browser
* @param {string} url
* @param {'mobile'|'desktop'} profileName
* @param {number} [runs]
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
* @returns {Promise<PageMeasurement>}
*/
export async function measureMedian(browser, url, profileName, runs = 3, options = {}) {
const all = []
for (let i = 0; i < runs; i++) {all.push(await measurePage(browser, url, profileName, options))}
const last = all.at(-1)
const out = { ...last, runs }
for (const key of ['cls', 'fcp', 'inp', 'lcp', 'load', 'requests', 'scriptMs', 'tbt', 'ttfb']) {out[key] = median(all.map((r) => r[key]))}
out.bytes = Object.fromEntries(Object.keys(last.bytes).map((k) => [k, median(all.map((r) => r.bytes[k]))]))
return out
}
export const launch = () => chromium.launch()
@@ -0,0 +1,48 @@
// e2e/performance.spec.ts — the project's performance budget gate (iapl-performance skill, docs/performance.md).
// Copy this file and perf-lab.mjs (same folder) to e2e/. Runs against the BUILT site: pnpm build && pnpm test:e2e.
// It fails when a page breaks a budget: the plugin's defaults (Core Web Vitals "good", bytes, requests), tightened
// below to what this site measured, so a change that makes it slower fails. Loosen a number only with a reason.
import type { Browser } from '@playwright/test'
import { overBudget, perfBudgets } from '@intecion/ipal-kit/doctor'
import { chromium, expect, test } from '@playwright/test'
// a plain ES module (JSDoc types) — perf-lab.mjs from the skill's resources
import { measureMedian } from './perf-lab.mjs'
const runs = Number(process.env.PERF_RUNS ?? 1)
// Start from the defaults; after the first run, set each number to what you measured plus ~20 % (the lab is noisy).
const budgets = perfBudgets({
desktop: {},
mobile: {},
})
// One page of each template the site has (AGENTS.md → Site map). `budget` changes a number for one page, with a reason.
const PAGES: Array<{ budget?: Partial<typeof budgets.mobile>; name: string; path: string }> = [
{ name: 'home', path: '/pl' },
// { name: 'page', path: '/pl/o-nas' },
// { name: 'post', path: '/pl/blog/<a-post>' },
// { name: 'form', path: '/pl/kontakt', budget: { thirdParty: ['https://challenges.cloudflare.com'] } }, // Turnstile
]
let browser: Browser
test.beforeAll(async () => {
browser = await chromium.launch()
})
test.afterAll(async () => {
await browser?.close()
})
for (const page of PAGES) {
for (const profile of ['mobile', 'desktop'] as const) {
test(`${page.name} (${profile}) stays within its performance budget`, async ({ baseURL }) => {
test.setTimeout(120_000)
// third-party requests are recorded, then aborted: an external host cannot fail or hang the test
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 }), type: 'measured' })
expect(overBudget(measured, { ...budgets[profile], ...page.budget }), `${page.path} ${profile}`).toEqual([])
if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, 'the LCP image is lazy').not.toBe('lazy')}
})
}
}
@@ -218,6 +218,7 @@ Mandatory set: AGENT.md §0b, skill **iapl-setup**; checks: **iapl-audit**, **ia
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → E-mail sending → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **iapl-form** |
| forms — retention | config (client decision) | `forms: { submissionRetentionDays: 365 }` (1.18.0; default: kept) | `iapl-doctor --deep --only growth-submissions` quiet; old submissions gone a day after the next submission | performance.md §6, forms.md |
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Spam protection or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
@@ -338,7 +338,7 @@ Opt-in with `iapl({ cookieScanner: true })`; the plugin wires the collection, en
|---|---|---|
| `createContentHelpers({ config, content?, i18n?, baseUrl?, … })` | `@intecion/ipal-kit` | factory for `src/lib/content.ts`: cached `getCachedPayload`, `getSettings`, `resolveRoute`, `getEntries`, `generatePageMetadata`, `getSiteShell`, `sitemap`, `robots`, `getRobots`, `isPathVisible`, `markdownRoute`, `healthRoute`, `mcpGET`/`mcpPOST`… — do not write these wrappers yourself |
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
| `createNotFoundPage(content, { load, placeholder? } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended; `placeholder` (1.18.0) reserves the 404 content's height until it arrives — no layout shift, performance.md) |
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); `nonce` (from `x-nonce`) goes on the theme script and the GA4/GTM tag; does not mount `AlternateLinksProvider` |
@@ -454,7 +454,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission (and, with `forms.submissionRetentionDays`, deletes older ones at most once a day); returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
@@ -532,7 +532,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `mediaImageProps(resource, { sizes?, priority?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>` |
| `mediaImageProps(resource, { sizes?, priority?, eager?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>`. `eager` (1.18.0): above the fold but not the LCP image (a logo) — eager without high priority or a preload |
| `videoProps(resource, { mode?, poster?, reducedMotion? })` | `@intecion/ipal-kit` | `<video>` attributes for a video upload (`'background'`: autoplay/muted/loop; `'player'`: controls, `preload="none"`) or `null` |
| `MEDIA_SIZES` | `@intecion/ipal-kit` | Ready constant `sizes` values: `full`, `half`, `third`, `quarter`, `thumb` |
| `normalizeFilename(filename)` | `@intecion/ipal-kit` | Slugifies a file name, keeping the extension (`"Zdjęcie 1.JPG"` → `"zdjecie-1.jpg"`) |
@@ -881,7 +881,10 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `iapl-doctor.json` wins. |
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `media` (images over `IMAGE_RULES`, 1.18.0), `plugin`, `node`. |
| `PERF_BUDGETS`, `SERVER_BUDGET`, `perfBudgets(overrides)`, `overBudget(measured, budget)`, `IMAGE_RULES` | `@intecion/ipal-kit/doctor` | Performance budgets (1.18.0, performance.md): the defaults per profile (`mobile`, `desktop`: `lcp`, `cls`, `inp`, `tbt`, `jsBytes`, `cssBytes`, `fontBytes`, `requests`, `renderBlocking`, `thirdParty`) and per render (`queriesPerRender`); a project's own on top; the broken budgets of one measurement as lines (empty = within budget); the image limits (1.5 MB, 2560 px, AVIF/WebP). Types `PerfBudget`, `PerfMeasurement`, `PerfProfile`, `ServerBudget`. The gate: `iapl-performance/resources/performance.spec.template.ts` + `perf-lab.mjs`. |
| `collectGrowth(payload)` → `GrowthStatus`, `growthRules`, `GROWTH_DEFAULTS`, `folderBytes(dir)` | `@intecion/ipal-kit/doctor` | What grows (1.18.0, performance.md §6): per collection documents, bytes (MongoDB) and the oldest record; versions per collection and global with their limit; `payload-kv` entries and expired ones; media no document points at (first 5000 documents) — counts only. The `growth` rules (`growth-size`, `-versions`, `-retention`, `-submissions`, `-kv`, `-media`, `-disk`) and their default thresholds (`iapl-doctor.json` → `growth`, type `GrowthThresholds`). |
| `performanceRules` | `@intecion/ipal-kit/doctor` | The doctor's `performance` group (`perf-images-config`, `perf-fonts`, `perf-render-blocking`, `perf-embeds`, `perf-animations`, `perf-budgets`, `perf-live`, `perf-images`) — part of `doctorRules`. |
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. |
| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. |
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
+175
View File
@@ -0,0 +1,175 @@
/**
* Lab measurements of one page in Chromium (Playwright + the DevTools protocol) — used by `pnpm perf:measure`
* (scripts/perf-measure.mjs, numbers for docs/performance.md) and by the budget gate (e2e/performance.spec.ts).
*
* Profiles follow Lighthouse's defaults so the numbers compare with PageSpeed Insights' lab data:
* - mobile: 412×823 at DPR 1.75, "Slow 4G" (150 ms RTT, 1.6 Mbit/s down, 750 kbit/s up), CPU 4× slower;
* - desktop: 1350×940, 40 ms RTT, 10 Mbit/s, CPU 1×.
* Every run is a fresh browser context (empty HTTP cache, no cookies): a first visit, the worst ordinary case.
*
* What is measured (all from the browser itself, web.dev/articles/vitals):
* ttfb, fcp, lcp (+ the LCP element: tag, src, loading, fetchpriority), cls (session windows, as web-vitals does),
* tbt (sum of long-task time over 50 ms between FCP and the end of the run: the lab stand-in for INP),
* inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button),
* scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type
* (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to
* another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are
* counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run.
* Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host
* cannot hold the page's load event, and the numbers are the site's own.
*/
import { chromium } from '@playwright/test'
export const PROFILES = {
desktop: { cpu: 1, network: { downloadThroughput: (10 * 1024 * 1024) / 8, latency: 40, uploadThroughput: (10 * 1024 * 1024) / 8 }, viewport: { deviceScaleFactor: 1, height: 940, isMobile: false, width: 1350 } },
mobile: { cpu: 4, network: { downloadThroughput: (1.6 * 1024 * 1024) / 8, latency: 150, uploadThroughput: (750 * 1024) / 8 }, viewport: { deviceScaleFactor: 1.75, hasTouch: true, height: 823, isMobile: true, width: 412 } },
}
const OBSERVERS = `(() => {
const v = (window.__perf = { cls: 0, events: [], lcp: null, longTasks: [] })
let win = 0, winStart = 0, winLast = 0
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
const el = e.element
v.lcp = { at: e.startTime, size: e.size, tag: el ? el.tagName.toLowerCase() : null, src: e.url || null,
loading: el && el.getAttribute ? el.getAttribute('loading') : null,
fetchpriority: el && el.getAttribute ? el.getAttribute('fetchpriority') : null }
} }).observe({ buffered: true, type: 'largest-contentful-paint' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
if (e.hadRecentInput) continue
if (win && e.startTime - winLast < 1000 && e.startTime - winStart < 5000) { win += e.value } else { win = e.value; winStart = e.startTime }
winLast = e.startTime
v.cls = Math.max(v.cls, win)
} }).observe({ buffered: true, type: 'layout-shift' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.longTasks.push([e.startTime, e.duration]) }).observe({ buffered: true, type: 'longtask' })
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.events.push({ d: e.duration, n: e.name }) }).observe({ buffered: true, durationThreshold: 16, type: 'event' })
})()`
/**
* @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number,
* fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number,
* lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string },
* load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number,
* status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement
*/
const typeOf = (resourceType, mime = '') => {
if (resourceType === 'Document') {return 'html'}
if (resourceType === 'Script') {return 'js'}
if (resourceType === 'Stylesheet') {return 'css'}
if (resourceType === 'Font') {return 'font'}
if (resourceType === 'Image' || mime.startsWith('image/')) {return 'image'}
return 'other'
}
/**
* @param {import('@playwright/test').Browser} browser
* @param {string} url
* @param {'mobile'|'desktop'} profileName
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
* @returns {Promise<PageMeasurement>}
*/
export async function measurePage(browser, url, profileName, options = {}) {
const profile = PROFILES[profileName]
const context = await browser.newContext({ ...profile.viewport, viewport: { height: profile.viewport.height, width: profile.viewport.width } })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
await cdp.send('Network.enable')
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network })
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
await cdp.send('Performance.enable')
await page.addInitScript(OBSERVERS)
const origin = new URL(url).origin
if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())}
const requests = new Map()
let prefetches = 0
cdp.on('Network.requestWillBeSent', (e) => {
if (e.request.url.startsWith('data:')) {return}
if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return}
requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })
})
cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} })
cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} })
const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' })
await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {})
await page.waitForTimeout(options.settleMs ?? 1000)
let interaction = null
if (options.interact !== false) {
// INP stand-in: one click on the first visible button (menu toggle, cookie settings, theme): a real handler runs
const button = page.locator('button:visible').first()
if (await button.count()) {
interaction = (await button.getAttribute('aria-label')) ?? (await button.innerText()).slice(0, 40)
await button.click({ timeout: 5000 }).catch(() => { interaction = null })
await page.waitForTimeout(500)
}
}
const nav = await page.evaluate(() => {
const n = performance.getEntriesByType('navigation')[0]
const fcp = performance.getEntriesByName('first-contentful-paint')[0]
const blocking = performance.getEntriesByType('resource').filter((r) => r.renderBlockingStatus === 'blocking').map((r) => r.name)
return { blocking, domContentLoaded: n.domContentLoadedEventEnd, fcp: fcp ? fcp.startTime : null, load: n.loadEventEnd, ttfb: n.responseStart }
})
const vitals = await page.evaluate(() => window.__perf)
const { metrics } = await cdp.send('Performance.getMetrics')
const metric = (name) => metrics.find((m) => m.name === name)?.value ?? 0
await context.close()
const list = [...requests.values()]
const bytes = { css: 0, font: 0, html: 0, image: 0, js: 0, other: 0 }
for (const r of list) {bytes[r.type] += r.bytes}
const fcp = nav.fcp ?? 0
const tbt = vitals.longTasks.filter(([start]) => start >= fcp).reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0)
const round = (n) => (n == null ? null : Math.round(n))
return {
bytes: Object.fromEntries(Object.entries(bytes).map(([k, b]) => [k, Math.round(b)])),
cls: Math.round(vitals.cls * 1000) / 1000,
fcp: round(nav.fcp),
inp: vitals.events.length ? round(Math.max(...vitals.events.map((e) => e.d))) : interaction ? 0 : null,
interaction,
lcp: round(vitals.lcp?.at),
lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null,
load: round(nav.load),
prefetches,
profile: profileName,
renderBlocking: nav.blocking.map((u) => u.replace(origin, '')),
requests: list.length,
scriptMs: round(metric('ScriptDuration') * 1000),
status: response?.status() ?? null,
tbt: round(tbt),
thirdParty: [...new Set(list.filter((r) => !r.url.startsWith(origin)).map((r) => new URL(r.url).origin))],
ttfb: round(nav.ttfb),
url: url.replace(origin, ''),
}
}
export const median = (values) => {
const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b)
if (!sorted.length) {return null}
const mid = Math.floor(sorted.length / 2)
return sorted.length % 2 ? sorted[mid] : Math.round(((sorted[mid - 1] + sorted[mid]) / 2) * 1000) / 1000
}
/**
* The median of `runs` measurements for every number; the rest from the last run.
* @param {import('@playwright/test').Browser} browser
* @param {string} url
* @param {'mobile'|'desktop'} profileName
* @param {number} [runs]
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
* @returns {Promise<PageMeasurement>}
*/
export async function measureMedian(browser, url, profileName, runs = 3, options = {}) {
const all = []
for (let i = 0; i < runs; i++) {all.push(await measurePage(browser, url, profileName, options))}
const last = all.at(-1)
const out = { ...last, runs }
for (const key of ['cls', 'fcp', 'inp', 'lcp', 'load', 'requests', 'scriptMs', 'tbt', 'ttfb']) {out[key] = median(all.map((r) => r[key]))}
out.bytes = Object.fromEntries(Object.keys(last.bytes).map((k) => [k, median(all.map((r) => r.bytes[k]))]))
return out
}
export const launch = () => chromium.launch()
+112
View File
@@ -0,0 +1,112 @@
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()
}
})
})
+1 -1
View File
@@ -28,7 +28,7 @@ export const Pages: CollectionConfig = {
{ name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 },
buildSummaryField(), // aiSummary — GEO (llms.txt, MCP)
buildNoindexField(),
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } },
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text', index: true }], labels: { plural: 'Old addresses', singular: 'Old address' } },
],
hooks: {
afterChange: [revalidate.afterChange],
+1 -1
View File
@@ -24,7 +24,7 @@ export async function Header({ header, locale, settings, themeLabel }: Props) {
<header className="sticky top-0 z-header border-b border-border bg-surface-raised/95 backdrop-blur">
<Container className="flex items-center justify-between gap-6 py-4">
<Link className="flex items-center gap-3 font-heading text-h4 text-fg-strong" href={home}>
{logo ? <Media alt="" className="h-8 w-auto" Image={Image} priority resource={logo} sizes="160px" /> : null}
{logo ? <Media alt="" className="h-8 w-auto" eager Image={Image} resource={logo} sizes="160px" /> : null}
<span>{typeof settings?.siteName === 'string' ? settings.siteName : null}</span>
</Link>
<nav aria-label={header.menuLabel ?? undefined} className="hidden md:block">
+4 -4
View File
@@ -2,9 +2,8 @@ import { faqItemsFromLayout } from '@intecion/ipal-kit/blocks'
// @starter:if localBusiness
import { buildLocalBusinessJsonLd, createContentHelpers } from '@intecion/ipal-kit'
import { getPayload } from 'payload'
import { contentConfig } from '@/content.config'
import { i18nConfig, type Locale } from '@/i18n.config'
import { i18nConfig } from '@/i18n.config'
// @starter:else
//: import { createContentHelpers } from '@intecion/ipal-kit'
//:
@@ -65,8 +64,9 @@ export const {
// @starter:if localBusiness
// LocalBusiness from the Company global (replaces the default WebSite + Organization from Site settings)
siteJsonLd: async ({ baseUrl, locale }) => {
const payload = await getPayload({ config })
const company = await payload.findGlobal({ slug: 'company', locale: locale as Locale })
// the layout's cached getter: one Company read per request, not two (docs/performance.md → server)
const { getCompany } = await import('./globals')
const company = await getCompany(locale)
return [
buildLocalBusinessJsonLd({
address: { city: company.address?.city ?? undefined, country: company.address?.country ?? 'PL', postalCode: company.address?.postalCode ?? undefined, street: company.address?.street ?? undefined },
+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)',
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
// Role predicates for client components (the main entry reaches 'server-only' modules and does not build
// there with webpack). Concrete file, not the access barrel. On the server import them from the main entry.
export { hasMinimumRole, isAdmin, isEditor } from '../modules/access/predicates.js'
+9
View File
@@ -7,12 +7,17 @@
*/
export { DOCTOR_USAGE, expandSites, parseDoctorArgs, runDoctorCli } from '../modules/doctor/cli.js'
export { formatDriftTable, formatReport } from '../modules/doctor/format.js'
// What grows (docs/performance.md → "What grows"): the deep collector, the rules and their thresholds
export { collectGrowth } from '../modules/doctor/growth.js'
export type { GrowthStatus } from '../modules/doctor/growth.js'
export { bareHost, createDoctorContext, loadDoctorConfig, parseEnvFile, readAuditSkips } from '../modules/doctor/project.js'
export type { DoctorContext } from '../modules/doctor/project.js'
export { planSkills } from '../modules/doctor/rules/agents.js'
export { folderBytes, GROWTH_DEFAULTS, growthRules } from '../modules/doctor/rules/growth.js'
export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.js'
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
export { performanceRules } from '../modules/doctor/rules/performance.js'
export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js'
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
export type { RunDoctorOptions } from '../modules/doctor/run.js'
@@ -29,6 +34,10 @@ export type {
DoctorStatus,
RuleFinding,
} from '../modules/doctor/types.js'
export type { GrowthThresholds } from '../modules/doctor/types.js'
// Performance budgets (docs/performance.md): the defaults, a project's own on top, and the check the gate runs
export { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets, SERVER_BUDGET } from '../modules/performance/budgets.js'
export type { PerfBudget, PerfMeasurement, PerfProfile, ServerBudget } from '../modules/performance/budgets.js'
// routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged")
export { runRouteCheck } from '../modules/security/routeCheck.js'
export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js'
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'
export { A11Y_DEFAULT_TEXTS, AccessibilityWidget } from './AccessibilityWidget.js'
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { Analytics } from './Analytics.js'
export type { AnalyticsProps } from './Analytics.js'
// Low-level pixel loaders — exported for manual conversion events if a project
+4 -2
View File
@@ -12,6 +12,8 @@ export type MediaProps = {
/** Override the document's alt text — `''` for a decorative image. */
alt?: string
className?: string
/** Above the fold, not the LCP image (a logo): eager, without fetchPriority="high" or a preload. */
eager?: boolean
poster?: MediaValue
/** Only the first visible image of the page (the LCP image). */
priority?: boolean
@@ -25,14 +27,14 @@ export type MediaProps = {
* Every image or video of the library blocks. With `Image` (next/image, bound by createBlockRegistry)
* images are optimized with blur-up; without it a plain <img> with width, height, lazy loading and focal point.
*/
export function Media({ alt, className, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
export function Media({ alt, className, eager = false, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
const video = videoProps(resource, { mode: videoMode, poster })
if (video) {
// Captions are not stored with media uploads; a project that needs them swaps Media (ui option).
// eslint-disable-next-line jsx-a11y/media-has-caption
return <video {...video} aria-hidden={videoMode === 'background' ? true : undefined} className={className} />
}
const img = mediaImageProps(resource, { priority, sizes, ...(alt !== undefined ? { alt } : {}) })
const img = mediaImageProps(resource, { eager, priority, sizes, ...(alt !== undefined ? { alt } : {}) })
if (!img) {return null}
if (Image) {return <Image {...img} className={className} />}
const { blurDataURL: _blur, placeholder: _placeholder, preload: _preload, ...plain } = img
+3 -3
View File
@@ -136,7 +136,7 @@ const defaults: Required<CookieBannerClassNames> = {
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]`,
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform motion-reduce:transition-none translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
cookie: `flex flex-col gap-1 border-t pt-2 first:border-t-0 first:pt-0 ${border}`,
cookieList: 'mt-3 flex flex-col gap-2',
cookieMeta: `grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs ${mutedText}`,
@@ -168,7 +168,7 @@ const defaults: Required<CookieBannerClassNames> = {
const DETAILED_DIALOG = `relative max-h-[90vh] w-full max-w-4xl overflow-y-auto ${radius} border p-6 shadow-2xl sm:p-8 ${surface} ${border}`
const SWITCH_TRACK =
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors motion-reduce:transition-none data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
type CookieBannerProps = {
classNames?: CookieBannerClassNames
@@ -358,7 +358,7 @@ export function CookieBanner({
return (
<details className={cn('cookies')} data-ipal="cookies">
<summary className={cn('cookiesToggle')}>
<svg aria-hidden="true" className="transition-transform group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
<svg aria-hidden="true" className="transition-transform motion-reduce:transition-none group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
<path d="m9 18 6-6-6-6" />
</svg>
{labels.cookies} ({rows.length})
+1 -1
View File
@@ -79,7 +79,7 @@ export function CookieButton({ avoid, className, reserve = COOKIE_BUTTON_RESERVE
const cls =
className ??
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] ' +
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] motion-reduce:transition-none ' +
'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))] border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]'
const position: CSSProperties = className
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.js'
export { readEffectiveConsent } from './consentStore.js'
+2
View File
@@ -141,6 +141,8 @@ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Prom
slug: settingsSlug as never,
depth: 1,
locale: 'all' as never,
// only the privacy page: without it depth 1 brought every page Site settings points at, in every language
select: { privacyPolicy: true } as never,
})) as { privacyPolicy?: unknown }
const page = settings.privacyPolicy
return page && typeof page === 'object' ? (page as PrivacyPage) : null
+140
View File
@@ -0,0 +1,140 @@
import type { BasePayload } from 'payload'
/**
* What grows in the database (docs/performance.md → "What grows"): read-only counts for the doctor's `growth` rules.
* Counts, sizes and dates only — never a value. Every read is capped, so the check stays cheap on a big site.
*/
export type GrowthStatus = {
/** Every collection (the plugin's, the project's and Payload's own): documents, bytes on MongoDB (null elsewhere), the oldest record. */
collections: Array<{ bytes: null | number; docs: number; oldest: null | string; slug: string }>
/** Key-value store entries (`payload-kv`): all of them, and those whose own expiry has passed (null = not readable). */
kv: { expired: null | number; total: number } | null
/** Media no document or global points at (by id), from the first `checked` documents. null = no upload collection. */
media: { capped: boolean; checked: number; orphaned: number; total: number } | null
/** Versioned collections and globals: the configured limit (0 = unlimited), all versions, and the documents. */
versions: Array<{ docs: number; kind: 'collection' | 'global'; max: number; slug: string; total: number }>
}
type CollectionLike = { slug: string; timestamps?: boolean; upload?: unknown; versions?: { maxPerDoc?: number } | false }
type GlobalLike = { slug: string; versions?: { max?: number } | false }
/** Documents read to find orphaned media (all collections and globals together). */
export const ORPHAN_SCAN_LIMIT = 5000
/** Key-value entries read to count expired ones. */
export const KV_SCAN_LIMIT = 5000
/** An expiry a plugin entry carries in its data (`resetAt`, `expiresAt`, `until`, epoch ms or ISO). */
function expiryOf(data: unknown): null | number {
if (!data || typeof data !== 'object') {return null}
for (const name of ['expiresAt', 'resetAt', 'until', 'exp']) {
const v = (data as Record<string, unknown>)[name]
const t = typeof v === 'number' ? v : typeof v === 'string' ? Date.parse(v) : Number.NaN
if (Number.isFinite(t)) {return t}
}
return null
}
async function mongoBytes(payload: BasePayload, slug: string): Promise<null | number> {
const db = payload.db as unknown as { collections?: Record<string, { collection?: { collectionName?: string } }>; connection?: { db?: { command: (c: object) => Promise<{ size?: number; totalIndexSize?: number }> } }; name?: string }
const name = db.collections?.[slug]?.collection?.collectionName
if (db.name !== 'mongoose' || !name || !db.connection?.db) {return null}
try {
const stats = await db.connection.db.command({ collStats: name })
return (stats.size ?? 0) + (stats.totalIndexSize ?? 0)
} catch {
return null
}
}
export async function collectGrowth(payload: BasePayload): Promise<GrowthStatus> {
const collections = (payload.config.collections ?? []) as unknown as CollectionLike[]
const globals = (payload.config.globals ?? []) as unknown as GlobalLike[]
const out: GrowthStatus = { collections: [], kv: null, media: null, versions: [] }
for (const c of collections) {
const collection = c.slug as never
try {
const docs = (await payload.count({ collection, overrideAccess: true })).totalDocs
let oldest: null | string = null
if (docs && c.timestamps !== false) {
const first = await payload.find({ collection, depth: 0, limit: 1, overrideAccess: true, pagination: false, select: { createdAt: true } as never, sort: 'createdAt' })
oldest = (first.docs[0] as { createdAt?: string } | undefined)?.createdAt ?? null
}
out.collections.push({ slug: c.slug, bytes: await mongoBytes(payload, c.slug), docs, oldest })
if (c.versions) {
const total = (await payload.countVersions({ collection, overrideAccess: true })).totalDocs
out.versions.push({ slug: c.slug, docs, kind: 'collection', max: c.versions.maxPerDoc ?? 100, total })
}
} catch {
// a collection the adapter cannot count (a virtual one): left out
}
}
for (const g of globals) {
if (!g.versions) {continue}
try {
const total = (await payload.countGlobalVersions({ global: g.slug as never, overrideAccess: true })).totalDocs
out.versions.push({ slug: g.slug, docs: 1, kind: 'global', max: g.versions.max ?? 100, total })
} catch {
// not countable on this adapter
}
}
// payload-kv: entries carry no expiry of their own in Payload; the plugin's carry one in their data
const kv = (payload as unknown as { kv?: { get: (k: string) => Promise<unknown>; keys: () => Promise<string[]> } }).kv
if (kv) {
try {
const keys = await kv.keys()
let expired = 0
const now = Date.now()
for (const key of keys.slice(0, KV_SCAN_LIMIT)) {
const t = expiryOf(await kv.get(key))
if (t !== null && t < now) {expired++}
}
out.kv = { expired: keys.length > KV_SCAN_LIMIT ? null : expired, total: keys.length }
} catch {
out.kv = null
}
}
// Orphaned media: ids of the upload collections that no other document or global mentions (any field, any depth)
const uploads = collections.filter((c) => c.upload)
if (uploads.length) {
const ids = new Set<string>()
for (const u of uploads) {
const res = await payload.find({ collection: u.slug as never, depth: 0, limit: ORPHAN_SCAN_LIMIT, overrideAccess: true, pagination: false, select: {} as never })
for (const d of res.docs as Array<{ id: number | string }>) {ids.add(String(d.id))}
}
const seen = new Set<string>()
let checked = 0
// every string and number anywhere in a document (relations, uploads, rich text, blocks) — ids are among them
const mark = (value: unknown, depth = 0): void => {
if (depth > 40 || value == null) {return}
if (typeof value === 'string' || typeof value === 'number') {
const key = String(value)
if (ids.has(key)) {seen.add(key)}
return
}
if (Array.isArray(value)) {for (const v of value) {mark(v, depth + 1)}}
else if (typeof value === 'object') {for (const v of Object.values(value)) {mark(v, depth + 1)}}
}
for (const c of collections) {
if (c.upload || c.slug.startsWith('payload-') || checked >= ORPHAN_SCAN_LIMIT) {continue}
try {
const res = await payload.find({ collection: c.slug as never, depth: 0, draft: true, limit: ORPHAN_SCAN_LIMIT - checked, locale: 'all' as never, overrideAccess: true, pagination: false })
checked += res.docs.length
for (const d of res.docs) {mark(d)}
} catch {
// not readable this way: its references are not counted (the orphan count can then be too high, never too low)
}
}
for (const g of globals) {
try {
mark(await payload.findGlobal({ slug: g.slug as never, depth: 0, draft: true, locale: 'all' as never, overrideAccess: true }))
} catch {
// not readable
}
}
out.media = { capped: checked >= ORPHAN_SCAN_LIMIT, checked, orphaned: [...ids].filter((id) => !seen.has(id)).length, total: ids.size }
}
return out
}
+180
View File
@@ -0,0 +1,180 @@
import { readdirSync, statSync } from 'node:fs'
import path from 'node:path'
import type { DoctorContext } from '../project.js'
import type { DoctorRule, GrowthThresholds, RuleFinding } from '../types.js'
/**
* The growth group (docs/performance.md → "What grows"): what makes a site and its database swell over the years.
* Deep rules read counts, sizes and dates (never values) from the status; the static one measures two folders on this
* machine. Warnings in 1.18.0, every threshold set in `iapl-doctor.json` → `growth`. Nothing here deletes anything.
*/
const DOCS = 'docs/performance.md'
const DAY = 86_400_000
export const GROWTH_DEFAULTS: Required<GrowthThresholds> = {
expiredKv: 1000,
imageCacheMB: 1024,
maxDocs: 200_000,
maxMB: 512,
maxVersions: 50_000,
orphanedMedia: 25,
submissionDays: 730,
uploadsMB: 2048,
}
const limits = (ctx: DoctorContext): Required<GrowthThresholds> => ({
...GROWTH_DEFAULTS,
// only numbers from iapl-doctor.json; anything else keeps the default
...Object.fromEntries(Object.entries(ctx.config.growth ?? {}).filter(([, v]) => typeof v === 'number' && Number.isFinite(v) && v >= 0)),
})
const days = (iso: null | string, today: string) => (iso ? Math.max(0, Math.floor((Date.parse(today) - Date.parse(iso)) / DAY)) : 0)
const mb = (bytes: number) => Math.round(bytes / 1024 / 1024)
/** Size of a folder on disk (bytes), capped at 200 000 files; 0 when it is not there. */
export function folderBytes(dir: string): number {
let total = 0
let files = 0
const walk = (d: string) => {
let names: string[]
try {
names = readdirSync(d)
} catch {
return
}
for (const name of names) {
if (++files > 200_000) {return}
const file = path.join(d, name)
try {
const s = statSync(file)
if (s.isDirectory()) {walk(file)} else {total += s.size}
} catch {
// gone meanwhile
}
}
}
walk(dir)
return total
}
export const growthRules: DoctorRule[] = [
{
// A collection past the thresholds: slower queries, backups and restores, a bigger bill on a managed database
id: 'growth-size',
check: (ctx) => {
const g = ctx.deep?.growth
if (!g) {return []}
const t = limits(ctx)
const big = g.collections.filter((c) => c.docs > t.maxDocs || (c.bytes ?? 0) > t.maxMB * 1024 * 1024)
return big.map((c) => ({
fix: 'a retention for logs (consentLog / stats retentionDays, forms.submissionRetentionDays), or raise growth.maxDocs / maxMB in iapl-doctor.json with a reason',
message: `${c.slug}: ${c.docs} documents${c.bytes === null ? '' : `, ${mb(c.bytes)} MB with indexes`}${c.oldest ? `, the oldest from ${c.oldest.slice(0, 10)}` : ''}`,
severity: 'warning' as const,
}))
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// Versions: Payload keeps 100 per document by default; 0 keeps every save forever
id: 'growth-versions',
check: (ctx) => {
const g = ctx.deep?.growth
if (!g) {return []}
const t = limits(ctx)
const out: RuleFinding[] = []
for (const v of g.versions) {
if (v.max === 0) {out.push({ fix: `versions: { ${v.kind === 'global' ? 'max' : 'maxPerDoc'}: 20 } (Payload's default is 100)`, message: `${v.kind} ${v.slug} keeps every version without a limit (${v.total} now)`, severity: 'warning' })}
else if (v.total > t.maxVersions) {out.push({ fix: `a lower ${v.kind === 'global' ? 'max' : 'maxPerDoc'} (now ${v.max}); Payload trims a document's oldest versions on its next save`, message: `${v.kind} ${v.slug}: ${v.total} versions for ${v.docs} document(s)`, severity: 'warning' })}
}
return out
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// A log with a retention whose oldest record is older than it: the purge is not running (it runs after a new
// record, at most once a day per process — a site without new records keeps the old ones)
id: 'growth-retention',
check: (ctx) => {
const g = ctx.deep?.growth
if (!g) {return []}
const out: RuleFinding[] = []
for (const [slug, keep] of Object.entries(g.retention)) {
const c = g.collections.find((x) => x.slug === slug)
if (!c || !keep || !c.oldest) {continue}
const age = days(c.oldest, ctx.today)
if (age > keep + 2) {out.push({ fix: 'check the server log for "retention purge failed"; the purge runs after the next new record', message: `${slug} keeps records for ${keep} days, but the oldest is ${age} days old`, severity: 'warning' })}
}
return out
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// Form submissions are personal data and the one plugin collection without a retention by default
id: 'growth-submissions',
check: (ctx) => {
const g = ctx.deep?.growth
const c = g?.collections.find((x) => x.slug === 'form-submissions')
if (!g || !c || !c.docs || g.retention['form-submissions']) {return []}
const age = days(c.oldest, ctx.today)
const t = limits(ctx)
return [{
fix: 'iapl({ forms: { submissionRetentionDays: 365 } }) — or delete old ones in the panel; a decision for the client (AGENTS.md → Project decisions)',
message: `${c.docs} form submissions kept without a retention, the oldest ${age} days old`,
severity: age > t.submissionDays ? 'warning' : 'info',
}]
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
id: 'growth-kv',
check: (ctx) => {
const kv = ctx.deep?.growth?.kv
if (!kv || kv.expired === null || kv.expired <= limits(ctx).expiredKv) {return []}
return [{ fix: 'expired entries are dead weight: the plugin sweeps its own mail-service nonces (1.18.0); entries of another package are its own', message: `payload-kv holds ${kv.total} entries, ${kv.expired} of them expired`, severity: 'warning' }]
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// Media nobody points at: storage, backups and the panel's media list grow for nothing
id: 'growth-media',
check: (ctx) => {
const m = ctx.deep?.growth?.media
if (!m || !m.orphaned) {return []}
return [{
fix: 'review them in the panel (Media) and delete what no page needs — the plugin never deletes media by itself',
message: `${m.orphaned} of ${m.total} media files are not used by any document or global${m.capped ? ` (from the first ${m.checked} documents: may be fewer)` : ''}`,
severity: m.orphaned > limits(ctx).orphanedMedia ? 'warning' : 'info',
}]
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// On this machine: Next's image cache has no size cap of its own; local uploads belong on R2 in production
id: 'growth-disk',
check: (ctx) => {
const t = limits(ctx)
const out: RuleFinding[] = []
const cache = folderBytes(path.join(ctx.root, '.next', 'cache', 'images'))
if (mb(cache) > t.imageCacheMB) {out.push({ file: '.next/cache/images', fix: 'it is rebuilt on demand: delete it, or let each Coolify deploy start with an empty one (no persistent volume on .next)', message: `the image cache is ${mb(cache)} MB (no size cap in Next; each image × width × format)`, severity: 'info' })}
const uploads = folderBytes(path.join(ctx.root, 'media'))
if (mb(uploads) > t.uploadsMB) {out.push({ file: 'media', fix: 'production media on R2 (buildR2Storage); locally, a copy of the database you no longer need can go', message: `the local upload folder is ${mb(uploads)} MB`, severity: 'info' })}
return out
},
docs: DOCS,
group: 'growth',
source: 'static',
},
]
+200
View File
@@ -0,0 +1,200 @@
import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { IMAGE_RULES } from '../../performance/budgets.js'
import { stripComments } from '../util.js'
/**
* The performance group (docs/performance.md): what makes a site slow and can be seen without a browser — images,
* fonts, embeds, render-blocking resources, animations, a budget gate — plus the running site (`--url`) and the stored
* media (`--deep`). Warnings in 1.18.0, as the owner decided for new rules: they report, they do not fail CI.
*/
const DOCS = 'docs/performance.md'
/** The site's own code and styles: src/app (not the panel's route group) and src/components, comments stripped. */
function siteFiles(ctx: DoctorContext, pattern = /\.(?:tsx?|jsx?|css|scss)$/): Array<{ code: string; file: string }> {
const files: string[] = []
const walk = (dir: string, depth: number) => {
for (const name of ctx.list(dir)) {
if (files.length >= 800 || name === 'node_modules' || name.startsWith('.') || name === '(payload)') {continue}
const rel = `${dir}/${name}`
if (pattern.test(name)) {files.push(rel)}
else if (!/\.[a-z0-9]+$/i.test(name) || /^\(.*\)$|^\[.*\]$/.test(name)) {if (depth < 8) {walk(rel, depth + 1)}}
}
}
for (const dir of ['app', 'components', 'blocks', 'design', 'styles']) {walk(`${ctx.src}${dir}`, 0)}
return files.map((file) => ({ code: /\.s?css$/.test(file) ? ctx.read(file).replace(/\/\*[\s\S]*?\*\//g, '') : stripComments(ctx.read(file)), file }))
}
const lineOf = (code: string, index: number) => code.slice(0, index).split('\n').length
/** Each match → one finding (at most `max` per rule, the rest summed up in the last one). */
function findAll(files: Array<{ code: string; file: string }>, re: RegExp, make: (file: string, line: number, match: RegExpExecArray) => null | RuleFinding, max = 10): RuleFinding[] {
const out: RuleFinding[] = []
let more = 0
for (const { code, file } of files) {
const global = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`)
for (let m = global.exec(code); m; m = global.exec(code)) {
const finding = make(file, lineOf(code, m.index), m)
if (!finding) {continue}
if (out.length < max) {out.push(finding)} else {more++}
}
}
if (more) {out[out.length - 1] = { ...out[out.length - 1], message: `${out[out.length - 1].message} (and ${more} more)` }}
return out
}
const nextConfig = (ctx: DoctorContext) => ['next.config.ts', 'next.config.mjs', 'next.config.js'].find((f) => ctx.exists(f))
/** Layout properties: animating them makes the browser lay the page out again on every frame. */
const LAYOUT_PROPS = '(?:width|height|top|left|right|bottom|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|inset|max-height|min-height)'
export const performanceRules: DoctorRule[] = [
{
// next/image serves AVIF / WebP in the right width only for hosts it is allowed to optimise; buildImagesConfig sets
// the formats, R2 and a long cache (web.dev/articles/serve-images-avif-webp — nextjs.org/docs/app/api-reference/components/image)
id: 'perf-images-config',
check: (ctx) => {
const file = nextConfig(ctx)
if (!file || /\bbuildImagesConfig\s*\(/.test(stripComments(ctx.read(file)))) {return []}
return [{ file, fix: 'images: buildImagesConfig() in next.config (from @intecion/ipal-kit)', message: 'next.config does not use buildImagesConfig(): images may not be served as AVIF / WebP or with a long cache, and media on R2 may not be optimised at all', severity: 'warning' }]
},
docs: DOCS,
group: 'performance',
source: 'static',
},
{
// Fonts: self-hosted by next/font (no request to Google, no layout shift — nextjs.org/docs/app/getting-started/fonts);
// at most two families; never font-display: block (invisible text — web.dev/articles/font-best-practices)
id: 'perf-fonts',
check: (ctx) => {
const files = siteFiles(ctx)
const out: RuleFinding[] = [
...findAll(files, /fonts\.googleapis\.com|fonts\.gstatic\.com|use\.typekit\.net/, (file, line) => ({ file: `${file}:${line}`, fix: 'load the font with next/font (self-hosted, subset, no extra connection)', message: 'a font is loaded from a third-party host: an extra connection before text shows, and a request to Google before consent', severity: 'warning' })),
...findAll(files, /display\s*:\s*['"]block['"]|font-display\s*:\s*block/, (file, line) => ({ file: `${file}:${line}`, fix: "display: 'swap' (next/font's default) or 'optional'", message: 'font-display: block hides the text until the font has loaded', severity: 'warning' })),
...findAll(files.filter((f) => /\.s?css$/.test(f.file)), /@font-face\s*\{(?![^}]*font-display)[^}]*\}/, (file, line) => ({ file: `${file}:${line}`, fix: 'font-display: swap in the @font-face — or next/font/local, which sets it', message: '@font-face without font-display (the browser may hide the text for up to 3 s)', severity: 'warning' })),
]
const families = new Set<string>()
for (const { code } of files) {
const imports = /import\s*\{([^}]+)\}\s*from\s*['"]next\/font\/google['"]/.exec(code)
for (const name of imports?.[1].split(',').map((n) => n.trim().split(/\s+as\s+/)[0]).filter(Boolean) ?? []) {families.add(name)}
for (const m of code.matchAll(/\blocalFont\s*\(/g)) {families.add(`localFont#${m.index}`)}
}
if (families.size > 2) {
out.push({ fix: 'two families at most (body + headings), variable fonts, the weights you use', message: `${families.size} font families on the site (${[...families].map((f) => f.replace(/#\d+$/, '')).join(', ')}): each one is more bytes before the text settles`, severity: 'warning' })
}
return out
},
docs: DOCS,
group: 'performance',
source: 'static',
},
{
// Nothing may hold the first paint except the one stylesheet (web.dev/articles/render-blocking-resources)
id: 'perf-render-blocking',
check: (ctx) => {
const files = siteFiles(ctx)
return [
...findAll(files.filter((f) => /\.[jt]sx$/.test(f.file)), /<script(?![^>]*\s(?:async|defer|type=["']module["']|dangerouslySetInnerHTML|type=["']application\/(?:ld\+)?json["']))[^>]*\ssrc=/, (file, line) => ({ file: `${file}:${line}`, fix: 'next/script with strategy="afterInteractive" or "lazyOnload", or the plugin\'s ConsentScript / Analytics', message: 'a <script src> without async / defer blocks the page until it has downloaded and run', severity: 'warning' })),
...findAll(files.filter((f) => /\.[jt]sx$/.test(f.file)), /<link(?=[^>]*\srel=["']stylesheet["'])[^>]*\shref=["']https?:/, (file, line) => ({ file: `${file}:${line}`, fix: 'import the CSS in the layout (bundled, one file) or self-host it', message: 'a stylesheet from another host blocks the first paint on an extra connection', severity: 'warning' })),
...findAll(files.filter((f) => /\.s?css$/.test(f.file)), /@import\s+(?:url\()?["']?https?:/, (file, line) => ({ file: `${file}:${line}`, fix: 'self-host it (next/font for fonts) — an @import of a URL is fetched only after this file has loaded', message: 'CSS @import of a remote URL: a request chain before the first paint', severity: 'warning' })),
]
},
docs: DOCS,
group: 'performance',
source: 'static',
},
{
// Embeds load a whole page each (YouTube ≈ 1 MB of JS): a facade until the click (web.dev/articles/third-party-facades)
id: 'perf-embeds',
check: (ctx) => findAll(siteFiles(ctx, /\.[jt]sx$/), /<iframe\b[^>]*>/, (file, line, m) => {
if (/youtube/i.test(m[0])) {return null} // iapl-audit reports a raw YouTube iframe (audit:raw YouTube iframe)
if (/loading=["']lazy["']/.test(m[0])) {return null}
return { file: `${file}:${line}`, fix: 'load it on click (a facade: a picture and a button, like <YouTubeEmbed>), or at least loading="lazy" below the fold', message: 'an <iframe> (map, video, widget) loads with the page: its whole page, scripts and cookies come before the visitor asked', severity: 'warning' }
}),
docs: DOCS,
group: 'performance',
source: 'static',
},
{
// transform / opacity only, reduced motion honoured, no work per scroll event
// (web.dev/articles/animations-guide, web.dev/articles/prefers-reduced-motion, web.dev/articles/optimize-inp)
id: 'perf-animations',
check: (ctx) => {
const files = siteFiles(ctx)
const css = files.filter((f) => /\.s?css$/.test(f.file))
const tsx = files.filter((f) => /\.[jt]sx?$/.test(f.file))
const out: RuleFinding[] = [
...findAll(css, new RegExp(`transition(?:-property)?\\s*:[^;}]*\\b${LAYOUT_PROPS}\\b`), (file, line) => ({ file: `${file}:${line}`, fix: 'animate transform (translate, scale) and opacity instead', message: 'a transition of a layout property (width, height, top, margin…): the page is laid out again on every frame', severity: 'warning' })),
...findAll(tsx, new RegExp(`\\btransition-(?:all|\\[[^\\]]*\\b${LAYOUT_PROPS}\\b[^\\]]*\\])`), (file, line) => ({ file: `${file}:${line}`, fix: 'transition-transform / transition-opacity / transition-colors', message: 'transition-all or a transition of a layout property animates layout on every frame', severity: 'warning' })),
...findAll(tsx, /addEventListener\(\s*['"]scroll['"]/, (file, line) => ({ file: `${file}:${line}`, fix: 'IntersectionObserver for "is it on screen", or at most one update per frame (requestAnimationFrame) with { passive: true }', message: 'a scroll listener runs on every scroll event: work on the main thread delays the next tap (INP)', severity: 'warning' })),
]
const animates = files.some((f) => /@keyframes|\banimate-[a-z]|animation\s*:/.test(f.code))
const reduces = files.some((f) => /prefers-reduced-motion|\bmotion-(?:reduce|safe):/.test(f.code)) || /ipal-kit\/(?:tokens|tailwind)\.css/.test(files.map((f) => f.code).join('\n'))
if (animates && !reduces) {
out.push({ fix: '@media (prefers-reduced-motion: reduce) { … } or motion-safe: / motion-reduce: classes — the plugin\'s tokens.css shortens its duration tokens for you', message: 'the site animates (@keyframes / animate-*) and nothing honours prefers-reduced-motion', severity: 'warning' })
}
return out
},
docs: DOCS,
group: 'performance',
source: 'static',
},
{
// A budget nobody runs is a wish: the gate test fails when a change makes the site slower
id: 'perf-budgets',
check: (ctx) => {
// only a project that already runs browser tests: there the budget test is one file to copy (a new site from the
// starter has none yet — AGENT.md §11 and the iapl-performance skill bring it in with the first e2e tests)
const playwright = !!ctx.installed('@playwright/test') || ['playwright.config.ts', 'playwright.config.js', 'playwright.config.mjs'].some((f) => ctx.exists(f))
if (!playwright) {return []}
const dirs = ['e2e', 'tests', 'test'].filter((d) => ctx.exists(d))
const has = dirs.some((d) => ctx.list(d).some((name) => /perf/i.test(name) || /\bperfBudgets\s*\(|\boverBudget\s*\(/.test(ctx.read(`${d}/${name}`))))
return has ? [] : [{ fix: 'copy the iapl-performance skill\'s resources/performance.spec.template.ts to e2e/ (budgets from perfBudgets())', message: 'no performance budget test: nothing fails when a change makes the site slower', severity: 'info' }]
},
docs: DOCS,
group: 'performance',
source: 'static',
},
{
// The first HTML as a visitor gets it: compression, render-blocking scripts, preloads, a lazy first image
id: 'perf-live',
check: async (ctx) => {
const home = await ctx.live!.fetch('/')
if (!home.status || home.status >= 400) {return []}
const out: RuleFinding[] = []
const html = home.text
const head = html.slice(0, Math.max(0, html.indexOf('</head>')) || 0)
if (!home.headers.get('content-encoding')) {
out.push({ fix: 'let the proxy compress (Coolify: Traefik compress middleware) or Next (compress: true, the default)', message: 'the HTML came back uncompressed (no Content-Encoding)', severity: 'warning' })
}
const blocking = [...head.matchAll(/<script(?![^>]*\s(?:async|defer|type="module"|nomodule))[^>]*\ssrc="([^"]+)"/gi)].map((m) => m[1])
if (blocking.length) {out.push({ message: `render-blocking scripts in <head>: ${blocking.slice(0, 3).join(', ')}`, severity: 'warning' })}
const fonts = (head.match(/<link[^>]*\srel="preload"[^>]*\sas="font"/g) ?? []).length
if (fonts > 4) {out.push({ fix: 'preload only the body font (next/font preload: false on the others) or fewer subsets', message: `${fonts} font files preloaded: they compete with the LCP image for the first round trips`, severity: 'warning' })}
const main = html.indexOf('<main')
const firstImg = main >= 0 ? /<img\b[^>]*>/.exec(html.slice(main))?.[0] : undefined
if (firstImg && /loading="lazy"/.test(firstImg)) {out.push({ fix: '<Media priority> on the first image of the page (the hero) — exactly one', message: 'the first image of the page is lazy-loaded: when it is the LCP element it starts late (web.dev/articles/lcp-lazy-loading)', severity: 'warning' })}
const kb = Math.round(Buffer.byteLength(html) / 1024)
if (kb > 150) {out.push({ message: `the home page HTML is ${kb} KB (budget 150 KB): a big RSC payload is parsed twice — check depth, relations and what the layout passes to client components`, severity: 'warning' })}
return out
},
docs: DOCS,
group: 'performance',
source: 'live',
},
{
// Images stored over the limits (an LCP image of 4 MB stays slow, whatever next/image does with it)
id: 'perf-images',
check: (ctx) => {
const media = ctx.deep?.media
if (!media || (!media.oversized && !media.tooWide)) {return []}
const mb = (IMAGE_RULES.maxBytes / 1024 / 1024).toFixed(1)
return [{ fix: `re-upload them prepared (≤ ${mb} MB, ≤ ${IMAGE_RULES.maxWidth} px) or tick "Optimise large image"; buildOptimizeUploadHook stops new ones`, message: `of ${media.images} images, ${media.oversized} are over ${mb} MB and ${media.tooWide} wider than ${IMAGE_RULES.maxWidth} px`, severity: 'warning' }]
},
docs: DOCS,
group: 'performance',
source: 'deep',
},
]
+4
View File
@@ -10,10 +10,12 @@ import { agentRules } from './rules/agents.js'
import { blockRules } from './rules/blocks.js'
import { consentRules } from './rules/consent.js'
import { envRules } from './rules/env.js'
import { growthRules } from './rules/growth.js'
import { layoutRules } from './rules/layout.js'
import { legacyRules } from './rules/legacy.js'
import { createLiveFetcher, liveRules } from './rules/live.js'
import { mailRules } from './rules/mail.js'
import { performanceRules } from './rules/performance.js'
import { securityRules } from './rules/security.js'
import { seedRules } from './rules/seeds.js'
import { toolingRules } from './rules/tooling.js'
@@ -41,6 +43,8 @@ export const doctorRules: DoctorRule[] = [
...legacyRules,
...seedRules,
...blockRules,
...performanceRules,
...growthRules,
...toolingRules,
...liveRules,
...deepRules,
+36 -2
View File
@@ -10,13 +10,16 @@ import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { graphAvailable } from '../email/mailAdapter.js'
import { mailPanelState } from '../email/relay/panel.js'
import { IMAGE_RULES } from '../performance/budgets.js'
import { countPendingEnrolments, mailConfigured } from '../security/totp/enrolmentConfirm.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { accessAllowed } from '../shared/accessAnswer.js'
import { readEnv } from '../shared/envName.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { retentionMap } from '../shared/retention.js'
import { turnstileSecretFromEnv } from '../turnstile/config.js'
import { collectGrowth } from './growth.js'
import { visitorWritableEntities } from './visitorWrites.js'
/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */
@@ -24,7 +27,31 @@ export function pluginVersion(): string {
return PLUGIN_VERSION
}
type CollectionLike = { fields?: Array<{ name?: string }>; slug: string }
type CollectionLike = { fields?: Array<{ name?: string }>; slug: string; upload?: unknown }
/**
* Images stored over the plugin's limits (IMAGE_RULES): counts per upload collection, never file names. Uploads made
* before `buildOptimizeUploadHook`, or let through by hand, are the usual cause of a slow LCP image.
*/
export async function countHeavyMedia(payload: BasePayload, collections: CollectionLike[]): Promise<DoctorStatus['media']> {
const uploads = collections.filter((c) => c.upload)
if (!uploads.length) {return null}
let images = 0
let oversized = 0
let tooWide = 0
for (const c of uploads) {
const collection = c.slug as never
const image = { mimeType: { like: 'image/' } }
try {
images += (await payload.count({ collection, overrideAccess: true, where: image })).totalDocs
oversized += (await payload.count({ collection, overrideAccess: true, where: { and: [image, { filesize: { greater_than: IMAGE_RULES.maxBytes } }] } })).totalDocs
tooWide += (await payload.count({ collection, overrideAccess: true, where: { and: [image, { width: { greater_than: IMAGE_RULES.maxWidth } }] } })).totalDocs
} catch {
// a collection without the standard upload fields: not counted
}
}
return { images, oversized, tooWide }
}
/**
* Read-only counts for iapl-doctor's deep rules: users without TOTP, cookies waiting for approval,
@@ -56,6 +83,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
: { on: false }
}
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
const media = await countHeavyMedia(payload, collections)
let growth: DoctorStatus['growth'] = null
try {
growth = { ...(await collectGrowth(payload)), retention: retentionMap(payload) }
} catch {
growth = null
}
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
let turnstile: DoctorStatus['turnstile'] = null
let secretFromEnv: boolean | null = null
@@ -130,7 +164,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
}
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, twoFactorConfirm, usersSetupClosed, usersWithout2fa, visitorWrites }
return { growth, mail, media, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, twoFactorConfirm, usersSetupClosed, usersWithout2fa, visitorWrites }
}
export type DoctorEndpointOptions = {
+27
View File
@@ -1,3 +1,4 @@
import type { GrowthStatus } from './growth.js'
import type { DoctorContext } from './project.js'
/** How bad a finding is: error fails CI, warning is drift to fix, info is worth knowing. */
@@ -40,6 +41,8 @@ export type DoctorConfig = {
domain?: string
/** Paths of extra rule modules (relative to the project), each exporting `rules: DoctorRule[]`. */
extraRules?: string[]
/** Thresholds of the `growth` rules (docs/performance.md → "What grows"). */
growth?: GrowthThresholds
/** true once the site is live: seeds must then name their records. */
launched?: boolean
/**
@@ -58,6 +61,8 @@ export type DoctorStatus = {
envProblems?: string[]
/** Why the deep check could not finish (first line). */
error?: string
/** What grows (1.18.0, docs/performance.md): counts, sizes, oldest dates, versions, KV, orphaned media, retention in days. */
growth?: ({ retention: Partial<Record<string, number>> } & GrowthStatus) | null
/** null = not compared (the endpoint cannot read files). */
importMapCurrent?: boolean | null
/**
@@ -96,6 +101,8 @@ export type DoctorStatus = {
status?: { code?: null | string; since?: null | string; state?: null | string } | null
transport: 'graph' | 'none' | 'relay' | 'smtp'
} | null
/** Images in the upload collections, and how many are over IMAGE_RULES (bytes, width). null = no upload collection. */
media?: { images: number; oversized: number; tooWide: number } | null
node?: string
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
openSignUp?: null | string[]
@@ -164,3 +171,23 @@ export type DoctorReport = {
skipped: string[]
summary: { error: number; info: number; silenced: number; warning: number }
}
/** When the `growth` rules speak up — every number can be set in iapl-doctor.json `growth`. */
export type GrowthThresholds = {
/** Expired entries in payload-kv. Default 1000. */
expiredKv?: number
/** `.next/cache/images` on this machine, MB. Default 1024. */
imageCacheMB?: number
/** Documents in one collection. Default 200 000. */
maxDocs?: number
/** Size of one collection with its indexes (MongoDB), MB. Default 512. */
maxMB?: number
/** Versions of one collection or global. Default 50 000. */
maxVersions?: number
/** Media no document points at. Default 25. */
orphanedMedia?: number
/** Form submissions kept without a retention: older than this many days is a warning. Default 730. */
submissionDays?: number
/** Local upload folder (`media/`), MB. Default 2048. */
uploadsMB?: number
}
+34
View File
@@ -173,6 +173,7 @@ export const dropRelayCandidate = (payload: BasePayload, host: string = ownHost(
/** Remembers that the site at `host` started an enrolment with `nonce`. Only the nonce's hash is stored. */
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number, host: string = ownHost(payload)): Promise<string> {
const nonceHash = sha256Hex(nonce)
await sweepExpiredNonces(payload)
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash, host })
return nonceHash
}
@@ -194,3 +195,36 @@ export async function takeNonce(payload: BasePayload, nonce: string): Promise<{
}
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
/**
* Removes held nonces whose time has passed (1.18.0). A nonce whose call-back never came stayed in payload-kv for
* good: its expiry was only checked when read. An expired nonce can never be taken again (takeNonce refuses it) and
* a new enrolment uses a new key, so this changes nothing but the size of the store. At most once a day per process,
* started by the next enrolment; a failure is ignored (the next one tries again).
*/
let lastNonceSweep = 0
export async function sweepExpiredNonces(payload: BasePayload, now = Date.now()): Promise<number> {
if (now - lastNonceSweep < 86_400_000) {return 0}
lastNonceSweep = now
let removed = 0
try {
const kv = kvOf(payload)
const prefix = nonceKey('')
if (typeof kv.keys !== 'function') {return 0}
for (const key of (await kv.keys()).filter((k) => k.startsWith(prefix))) {
const held = (await kv.get(key)) as { expiresAt?: unknown } | null
if (held && typeof held.expiresAt === 'number' && held.expiresAt < now) {
await kv.delete(key)
removed++
}
}
} catch {
lastNonceSweep = 0
}
return removed
}
/** Tests: forget when the last sweep ran. */
export const resetNonceSweep = () => {
lastNonceSweep = 0
}
+7
View File
@@ -6,6 +6,8 @@ import type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.j
import type { FormValidationResult } from './validateSubmission.js'
import { mailAttachmentLimit } from '../email/attachmentLimit.js'
import { createDailyPurge } from '../shared/purge.js'
import { retentionOf } from '../shared/retention.js'
import { getTurnstileConfig } from '../turnstile/config.js'
import { verifyTurnstile } from '../turnstile/verify.js'
import { getFormAttachments } from './attachments/config.js'
@@ -15,6 +17,9 @@ import { formatFileSize } from './attachments/fileTypes.js'
import { consumeRateLimit } from './rateLimit.js'
import { validateSubmission } from './validateSubmission.js'
/** forms.submissionRetentionDays: old submissions deleted at most once a day, off the visitor's request. */
const purgeSubmissions = createDailyPurge('form-submissions')
export type SubmitFormArgs = {
/**
* A key the browser makes per submit attempt (16–64 letters, digits, `-`, `_`).
@@ -333,6 +338,8 @@ export async function storeSubmission({
...(delivery ? { filesDelivery: 'failed', submissionFiles: files.map((f) => ({ name: f.name, type: f.type, field: f.field, size: f.size })) } : {}),
} as never,
})
const keepDays = retentionOf(payload, 'form-submissions')
if (keepDays) {purgeSubmissions(payload, { createdAt: { less_than: new Date(Date.now() - keepDays * 86_400_000).toISOString() } })}
if (!delivery) {return { submissionId: submission.id, success: true }}
const result = delivery.result ?? { note: 'No e-mail was sent for this form.', state: 'failed' as const }
+6
View File
@@ -104,6 +104,12 @@ export type FormsOption = {
formSubmissionOverrides?: FormsCollectionOverrides
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* Keep form submissions this many days, then delete them (1.18.0; checked at most once a day, after a new
* submission). Default: kept until someone deletes them in the panel, as before. Submissions hold personal data
* (GDPR: no longer than needed) and are the one plugin collection that grows without end (docs/performance.md).
*/
submissionRetentionDays?: number
/**
* What a form does while Turnstile CANNOT check — the secret is missing or
* wrong, Cloudflare is down (the "degraded" state, shown in Site
+17 -4
View File
@@ -241,12 +241,18 @@ export function createContentHelpers({
})
/** What does this URL point at? Routing only — no listing data. */
const resolveRoute = cache(
// React cache() compares arguments by identity: the page passes the params' array, metadata and JSON-LD pass
// `segments ?? []` — a new array each time — so every caller missed and the homepage (no segments) was read in
// full four times per render. The segments travel as a string key instead (measured: docs/performance.md).
const resolveRoute = (locale: string, segments: string[] | undefined, page: number): Promise<null | ResolvedRoute> =>
resolveRouteCached(locale, JSON.stringify(segments ?? []), page)
const resolveRouteCached = cache(
async (
locale: string,
segments: string[] | undefined,
segmentsKey: string,
page: number,
): Promise<null | ResolvedRoute> => {
const segments = JSON.parse(segmentsKey) as string[]
const payload = await getCachedPayload()
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
@@ -275,10 +281,17 @@ export function createContentHelpers({
* }
*/
let pageMetadata: ReturnType<typeof createPageMetadata> | undefined
const generatePageMetadata = async (
// One build per request and URL: the page's generateMetadata, its render (alternate links) and getPageJsonLd all
// ask for it — uncached that was three times the homepage and document reads in every locale (measured: 43 → fewer
// MongoDB queries per render, docs/performance.md). The segments travel as a string so separate arrays still match.
const pageMetadataCached = cache(async (locale: string, segmentsKey: null | string, page: number): Promise<PageMetadata> =>
buildPageMetadata(locale, segmentsKey === null ? undefined : (JSON.parse(segmentsKey) as string[]), page))
const generatePageMetadata = (locale: string, segments: string[] | undefined, page = 1): Promise<PageMetadata> =>
pageMetadataCached(locale, segments === undefined ? null : JSON.stringify(segments), page)
const buildPageMetadata = async (
locale: string,
segments: string[] | undefined,
page = 1,
page: number,
): Promise<PageMetadata> => {
if (!i18n) {
throw new Error('[iapl] createContentHelpers: pass `i18n` to use generatePageMetadata.')
+6 -1
View File
@@ -174,6 +174,11 @@ export type NotFoundPageOptions =
* carries the whole 404 page in every locale.
*/
load: (locale: string) => Promise<ReactNode>
/**
* What the lazy 404 shows until its content arrives (default nothing). A block as tall as the site's 404
* content keeps the footer from moving when the content comes in (no layout shift, docs/performance.md).
*/
placeholder?: ReactNode
}
| ({ load?: undefined } & NotFoundViewOptions)
@@ -230,7 +235,7 @@ export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPa
const locales = await localesOf(helpers)
const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0]
if (options.load) {
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} />
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} placeholder={options.placeholder} />
}
const eager = options
const views = Object.fromEntries(
+6 -3
View File
@@ -2,14 +2,17 @@
import type { CSSProperties, ReactNode } from 'react'
import { createContext, use, useCallback, useId, useMemo, useRef, useState } from 'react'
import { createContext, lazy, Suspense, use, useCallback, useId, useMemo, useRef, useState } from 'react'
import type { LightboxDialogProps } from './LightboxDialog.js'
import type { LightboxClassNames, LightboxImage, LightboxRenderImage, LightboxTexts } from './types.js'
import { LightboxDialog } from './LightboxDialog.js'
import { lightboxIndex, resolveLightboxTexts } from './texts.js'
// The viewer (dialog, swipe, keyboard, icons) is loaded the first time an image is opened, not with every page:
// most visitors never open one. The triggers and this provider stay small.
const LightboxDialog = lazy(() => import('./LightboxDialog.js').then((m) => ({ default: m.LightboxDialog })))
type Entry = { el: { current: HTMLElement | null }; group?: string; image: { current: LightboxImage } }
type OpenState = { images: readonly LightboxImage[]; index: number; returnFocus: HTMLElement | null }
@@ -152,7 +155,7 @@ export function LightboxProvider({ children, classNames, icons, loop = true, ren
<LightboxContext value={api}>
<TriggerContext value={triggerApi}>
{children}
{dialogProps ? (renderDialog ? renderDialog(dialogProps) : <LightboxDialog {...dialogProps} />) : null}
{dialogProps ? (renderDialog ? renderDialog(dialogProps) : <Suspense fallback={null}><LightboxDialog {...dialogProps} /></Suspense>) : null}
</TriggerContext>
</LightboxContext>
)
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { LightboxDialog, prefersReducedMotion } from './LightboxDialog.js'
export type { LightboxDialogProps } from './LightboxDialog.js'
export { LightboxProvider, LightboxTrigger, useLightbox, useOptionalLightbox } from './LightboxProvider.js'
+7 -2
View File
@@ -42,6 +42,11 @@ export const MEDIA_SIZES = {
export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string
/**
* Above the fold but not the LCP image (a header logo): loads at once (`loading="eager"`) WITHOUT
* fetchPriority="high" or a preload, so it does not compete with the one `priority` image. Ignored with `priority`.
*/
eager?: boolean
/**
* Dominant colour as the <img> background while it loads. The style stays after
* load, so it would show through transparent pixels (white logo on a black box).
@@ -88,7 +93,7 @@ const asDoc = (resource: unknown): MediaDoc | null =>
*/
export function mediaImageProps(
resource: unknown,
{ alt, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
{ alt, eager = false, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
): MediaImageProps | null {
const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
@@ -109,7 +114,7 @@ export function mediaImageProps(
width: doc.width,
...(priority
? { fetchPriority: 'high' as const, loading: 'eager' as const, preload: true }
: { loading: 'lazy' as const }),
: { loading: eager ? ('eager' as const) : ('lazy' as const) }),
...(blur ? { blurDataURL: blur, placeholder: 'blur' as const } : {}),
...(Object.keys(style).length ? { style } : {}),
}
+9 -11
View File
@@ -12,18 +12,16 @@ type NotFoundLoaderProps = {
/** The project's server action: `(locale) => renderNotFoundView(content, options, locale)`. */
load: (locale: string) => Promise<ReactNode>
locales: string[]
/**
* Shown until the content arrives (default nothing). The 404 content comes after hydration, so the footer moves
* when it arrives (a layout shift: measured CLS 0.32 on a phone for the reference site). A block as tall as the
* site's own 404 content keeps the footer still: `placeholder={<div style={{ minHeight: '36rem' }} />}`. A fixed
* one-screen block is no fix in general: shorter content then pulls the footer UP into view (measured 0.36).
*/
placeholder?: ReactNode
}
/**
* The 404 content, fetched only when the 404 is actually shown.
*
* Next puts the `not-found` tree of a layout into the RSC payload of EVERY page
* under it (the router needs it for a client-side 404). A 404 page with real
* content (often the homepage) rendered there in every locale multiplied the
* size of each page. Here only this small component is in the payload; the
* content comes from a server action on mount.
*/
export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderProps) {
export function NotFoundLoader({ defaultLocale, load, locales, placeholder = null }: NotFoundLoaderProps) {
const pathname = usePathname() ?? ''
const locale = localeFromPath(pathname, locales, defaultLocale)
const [view, setView] = useState<{ locale: string; node: ReactNode } | null>(null)
@@ -43,5 +41,5 @@ export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderP
}
}, [load, locale])
return <>{view?.locale === locale ? view.node : null}</>
return <>{view?.locale === locale ? view.node : placeholder}</>
}
+10 -1
View File
@@ -101,5 +101,14 @@ export function getSiteIntegrations<T = Record<string, unknown>>(
payload: BasePayload,
options?: GlobalQueryOptions,
): Promise<T> {
return findSiteIntegrations<T>(payload, options)
if (options && Object.keys(options).length) {return findSiteIntegrations<T>(payload, options)}
// Callers that start together (the layout reads analytics IDs and the Turnstile key side by side) share ONE read
// while it is in flight; the next call reads again, so nothing is cached between requests or after a save.
const pending = inFlight.get(payload)
if (pending) {return pending as Promise<T>}
const read = findSiteIntegrations<T>(payload).finally(() => inFlight.delete(payload))
inFlight.set(payload, read)
return read
}
const inFlight = new WeakMap<BasePayload, Promise<unknown>>()
+105
View File
@@ -0,0 +1,105 @@
/**
* Performance budgets — the numbers a site must stay within, measured in the lab (docs/performance.md).
*
* One set of defaults for every IAPL site (and shared with IAWL where the measurement is the same): Core Web Vitals
* "good" (web.dev/articles/vitals) for LCP, CLS and INP, plus byte, request and query budgets that keep a brochure
* site light. A project tightens or loosens any number with `perfBudgets({ … })`; the reference site's gate
* (reference/e2e/performance.spec.ts) tightens them to its measured numbers, so a change that makes it slower fails.
*
* Node and browser safe: no imports.
*/
/** What one page may cost on a first visit (empty cache), in Lighthouse's mobile or desktop lab profile. */
export type PerfBudget = {
/** Cumulative Layout Shift (session window). Good ≤ 0.1. */
cls: number
/** CSS bytes over the wire (compressed). */
cssBytes: number
/** Font bytes over the wire. */
fontBytes: number
/** The slowest response to one scripted tap (Event Timing), ms. A lab stand-in for INP. Good ≤ 200. */
inp: number
/** JavaScript bytes over the wire (compressed). */
jsBytes: number
/** Largest Contentful Paint, ms. Good ≤ 2500 (mobile). */
lcp: number
/** Render-blocking resources (resource timing `renderBlockingStatus`): the one stylesheet, nothing else. */
renderBlocking: number
/** Requests on load (HTML, CSS, JS, fonts, the images above the fold). */
requests: number
/** Total Blocking Time after first paint, ms: long main-thread tasks that would delay a tap. */
tbt: number
/** Origins other than the site that may be asked before the visitor chose in the consent banner. */
thirdParty: string[]
}
export type PerfProfile = 'desktop' | 'mobile'
/** Server budgets: one render of a page that is not in the ISR cache. */
export type ServerBudget = {
/** Database queries one render of a page may make (MongoDB profiler, docs/performance.md). */
queriesPerRender: number
}
/** The defaults: CWV "good" for the vitals, and sizes a brochure site needs no more than. */
export const PERF_BUDGETS: Readonly<Record<PerfProfile, Readonly<PerfBudget>>> = {
desktop: { cls: 0.1, cssBytes: 50_000, fontBytes: 250_000, inp: 100, jsBytes: 250_000, lcp: 1200, renderBlocking: 2, requests: 50, tbt: 100, thirdParty: [] },
mobile: { cls: 0.1, cssBytes: 50_000, fontBytes: 250_000, inp: 200, jsBytes: 250_000, lcp: 2500, renderBlocking: 2, requests: 40, tbt: 200, thirdParty: [] },
}
export const SERVER_BUDGET: Readonly<ServerBudget> = { queriesPerRender: 40 }
/**
* Image rules every upload and every rendered image should meet — the doctor checks the stored media against them,
* `buildOptimizeUploadHook` enforces the first two at upload. Shared with IAWL (WordPress) as the same numbers.
*/
export const IMAGE_RULES = {
/** An image larger than this is stopped at upload (the editor may let the plugin shrink it). */
maxBytes: 1.5 * 1024 * 1024,
/** Wider than this is never needed on screen (a 1280 px wide slot at DPR 2). */
maxWidth: 2560,
/** Formats the site serves (next/image converts; buildImagesConfig sets them). */
servedFormats: ['image/avif', 'image/webp'] as const,
} as const
/** The defaults with a project's changes on top (per profile; `thirdParty` replaces, everything else merges). */
export function perfBudgets(overrides: Partial<Record<PerfProfile, Partial<PerfBudget>>> = {}): Record<PerfProfile, PerfBudget> {
return {
desktop: { ...PERF_BUDGETS.desktop, thirdParty: [...PERF_BUDGETS.desktop.thirdParty], ...overrides.desktop },
mobile: { ...PERF_BUDGETS.mobile, thirdParty: [...PERF_BUDGETS.mobile.thirdParty], ...overrides.mobile },
}
}
/** One lab measurement of a page (reference/e2e/perf-lab.mjs returns this shape). */
export type PerfMeasurement = {
bytes: { css: number; font: number; js: number }
cls: null | number
inp: null | number
lcp: null | number
renderBlocking: string[]
requests: number
tbt: null | number
thirdParty: string[]
}
/** Every budget a measurement breaks, as readable lines (empty = within budget). */
export function overBudget(measured: PerfMeasurement, budget: PerfBudget): string[] {
const out: string[] = []
const over = (name: string, value: null | number | undefined, limit: number, unit = '') => {
if (typeof value === 'number' && value > limit) {out.push(`${name} ${value}${unit} > ${limit}${unit}`)}
}
over('LCP', measured.lcp, budget.lcp, ' ms')
over('CLS', measured.cls, budget.cls)
over('TBT', measured.tbt, budget.tbt, ' ms')
over('INP (scripted tap)', measured.inp, budget.inp, ' ms')
over('JS', measured.bytes.js, budget.jsBytes, ' B')
over('CSS', measured.bytes.css, budget.cssBytes, ' B')
over('fonts', measured.bytes.font, budget.fontBytes, ' B')
over('requests', measured.requests, budget.requests)
if (measured.renderBlocking.length > budget.renderBlocking) {
out.push(`render-blocking ${measured.renderBlocking.length} > ${budget.renderBlocking}: ${measured.renderBlocking.join(', ')}`)
}
const foreign = measured.thirdParty.filter((origin) => !budget.thirdParty.includes(origin))
if (foreign.length) {out.push(`third-party requests before consent: ${foreign.join(', ')}`)}
return out
}
+14 -4
View File
@@ -49,11 +49,21 @@ export function TableOfContents({ classNames: cn = {}, items, label, offset = 0.
setActive(current)
}
update()
window.addEventListener('scroll', update, { passive: true })
window.addEventListener('resize', update)
// At most one measurement per frame: a scroll fires many events between two paints, and each one read the
// position of every heading (forced layout on the main thread, which delays the next tap — INP).
let frame = 0
const schedule = () => {
if (!frame) {frame = requestAnimationFrame(() => {
frame = 0
update()
})}
}
window.addEventListener('scroll', schedule, { passive: true })
window.addEventListener('resize', schedule)
return () => {
window.removeEventListener('scroll', update)
window.removeEventListener('resize', update)
cancelAnimationFrame(frame)
window.removeEventListener('scroll', schedule)
window.removeEventListener('resize', schedule)
}
}, [items, offset])
+1
View File
@@ -82,6 +82,7 @@ export async function readSiteMetaConfig({
collection: pagesSlug as never,
depth: 0,
locale: 'all' as never,
select: { slug: true } as never, // only the slug map is used: not the layout in every language
})) as { slug?: unknown }
const slugField = homeDoc.slug
if (slugField && typeof slugField === 'object') {
+1
View File
@@ -30,6 +30,7 @@ export async function slugsAcrossLocales({
collection: collection as never,
depth: 0,
locale: 'all',
select: { slug: true } as never, // only the slug map is used: not the layout in every language
})) as { slug?: unknown }
return doc.slug && typeof doc.slug === 'object'
+22
View File
@@ -0,0 +1,22 @@
import type { BasePayload, Config } from 'payload'
/**
* How long each plugin log keeps its records, in days (`config.custom.iapl.retention`): written by iapl() for the
* consent log, the statistics and — when the project sets one — form submissions. The purge reads it; the doctor's
* `growth-retention` rule checks that the oldest record is not older (the purge runs), docs/performance.md.
*/
export type RetentionMap = Partial<Record<string, number>>
export function withRetention(config: Config, slug: string, days: number | undefined): Config {
if (typeof days !== 'number' || !(days > 0)) {return config}
const iapl = (config.custom?.iapl ?? {}) as { retention?: RetentionMap }
return { ...config, custom: { ...config.custom, iapl: { ...iapl, retention: { ...iapl.retention, [slug]: days } } } }
}
export function retentionOf(payload: Pick<BasePayload, 'config'>, slug: string): number | undefined {
const days = ((payload.config?.custom as { iapl?: { retention?: RetentionMap } } | undefined)?.iapl?.retention ?? {})[slug]
return typeof days === 'number' && days > 0 ? days : undefined
}
export const retentionMap = (payload: Pick<BasePayload, 'config'>): RetentionMap =>
({ ...((payload.config?.custom as { iapl?: { retention?: RetentionMap } } | undefined)?.iapl?.retention ?? {}) })
+2 -1
View File
@@ -1,3 +1,4 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { IAPL_VISITOR_COOKIE, PageStats, VISITOR_COOKIE } from './PageStats.js'
export type { PageStatsProps } from './PageStats.js'
+7 -3
View File
@@ -85,7 +85,11 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }:
ensureScript()
function render() {
if (!ref.current || !window.turnstile || widgetId.current) {return}
if (widgetId.current) {
clearInterval(interval) // rendered: stop polling (it used to tick every 300 ms for the life of the form)
return
}
if (!ref.current || !window.turnstile) {return}
widgetId.current = window.turnstile.render(ref.current, {
callback: (token: string) => onToken(token),
'error-callback': () => onToken(null),
@@ -95,9 +99,9 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }:
})
}
render()
// Script may load after mount — retry briefly until ready.
// Script may load after mount — retry until it is ready, then stop.
const interval = setInterval(render, 300)
render()
return () => clearInterval(interval)
}, [siteKey, widgetTheme, onToken])
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
// Client-only exports — the Turnstile widget. Kept separate from index.ts so
// the server-only verify never leaks into a browser bundle.
export { Turnstile } from './Turnstile.js'
+9
View File
@@ -76,6 +76,7 @@ import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { withRetention } from './modules/shared/retention.js'
import { assertPluginSwitches } from './modules/shared/switches.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.js'
@@ -754,6 +755,12 @@ export const iapl = (options: IaplOptions): Plugin => {
// --- forms: apply @payloadcms/plugin-form-builder directly ---
if (options.forms) {
config = await buildFormsPlugin(options.forms)(config)
if (options.forms.submissionRetentionDays !== undefined) {
if (!(Number.isFinite(options.forms.submissionRetentionDays) && options.forms.submissionRetentionDays > 0)) {
throw new Error('[iapl] forms.submissionRetentionDays must be a number of days above 0 (leave it out to keep submissions)')
}
config = withRetention(config, 'form-submissions', options.forms.submissionRetentionDays)
}
// submitForm reads it from payload.config when the call doesn't pass one
if (options.forms.consentFieldName) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } }
@@ -868,6 +875,7 @@ export const iapl = (options: IaplOptions): Plugin => {
const logOptions = options.consentLog === true || options.consentLog === undefined ? {} : options.consentLog
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
config = withRetention(config, 'consent-records', logOptions.retentionDays ?? 1095)
}
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
@@ -949,6 +957,7 @@ export const iapl = (options: IaplOptions): Plugin => {
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
config = withRetention(config, 'stats-visits', statsOptions.retentionDays ?? 90)
config.admin = {
...(config.admin ?? {}),
components: {
+2 -1
View File
@@ -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 = {
+171
View File
@@ -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) } } }))
})
})
+4 -3
View File
@@ -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')
+13
View File
@@ -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()
+228
View File
@@ -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()
})
})