Doctor: the performance rules are errors (owner's decision for 1.18.0); lowered or silenced per rule in iapl-doctor.json; growth stays warnings; audit reports them as errors; legacy:site lists perf-* errors an old site meets; docs, skills, changelog; reference skills refreshed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f0127ac1b8
commit
8cf5a58045
+11
-2
@@ -67,13 +67,22 @@ once there are more than 20.
|
||||
> barrels are no longer one client boundary, the table of contents measures once per frame, Turnstile stops
|
||||
> polling once drawn, the cookie banner honours reduced motion. Nothing to do.
|
||||
>
|
||||
> 9. **`iapl-doctor` can now fail on the performance rules** (`perf-*`: images config, fonts, render-blocking,
|
||||
> embeds, animations, a budget test; `--url`: uncompressed HTML, blocking scripts, more than four font preloads, a
|
||||
> lazy first image, HTML over 150 KB; `--deep`: stored images over 1.5 MB / 2560 px) — they are **errors**, so a
|
||||
> plain run exits 1 on them and `--strict` too. None measures time: the same site gives the same answer every run.
|
||||
> A site with Playwright and no budget test gets `perf-budgets` (copy the `iapl-performance` skill's template).
|
||||
> Lower one with a reason: `iapl-doctor.json` → `"rules": { "perf-fonts": { "severity": "warning", "reason": "…" } }`;
|
||||
> silence one: `{ "off": true, "reason": "…", "until": "2027-03-01" }` (docs/doctor.md). The `growth-*` rules stay
|
||||
> warnings and infos.
|
||||
>
|
||||
> **New, off until a project turns it on:** `iapl({ unusedMedia: true })` — above the Media list, how many files no
|
||||
> page, entry or setting uses, with a link to Payload's list filtered to them (deleting stays manual; **run
|
||||
> `pnpm generate:importmap`** after turning it on); `forms: { submissionRetentionDays }`; `Media eager` (a logo
|
||||
> above the fold, no high priority); `createNotFoundPage({ load, placeholder })` (the reference site keeps its 404
|
||||
> height: CLS 0).
|
||||
> **Doctor:** the `performance` and `growth` groups (warnings; `growth-versions-config` is a hint), thresholds in
|
||||
> `iapl-doctor.json` → `growth`. **Agents:** the `iapl-performance` skill (`pnpm exec iapl-skills`) and the budget
|
||||
> **Doctor:** the `performance` group (errors, point 9) and the `growth` group (warnings and infos;
|
||||
> `growth-versions-config` is a hint), thresholds in `iapl-doctor.json` → `growth`. **Agents:** the `iapl-performance` skill (`pnpm exec iapl-skills`) and the budget
|
||||
> gate template. **Recommended for projects:** `index: true` on `slugHistory.slug`; the heading font with
|
||||
> `preload: false` (the starter's default now); a placeholder of the 404 content's height.
|
||||
|
||||
|
||||
+1
-1
@@ -1063,7 +1063,7 @@ Example `styles.css`: [section-code.md](./skills/iapl-block/resources/section-co
|
||||
| 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 — the plugin's default
|
||||
budgets (`PERF_BUDGETS`). Checks: `iapl-doctor --only performance` (images config, fonts, render-blocking, embeds,
|
||||
budgets (`PERF_BUDGETS`). Checks: `iapl-doctor --only performance` — **errors** since 1.18.0, an accepted exception lowered or silenced with a reason in `iapl-doctor.json` (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).
|
||||
|
||||
@@ -43,7 +43,7 @@ next/font in `--font-body` with the preset (warning), and with `src/design/token
|
||||
`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
|
||||
The full run (not `--quick`) lists the doctor's `performance` group as errors (since 1.18.0; a rule the project lowered in `iapl-doctor.json` shows as a warning): `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
|
||||
|
||||
@@ -362,12 +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.
|
||||
# --- Speed (§6.11b, performance.md) — the doctor's performance group (errors since 1.18.0): 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
|
||||
# errors since 1.18.0; a rule the project lowered in iapl-doctor.json comes back as a warning, a silenced one not at all
|
||||
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"
|
||||
| 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.severity==="error"?"E":"W"}|${f.file??"(site)"} [${f.rule}] ${f.message}`)}}}catch{}})')
|
||||
report ERROR "speed (iapl-doctor --only performance)" "§6.11b / performance.md — each line names the rule; lower or silence one with a reason in iapl-doctor.json" "$(printf '%s\n' "$PERF" | sed -n 's/^E|//p')"
|
||||
report WARNING "speed, lowered to a warning in iapl-doctor.json" "§6.11b / performance.md" "$(printf '%s\n' "$PERF" | sed -n 's/^W|//p')"
|
||||
fi
|
||||
|
||||
# --- Compile & build ---
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: iapl-doctor
|
||||
description: Checks the whole site against the IAPL team standard with one command (`pnpm exec iapl-doctor`) — plugin, Next, sharp and Node versions, the AGENT.md §3 folder layout and naming, database names (<domain>_dev/_prod), env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta/agency, AGENTS.md "Project decisions", current iapl-* skills, seeds (createSeeder, SEED_ONLY, no deletes), the block library, pnpm audit, hardcoded texts, and with --url / --deep the running site and the database. Use after setting up a site, after an IAPL upgrade, before a deploy, in CI of a new site, and when asked whether a site follows the team rules.
|
||||
description: Checks the whole site against the IAPL team standard with one command (`pnpm exec iapl-doctor`) — plugin, Next, sharp and Node versions, the AGENT.md §3 folder layout and naming, database names (<domain>_dev/_prod), env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta/agency, AGENTS.md "Project decisions", current iapl-* skills, seeds (createSeeder, SEED_ONLY, no deletes), the block library, pnpm audit, hardcoded texts, speed (the performance rules — errors) and what grows (sizes, versions, retention, unused media), and with --url / --deep the running site and the database. Use after setting up a site, after an IAPL upgrade, before a deploy, in CI of a new site, and when asked whether a site follows the team rules.
|
||||
---
|
||||
|
||||
# iapl-doctor
|
||||
@@ -25,11 +25,16 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
with the Intecion mail service (IWSN in the panel): waiting for approval, stopped, refused, disconnected, a replaced sender name),
|
||||
`mail-reply-address`, `mail-graph-deprecated`, `mail-relay-route` (trailing slashes, another API route, a redirect or a
|
||||
block in front of `/api/iapl/mail-relay/confirm`) — fixes: `iapl-debug` "Consent / analytics / forms / email".
|
||||
**Speed (`perf-*`) findings are errors since 1.18.0** (images config, fonts, render-blocking, embeds, animations,
|
||||
a budget test; `--url`: compression, blocking scripts, font preloads, a lazy first image, HTML size; `--deep`:
|
||||
oversized stored images) — the `iapl-performance` skill. The `growth-*` findings stay warnings and infos.
|
||||
4. A deliberate exception (the owner's decision) goes into `iapl-doctor.json` **with a reason** — the same reason as in
|
||||
AGENTS.md "Project decisions". Never silence a rule just to make the run pass:
|
||||
```json
|
||||
{ "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } }
|
||||
```
|
||||
A speed rule the client accepts is lowered rather than silenced, so it stays in the report:
|
||||
`"perf-fonts": { "severity": "warning", "reason": "the client's brand font, replaced in Q1" }`.
|
||||
Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`,
|
||||
`layout.allow`, `layout.frontend` (the pages' folder, e.g. `src/app/(site)` — found by structure otherwise; any route
|
||||
group name works), `seen` (written by the doctor), `extraRules`.
|
||||
|
||||
@@ -13,7 +13,10 @@ must do, how to measure, how to read the findings. This skill is the order of wo
|
||||
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:
|
||||
These are **errors** since 1.18.0 (`iapl-doctor` fails). Fix each — it names the file, the fix and the doc. When the
|
||||
client accepts one (a brand font, a map that is the page's content), lower it with a reason in `iapl-doctor.json`
|
||||
(`"perf-fonts": { "severity": "warning", "reason": "…" }`) or silence it (`"off": true`, optionally `until`), and record
|
||||
it in AGENTS.md → Project decisions. The rules that matter most:
|
||||
|
||||
| Area | Do | Never |
|
||||
|---|---|---|
|
||||
@@ -64,6 +67,6 @@ pnpm exec iapl-doctor --deep --only growth # counts and sizes per collection,
|
||||
- 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`),
|
||||
`iapl-doctor --only performance` without errors (each exception lowered or 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).
|
||||
|
||||
@@ -136,7 +136,7 @@ the proxy does no database work; the 434 KB cookie database is loaded only by a
|
||||
| 5 | Consent Mode `basic` as default | **no** (stays `advanced`) | — |
|
||||
| 6 | Card hover animates `box-shadow` | yes | an `::after` shadow layer fades with `opacity`; `CARD_INTERACTIVE_SHADOW_CLASS` = the 1.17 class |
|
||||
| 7 | Metadata on uploads | yes, no stored variants | lossless strip of JPEG APP1/APP13/COM and PNG text/eXIf/tIME (pixels and ICC byte for byte), EXIF rotation applied once; `stripMetadata: false` |
|
||||
| 8 | Doctor warnings → errors | **open** (warnings stay) | — |
|
||||
| 8 | Doctor performance rules: warnings or errors | **errors** | every `perf-*` rule is an error (none measures time, so none fails at random); lowered or silenced per rule in `iapl-doctor.json`; `growth-*` stay warnings and infos. `legacy:site` lists `perf-*` errors an old site meets (its Playwright without a budget test: `perf-budgets`) instead of failing on them |
|
||||
## 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
|
||||
|
||||
+23
-8
@@ -144,14 +144,14 @@ 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`) |
|
||||
| performance | `perf-images-config` | error | `next.config` uses `buildImagesConfig()` (AVIF / WebP, R2, long cache) — [performance.md](./performance.md) |
|
||||
| | `perf-fonts` | error | 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` | error | no `<script src>` without `async` / `defer`, no stylesheet `<link>` or CSS `@import` from another host |
|
||||
| | `perf-embeds` | error | no `<iframe>` (map, widget) that loads with the page — a click-to-load facade, or `loading="lazy"`; YouTube is `iapl-audit`'s |
|
||||
| | `perf-animations` | error | no transition of a layout property or `transition-all`, no `scroll` listener, something honours `prefers-reduced-motion` when the site animates |
|
||||
| | `perf-budgets` | error | a project that runs Playwright has a performance budget test in `e2e/` (the `iapl-performance` skill's template) |
|
||||
| | `perf-live` | error | (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` | error | (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 |
|
||||
@@ -170,6 +170,21 @@ Turn off: `iapl({ doctor: false })`. Adapt: `iapl({ doctor: { tokenVar: 'MY_TOKE
|
||||
The block rules read `blockLibraryManifest` (`@intecion/ipal-kit/blocks`), so a new library block needs no doctor
|
||||
change.
|
||||
|
||||
### The performance rules are errors (1.18.0)
|
||||
|
||||
`iapl-doctor` (and `--strict`) fails on every `perf-*` finding. None of them measures time — each reads the
|
||||
project's files, the home page's HTML or stored counts — so the same site gives the same answer every run. A project
|
||||
that accepts one for a reason lowers or silences it in `iapl-doctor.json`, per rule:
|
||||
|
||||
```json
|
||||
{ "rules": {
|
||||
"perf-fonts": { "severity": "warning", "reason": "the client's brand font, replaced in Q1" },
|
||||
"perf-embeds": { "off": true, "reason": "the map is the page's content (client decision)", "files": ["src/components/Map.tsx"] },
|
||||
"perf-budgets": { "off": true, "reason": "no e2e on this site yet", "until": "2027-03-01" }
|
||||
} }
|
||||
```
|
||||
The `growth` group stays warnings and infos.
|
||||
|
||||
## Adapt it — `iapl-doctor.json`
|
||||
|
||||
Every rule can be silenced, lowered or raised — **with a reason** — in `iapl-doctor.json` in the project root
|
||||
|
||||
+2
-2
@@ -128,7 +128,7 @@ both bundlers) holds each page type to its own numbers and counts the database q
|
||||
|
||||
## 5. The doctor's findings
|
||||
|
||||
All in the `performance` group (`iapl-doctor --only performance`), warnings in 1.18.0 (`perf-budgets` is info):
|
||||
All in the `performance` group (`iapl-doctor --only performance`), **errors** since 1.18.0: `iapl-doctor` fails on them. None measures time, so they do not fail at random. Lower one to a warning or silence it with a reason in `iapl-doctor.json` (`"rules": { "perf-fonts": { "severity": "warning", "reason": "…" } }`, [doctor.md](./doctor.md)):
|
||||
|
||||
| Rule | Source | It means | Fix |
|
||||
|---|---|---|---|
|
||||
@@ -141,7 +141,7 @@ All in the `performance` group (`iapl-doctor --only performance`), warnings in 1
|
||||
| `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)).
|
||||
Lower or silence a finding with a reason in `iapl-doctor.json` like any other ([doctor.md](./doctor.md)); the `growth` group (below) stays warnings and infos.
|
||||
|
||||
## 6. What grows — keeping the site and its database small over the years
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ next/font in `--font-body` with the preset (warning), and with `src/design/token
|
||||
`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
|
||||
The full run (not `--quick`) lists the doctor's `performance` group as errors (since 1.18.0; a rule the project lowered in `iapl-doctor.json` shows as a warning): `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
|
||||
|
||||
@@ -362,12 +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.
|
||||
# --- Speed (§6.11b, performance.md) — the doctor's performance group (errors since 1.18.0): 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
|
||||
# errors since 1.18.0; a rule the project lowered in iapl-doctor.json comes back as a warning, a silenced one not at all
|
||||
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"
|
||||
| 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.severity==="error"?"E":"W"}|${f.file??"(site)"} [${f.rule}] ${f.message}`)}}}catch{}})')
|
||||
report ERROR "speed (iapl-doctor --only performance)" "§6.11b / performance.md — each line names the rule; lower or silence one with a reason in iapl-doctor.json" "$(printf '%s\n' "$PERF" | sed -n 's/^E|//p')"
|
||||
report WARNING "speed, lowered to a warning in iapl-doctor.json" "§6.11b / performance.md" "$(printf '%s\n' "$PERF" | sed -n 's/^W|//p')"
|
||||
fi
|
||||
|
||||
# --- Compile & build ---
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: iapl-doctor
|
||||
description: Checks the whole site against the IAPL team standard with one command (`pnpm exec iapl-doctor`) — plugin, Next, sharp and Node versions, the AGENT.md §3 folder layout and naming, database names (<domain>_dev/_prod), env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta/agency, AGENTS.md "Project decisions", current iapl-* skills, seeds (createSeeder, SEED_ONLY, no deletes), the block library, pnpm audit, hardcoded texts, and with --url / --deep the running site and the database. Use after setting up a site, after an IAPL upgrade, before a deploy, in CI of a new site, and when asked whether a site follows the team rules.
|
||||
description: Checks the whole site against the IAPL team standard with one command (`pnpm exec iapl-doctor`) — plugin, Next, sharp and Node versions, the AGENT.md §3 folder layout and naming, database names (<domain>_dev/_prod), env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta/agency, AGENTS.md "Project decisions", current iapl-* skills, seeds (createSeeder, SEED_ONLY, no deletes), the block library, pnpm audit, hardcoded texts, speed (the performance rules — errors) and what grows (sizes, versions, retention, unused media), and with --url / --deep the running site and the database. Use after setting up a site, after an IAPL upgrade, before a deploy, in CI of a new site, and when asked whether a site follows the team rules.
|
||||
---
|
||||
|
||||
# iapl-doctor
|
||||
@@ -25,11 +25,16 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
with the Intecion mail service (IWSN in the panel): waiting for approval, stopped, refused, disconnected, a replaced sender name),
|
||||
`mail-reply-address`, `mail-graph-deprecated`, `mail-relay-route` (trailing slashes, another API route, a redirect or a
|
||||
block in front of `/api/iapl/mail-relay/confirm`) — fixes: `iapl-debug` "Consent / analytics / forms / email".
|
||||
**Speed (`perf-*`) findings are errors since 1.18.0** (images config, fonts, render-blocking, embeds, animations,
|
||||
a budget test; `--url`: compression, blocking scripts, font preloads, a lazy first image, HTML size; `--deep`:
|
||||
oversized stored images) — the `iapl-performance` skill. The `growth-*` findings stay warnings and infos.
|
||||
4. A deliberate exception (the owner's decision) goes into `iapl-doctor.json` **with a reason** — the same reason as in
|
||||
AGENTS.md "Project decisions". Never silence a rule just to make the run pass:
|
||||
```json
|
||||
{ "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } }
|
||||
```
|
||||
A speed rule the client accepts is lowered rather than silenced, so it stays in the report:
|
||||
`"perf-fonts": { "severity": "warning", "reason": "the client's brand font, replaced in Q1" }`.
|
||||
Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`,
|
||||
`layout.allow`, `layout.frontend` (the pages' folder, e.g. `src/app/(site)` — found by structure otherwise; any route
|
||||
group name works), `seen` (written by the doctor), `extraRules`.
|
||||
|
||||
@@ -13,17 +13,21 @@ must do, how to measure, how to read the findings. This skill is the order of wo
|
||||
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:
|
||||
These are **errors** since 1.18.0 (`iapl-doctor` fails). Fix each — it names the file, the fix and the doc. When the
|
||||
client accepts one (a brand font, a map that is the page's content), lower it with a reason in `iapl-doctor.json`
|
||||
(`"perf-fonts": { "severity": "warning", "reason": "…" }`) or silence it (`"off": true`, optionally `until`), and record
|
||||
it in AGENTS.md → Project decisions. 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 |
|
||||
| layout shift | content that arrives late keeps its space: the lazy 404's `placeholder` (its content's height), the Turnstile widget's 73 px (kept by the plugin) | an empty box a widget or a server action fills later |
|
||||
| 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'` |
|
||||
| fonts | `next/font` (self-hosted), ≤ 2 families, variable, `display: 'swap'`, the heading font `preload: false` | 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'` |
|
||||
| client code | small `'use client'` leaves; server components by default; forms through `RenderForm` / `BuilderForm` from `/client` (their code loads only where a form is shown) | a whole section `'use client'`; importing `/client/eager` without a reason |
|
||||
| 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
|
||||
@@ -55,12 +59,14 @@ pnpm exec iapl-doctor --deep --only growth # counts and sizes per collection,
|
||||
- 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.
|
||||
- Unused media: `iapl({ unusedMedia: true })` (then `pnpm generate:importmap`) shows them above the Media list with a
|
||||
link to Payload's filtered list; the editor deletes them there. The plugin never deletes media or submissions by itself.
|
||||
- MongoDB: the consent log and statistics are deleted by TTL indexes at their retention (`ttlIndex: false` turns that off).
|
||||
- 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`),
|
||||
`iapl-doctor --only performance` without errors (each exception lowered or 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).
|
||||
|
||||
@@ -105,7 +105,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
| `forms.turnstileOnConfigError` | `{ text: 'allow', files: 'reject' }` | what a form does while Turnstile CANNOT check (wrong / missing secret, Cloudflare down): a text form is accepted, a submission to the file endpoint is refused. Not involved while Turnstile is off | `'allow'` / `'reject'` for every form, or `{ text, files }`; `turnstileOnConfigError` at a call site (`createSubmitAction`, `attachments.submit`) wins |
|
||||
| `forms.attachments` | off | **File** field in the form builder; a file is checked (size, count, type by content, refused extensions), attached to the company e-mail and dropped — **never stored**; adds `POST /api/ipal/forms/submit`, the fields `submissionFiles` / `filesDelivery` / `filesDeliveryNote` / `attemptKey` on `form-submissions`, and the **Files** texts in Form messages | `true` / `FormAttachmentsOption`: `maxSizeMB` (10), `maxTotalMB`, `maxFiles` (3), `fileTypes`, `allowRisky`, `scan` (antivirus hook — none built in), `strictPdf`, `notice`, `maxConcurrent` (2), `path`, `submit` (`maxPerMinute`, `clientIp`, `honeypotField`, `turnstileHostnames`, `turnstileOnConfigError`, `allowedOrigins`, `idleTimeoutMs`, `timeoutMs`); block only: `forms.fields.file: false` or `buildFileBlock(…)`. Postgres: `migrate:create`. Check: submit a PDF → attached to the company e-mail, absent from the customer e-mail, submission shows *File delivery: Handed to the mail server* (forms.md "Files") |
|
||||
| `forms.consentFieldName` | `'consent'` | name of the GDPR consent field `submitForm` requires (read from `config.custom.ipal`) | `createSubmitAction({ consentFieldName })` / `submitForm` argument wins |
|
||||
| `consentLog` | **on** (since 1.17.0) | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min); Postgres / SQLite: a table, migration in the same deploy | `false` / `{ retentionDays }` (default 1095) |
|
||||
| `consentLog` | **on** (since 1.17.0) | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min); Postgres / SQLite: a table, migration in the same deploy; MongoDB: a TTL index deletes records older than the retention (1.18.0) | `false` / `{ retentionDays }` (default 1095) / `{ ttlIndex: false }` |
|
||||
| `unusedMedia` | off | 1.18.0: a notice above upload lists with a link to the files nothing uses (manual delete); then `pnpm generate:importmap` | `true` / `{ collections: ['media'] }` |
|
||||
| `consentLog.collectionOverrides` | none | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug) | e.g. `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }` — narrows who reads records in a project without roles |
|
||||
| `jobsRunAccess` | on (since 1.17.2), only when the project writes no `jobs.access.run` | Payload's job queue over HTTP (`/api/payload-jobs/run`, `/handle-schedules`): an admin with the second factor (an admin API key counts) or `Authorization: Bearer <CRON_SECRET>` (16+ chars); before: any signed-in account of any auth collection. In-process runs (`jobs.autoRun`, `payload jobs:run`) unaffected | `false` = Payload's default; `{ secretVar }` = another variable; your own `jobs.access.run` wins. Check: `curl -H "Authorization: Bearer $CRON_SECRET" $URL/api/payload-jobs/run` → 200, without it 401 (security.md "Payload's job queue") |
|
||||
| `doctor` | on (404 until `IAPL_DOCTOR_TOKEN` is set) | `GET /api/ipal/doctor` — read-only counts for `iapl-doctor --url` (users without TOTP, cookies waiting for approval, versions); Bearer token ≥ 32 characters, rate-limited, never names or values | `false` = no endpoint; `{ tokenVar, access }` (doctor.md) |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# IAPL — export index
|
||||
|
||||
Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`,
|
||||
`/server`, `/seed`, `/starter`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`, `/doctor`), grouped by module. Search with grep
|
||||
`/client/eager`, `/server`, `/seed`, `/starter`, `/next/middleware`, `/admin`, `/env`, `/blocks`, `/blocks/rsc`, `/templates`, `/tokens`, `/doctor`), grouped by module. Search with grep
|
||||
(`grep -n "name" .agents/skills/iapl-reference/resources/api.md`) before you write anything yourself.
|
||||
"Import from" column — the first entry is preferred. Plugin options, env, routes and what the
|
||||
project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`.
|
||||
@@ -13,7 +13,7 @@ project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/d
|
||||
| `ipalKit`, `IpalOptions`, `ipalEnvRules`, `IpalEnvFeatures`, `ipalT`, `ipalVar`, `IPAL_TOKENS`, `IPAL_BREAKPOINTS`, `IpalTokenName`, `IpalGlobalSlug` | as their new names | The names before 1.17.0 of `iapl`, `IaplOptions`, `iaplEnvRules`, `IaplEnvFeatures`, `iaplT`, `iaplVar`, `IAPL_TOKENS`, `IAPL_BREAKPOINTS`, `IaplTokenName`, `IaplGlobalSlug`: the same values, deprecated, removed in 2.0. Existing code keeps them; new code uses the new names (AGENT.md "Names: IAPL and ipal-kit"). |
|
||||
| `iapl(options)` | `@intecion/ipal-kit` | Payload 3 plugin (`plugins: [iapl({...})]`) — the only wiring point: adds globals (SiteSettings, SiteIntegrations, CookieSettings, Notifications), roles, enforced 2FA, SEO, forms, i18n (localization), white-label, stats, consent log, `/api/ipal/*` endpoints; no auth collection → injects a simple `users`. Validates `i18n` right away (fail fast). `enabled: false` = schema stays, behaviour off. |
|
||||
|
||||
**Types:** `IaplOptions` — `iapl()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `cookieScanner`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IaplGlobalSlug` — see Payload globals below.
|
||||
**Types:** `IaplOptions` — `iapl()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `cookieScanner`, `forms`, `pages`, `seo`, `searchSettings`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `globalOverrides`, `revalidatePath`, `unusedMedia`, `enabled`. `GlobalOverride`, `GlobalOverrides`, `IaplGlobalSlug` — see Payload globals below.
|
||||
|
||||
## Admin (import map) (`admin`, `branding`, `admin-ui`, `globals/SiteIntegrations`) — details: `node_modules/@intecion/ipal-kit/docs/white-label.md`, `…/docs/integrations.md`, `…/docs/email.md`, `…/docs/links.md`
|
||||
|
||||
@@ -155,7 +155,7 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|
||||
| `HeroBlock`, `TextMediaBlock`, `FeatureGridBlock`, `GalleryBlock`, `FaqBlock`, `CtaBlock`, `ContactBlock`, `TeamBlock`, `PricingBlock`, `LogosBlock`, `TestimonialsBlock`, `StatsBlock`, `RichTextBlock`, `StepsBlock`, `EntryListBlock` | `@intecion/ipal-kit/blocks/rsc` | The block components (server; props `LibraryBlockProps`: data + `locale`, `isFirst`, `ui`, `ctx`, `classNames`). |
|
||||
| `HERO_PARTS`, `TEXT_MEDIA_PARTS`, `FEATURE_GRID_PARTS`, `GALLERY_PARTS`, `FAQ_PARTS`, `CTA_PARTS`, `CONTACT_PARTS`, `TEAM_PARTS`, `PRICING_PARTS`, `LOGOS_PARTS`, `TESTIMONIALS_PARTS`, `STATS_PARTS`, `RICH_TEXT_PARTS`, `STEPS_PARTS`, `ENTRY_LIST_PARTS` | `@intecion/ipal-kit/blocks/rsc` | Default token classes per block part — the keys of `classNames`. |
|
||||
| `defaultEntryCard(doc)`, `defaultTestimonial(doc)` | `@intecion/ipal-kit/blocks/rsc` | Default mapping of a collection document to an entry card / a testimonial (`entryCard`, `mapTestimonial` replace them). |
|
||||
| `Section`, `SECTION_BACKGROUNDS`, `SectionHeader`, `Media`, `CMSLink`, `Anchor`, `buttonClass`, `BUTTON_CLASSES`, `Container`, `CONTAINER_WIDTHS`, `Card`, `CARD_CLASS`, `CARD_INTERACTIVE_CLASS` | `@intecion/ipal-kit/blocks/rsc` | UI primitives, token utilities only: section (anchor, background, `data-surface`), heading group, image/video, panel link, link element, button looks, page column, card. |
|
||||
| `Section`, `SECTION_BACKGROUNDS`, `SectionHeader`, `Media`, `CMSLink`, `Anchor`, `buttonClass`, `BUTTON_CLASSES`, `Container`, `CONTAINER_WIDTHS`, `Card`, `CARD_CLASS`, `CARD_INTERACTIVE_CLASS`, `CARD_INTERACTIVE_SHADOW_CLASS` | `@intecion/ipal-kit/blocks/rsc` | UI primitives, token utilities only: section (anchor, background, `data-surface`), heading group, image/video (`Media`: `priority`, `eager`, `sizes`, `videoMode`, `pauseForReducedMotion` — a background video paused for "reduce motion", default true), panel link, link element, button looks, page column, card (hover: an `::after` shadow layer fading with `opacity`; the 1.17 `box-shadow` transition is `CARD_INTERACTIVE_SHADOW_CLASS`). |
|
||||
| `itemHeadingLevel(slug, props)`, `leadsWithImage(props)` | `@intecion/ipal-kit/blocks/rsc` | Item heading tag (one below the section heading; `h2` without one; `itemHeadings` overrides) and whether the block's first image is the page's LCP image (`isFirst` / `firstImage`; `priorityImage: false` turns it off). |
|
||||
| `Buttons`, `headingId(block)`, `TitleLink`, `GRID_COLUMNS`, `cx`, `parts(defaults, overrides)` | `@intecion/ipal-kit/blocks/rsc` | Helpers for own blocks: button row, heading id for `aria-labelledby`, card title link (plain text when the link is dead), grid columns, class joining, part classes. |
|
||||
| `BLOCK_TEXTS`, `blockTexts(locale, own?)`, `fillText(text, value)` | `@intecion/ipal-kit/blocks/rsc` | Visitor texts the blocks write (rating, step) in en/pl; override with `texts`. |
|
||||
@@ -204,7 +204,7 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|
||||
| `readEffectiveConsent(version, gpc?)` | `@intecion/ipal-kit/client` | The stored choice under `version` with Global Privacy Control applied, read live from the cookie and `navigator` (not React state) — for your own tag loader's effects. |
|
||||
| `signalVendors(prev, next)` / `clarityConsent(state)` | `@intecion/ipal-kit/client` | Tells the running Meta Pixel (`fbq('consent', …)`), TikTok (`ttq.revokeConsent` / `grantConsent`) and Clarity (`consentv2` / `consent false`) about a change; `useConsent` calls it on every decision — for your own banner. `clarityConsent` → Clarity's `{ ad_Storage, analytics_Storage }`. |
|
||||
| `buildConsentLogCollection()` | `@intecion/ipal-kit` | Consent log collection (id, choices, version, time — no IP/personal data; proof of consent under GDPR Art. 7(1)). The plugin wires it itself with `consentLog: true` — do not call. |
|
||||
| `buildConsentLogEndpoint({ retentionDays? })` | `@intecion/ipal-kit` | `POST /api/ipal/consent` endpoint that saves decisions and deletes records older than `retentionDays` (default 1095). The plugin wires it itself with `consentLog` — do not call. |
|
||||
| `buildConsentLogEndpoint({ retentionDays? })` | `@intecion/ipal-kit` | `POST /api/ipal/consent` endpoint that saves decisions and deletes records older than `retentionDays` (default 1095). The plugin wires it itself with `consentLog` — do not call. On MongoDB a TTL index (`consentLog.ttlIndex`, default true) deletes them too, also without new records. |
|
||||
|
||||
**Built-in texts:** `CONSENT_FALLBACK`, `CONSENT_FALLBACK_PL`, `consentFallback(locale)` (banner defaults by page language), `CONSENT_CATEGORY_LABELS` / `consentCategoryOptions()` (category names `{ en, pl }`), `COOKIE_TABLE_LABELS` (`/rsc`, `<CookieTable locale>` defaults), `COOKIE_STORAGE_LABELS` (`/rsc`, type names per language).
|
||||
|
||||
@@ -401,6 +401,7 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
|
||||
| `recordIntegrationStatus(payload, field, previous, { state, code?, message? })` | `@intecion/ipal-kit` | saves the state of your own integration in Site integrations (only on change / every 10 min); does not throw. For e-mail and Turnstile the plugin calls it itself — do not call |
|
||||
| `buildIntegrationStatusField(name)` | `@intecion/ipal-kit` | hidden status group field (`state`, `code`, `message`, `since`, `checkedAt`) for `integrationsFields` |
|
||||
| `buildIntegrationStatusBanner(statusField, label, texts?)` | `@intecion/ipal-kit` | UI field with a status banner on the integration tab (`label` string or `{ en, pl }`; `texts` = `{ failing, hint }` keys of your own `ipal` translations) (`integrationsFields`; then `pnpm generate:importmap`) |
|
||||
| `UnusedMediaNotice`, `UNUSED_MEDIA_LINK_LIMIT` | `@intecion/ipal-kit/admin` | `iapl({ unusedMedia })` (1.18.0, opt-in): above an upload collection's list, how many files nothing uses (`findUnusedMedia` from `/doctor`) and a link to Payload's list filtered to them (first 100); editors and admins; deletes nothing; a hint only when the site is too big to check here |
|
||||
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | dashboard alert about integrations in the `degraded` state; always injected by the plugin (`beforeDashboard`); your own integrations: a second instance with `checks`. By role: the detail (error text, link) for `details` and above (`'admin'` default, `'editor'`, `'all'`), a neutral "ask an administrator" for editors below it, nothing for others or for a session that owes its second factor (`dashboardAlerts.integrations`). `CookieCrawlAlert` takes `audience: 'editor' \| 'all'` the same way |
|
||||
| `IntegrationStatusBanner` | `@intecion/ipal-kit/admin` | status banner on the tab; injected by the plugin / `buildIntegrationStatusBanner` through the import map (`pnpm generate:importmap`), the project does not import it |
|
||||
|
||||
@@ -431,10 +432,11 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `RenderForm({ form, action, locale, texts, classNames?, values?, … })` | `@intecion/ipal-kit/rsc` | A panel form in a block in one line (RSC): renders message blocks and the confirmation, binds `sendForm` to the form and language, resolves the redirect, sends only `publicForm` to the browser; `form` not populated → nothing |
|
||||
| `RenderForm({ form, action, locale, texts, classNames?, values?, Form?, turnstileReserveHeight?, … })` | `@intecion/ipal-kit/rsc` | A panel form in a block in one line (RSC): renders message blocks and the confirmation, binds `sendForm` to the form and language, resolves the redirect, sends only `publicForm` to the browser; `form` not populated → nothing. Renders the lazy `BuilderForm` (its code only on pages with a form, the HTML complete); `Form` swaps the component (the eager one from `/client/eager`); `turnstileReserveHeight` (default 73, 0 for an invisible widget) |
|
||||
| `prepareBuilderForm({ form, action, locale, … })` | `@intecion/ipal-kit/rsc` | The server half of `RenderForm` without markup → `PreparedBuilderForm` (or `null`) to spread into `<BuilderForm>` in a client component (e.g. a configurator with changing `values`) |
|
||||
| `publicForm(form)` | `@intecion/ipal-kit/rsc` | Public part of the form document (no Emails tab, no message rich text, safe redirect URL) — when you pass the form to the client yourself; never pass the raw document |
|
||||
| `BuilderForm(props)` | `@intecion/ipal-kit/client` | Client renderer for any panel form (steps, all field types, Turnstile, honeypot, a11y), unstyled — look via `classNames`, field replacement via `renderField`; usually used indirectly through `RenderForm` |
|
||||
| `BuilderForm(props)` | `@intecion/ipal-kit/client` | Client renderer for any panel form (steps, all field types, Turnstile, honeypot, a11y), unstyled — look via `classNames`, field replacement via `renderField`; usually used indirectly through `RenderForm`. Since 1.18.0 the `/client` export is a lazy wrapper with the same props (the code loads where a form is shown; SSR complete); `turnstileReserveHeight` keeps the widget's space |
|
||||
| `BuilderForm`, `Turnstile` | `@intecion/ipal-kit/client/eager` | The same components without lazy loading — in every page's bundle. Only when a project needs them eager: `<RenderForm Form={BuilderForm}>` |
|
||||
| `useBuilderForm({ form, action, texts, values?, onSuccess?, navigate?, redirectHref? })` | `@intecion/ipal-kit/client` | Panel form engine without markup (steps, `next/back/goTo`, per-step validation, server errors, redirect, analytics, `getInputProps`/`getSelectProps`/…, `TurnstileWidget`) — for your own markup of an unusual form |
|
||||
|
||||
### Pure panel form logic (client and server)
|
||||
@@ -537,7 +539,8 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
| `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"`) |
|
||||
| `normalizeFilenameHook` | `@intecion/ipal-kit` | `beforeOperation` hook for an upload collection (Media) that normalizes the file name; the project adds it to its Media collection |
|
||||
| `buildOptimizeUploadHook(options?)` | `@intecion/ipal-kit` | `beforeOperation` hook: blocks oversized JPG/PNG/video, converts the image to WebP after the editor agrees (sharp from `buildConfig`); the project adds it to Media |
|
||||
| `buildOptimizeUploadHook(options?)` | `@intecion/ipal-kit` | `beforeOperation` hook: blocks oversized JPG/PNG/video, converts the image to WebP after the editor agrees (sharp from `buildConfig`); removes the metadata of JPEG/PNG uploads that pass without re-encoding (`stripMetadata`, default true; 1.18.0); the project adds it to Media |
|
||||
| `stripImageMetadata(buffer, mimeType)`, `exifOrientation(app1)` | `@intecion/ipal-kit` | Lossless metadata removal: JPEG APP1/APP13/COM, PNG tEXt/zTXt/iTXt/eXIf/tIME → `{ buffer, changed, orientation }` (the EXIF rotation, to apply before); anything unreadable comes back unchanged. Type `StripResult` |
|
||||
| `buildOptimizeUploadField(name?)` | `@intecion/ipal-kit` | "Optimize this upload" consent checkbox (default `optimizeOnUpload`) for Media, paired with `buildOptimizeUploadHook` |
|
||||
| `buildMediaPlaceholderHook({ field?, size? })` | `@intecion/ipal-kit` | `beforeOperation` hook that computes a tiny blur preview (base64 WebP) and the dominant colour on upload; the project adds it to Media |
|
||||
| `buildMediaPlaceholderField(name?)` | `@intecion/ipal-kit` | Hidden field group for the placeholder (read by `mediaImageProps`), paired with `buildMediaPlaceholderHook` |
|
||||
@@ -883,7 +886,10 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `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`, `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`). |
|
||||
| `findUnusedMedia(payload, { limit?, only? })` → `UnusedMedia \| null` | `@intecion/ipal-kit/doctor` | Media of the upload collections no document or global mentions — by id or by file name in a text; `{ byCollection, checked, complete, total }`; reads only. The panel notice lists them only when `complete` |
|
||||
| `syncTtlIndex(payload, slug, { days, enabled, from })`, `ttlField()`, `TTL_FIELD`, `TTL_INDEX`, `isMongo(config)` | `@intecion/ipal-kit` | The MongoDB TTL index the plugin keeps for the consent log and statistics (1.18.0): created / moved to the current retention (`collMod`) / dropped; records backfilled once from `from`. For a log collection of your own: add `ttlField()`, call it in `onInit`. Type `TtlSyncResult` |
|
||||
| `withVersionLimit(entity, 'collection' \| 'global', limit?)`, `PLUGIN_VERSION_LIMIT` | `@intecion/ipal-kit` | A collection or global whose versions are on without a limit gets `maxPerDoc` / `max` (default 20); a limit already set wins. iapl() applies it to its own entities |
|
||||
| `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`, `-versions-config`, `-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`. |
|
||||
|
||||
@@ -104,7 +104,12 @@ const open = report.findings.filter((f) => !f.silenced)
|
||||
const count = (severity) => open.filter((f) => f.severity === severity)
|
||||
for (const f of open.filter((x) => x.severity !== 'info')) {console.log(` ${f.severity}: ${f.rule} — ${f.message}`)}
|
||||
results.push(`ipal-doctor: ${count('error').length} error(s), ${count('warning').length} warning(s) [${[...new Set(count('warning').map((f) => f.rule))].join(', ')}], ${count('info').length} info [${[...new Set(count('info').map((f) => f.rule))].join(', ')}]`)
|
||||
if (count('error').length) {
|
||||
// The performance rules are errors since 1.18.0 (the owner's decision; the changelog tells existing sites that
|
||||
// iapl-doctor can fail on them and how to lower or silence one). An old site may meet them — e.g. Playwright without a
|
||||
// budget test (perf-budgets) — and still work: they are listed, not failed. Any other error still fails.
|
||||
const expected = count('error').filter((f) => f.rule.startsWith('perf-'))
|
||||
if (expected.length) {results.push(`ipal-doctor: performance rules an old site meets (errors since 1.18.0, expected): ${[...new Set(expected.map((f) => f.rule))].join(', ')}`)}
|
||||
if (count('error').length > expected.length) {
|
||||
console.error('[legacy:site] ✗ the doctor reports an error on a site that had none')
|
||||
finish(1)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { stripComments } from '../util.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.
|
||||
* machine. Warnings and infos (the owner's decision), every threshold set in `iapl-doctor.json` → `growth`. Nothing here deletes anything.
|
||||
*/
|
||||
|
||||
const DOCS = 'docs/performance.md'
|
||||
|
||||
@@ -6,8 +6,10 @@ 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.
|
||||
* fonts, embeds, render-blocking resources, animations, a budget test — plus the running site (`--url`) and the stored
|
||||
* media (`--deep`). Errors since 1.18.0 (the owner's decision): `iapl-doctor` fails on them. None of them measures time:
|
||||
* each reads files, the home page's HTML or stored counts, so the same site gives the same answer every run. A project
|
||||
* lowers or silences one with a reason in `iapl-doctor.json` (`rules.<id>: { severity: 'warning' | off: true, reason }`).
|
||||
*/
|
||||
|
||||
const DOCS = 'docs/performance.md'
|
||||
@@ -58,7 +60,7 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' }]
|
||||
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: 'error' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
@@ -71,9 +73,9 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' })),
|
||||
...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: 'error' })),
|
||||
...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: 'error' })),
|
||||
...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: 'error' })),
|
||||
]
|
||||
const families = new Set<string>()
|
||||
for (const { code } of files) {
|
||||
@@ -82,7 +84,7 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' })
|
||||
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: 'error' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
@@ -96,9 +98,9 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' })),
|
||||
...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: 'error' })),
|
||||
...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: 'error' })),
|
||||
...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: 'error' })),
|
||||
]
|
||||
},
|
||||
docs: DOCS,
|
||||
@@ -111,7 +113,7 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' }
|
||||
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: 'error' }
|
||||
}),
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
@@ -126,14 +128,14 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' })),
|
||||
...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: 'error' })),
|
||||
...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: 'error' })),
|
||||
...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: 'error' })),
|
||||
]
|
||||
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' })
|
||||
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: 'error' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
@@ -151,7 +153,7 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' }]
|
||||
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: 'error' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
@@ -167,17 +169,17 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' })
|
||||
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: 'error' })
|
||||
}
|
||||
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' })}
|
||||
if (blocking.length) {out.push({ message: `render-blocking scripts in <head>: ${blocking.slice(0, 3).join(', ')}`, severity: 'error' })}
|
||||
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' })}
|
||||
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: 'error' })}
|
||||
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' })}
|
||||
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: 'error' })}
|
||||
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' })}
|
||||
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: 'error' })}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
@@ -191,7 +193,7 @@ export const performanceRules: DoctorRule[] = [
|
||||
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' }]
|
||||
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: 'error' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
|
||||
@@ -30,7 +30,7 @@ function project(files: Record<string, string>): string {
|
||||
}
|
||||
return root
|
||||
}
|
||||
const doctor = (root: string, only: string[], extra: { deepStatus?: object; url?: string } = {}) =>
|
||||
const doctor = (root: string, only: string[], extra: { config?: object; 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[]) => {
|
||||
@@ -84,9 +84,15 @@ describe('doctor: performance group (static)', () => {
|
||||
'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
|
||||
// every finding is an error since 1.18.0 (the owner's decision): iapl-doctor fails on them
|
||||
const report = await doctor(root, ['performance'])
|
||||
expect(new Set(report.findings.map((f) => f.severity))).toEqual(new Set(['info', 'warning']))
|
||||
expect(new Set(report.findings.map((f) => f.severity))).toEqual(new Set(['error']))
|
||||
// … and a project lowers one or silences one, with a reason, in iapl-doctor.json
|
||||
const config = { rules: { 'perf-embeds': { off: true, reason: 'the map is the page (client decision)' }, 'perf-fonts': { reason: 'the brand font from the client, being replaced', severity: 'warning' } } }
|
||||
const adapted = await doctor(root, ['performance'], { config })
|
||||
expect(new Set(adapted.findings.filter((f) => f.rule === 'perf-fonts').map((f) => f.severity))).toEqual(new Set(['warning']))
|
||||
expect(adapted.findings.filter((f) => f.rule === 'perf-embeds').every((f) => f.silenced)).toBe(true)
|
||||
expect(adapted.summary.error).toBe(report.summary.error - 4 - 1) // four font findings lowered, the map silenced
|
||||
})
|
||||
|
||||
test('a remote stylesheet <link> is reported as render-blocking', async () => {
|
||||
|
||||
Reference in New Issue
Block a user