Merge claude/performance-1180-items: the owner's performance decisions for 1.18.0 (lazy form and Turnstile with /client/eager, metadata stripped on upload, MongoDB TTL indexes, version limit, unused-media notice, performance rules as errors)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 16:20:07 +01:00
co-authored by Claude Opus 5.5
78 changed files with 3640 additions and 239 deletions
+53
View File
@@ -33,6 +33,59 @@ once there are more than 20.
> `confirmByEmail: { linkMinutes, sameBrowser, adminConfirm, logLinkWhenMailFails, notices, maxMailsPerHour }`
> (security.md "Set-up confirmed by e-mail").
### Speed and growth (docs/performance.md)
> **What changes for an existing site** (no edit needed unless a line says so; each with its opt-out):
>
> 1. **Metadata is removed from JPEG and PNG uploads** (camera, date, GPS position, comments) — without
> re-encoding: the pixels stay byte for byte, the colour profile stays. A photo whose EXIF says "rotate" is turned
> once (JPEG quality 92) so it does not show sideways. Only new uploads; stored files are not touched.
> Off: `buildOptimizeUploadHook({ stripMetadata: false })`.
> 2. **MongoDB: TTL indexes delete old consent records and statistics by themselves** — the records the daily purge
> already deleted (older than `retentionDays`: 1095 days for the consent log, 90 for statistics), now also on a
> quiet site where no new record starts the purge. At the first start the plugin adds a hidden date
> (`iaplTtlFrom`) to every existing record and creates the index `iapl_ttl`; **records older than the retention
> are deleted by MongoDB within a minute of that start** (they were due already). Off: `consentLog: { ttlIndex:
> false }`, `stats: { ttlIndex: false }` (the index is dropped at the next start; the purge stays). Postgres /
> SQLite: nothing changes (no field, no migration).
> 3. **A versioned plugin collection or global keeps 20 versions per document** (Site settings, Site integrations,
> the forms…) when a project turned its versions on without a limit — Payload's default is 100. **The oldest
> versions above 20 are removed when such a document is saved next.** Keep more: set `max` / `maxPerDoc` in your
> override. The plugin itself turns versions on nowhere.
> 4. **Forms load their code only on pages that show a form.** `BuilderForm` and `Turnstile` from
> `@intecion/ipal-kit/client` are now lazy wrappers with the same props; the server renders the whole form as
> before. On other pages 6–9 KB less JavaScript (gzip; reference site: webpack −8.8 KB, Turbopack −6.1 KB). The eager components: `@intecion/ipal-kit/client/eager`
> (`<RenderForm Form={BuilderForm}>`).
> 5. **The Turnstile widget's height is kept free before Cloudflare draws it** (73 px): the form no longer jumps when
> it appears. For an invisible widget: `turnstileReserveHeight={0}` on `RenderForm` / `BuilderForm`
> (`reserveHeight={0}` on `Turnstile`).
> 6. **A background video stops for visitors who asked for less motion** (`prefers-reduced-motion`), after
> hydration; everyone else sees no change. Off: `<Media pauseForReducedMotion={false}>`.
> 7. **Card hover** (`Card interactive`, the library's link cards) fades a shadow layer instead of animating the
> card's shadow: the same lift, drawn by the compositor. The 1.17 class: `CARD_INTERACTIVE_SHADOW_CLASS`.
> 8. **Fewer database queries per page render** (36–44 %), the lightbox viewer loads on first open, the `/client`
> 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` 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.17.2 — version history with readPublished, sign-in and panel actions, staff-only REST submissions and jobs, the cookie button
> **Read before upgrading.** No schema change, no migration on any database, no import-map change. What changes for
+8 -7
View File
@@ -1048,21 +1048,22 @@ Example `styles.css`: [section-code.md](./skills/iapl-block/resources/section-co
| 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 |
| uploads | `buildOptimizeUploadHook` (stops images over 1.5 MB / 2560 px, converts on request, removes JPEG/PNG metadata — GPS, camera — without re-encoding; `stripMetadata: false` keeps it); `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; paused for "reduce motion" by itself (`pauseForReducedMotion={false}` turns that off) | a video as the hero without a poster, `autoplay` with sound |
| video with content | `videoMode="player"` (loads after a click) | `preload="auto"` |
| 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" |
| fonts | `next/font`, max 2 families, variable, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'`; the heading font `preload: false` (the starter's default: the stylesheet and the hero load first) | 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'` |
| animations | `transform` / `opacity` only (the library's card hover fades a shadow layer), 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; `BuilderForm` and `Turnstile` there load their code only where a form is shown (`/client/eager` for the eager ones, `RenderForm Form={…}`); the Turnstile widget's 73 px are kept free (`turnstileReserveHeight={0}` for an invisible widget) | a whole section `'use client'`; an empty box that a widget fills later |
| 404 | `createNotFoundPage({ load, placeholder })` with a block as tall as the 404 content (reference `not-found.tsx`) | a lazy 404 that moves the footer |
| 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` |
| what grows | logs with a retention (consent log 1095 days, statistics 90 — on MongoDB a TTL index deletes them by itself, `ttlIndex: false` turns it off; `forms: { submissionRetentionDays }` on the client's decision), `versions: { maxPerDoc: 20 }` where you turn versions on (the plugin's own entities get 20 by themselves), unused media reviewed in the panel (`iapl({ unusedMedia: true })`, then `pnpm generate:importmap`); `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 — 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).
+7 -1
View File
@@ -829,7 +829,12 @@ import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
// The lazy 404 content arrives after hydration: a block as tall as it keeps the footer still (no layout shift).
// Measured for this site's 404 content: 282 px at 360 px wide to 432 px at 1920 — change it with that content.
export default createNotFoundPage(content, {
load: loadNotFoundView,
placeholder: <div aria-hidden style={{ minHeight: 'max(290px, calc(212px + 11.5vw))' }} />,
})
```
### `src/app/(frontend)/[locale]/notFoundView.ts`
@@ -1150,6 +1155,7 @@ Rules: AGENT.md §8a.
| `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed |
| `e2e/two-factor-enrolment.spec.ts` | the first 2FA set-up confirmed by e-mail on the built site (run by `pnpm e2e:built` in both bundlers): the password alone no longer enrols an attacker's factor (the link goes to the owner and is refused in another browser), and the panel flow — code, notice, link from the mail sink, sign in again |
| `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/unused-media.spec.ts` | the unused-files notice above the Media list (`unusedMedia: true`): an image nothing uses is listed and the link opens Payload's list filtered to it; the test deletes its own upload, the panel never deletes |
### `e2e/enrolment.ts`
+1 -1
View File
@@ -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 ---
+6 -1
View File
@@ -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`.
+11 -5
View File
@@ -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).
+2 -1
View File
@@ -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`. |
+4 -1
View File
@@ -180,7 +180,10 @@ plugin's components. `content` needs `resolveLink`; `getEntries` (entry list), `
`CMSLink` (a panel link → `Anchor`, with `buttonClass`; a link that wraps something — a logo, a card — and leads nowhere
keeps its content without a link, so an empty link group never hides it),
`buttonClass` / `BUTTON_CLASSES` (button looks by appearance), `Container` / `CONTAINER_WIDTHS`, `Card` / `CARD_CLASS` /
`CARD_INTERACTIVE_CLASS`. Helpers for the project's own blocks: `Buttons` (a block's button row), `headingId(block)`
`CARD_INTERACTIVE_CLASS` (1.18.0: the hover lift fades an `::after` shadow layer with `opacity` — drawn by the
compositor, no repaint per frame; the 1.17 `box-shadow` transition is `CARD_INTERACTIVE_SHADOW_CLASS`). `Media` pauses
a background video for visitors with "reduce motion" (`pauseForReducedMotion={false}` turns that off) and takes `eager`
for an image above the fold that is not the LCP image. Helpers for the project's own blocks: `Buttons` (a block's button row), `headingId(block)`
(the heading id for `aria-labelledby`), `TitleLink` (a card title that links when its link resolves), `GRID_COLUMNS`,
`cx`, `parts(defaults, overrides)`, `itemHeadingLevel(slug, props)` (the item heading tag) and `leadsWithImage(props)`
(whether the block's first image is the LCP image).
+2 -1
View File
@@ -617,8 +617,9 @@ to add the hook to a config. Nothing to migrate.
| Item | Value |
|---|---|
| Option | `consentLog?: boolean \| { retentionDays?: number; collectionOverrides?: CollectionOverride }` (type `ConsentLogOptions`) |
| Option | `consentLog?: boolean \| { retentionDays?: number; ttlIndex?: boolean; collectionOverrides?: CollectionOverride }` (type `ConsentLogOptions`) |
| `retentionDays` | default `1095` (3 years) |
| `ttlIndex` | 1.18.0, MongoDB: default `true` — a TTL index (`iapl_ttl` on the hidden date `iaplTtlFrom`) deletes records older than `retentionDays` by itself, also when no new record comes; kept at the current retention at every start; `false` drops it at the next start (the purge after a new record stays). Postgres / SQLite: not used, no column |
| `collectionOverrides` | changes `consent-records`: an object merges `access` / `admin` / `hooks` key by key (your keys win), other keys replace; a function `(collection) => collection` takes over (keep the slug — the endpoint writes to it) |
| Collection | `consent-records` (`CONSENT_LOG_SLUG`), group *Privacy*; fields `consentId` (index), `version`, `choices.{necessary,functional,analytics,marketing}`, `createdAt` |
| Collection access | `read` / `delete` — admin (without `access`, i.e. no roles: any logged-in account — narrow it with `collectionOverrides`); `create` / `update` — nobody through the API (written only by the endpoint, `overrideAccess`) |
+35 -41
View File
@@ -73,6 +73,22 @@ less JS and nothing new blocks: Turbopack splits the client chunks differently o
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).
### The owner's items (second branch, from main 076b3ef): before → after, median of 3
| | webpack | Turbopack |
|---|---|---|
| JS per page without a form (compressed) | 188.1 → 179.3 KB | 181.6 → 175.5 KB |
| JS on a page with a form (the form's chunk loads there) | 188.1 → 187.7 KB | 181.6 → 183.6 KB |
| JS on the showcase (every block) | 216.4 → 218.7 KB | 209.9 → 214.0 KB |
| LCP phone, pages | 796–848 → 740–776 ms | 820–868 → 780–820 ms |
| LCP desktop, pages | 280–304 → 272–288 ms | 288–308 → 276–292 ms |
| 404 phone: LCP / CLS | 2.52 s / 0.319 → 1.84 s / 0 | 2.31 s / 0.319 → 1.72 s / 0 |
| CLS home (the headings swap to their font) | 0.036 → 0.036 | 0 → 0.036 |
| Queries per render | unchanged (19–27) | unchanged |
Raw: `webpack-1180-before.json`, `webpack-1180-after.json`, `turbopack-1180-after.json` (Turbopack "before" =
`turbopack-after.json` of the first branch).
## 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,
@@ -109,37 +125,18 @@ conversion (metadata dropped); `YouTubeEmbed` is a facade; Meta, LinkedIn, TikTo
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.
### The owner's decisions (2026-12-01) — all in 1.18.0
| # | Item | Decision | What was built (measured on the reference site) |
|---|---|---|---|
| 1 | Lazy 404 moves the footer (CLS 0.319, LCP 2.5 s on a phone) | yes (a) | the reference `not-found.tsx` passes a `placeholder` of its content's height (`max(290px, calc(212px + 11.5vw))`, measured 360–1920 px): CLS 0.319 → 0, LCP 2.52 → 1.90 s |
| 2 | Heading font preloaded (four font files compete with the stylesheet) | yes | `preload: false` on Fraunces in the reference layout, and so in every new site (`iapl create` keeps the call's options): phone LCP −36 to −52 ms; home CLS stays 0.036 |
| 3 | Form code on every page | yes | `BuilderForm` / `Turnstile` from `/client` are lazy wrappers (same props; the server renders the whole form); the hooks behind them lost a needless `'use client'` (each was a client boundary the entry shipped); eager ones in `@intecion/ipal-kit/client/eager`, `RenderForm Form={…}`: −8.8 KB (webpack) / −6.1 KB (Turbopack) gzip on every page without a form; a form page loads the form's chunk as before. Found on the way: the Turnstile widget (72.6 px) appeared in an empty box and moved the form — its height is now kept (73 px, `turnstileReserveHeight`) |
| 4 | Background video ignores reduced motion | yes | `BackgroundVideo` (client) pauses it after hydration for `prefers-reduced-motion`, follows a change; `Media pauseForReducedMotion={false}` |
| 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 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
@@ -163,18 +160,15 @@ retention; 1 of 17 media unused — `logo-example-studio-1.webp`, a duplicate lo
Postgres / SQLite: the same purges through Drizzle's `deleteMany`; no TTL indexes; sizes not read (counts only).
### Growth — for the owner (yes / no)
### Growth — the owner's decisions (2026-12-01)
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).
| # | Item | Decision | What was built |
|---|---|---|---|
| 9 | A default retention for form submissions | **no** | the opt-in `forms.submissionRetentionDays` stays; the doctor reports sites without one |
| 10 | MongoDB TTL indexes for the consent log and statistics | yes | `iapl_ttl` on a hidden `iaplTtlFrom` (Payload's own `createdAt` index cannot become a TTL one: Mongoose recreates it at every start — tested, IndexOptionsConflict); backfilled once from `createdAt` / `lastAt`, kept at the current `retentionDays` by `collMod` at every start; `ttlIndex: false` drops it; Postgres / SQLite unchanged. Checked in the reference gate against the real database |
| 11 | Delete `gone` cookie-review rows | **no** | — |
| 12 | Review and delete unused media in the panel | yes, manual, optional | `iapl({ unusedMedia: true })`: a notice above each upload list with a link to Payload's list filtered to the unused files (by id or by file name in a text; nothing listed when the site is too big to check every document there); deleting is Payload's bulk delete. Off by default (it adds an import-map entry); the reference site has it on; e2e `unused-media.spec.ts` |
| 13 | `maxPerDoc: 20` where versions are on | yes | the plugin's collections and globals whose versions a project turns on get 20 unless the project sets a limit; the doctor's `growth-versions-config` hints the project's own collections. Neither the plugin nor the reference site turns versions on |
### Shared with IAWL
+770
View File
@@ -0,0 +1,770 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 19936,
"image": 9544,
"js": 175539,
"other": 0
},
"cls": 0.036,
"fcp": 812,
"inp": 40,
"interaction": "PL",
"lcp": 812,
"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": 2365,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 22,
"scriptMs": 80,
"status": 200,
"tbt": 7,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 17074,
"image": 8457,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 784,
"inp": 32,
"interaction": "PL",
"lcp": 784,
"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": 2374,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 19,
"scriptMs": 69,
"status": 200,
"tbt": 6,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 16563,
"image": 5322,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 780,
"inp": 40,
"interaction": "PL",
"lcp": 780,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2365,
"prefetches": 3,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 19,
"scriptMs": 75,
"status": 200,
"tbt": 5,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 17107,
"image": 5322,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 792,
"inp": 40,
"interaction": "PL",
"lcp": 792,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2381,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 19,
"scriptMs": 76,
"status": 200,
"tbt": 6,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 16528,
"image": 4376,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 800,
"inp": 40,
"interaction": "PL",
"lcp": 800,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2385,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 18,
"scriptMs": 78,
"status": 200,
"tbt": 8,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 16819,
"image": 0,
"js": 183565,
"other": 0
},
"cls": 0,
"fcp": 800,
"inp": 32,
"interaction": "PL",
"lcp": 800,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2551,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 17,
"scriptMs": 88,
"status": 200,
"tbt": 7,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 37329,
"image": 2018,
"js": 214068,
"other": 0
},
"cls": 0,
"fcp": 820,
"inp": 40,
"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": 2384,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 23,
"scriptMs": 161,
"status": 200,
"tbt": 10,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 7740,
"image": 0,
"js": 175539,
"other": 2380
},
"cls": 0,
"fcp": 1724,
"inp": 32,
"interaction": "PL",
"lcp": 1724,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2789,
"prefetches": 10,
"profile": "mobile",
"renderBlocking": [],
"requests": 17,
"scriptMs": 118,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 19936,
"image": 9286,
"js": 175539,
"other": 0
},
"cls": 0.001,
"fcp": 288,
"inp": 40,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 464,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 22,
"scriptMs": 38,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 17074,
"image": 10684,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary-3.webp&w=750&q=75",
"tag": "img"
},
"load": 444,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 20,
"scriptMs": 18,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 16563,
"image": 4815,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 276,
"inp": 40,
"interaction": "PL",
"lcp": 276,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 454,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 19,
"scriptMs": 32,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 17107,
"image": 4815,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 276,
"inp": 40,
"interaction": "PL",
"lcp": 276,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 437,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 19,
"scriptMs": 20,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 16528,
"image": 9286,
"js": 175539,
"other": 0
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 445,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 20,
"scriptMs": 19,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 16819,
"image": 0,
"js": 183565,
"other": 0
},
"cls": 0,
"fcp": 280,
"inp": 40,
"interaction": "PL",
"lcp": 280,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 492,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 17,
"scriptMs": 39,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 37329,
"image": 5267,
"js": 214011,
"other": 0
},
"cls": 0,
"fcp": 288,
"inp": 40,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 447,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/chunks/3_r2-9g9f0xzb.css"
],
"requests": 24,
"scriptMs": 42,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 12161,
"font": 209501,
"html": 7740,
"image": 0,
"js": 175539,
"other": 2380
},
"cls": 0,
"fcp": 392,
"inp": 40,
"interaction": "PL",
"lcp": 444,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 518,
"prefetches": 14,
"profile": "desktop",
"renderBlocking": [],
"requests": 17,
"scriptMs": 34,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98914,
"font": 0,
"html": 24294,
"image": 0,
"js": 876299,
"other": 1690
},
"cls": 0,
"fcp": 1048,
"inp": null,
"interaction": null,
"lcp": 1048,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 970,
"prefetches": 0,
"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/2do7kfo662xwp.css",
"/_next/static/chunks/1z_mbvpkjhpd5.css"
],
"requests": 23,
"scriptMs": 411,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 85,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T14:43:52.891Z",
"label": "turbopack-1180-after",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1081,
"coldStartFirstPageMs": 1101,
"firstPageMs": 18,
"ttfb_home": {
"median": 3,
"p95": 4.7
},
"ttfb_md": {
"median": 23.7,
"p95": 38.1
},
"ttfb_sitemap": {
"median": 1.6,
"p95": 2.6
},
"ttfb_llms": {
"median": 27.7,
"p95": 42.4
},
"render": {
"home": {
"medianMs": 39.6,
"queries": 24,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 33,
"media": 9,
"forms": 3
}
},
"page": {
"medianMs": 29.9,
"queries": 21,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 6,
"pages": 27,
"forms": 3
}
},
"archive": {
"medianMs": 30.1,
"queries": 23,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3,
"posts": 6
}
},
"post": {
"medianMs": 27.9,
"queries": 26,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 9,
"pages": 24,
"posts": 15,
"forms": 3
}
},
"caseStudy": {
"medianMs": 25.7,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 21,
"media": 6,
"casestudies": 9,
"forms": 3
}
},
"form": {
"medianMs": 23.7,
"queries": 19,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 3,
"pages": 24,
"forms": 3
}
},
"showcase": {
"medianMs": 48.9,
"queries": 27,
"queryMs": 0,
"byCollection": {
"globals": 24,
"pages": 33,
"media": 12,
"forms": 6,
"posts": 6
}
},
"notFound": {
"medianMs": 31.3,
"queries": 20,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6
}
},
"md": {
"medianMs": 25,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 2,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 40,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 58,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 472
}
}
+768
View File
@@ -0,0 +1,768 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 19887,
"image": 9544,
"js": 179297,
"other": 0
},
"cls": 0.036,
"fcp": 768,
"inp": 40,
"interaction": "PL",
"lcp": 768,
"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": 2374,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 21,
"scriptMs": 132,
"status": 200,
"tbt": 20,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17027,
"image": 8457,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 752,
"inp": 40,
"interaction": "PL",
"lcp": 752,
"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": 2373,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 18,
"scriptMs": 125,
"status": 200,
"tbt": 21,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16588,
"image": 5322,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 740,
"inp": 40,
"interaction": "PL",
"lcp": 740,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2378,
"prefetches": 3,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 18,
"scriptMs": 126,
"status": 200,
"tbt": 20,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17071,
"image": 5322,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 744,
"inp": 40,
"interaction": "PL",
"lcp": 744,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2374,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 18,
"scriptMs": 121,
"status": 200,
"tbt": 21,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16486,
"image": 4376,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 772,
"inp": 40,
"interaction": "PL",
"lcp": 772,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2373,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 17,
"scriptMs": 119,
"status": 200,
"tbt": 19,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16753,
"image": 0,
"js": 187749,
"other": 0
},
"cls": 0,
"fcp": 776,
"inp": 32,
"interaction": "PL",
"lcp": 776,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2565,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 16,
"scriptMs": 151,
"status": 200,
"tbt": 15,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 37304,
"image": 2018,
"js": 218738,
"other": 0
},
"cls": 0,
"fcp": 760,
"inp": 40,
"interaction": "PL",
"lcp": 760,
"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": 2415,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 22,
"scriptMs": 213,
"status": 200,
"tbt": 23,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 7677,
"image": 0,
"js": 179297,
"other": 2450
},
"cls": 0,
"fcp": 1836,
"inp": 32,
"interaction": "PL",
"lcp": 1836,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2802,
"prefetches": 10,
"profile": "mobile",
"renderBlocking": [],
"requests": 16,
"scriptMs": 167,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 19887,
"image": 9286,
"js": 179297,
"other": 0
},
"cls": 0.001,
"fcp": 280,
"inp": 40,
"interaction": "PL",
"lcp": 280,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 463,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 21,
"scriptMs": 45,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17027,
"image": 10684,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 276,
"inp": 40,
"interaction": "PL",
"lcp": 276,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary-3.webp&w=750&q=75",
"tag": "img"
},
"load": 444,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 28,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16588,
"image": 4815,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 272,
"inp": 40,
"interaction": "PL",
"lcp": 272,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 456,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 18,
"scriptMs": 43,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17071,
"image": 4815,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 276,
"inp": 40,
"interaction": "PL",
"lcp": 276,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 441,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 18,
"scriptMs": 30,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16486,
"image": 9286,
"js": 179297,
"other": 0
},
"cls": 0,
"fcp": 288,
"inp": 40,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 453,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 31,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16753,
"image": 0,
"js": 187749,
"other": 0
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 438,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 16,
"scriptMs": 47,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 37304,
"image": 5267,
"js": 218795,
"other": 0
},
"cls": 0,
"fcp": 288,
"inp": 40,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 452,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 23,
"scriptMs": 52,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 7677,
"image": 0,
"js": 179297,
"other": 2450
},
"cls": 0,
"fcp": 404,
"inp": 32,
"interaction": "PL",
"lcp": 464,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 523,
"prefetches": 14,
"profile": "desktop",
"renderBlocking": [],
"requests": 16,
"scriptMs": 47,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98168,
"font": 0,
"html": 24043,
"image": 0,
"js": 843368,
"other": 1690
},
"cls": 0,
"fcp": 1016,
"inp": null,
"interaction": null,
"lcp": 1016,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 944,
"prefetches": 0,
"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": 348,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 87,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T14:38:54.097Z",
"label": "webpack-1180-after",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 984,
"coldStartFirstPageMs": 1003,
"firstPageMs": 18,
"ttfb_home": {
"median": 3.6,
"p95": 5.6
},
"ttfb_md": {
"median": 21.7,
"p95": 27.5
},
"ttfb_sitemap": {
"median": 1.1,
"p95": 1.4
},
"ttfb_llms": {
"median": 34.1,
"p95": 42
},
"render": {
"home": {
"medianMs": 52.1,
"queries": 24,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 9,
"pages": 33,
"forms": 3
}
},
"page": {
"medianMs": 32.2,
"queries": 21,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3
}
},
"archive": {
"medianMs": 41.5,
"queries": 23,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3,
"posts": 6
}
},
"post": {
"medianMs": 27.5,
"queries": 26,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 9,
"posts": 15,
"forms": 3
}
},
"caseStudy": {
"medianMs": 29.9,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 21,
"media": 6,
"casestudies": 9,
"forms": 3
}
},
"form": {
"medianMs": 21.5,
"queries": 19,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 3,
"forms": 3
}
},
"showcase": {
"medianMs": 50,
"queries": 27,
"queryMs": 0,
"byCollection": {
"globals": 24,
"media": 12,
"pages": 33,
"forms": 6,
"posts": 6
}
},
"notFound": {
"medianMs": 26.6,
"queries": 20,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6
}
},
"md": {
"medianMs": 37,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 3,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 43,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 56,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 410
}
}
+768
View File
@@ -0,0 +1,768 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 19869,
"image": 9544,
"js": 188112,
"other": 0
},
"cls": 0.036,
"fcp": 812,
"inp": 40,
"interaction": "PL",
"lcp": 812,
"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": 2543,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 22,
"scriptMs": 174,
"status": 200,
"tbt": 46,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 17109,
"image": 8457,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 812,
"inp": 48,
"interaction": "PL",
"lcp": 812,
"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": 2571,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 19,
"scriptMs": 197,
"status": 200,
"tbt": 73,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 16552,
"image": 5322,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 836,
"inp": 48,
"interaction": "PL",
"lcp": 836,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2548,
"prefetches": 3,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 19,
"scriptMs": 179,
"status": 200,
"tbt": 59,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 17079,
"image": 5322,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 796,
"inp": 40,
"interaction": "PL",
"lcp": 796,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2511,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 19,
"scriptMs": 128,
"status": 200,
"tbt": 27,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 16570,
"image": 4376,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 816,
"inp": 40,
"interaction": "PL",
"lcp": 816,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2502,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 18,
"scriptMs": 132,
"status": 200,
"tbt": 35,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 16294,
"image": 0,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 816,
"inp": 40,
"interaction": "PL",
"lcp": 816,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2466,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 16,
"scriptMs": 126,
"status": 200,
"tbt": 23,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 36926,
"image": 2018,
"js": 216415,
"other": 0
},
"cls": 0,
"fcp": 848,
"inp": 40,
"interaction": "PL",
"lcp": 848,
"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": 2485,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 21,
"scriptMs": 207,
"status": 200,
"tbt": 31,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 7700,
"image": 0,
"js": 188112,
"other": 2470
},
"cls": 0.319,
"fcp": 2524,
"inp": 40,
"interaction": "PL",
"lcp": 2524,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2594,
"prefetches": 10,
"profile": "mobile",
"renderBlocking": [],
"requests": 17,
"scriptMs": 232,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 19869,
"image": 9286,
"js": 188112,
"other": 0
},
"cls": 0.001,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 479,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 22,
"scriptMs": 43,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 17109,
"image": 10684,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": "high",
"loading": "eager",
"src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary-2.webp&w=750&q=75",
"tag": "img"
},
"load": 460,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 20,
"scriptMs": 29,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 16552,
"image": 4815,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 288,
"inp": 40,
"interaction": "PL",
"lcp": 288,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 473,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 19,
"scriptMs": 31,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 17079,
"image": 4815,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 280,
"inp": 40,
"interaction": "PL",
"lcp": 280,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 461,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 19,
"scriptMs": 29,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 16570,
"image": 9286,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 304,
"inp": 40,
"interaction": "PL",
"lcp": 304,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 465,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 20,
"scriptMs": 31,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 16294,
"image": 0,
"js": 188112,
"other": 0
},
"cls": 0,
"fcp": 280,
"inp": 40,
"interaction": "PL",
"lcp": 280,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 457,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 16,
"scriptMs": 29,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 36926,
"image": 5267,
"js": 216415,
"other": 0
},
"cls": 0,
"fcp": 304,
"inp": 40,
"interaction": "PL",
"lcp": 304,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 470,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/2419e69855bb1a63.css"
],
"requests": 22,
"scriptMs": 47,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11070,
"font": 209501,
"html": 7700,
"image": 0,
"js": 188112,
"other": 2470
},
"cls": 0,
"fcp": 508,
"inp": 40,
"interaction": "PL",
"lcp": 564,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 500,
"prefetches": 14,
"profile": "desktop",
"renderBlocking": [],
"requests": 17,
"scriptMs": 43,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98168,
"font": 0,
"html": 24044,
"image": 0,
"js": 843325,
"other": 1690
},
"cls": 0,
"fcp": 1012,
"inp": null,
"interaction": null,
"lcp": 1012,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 942,
"prefetches": 0,
"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": 348,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 86,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T14:02:14.941Z",
"label": "webpack-1180-before",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1460,
"coldStartFirstPageMs": 1487,
"firstPageMs": 26,
"ttfb_home": {
"median": 3.5,
"p95": 6
},
"ttfb_md": {
"median": 38.1,
"p95": 54.6
},
"ttfb_sitemap": {
"median": 2,
"p95": 3.2
},
"ttfb_llms": {
"median": 53.1,
"p95": 83.3
},
"render": {
"home": {
"medianMs": 63.8,
"queries": 24,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 33,
"media": 9,
"forms": 3
}
},
"page": {
"medianMs": 38.7,
"queries": 21,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3
}
},
"archive": {
"medianMs": 40.8,
"queries": 23,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 6,
"pages": 27,
"forms": 3,
"posts": 6
}
},
"post": {
"medianMs": 42.1,
"queries": 26,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 9,
"posts": 15,
"forms": 3
}
},
"caseStudy": {
"medianMs": 45.1,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 21,
"media": 6,
"casestudies": 9,
"forms": 3
}
},
"form": {
"medianMs": 30.6,
"queries": 19,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 3,
"forms": 3
}
},
"showcase": {
"medianMs": 75.5,
"queries": 27,
"queryMs": 0,
"byCollection": {
"globals": 24,
"pages": 33,
"media": 12,
"forms": 6,
"posts": 6
}
},
"notFound": {
"medianMs": 45.8,
"queries": 20,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6
}
},
"md": {
"medianMs": 38,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 2,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 59,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 71,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 378
}
}
+24 -8
View File
@@ -144,20 +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`) |
| 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 |
| | `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-versions-config` | info | a collection or global in `src/collections` / `src/globals` turns versions on without `maxPerDoc` / `max` (Payload keeps 100) — the hint names the limit to add |
| | `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 |
@@ -169,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
+7
View File
@@ -99,6 +99,13 @@ the action to the form and the language, resolves the redirect and gives the bro
form** — the Local API reads with `overrideAccess`, so the document has the Emails tab (company addresses);
a hand-written `<FormRenderer form={form}>` used to send them in the HTML. Underneath it is `BuilderForm` (client).
**The form's code loads only on pages that show a form (1.18.0).** `RenderForm` renders a lazy `BuilderForm`, and
`BuilderForm` / `Turnstile` from `@intecion/ipal-kit/client` are the lazy wrappers (same props): the server renders the
whole form, the browser fetches the code while it hydrates — every other page carries none of it (reference site: −8.8 KB gzip with webpack, −6.1 KB with
Turbopack). The eager component, in every page's bundle: `import { BuilderForm } from
'@intecion/ipal-kit/client/eager'` and `<RenderForm Form={BuilderForm} …>`. The Turnstile widget's height is kept free
before Cloudflare draws it: `turnstileReserveHeight` (default 73, `0` for an invisible widget).
### Field types in the panel
text, email, textarea, number, **date**, **time** (1.11.1), select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state as text), and **File** when `forms.attachments` is on ("Files" below).
+15
View File
@@ -50,6 +50,21 @@ export const Media: CollectionConfig = {
}
```
**Metadata (1.18.0).** Every JPEG and PNG upload that passes the limits loses its metadata — camera, date, GPS
position, comments — without re-encoding: `stripImageMetadata` drops the JPEG APP1 (EXIF, XMP), APP13 (IPTC) and
comment segments and the PNG text, eXIf and tIME chunks; the pixels and the colour profile stay byte for byte. A photo
whose EXIF says "rotate" is turned once (sharp, JPEG quality 92) so it does not show sideways. Only new uploads; no
stored variants are added. Off: `buildOptimizeUploadHook({ stripMetadata: false })`. Building blocks:
`stripImageMetadata(buffer, mimeType)` → `{ buffer, changed, orientation }`, `exifOrientation(app1)`.
**Unused media in the panel (1.18.0, opt-in).** `iapl({ unusedMedia: true })` (or `{ collections: ['media'] }`) puts a
notice above the list of each upload collection: how many files no page, entry or setting uses — by id (relations,
uploads in rich text and blocks, drafts and every language) or by file name inside a text — with a link that opens
Payload's own list filtered to them. The editor checks them and deletes them there (bulk delete, with its confirmation
and access rules); nothing is deleted by itself. Editors and admins see it; on a site with more than 5000 documents it
shows only a hint to run `iapl-doctor --deep` (`growth-media`). After turning it on: `pnpm generate:importmap`
(`@intecion/ipal-kit/admin#UnusedMediaNotice`).
`buildOptimizeUploadHook` and `buildMediaPlaceholderHook` use the `sharp` passed to
`buildConfig({ sharp })` — the plugin does not import it. Postgres with migrations: new fields →
`pnpm payload migrate:create`.
+24 -18
View File
@@ -20,12 +20,15 @@ response on that profile (the 404 page is the exception, below).
| 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` |
| Upload metadata | every JPEG and PNG that passes the limits loses its metadata (camera, date, GPS, comments) without re-encoding — pixels and colour profile byte for byte; an EXIF "rotate" is applied once (JPEG q92) | `buildOptimizeUploadHook({ stripMetadata: false })`; the building block `stripImageMetadata(buffer, mime)` |
| 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 | — |
| Client JavaScript | small client leaves; a page ships only the client components it renders (the `/client` barrels are no longer one client boundary); the lightbox viewer loads on the first open; the form engine and the Turnstile widget load only on pages that show a form (`BuilderForm` / `Turnstile` from `/client` are lazy wrappers, the server renders the whole form) — 6–9 KB gzip less JavaScript on every other page of the reference site (webpack −8.8, Turbopack −6.1) | `@intecion/ipal-kit/client/eager` → `<RenderForm Form={BuilderForm}>` |
| Turnstile | its 73 px are kept free before Cloudflare draws the widget: the form does not jump | `turnstileReserveHeight={0}` (an invisible widget) |
| 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 |
| Fonts | the reference layout (and every new site from `iapl create`) uses `next/font` (self-hosted, `display: 'swap'`, fallback metrics against layout shift) and does not preload the heading font: the stylesheet and the hero get the first round trips (phone: first paint and LCP 36–52 ms sooner) | the project's own fonts; `preload: true` on the heading font |
| 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; a background video (`<Media videoMode="background">`) is paused for those visitors; the card hover fades a shadow layer (`opacity`, compositor-only) instead of animating `box-shadow` | `motion-reduce:` classes; `<Media pauseForReducedMotion={false}>`; `CARD_INTERACTIVE_SHADOW_CLASS` (the 1.17 hover) |
| 404 | the lazy 404 (`createNotFoundPage({ load })`) keeps its content's height with `placeholder` — the reference site sets it (phone: CLS 0.319 → 0, LCP 2.5 → 1.9 s) | the placeholder's height follows your 404 content |
| 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
@@ -43,16 +46,18 @@ Every row is something the plugin cannot decide for you. `iapl-doctor --only per
**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.
- Content that arrives after the first paint reserves its space. The lazy 404 is the plugin's own case: the
reference `not-found.tsx` passes `placeholder: <div aria-hidden style={{ minHeight: 'max(290px, calc(212px + 11.5vw))' }} />`
— its 404 content's height, measured from 360 to 1920 px wide. Measure yours the same way when the 404 content
changes (the footer must not move when it arrives).
- 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.
four files (the reference site: 209 KB). The heading font gets `preload: false` (the starter's default): its files
still come, after the stylesheet and the hero. 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))
@@ -123,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 |
|---|---|---|---|
@@ -136,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
@@ -145,24 +150,24 @@ Measured on the reference site after a full test run (MongoDB; average record wi
| 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 }` |
| Consent log (`consent-records`) | one record per banner choice | deleted after `retentionDays` (default 1095 — three years, the proof-of-consent period): on MongoDB by a TTL index (`iapl_ttl` on the hidden `iaplTtlFrom`, kept at the current retention at every start), also on a quiet site; everywhere also by the purge after a new record (at most once a day) | `consentLog: { retentionDays, ttlIndex: false }` |
| Statistics (`stats-visits`, opt-in) | one record per visit | deleted after `retentionDays` (default 90) since the visit's last page view: TTL index on MongoDB, the same purge | `stats: { retentionDays, ttlIndex: false }` |
| 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) |
| Versions and drafts | every save | the plugin turns versions on nowhere; when a project turns them on for one of the plugin's collections or globals (overrides) without a limit, it keeps 20 per document (Payload's default is 100) | your own limit wins (`max`, `maxPerDoc`); on your own collections `versions: { maxPerDoc: 20 }` (the doctor's `growth-versions-config` hint); never `0` |
| `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 |
| Media | uploads | Payload deletes the files (and R2 objects) with the document; nothing deletes media by itself. `iapl({ unusedMedia: true })` shows above the Media list how many files no page, entry or setting uses (by id, or by file name inside a text) and links to Payload's list filtered to them; the editor checks and deletes them there | turn it on (then `pnpm generate:importmap`); the doctor's `growth-media` counts them either way |
| `.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.
**Postgres and SQLite:** the same purges (one `DELETE … WHERE created_at < …`); no TTL index and no `iaplTtlFrom`
column (no migration); 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).
**What a project schedules:** nothing for the plugin's own logs — on MongoDB the TTL indexes delete by themselves,
elsewhere the purges run inside the site after a new record. A SQL 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
@@ -181,6 +186,7 @@ document points at; and on the machine it runs on, the image cache and the local
| `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-versions-config` | static | a collection or global of the project turns versions on without `maxPerDoc` / `max` (info: Payload keeps 100) |
| `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.
+2 -1
View File
@@ -43,6 +43,7 @@ iapl({
| Option (`StatsOptions`) | Default | Description |
|---|---|---|
| `retentionDays` | `90` | older visits (by `lastAt`) are deleted |
| `ttlIndex` | `true` | 1.18.0, MongoDB: a TTL index deletes visits whose last page view is older than `retentionDays`, also on a quiet site; `false` drops it at the next start. Postgres / SQLite: not used |
| `timeZone` | `'Europe/Warsaw'` | day boundary (`day` field, salt rotation, charts) |
| `dashboard` | `true` | `false` removes only `StatsWidget` from the dashboard — the view and the nav link stay |
| `collectionOverrides` | none | changes `stats-visits`: an object merges `access` / `admin` / `hooks` key by key (your keys win), a function `(collection) => collection` takes over (keep the slug). Its `access.read` also decides who sees the stats view and the dashboard chart |
@@ -124,7 +125,7 @@ A sequence of page views with gaps under 30 minutes, within one day. A server re
instances (each has its own salt) can split an ongoing visit in two — irrelevant for statistics. Do
**not** store the salt in the database to "fix" this: then yesterday's hashes could be reversed to IPs.
Visits older than `retentionDays` are deleted automatically — at most once a day per server process,
On MongoDB a TTL index deletes them by itself (`ttlIndex`, 1.18.0). Everywhere, visits older than `retentionDays` are also deleted — at most once a day per server process,
on a page view, with one `db.deleteMany` query **in the background** (the page view does not wait for
the cleanup; an error goes to the log and the cleanup is retried on the next page view). The salt
changes when `day` changes in the `timeZone` zone.
+5
View File
@@ -231,6 +231,11 @@ provider: change its `resetSignal` prop to get the same.
| `onToken` | `(token: string \| null) => void` | — | token once solved; `null` on expiry / error / theme change |
| `theme` | `'page' \| 'auto' \| 'light' \| 'dark'` | `'page'` | `'page'` = the site's theme (`data-theme`, ThemeScript), no theme → `'auto'` |
| `resetSignal` | `number` | `0` | change the value → the widget issues a new token (what `reset()` does for the provider's widget) |
| `reserveHeight` | `number` | `73` | 1.18.0: the widget's height kept free before Cloudflare draws it (the form below does not jump); `0` for an invisible widget. Through a form: `turnstileReserveHeight` on `RenderForm` / `BuilderForm`, `TurnstileWidget({ reserveHeight })` |
`<Turnstile>` from `@intecion/ipal-kit/client` is a lazy wrapper since 1.18.0 (same props): the widget's code loads
where a form shows it, not with every page; the provider in the layout loads it the same way. The eager component:
`@intecion/ipal-kit/client/eager`.
### Why Turnstile is NOT fully "drop in and forget" like CookieBanner
+5
View File
@@ -19,6 +19,11 @@
"types": "./dist/exports/client.d.ts",
"default": "./dist/exports/client.js"
},
"./client/eager": {
"import": "./dist/exports/client-eager.js",
"types": "./dist/exports/client-eager.d.ts",
"default": "./dist/exports/client-eager.js"
},
"./rsc": {
"import": "./dist/exports/rsc.js",
"types": "./dist/exports/rsc.d.ts",
+1 -1
View File
@@ -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`. |
+38 -8
View File
@@ -20,10 +20,11 @@ import { measureMedian } from './perf-lab.mjs'
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 },
// measured 1.18.0 (docs/dev/perf/*-1180-after.json): JS 175–180 kB on a page without a form, 184–188 kB with one
// (the form's code loads there only), CSS 11–12 kB, fonts 209.5 kB (Inter + Fraunces, latin + latin-ext; the
// heading font not preloaded), LCP 0.74–0.82 s on the phone, 0.28–0.30 s on the desktop
desktop: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 195_000, lcp: 800, renderBlocking: 1, requests: 36, tbt: 50 },
mobile: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 195_000, lcp: 1500, renderBlocking: 1, requests: 30, tbt: 100 },
})
/** One of each template (AGENTS.md → Site map), with what differs for that page. */
@@ -37,10 +38,8 @@ const PAGES: Array<{ budget?: { desktop?: Budget; mobile?: Budget }; name: strin
{ 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)' },
// the lazy 404: its content arrives after hydration; the placeholder in not-found.tsx keeps its height (CLS 0)
{ budget: { mobile: { lcp: 2200 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'the 404 content comes from a server action after hydration' },
]
let browser: Browser
@@ -110,3 +109,34 @@ test.describe('queries per render', () => {
}
})
})
/**
* MongoDB TTL index of the consent log (1.18.0, shared/ttl.ts): the database deletes records older than the retention
* itself, also on a quiet site. The index exists with the retention's lifetime, and a new record carries the date it
* counts from. Skipped when not MongoDB.
*/
test('consent log: the TTL index is there and a new record carries its date', async ({ baseURL }) => {
const uri = process.env.DATABASE_URI
test.skip(!uri?.startsWith('mongodb'), 'not MongoDB')
const site = process.cwd()
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()
try {
const records = conn.db!.collection('consent-records')
const ttl = (await records.indexes()).find((i) => i.name === 'iapl_ttl')
expect(ttl, 'the TTL index').toMatchObject({ expireAfterSeconds: 1095 * 86_400, key: { iaplTtlFrom: 1 } })
const id = [...crypto.getRandomValues(new Uint8Array(12))].map((b) => b.toString(16).padStart(2, '0')).join('')
const res = await fetch(`${baseURL}/api/ipal/consent`, {
body: JSON.stringify({ id, state: { analytics: false, functional: false, marketing: false, necessary: true }, version: 1 }),
headers: { 'content-type': 'application/json', origin: baseURL! },
method: 'POST',
})
expect(res.status).toBe(201)
const record = await records.findOne({ consentId: id })
expect(record?.iaplTtlFrom, 'the date the TTL counts from').toBeInstanceOf(Date)
await records.deleteOne({ consentId: id })
} finally {
await conn.close()
}
})
+46
View File
@@ -0,0 +1,46 @@
import { expect, test } from '@playwright/test'
import { editorTestAccount, totp } from './totp'
/**
* `iapl({ unusedMedia: true })` (1.18.0; docs/media.md): above the Media list, how many files nothing uses, with a
* link to Payload's own list filtered to them. An image uploaded here and used nowhere must be listed; it is deleted
* by this test afterwards, never by the panel. Signs in as the test editor (the admins' 2FA attempts stay for the
* other specs).
*/
test('Media: the unused-files notice lists a file nothing uses and links to the filtered list', async ({ baseURL, page }) => {
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env
test.skip(!email || !password || !secret, 'E2E_* test admin not configured')
await page.goto('/admin/login')
await page.fill('#field-email', editorTestAccount(email!))
await page.fill('#field-password', password!)
await page.click('.form-submit button')
await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' })
if (page.url().includes('verify-totp')) {
await page.getByRole('textbox').first().click()
await page.keyboard.type(totp(secret!))
}
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
// a 1×1 PNG nobody points at
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64')
// the session cookie counts only with the site's own Origin (Payload's CSRF rule)
const origin = { origin: new URL(baseURL!).origin }
const created = await page.request.post('/api/media', {
headers: origin,
multipart: { _payload: JSON.stringify({ alt: 'unused-media e2e' }), file: { buffer: png, mimeType: 'image/png', name: 'unused-media-e2e.png' } },
})
expect(created.status(), await created.text()).toBe(201)
const id = ((await created.json()) as { doc: { id: string } }).doc.id
try {
await page.goto('/admin/collections/media')
const notice = page.locator('[data-iapl="unused-media"]')
await expect(notice).toBeVisible()
const href = await notice.locator('a').getAttribute('href')
expect(href).toContain(`=${id}`)
await notice.locator('a').click()
await expect(page.getByText('unused-media-e2e', { exact: false }).first()).toBeVisible()
} finally {
await page.request.delete(`/api/media/${id}`, { headers: origin })
}
})
@@ -15,7 +15,9 @@ import '../styles.css'
// Fixed slot names from the token standard: --font-family-body / --font-family-heading (design-tokens.md)
const body = Inter({ display: 'swap', subsets: ['latin', 'latin-ext'], variable: '--font-family-body' })
const heading = Fraunces({ display: 'swap', subsets: ['latin', 'latin-ext'], variable: '--font-family-heading' })
// The heading font is not preloaded: the stylesheet and the hero image get the first round trips (measured on a
// phone: first paint and LCP 36–52 ms sooner; headings swap in with fallback metrics, CLS stays < 0.1 — docs/performance.md)
const heading = Fraunces({ display: 'swap', preload: false, subsets: ['latin', 'latin-ext'], variable: '--font-family-heading' })
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
@@ -4,4 +4,9 @@ import * as content from '@/lib/content'
import { loadNotFoundView } from './notFoundView'
export default createNotFoundPage(content, { load: loadNotFoundView })
// The lazy 404 content arrives after hydration: a block as tall as it keeps the footer still (no layout shift).
// Measured for this site's 404 content: 282 px at 360 px wide to 432 px at 1920 — change it with that content.
export default createNotFoundPage(content, {
load: loadNotFoundView,
placeholder: <div aria-hidden style={{ minHeight: 'max(290px, calc(212px + 11.5vw))' }} />,
})
@@ -28,6 +28,7 @@ import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea
import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { UnusedMediaNotice as UnusedMediaNotice_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TwoFactorStatusField as TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
@@ -84,6 +85,7 @@ export const importMap = {
"@intecion/ipal-kit/admin#MetaDescriptionCheck": MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/admin#UnusedMediaNotice": UnusedMediaNotice_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#TwoFactorStatusField": TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23,
+2
View File
@@ -1372,6 +1372,7 @@ export interface ConsentRecord {
analytics?: boolean | null;
marketing?: boolean | null;
};
iaplTtlFrom?: string | null;
updatedAt: string;
createdAt: string;
}
@@ -2442,6 +2443,7 @@ export interface ConsentRecordsSelect<T extends boolean = true> {
analytics?: T;
marketing?: T;
};
iaplTtlFrom?: T;
updatedAt?: T;
createdAt?: T;
}
+2
View File
@@ -94,6 +94,8 @@ export default buildConfig({
// @starter:else
//: forms: { redirectRelationships: ['pages'], emailLayout: true }, // files on forms: add `attachments: true` (forms.md "Files")
// @starter:endif
// Media → above the list: files no page, entry or setting uses, with a link to review and delete them by hand
unusedMedia: true,
// @starter:if twoFactor
twoFactor: { issuer: 'Example Studio', plugin: payloadTotp },
// @starter:else
+1 -1
View File
@@ -100,7 +100,7 @@ for (const bundler of bundlers) {
process.exit(1)
}
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' })
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, the own account and the unused-files notice`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', 'unused-media', '--grep', 'unused-files notice|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)
+6 -1
View File
@@ -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)
}
+1
View File
@@ -70,6 +70,7 @@ export const DESCRIPTIONS = {
'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/unused-media.spec.ts': 'the unused-files notice above the Media list (`unusedMedia: true`): an image nothing uses is listed and the link opens Payload\'s list filtered to it; the test deletes its own upload, the panel never deletes',
'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)',
+1
View File
@@ -23,6 +23,7 @@ export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTa
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { UNUSED_MEDIA_LINK_LIMIT, UnusedMediaNotice } from '../modules/media/UnusedMediaNotice.js'
export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js'
export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.js'
export { TotpRedirectProvider } from '../modules/security/totp/TotpRedirectProvider.js'
+1 -1
View File
@@ -46,7 +46,7 @@ export { Anchor } from '../modules/block-library/ui/Anchor.js'
export type { LinkComponent } from '../modules/block-library/ui/Anchor.js'
export { BUTTON_CLASSES, buttonClass } from '../modules/block-library/ui/Button.js'
export { Buttons, GRID_COLUMNS, headingId } from '../modules/block-library/ui/Buttons.js'
export { Card, CARD_CLASS, CARD_INTERACTIVE_CLASS } from '../modules/block-library/ui/Card.js'
export { Card, CARD_CLASS, CARD_INTERACTIVE_CLASS, CARD_INTERACTIVE_SHADOW_CLASS } from '../modules/block-library/ui/Card.js'
export type { CardProps } from '../modules/block-library/ui/Card.js'
export { CMSLink } from '../modules/block-library/ui/CMSLink.js'
export type { CMSLinkProps, ResolveLink } from '../modules/block-library/ui/CMSLink.js'
+11
View File
@@ -0,0 +1,11 @@
/**
* Entry point: @intecion/ipal-kit/client/eager
*
* The form and the Turnstile widget WITHOUT lazy loading (1.18.0). `@intecion/ipal-kit/client` exports lazy wrappers
* with the same props, so a page without a form carries none of this code. Import from here only when a project
* wants the code in every page's bundle (e.g. a form that must work before hydration finishes):
* import { BuilderForm } from '@intecion/ipal-kit/client/eager'
* <RenderForm Form={BuilderForm} … />
*/
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export { Turnstile } from '../modules/turnstile/Turnstile.js'
+3 -1
View File
@@ -41,7 +41,6 @@ export type { ConstructionNoticeClassNames } from '../modules/construction/Const
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
export type { ConstructionMode } from '../modules/construction/types.js'
export { formatFileSize } from '../modules/forms/attachments/fileTypes.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js'
export type { BuilderFile } from '../modules/forms/builderLogic.js'
@@ -58,6 +57,9 @@ export type {
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
// `BuilderForm` is the lazy wrapper since 1.18.0 (same props, the server renders the whole form): the form's code
// loads only on a page that shows one. The eager component: `@intecion/ipal-kit/client/eager`.
export { LazyBuilderForm as BuilderForm } from '../modules/forms/LazyBuilderForm.js'
export { useBuilderForm } from '../modules/forms/useBuilderForm.js'
export type { BuilderFormApi, UseBuilderFormOptions } from '../modules/forms/useBuilderForm.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
+2 -2
View File
@@ -8,8 +8,8 @@
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 { collectGrowth, findUnusedMedia } from '../modules/doctor/growth.js'
export type { GrowthStatus, UnusedMedia } 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'
+7 -1
View File
@@ -435,7 +435,8 @@ export type {
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook, exifOrientation, normalizeFilename, normalizeFilenameHook, stripImageMetadata } from './modules/media/index.js'
export type { StripResult } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js'
export {
buildMediaPlaceholderField,
@@ -617,6 +618,10 @@ export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, m
export { clientIp, ipRateKey, releaseRateLimit, setIpv6Grouping, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { Ipv6Grouping } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
// What grows (docs/performance.md §6): MongoDB TTL indexes of the plugin's logs, the version limit of its own entities
export { isMongo, syncTtlIndex, TTL_FIELD, TTL_INDEX, ttlField } from './modules/shared/ttl.js'
export type { TtlSyncResult } from './modules/shared/ttl.js'
export { PLUGIN_VERSION_LIMIT, withVersionLimit } from './modules/shared/versionLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { STATS_SLUG } from './modules/stats/index.js'
export type { StatsOptions, StatsPage, StatsVisit } from './modules/stats/index.js'
@@ -632,6 +637,7 @@ export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js'
export { defineTokens, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js'
export type { IaplTokenName, IpalTokenName, TokensInput } from './modules/tokens/index.js'
export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js'
export type { TurnstileConfig } from './modules/turnstile/config.js'
export { iapl, ipalKit } from './plugin.js'
export type { IaplOptions, IpalOptions, MailOptions, ThemeOptions } from './types.js'
@@ -0,0 +1,34 @@
'use client'
import type { VideoHTMLAttributes } from 'react'
import { useEffect, useRef } from 'react'
const QUERY = '(prefers-reduced-motion: reduce)'
/**
* A background video that stops for visitors who asked for less motion (WCAG 2.2.2, 2.3.3;
* web.dev/articles/prefers-reduced-motion). The server renders the same <video autoplay muted loop>, so nothing
* changes for anyone else; after hydration a visitor with "reduce motion" gets it paused on its first frame (the
* poster stays), and the setting is followed if it changes while the page is open. Used by the library's <Media>
* for `videoMode="background"`; off with `<Media pauseForReducedMotion={false}>`.
*/
export function BackgroundVideo(props: VideoHTMLAttributes<HTMLVideoElement>) {
const ref = useRef<HTMLVideoElement>(null)
useEffect(() => {
const video = ref.current
if (!video || typeof window.matchMedia !== 'function') {return}
const media = window.matchMedia(QUERY)
const apply = () => {
if (media.matches) {
video.pause()
} else if (props.autoPlay) {
void video.play().catch(() => {})
}
}
apply()
media.addEventListener('change', apply)
return () => media.removeEventListener('change', apply)
}, [props.autoPlay])
// eslint-disable-next-line jsx-a11y/media-has-caption -- a silent background loop (aria-hidden by Media)
return <video {...props} ref={ref} />
}
+9 -1
View File
@@ -3,7 +3,15 @@ import type { ElementType, ReactNode } from 'react'
import { cx } from './cx.js'
export const CARD_CLASS = 'flex flex-col rounded-card border border-border bg-surface text-fg shadow-sm'
export const CARD_INTERACTIVE_CLASS = 'relative transition-shadow duration-fast ease-out hover:shadow-md focus-within:shadow-md'
/**
* Hover and focus lift (1.18.0): the larger shadow sits on an ::after layer whose opacity fades in — the browser
* composites it instead of repainting the card's shadow on every frame (web.dev/articles/animations-guide). The
* token duration makes it instant with "reduce motion". The 1.17 look: CARD_INTERACTIVE_SHADOW_CLASS.
*/
export const CARD_INTERACTIVE_CLASS =
'relative after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:shadow-md after:opacity-0 after:transition-opacity after:duration-fast after:ease-out hover:after:opacity-100 focus-within:after:opacity-100'
/** The 1.17 hover: `box-shadow` itself transitions (a repaint per frame) — for a project that wants it back. */
export const CARD_INTERACTIVE_SHADOW_CLASS = 'relative transition-shadow duration-fast ease-out hover:shadow-md focus-within:shadow-md'
export type CardProps = { as?: ElementType; children: ReactNode; className?: string; interactive?: boolean }
+5 -1
View File
@@ -4,6 +4,7 @@ import type { MediaImageProps, VideoMode } from '../../media/mediaProps.js'
import type { MediaValue } from '../data.js'
import { MEDIA_SIZES, mediaImageProps, videoProps } from '../../media/mediaProps.js'
import { BackgroundVideo } from './BackgroundVideo.js'
/** next/image, passed in by the project (the plugin never imports next/*). */
export type ImageComponent = ComponentType<{ className?: string } & MediaImageProps>
@@ -14,6 +15,8 @@ export type MediaProps = {
className?: string
/** Above the fold, not the LCP image (a logo): eager, without fetchPriority="high" or a preload. */
eager?: boolean
/** `videoMode="background"`: paused for visitors with "reduce motion" (default true; 1.18.0). */
pauseForReducedMotion?: boolean
poster?: MediaValue
/** Only the first visible image of the page (the LCP image). */
priority?: boolean
@@ -27,9 +30,10 @@ 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, eager = false, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
export function Media({ alt, className, eager = false, Image, pauseForReducedMotion = true, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
const video = videoProps(resource, { mode: videoMode, poster })
if (video) {
if (videoMode === 'background' && pauseForReducedMotion) {return <BackgroundVideo {...video} aria-hidden className={className} />}
// 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} />
+8
View File
@@ -6,6 +6,7 @@ import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody as readCapped } from '../shared/readCappedBody.js'
import { TTL_FIELD } from '../shared/ttl.js'
import { CONSENT_CATEGORIES } from './categories.js'
import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js'
import { CONSENT_VERSION } from './storage.js'
@@ -44,6 +45,12 @@ export type ConsentLogOptions = {
collectionOverrides?: CollectionOverride
/** Days a record is kept. Default 1095 (3 years). */
retentionDays?: number
/**
* MongoDB: a TTL index deletes records older than `retentionDays` by itself, also when no new record comes
* (1.18.0; shared/ttl.ts). Default true; `false` drops the index at the next start — the purge after a new record
* stays. Postgres / SQLite: not used.
*/
ttlIndex?: boolean
}
export function buildConsentLogCollection(): CollectionConfig {
@@ -154,6 +161,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
data: {
choices: Object.fromEntries(CONSENT_CATEGORIES.map((c) => [c, b.state![c] === true])),
consentId: b.id,
[TTL_FIELD]: new Date().toISOString(), // MongoDB TTL counts from here (dropped where the field is not there)
version: b.version,
} as never,
overrideAccess: true,
+83 -39
View File
@@ -96,45 +96,89 @@ export async function collectGrowth(payload: BasePayload): Promise<GrowthStatus>
}
}
// 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 }
const unused = await findUnusedMedia(payload)
if (unused) {
const orphaned = Object.values(unused.byCollection).reduce((n, list) => n + list.length, 0)
out.media = { capped: !unused.complete, checked: unused.checked, orphaned, total: unused.total }
}
return out
}
export type UnusedMedia = {
/** Unused files per upload collection: id and file name. */
byCollection: Record<string, Array<{ filename: null | string; id: number | string }>>
/** Documents read (all collections and globals together). */
checked: number
/** false when the cap was reached or a collection could not be read: then some listed files may be used. */
complete: boolean
total: number
}
const FILE_NAME = /[\w.-]+\.(?:avif|gif|jpe?g|mp4|pdf|png|svg|webm|webp)\b/gi
/**
* Media of the upload collections that no other document or global mentions — by id (relations, uploads in rich
* text and blocks, any depth, drafts and every language included) or by file name inside a text (a link to
* `/api/media/file/plan.pdf`). Reads only; deletes nothing. null = no upload collection. The doctor counts them
* (`growth-media`); the panel lists them (`unusedMedia`) only when `complete`.
*/
export async function findUnusedMedia(payload: BasePayload, { limit = ORPHAN_SCAN_LIMIT, only }: { limit?: number; only?: string[] } = {}): Promise<null | UnusedMedia> {
const collections = (payload.config.collections ?? []) as unknown as CollectionLike[]
const globals = (payload.config.globals ?? []) as unknown as GlobalLike[]
const uploads = collections.filter((c) => c.upload && (!only || only.includes(c.slug)))
if (!uploads.length) {return null}
const files = new Map<string, { filename: null | string; id: number | string; slug: string }>()
const byName = new Map<string, string>()
for (const u of uploads) {
const res = await payload.find({ collection: u.slug as never, depth: 0, limit, overrideAccess: true, pagination: false, select: { filename: true } as never })
for (const d of res.docs as Array<{ filename?: null | string; id: number | string }>) {
files.set(String(d.id), { id: d.id, slug: u.slug, filename: d.filename ?? null })
if (d.filename) {byName.set(d.filename.toLowerCase(), String(d.id))}
}
}
const seen = new Set<string>()
let checked = 0
let complete = true
// every string and number anywhere in a document — ids are among them, file names inside texts
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 (files.has(key)) {seen.add(key)}
if (typeof value === 'string' && byName.size) {
for (const m of value.matchAll(FILE_NAME)) {
const id = byName.get(m[0].toLowerCase())
if (id) {seen.add(id)}
}
}
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-')) {continue}
if (checked >= limit) {
complete = false
break
}
try {
const res = await payload.find({ collection: c.slug as never, depth: 0, draft: true, limit: limit - checked + 1, locale: 'all' as never, overrideAccess: true, pagination: false })
if (res.docs.length > limit - checked) {complete = false}
checked += Math.min(res.docs.length, limit - checked)
for (const d of res.docs) {mark(d)}
} catch {
complete = false // not readable this way: its references are not known
}
}
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 {
complete = false
}
}
const byCollection: UnusedMedia['byCollection'] = Object.fromEntries(uploads.map((u) => [u.slug, []]))
for (const [key, f] of files) {if (!seen.has(key)) {byCollection[f.slug].push({ id: f.id, filename: f.filename })}}
return { byCollection, checked, complete, total: files.size }
}
+35 -1
View File
@@ -4,10 +4,12 @@ import path from 'node:path'
import type { DoctorContext } from '../project.js'
import type { DoctorRule, GrowthThresholds, RuleFinding } from '../types.js'
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'
@@ -95,6 +97,38 @@ export const growthRules: DoctorRule[] = [
group: 'growth',
source: 'deep',
},
{
// The project turns versions on itself: Payload keeps 100 per document unless the config says less
id: 'growth-versions-config',
check: (ctx) => {
const out: RuleFinding[] = []
for (const dir of [`${ctx.src}collections`, `${ctx.src}globals`]) {
for (const name of ctx.list(dir).filter((n) => /\.(?:ts|js)$/.test(n))) {
const file = `${dir}/${name}`
const code = stripComments(ctx.read(file))
for (const m of code.matchAll(/\bversions\s*:\s*(true|\{)/g)) {
let body = ''
if (m[1] === '{') {
let depth = 0
let i = m.index + m[0].length - 1
for (; i < code.length; i++) {
if (code[i] === '{') {depth++}
else if (code[i] === '}' && --depth === 0) {break}
}
body = code.slice(m.index, i + 1)
}
if (/\bmaxPerDoc\s*:|\bmax\s*:/.test(body)) {continue}
const global = dir.endsWith('globals')
out.push({ file, fix: `versions: { ${m[1] === '{' ? '…, ' : ''}${global ? 'max' : 'maxPerDoc'}: 20 }`, message: `versions are on without a limit: Payload keeps 100 per ${global ? 'global' : 'document'} (every save, drafts and autosave included)`, severity: 'info' })
}
}
}
return out
},
docs: DOCS,
group: 'growth',
source: 'static',
},
{
// 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)
+24 -22
View File
@@ -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',
+4 -1
View File
@@ -50,6 +50,8 @@ export type BuilderFormProps = {
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode
/** Space kept for the Turnstile widget before it is drawn (default 73 px; 0 for an invisible widget). */
turnstileReserveHeight?: number
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
turnstileTheme?: TurnstileTheme
} & UseBuilderFormOptions
@@ -75,6 +77,7 @@ export function BuilderForm({
messages = {},
renderField,
requiredMark,
turnstileReserveHeight,
turnstileTheme,
...options
}: BuilderFormProps) {
@@ -249,7 +252,7 @@ export function BuilderForm({
})}
</div>
</div>
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget theme={turnstileTheme} /></div> : null}
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget reserveHeight={turnstileReserveHeight} theme={turnstileTheme} /></div> : null}
{f.errorMessage ? <p className={cn.formError} role="alert">{f.errorMessage}</p> : null}
<div className={cn.actions}>
{!f.isFirst ? <button className={cn.back} onClick={f.back} type="button">{options.texts.back ?? 'Back'}</button> : null}
+22
View File
@@ -0,0 +1,22 @@
'use client'
import { lazy, Suspense } from 'react'
import type { BuilderFormProps } from './BuilderForm.js'
/**
* <BuilderForm> loaded only on a page that renders a form (1.18.0). RenderForm uses this: the catch-all route can
* render any block, so a static import put the form engine (fields, steps, validation, the Turnstile widget) into
* the JavaScript of every page. The server still renders the whole form (the HTML is complete without JavaScript,
* search engines and the first paint see it); the browser fetches the code while it hydrates the rest of the page.
* It is `BuilderForm` in `@intecion/ipal-kit/client` (same props). The eager component, in every page's bundle:
* `@intecion/ipal-kit/client/eager` → `<RenderForm Form={BuilderForm}>` (docs/forms.md).
*/
const Impl = lazy(() => import('./BuilderForm.js').then((m) => ({ default: m.BuilderForm })))
export function LazyBuilderForm(props: BuilderFormProps) {
return (
<Suspense fallback={null}>
<Impl {...props} />
</Suspense>
)
}
+15 -4
View File
@@ -1,16 +1,16 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react'
import type { ComponentType, ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { TurnstileTheme } from '../turnstile/Turnstile.js'
import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderFormClassNames, BuilderFormProps } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js'
import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js'
import { RenderRichText } from '../richtext/RenderRichText.js'
import { BuilderForm } from './BuilderForm.js'
import { LazyBuilderForm } from './LazyBuilderForm.js'
/** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */
export type SendFormAction = (
@@ -26,6 +26,11 @@ export type RenderFormProps = {
classNames?: BuilderFormClassNames
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
converters?: JSXConvertersFunction
/**
* The client form component. Default: the lazy one (1.18.0) — its code loads only on pages with a form, the HTML
* is complete either way. `Form={BuilderForm}` from `@intecion/ipal-kit/client/eager` = in every page's bundle.
*/
Form?: ComponentType<BuilderFormProps>
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
form: BuilderFormDoc | null | number | string | undefined
/**
@@ -39,6 +44,8 @@ export type RenderFormProps = {
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
/** Widget theme. Default 'page' — follows the site's light/dark theme. */
/** Space kept for the Turnstile widget before it is drawn (default 73 px; 0 for an invisible widget). */
turnstileReserveHeight?: number
turnstileTheme?: TurnstileTheme
/** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */
values?: Record<string, string>
@@ -143,22 +150,26 @@ export function RenderForm({
classNames,
converters,
form,
Form = LazyBuilderForm,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileReserveHeight,
turnstileTheme,
values,
}: RenderFormProps) {
const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName })
if (!prepared) {return null}
// the form's code is fetched only on pages that have a form (the HTML stays complete): LazyBuilderForm.tsx
return (
<BuilderForm
<Form
{...prepared}
classNames={classNames}
requiredMark={requiredMark}
texts={texts}
turnstileReserveHeight={turnstileReserveHeight}
turnstileTheme={turnstileTheme}
values={values}
/>
+2 -2
View File
@@ -1,5 +1,5 @@
'use client'
// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the
// /client entry shipped it with every page (docs/performance.md).
import type { ChangeEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+2 -2
View File
@@ -1,5 +1,5 @@
'use client'
// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the
// /client entry shipped it with every page (docs/performance.md).
import { useMemo } from 'react'
import { type FormSubmitAction, useForm } from './useForm.js'
+2 -2
View File
@@ -1,5 +1,5 @@
'use client'
// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the
// /client entry shipped it with every page (docs/performance.md).
import { useCallback, useMemo, useRef, useState } from 'react'
/**
+66
View File
@@ -0,0 +1,66 @@
import type { Payload } from 'payload'
import { userMeetsRole } from '../access/predicates.js'
import { findUnusedMedia } from '../doctor/growth.js'
type Props = {
adminRoute?: string
/** The upload collection this list shows (set by iapl). */
collection?: string
/** Injected by Payload into admin server components. */
i18n?: { language?: string }
/** Injected by Payload into admin server components. */
payload?: Payload
/** Injected by Payload into admin server components. */
user?: null | Record<string, unknown>
}
/** Files listed in one link: a longer address may be cut by a proxy. */
export const UNUSED_MEDIA_LINK_LIMIT = 100
const TEXT = {
en: {
incomplete: 'Unused files: the site has too many documents to check them all here — run iapl-doctor --deep (growth-media).',
none: '',
show: (n: number) => (n > UNUSED_MEDIA_LINK_LIMIT ? `Show the first ${UNUSED_MEDIA_LINK_LIMIT}` : 'Show them'),
title: (n: number) => `${n} file${n === 1 ? ' is' : 's are'} not used on any page, entry or setting.`,
why: 'Check each one before you delete it (select them in the list → Delete). Nothing is deleted by itself.',
},
pl: {
incomplete: 'Nieużywane pliki: strona ma zbyt wiele dokumentów, by sprawdzić je tutaj — uruchom iapl-doctor --deep (growth-media).',
none: '',
show: (n: number) => (n > UNUSED_MEDIA_LINK_LIMIT ? `Pokaż pierwsze ${UNUSED_MEDIA_LINK_LIMIT}` : 'Pokaż je'),
title: (n: number) => `Plików nieużywanych na żadnej stronie, we wpisie ani w ustawieniach: ${n}.`,
why: 'Sprawdź każdy przed usunięciem (zaznacz je na liście → Usuń). Nic nie jest usuwane samo.',
},
}
/**
* `iapl({ unusedMedia: true })` (1.18.0; docs/media.md): above the list of an upload collection, how many files no
* document or global uses, and a link that opens Payload's own list filtered to them — deleting stays the panel's
* manual bulk delete, with its confirmation and access rules. For editors and admins; renders nothing when every
* file is used, and only a hint when the site is too big to check every document here. Never throws.
*/
export async function UnusedMediaNotice({ adminRoute = '/admin', collection, i18n, payload, user }: Props) {
if (!payload || !collection || !user || !userMeetsRole({ payload, user }, 'editor')) {return null}
const t = i18n?.language === 'pl' ? TEXT.pl : TEXT.en
let ids: Array<number | string>
try {
const unused = await findUnusedMedia(payload, { only: [collection] })
if (!unused) {return null}
if (!unused.complete) {return <p style={BOX}>{t.incomplete}</p>}
ids = (unused.byCollection[collection] ?? []).map((f) => f.id)
} catch {
return null
}
if (!ids.length) {return null}
const query = ids.slice(0, UNUSED_MEDIA_LINK_LIMIT).map((id, i) => `where[id][in][${i}]=${encodeURIComponent(String(id))}`).join('&')
return (
<div data-iapl="unused-media" style={BOX}>
<strong>{t.title(ids.length)}</strong> {t.why}{' '}
<a href={`${adminRoute}/collections/${collection}?${query}`}>{t.show(ids.length)}</a>
</div>
)
}
const BOX = { border: '1px solid var(--theme-elevation-150)', borderRadius: 4, margin: '0 0 1rem', padding: '0.75rem 1rem' } as const
+2
View File
@@ -4,3 +4,5 @@ export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
export type { OptimizeUploadOptions } from './optimizeUpload.js'
export { buildMediaPlaceholderField, buildMediaPlaceholderHook } from './placeholder.js'
export { exifOrientation, stripImageMetadata } from './stripMetadata.js'
export type { StripResult } from './stripMetadata.js'
+32 -2
View File
@@ -1,8 +1,10 @@
import type { CheckboxField, CollectionBeforeOperationHook } from 'payload'
import type { CheckboxField, CollectionBeforeOperationHook, PayloadRequest } from 'payload'
import { readFile } from 'node:fs/promises'
import { APIError } from 'payload'
import { stripImageMetadata } from './stripMetadata.js'
/**
* Safety net for oversized uploads — NOT an image pipeline. The developer and
* editor are expected to upload prepared files; this only catches the 8 MB
@@ -35,9 +37,33 @@ export type OptimizeUploadOptions = {
png?: 'lossless' | 'lossy'
/** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */
quality?: number
/**
* Remove the metadata (camera, date, GPS position, comments) of every JPEG and PNG upload that passes the limits,
* without re-encoding it (stripImageMetadata; 1.18.0). A photo whose EXIF says "rotate" is turned once (sharp,
* JPEG quality 92) so it does not show sideways. Default true; `false` keeps uploads byte for byte as before.
* Images over the limits lose their metadata anyway when the editor lets the plugin optimise them.
*/
stripMetadata?: boolean
}
const OPTIMIZABLE = new Set(['image/jpeg', 'image/png'])
type Sharp = NonNullable<PayloadRequest['payload']['config']['sharp']>
/** The upload without its metadata (stripImageMetadata); a "rotate" in the EXIF is applied to the pixels first. */
async function stripUploadMetadata(file: UploadFile, buffer: Buffer, sharp: Sharp | undefined): Promise<void> {
const result = stripImageMetadata(buffer, file.mimetype)
if (!result.changed) {return}
let output = result.buffer
if (result.orientation !== 1) {
// without sharp the file stays as it was: an upright picture matters more than its metadata
if (!sharp) {return}
output = await sharp(buffer).rotate().jpeg({ quality: 92 }).toBuffer()
}
file.data = output
file.size = output.length
delete file.tempFilePath // Payload must read the new buffer, not the temp file
}
const MB = 1024 * 1024
/** Size in MB with one decimal, in the admin language's number format. */
const fmt = (bytes: number, language: string) =>
@@ -90,6 +116,7 @@ export function buildOptimizeUploadHook(
maxVideoBytes = 20 * MB,
png = 'lossless',
quality = 82,
stripMetadata = true,
} = options
return async ({ args, operation, req }) => {
@@ -142,7 +169,10 @@ export function buildOptimizeUploadHook(
const tooHeavy = size > maxImageBytes
const tooWide = width !== undefined && width > maxImageWidth
if (!tooHeavy && !tooWide) {return}
if (!tooHeavy && !tooWide) {
if (stripMetadata) {await stripUploadMetadata(file, buffer, sharp)}
return
}
const problem = [
tooHeavy ? `${fmt(size, lang)} (limit ${fmt(maxImageBytes, lang)})` : null,
+94
View File
@@ -0,0 +1,94 @@
/**
* Removes the metadata a photo carries (camera, date, GPS position, editing software, comments) from a JPEG or a PNG
* WITHOUT re-encoding it: the pixels and the file's quality stay byte for byte, only the metadata blocks go
* (1.18.0; docs/media.md). Kept: what changes how the image looks — the JFIF header and Adobe marker, the colour
* profile (ICC), PNG gamma, chromaticity, sRGB and pixel density.
*
* JPEG: the APP1 (EXIF, XMP), APP13 (IPTC / Photoshop) and COM segments before the image data are dropped. EXIF also
* holds the orientation: `orientation` reports it (1 = upright), so a caller can rotate the pixels first — otherwise a
* phone photo taken sideways would show sideways.
* PNG: tEXt, zTXt, iTXt, eXIf and tIME chunks are dropped.
* Anything it cannot read is returned unchanged (`changed: false`).
*/
export type StripResult = { buffer: Buffer; changed: boolean; orientation: number }
const JPEG_DROP = new Set([0xe1, 0xed, 0xfe]) // APP1 (EXIF/XMP), APP13 (IPTC), COM
const PNG_DROP = new Set(['eXIf', 'iTXt', 'tEXt', 'tIME', 'zTXt'])
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
/** EXIF orientation (tag 0x0112 of IFD0) in an APP1 payload, or 1. */
export function exifOrientation(app1: Buffer): number {
if (app1.length < 14 || app1.toString('latin1', 0, 6) !== 'Exif\0\0') {return 1}
const tiff = app1.subarray(6)
const little = tiff.toString('latin1', 0, 2) === 'II'
if (!little && tiff.toString('latin1', 0, 2) !== 'MM') {return 1}
const u16 = (at: number) => (little ? tiff.readUInt16LE(at) : tiff.readUInt16BE(at))
const u32 = (at: number) => (little ? tiff.readUInt32LE(at) : tiff.readUInt32BE(at))
try {
const ifd = u32(4)
const entries = u16(ifd)
for (let i = 0; i < entries; i++) {
const at = ifd + 2 + i * 12
if (u16(at) === 0x0112) {
const value = u16(at + 8)
return value >= 1 && value <= 8 ? value : 1
}
}
} catch {
// truncated EXIF: no orientation
}
return 1
}
function stripJpeg(input: Buffer): StripResult {
const same = { buffer: input, changed: false, orientation: 1 }
if (input.length < 4 || input[0] !== 0xff || input[1] !== 0xd8) {return same}
const parts: Buffer[] = [input.subarray(0, 2)]
let orientation = 1
let changed = false
let at = 2
while (at + 4 <= input.length) {
if (input[at] !== 0xff) {return same} // not a marker where one must be: leave the file alone
const marker = input[at + 1]
if (marker === 0xff) {at++; continue} // fill byte
if (marker === 0xda || marker === 0xd9) { // start of scan / end: the rest is image data
parts.push(input.subarray(at))
break
}
const length = input.readUInt16BE(at + 2)
if (length < 2 || at + 2 + length > input.length) {return same}
const segment = input.subarray(at, at + 2 + length)
if (JPEG_DROP.has(marker)) {
if (marker === 0xe1 && orientation === 1) {orientation = exifOrientation(segment.subarray(4))}
changed = true
} else {
parts.push(segment)
}
at += 2 + length
}
return changed ? { buffer: Buffer.concat(parts), changed, orientation } : same
}
function stripPng(input: Buffer): StripResult {
const same = { buffer: input, changed: false, orientation: 1 }
if (input.length < 8 || !input.subarray(0, 8).equals(PNG_SIGNATURE)) {return same}
const parts: Buffer[] = [PNG_SIGNATURE]
let changed = false
let at = 8
while (at + 12 <= input.length) {
const length = input.readUInt32BE(at)
const type = input.toString('latin1', at + 4, at + 8)
const end = at + 12 + length
if (end > input.length) {return same}
if (PNG_DROP.has(type)) {changed = true} else {parts.push(input.subarray(at, end))}
at = end
if (type === 'IEND') {break}
}
return changed ? { buffer: Buffer.concat(parts), changed, orientation: 1 } : same
}
export function stripImageMetadata(input: Buffer, mimeType: string): StripResult {
if (mimeType === 'image/jpeg' || mimeType === 'image/jpg' || mimeType === 'image/pjpeg') {return stripJpeg(input)}
if (mimeType === 'image/png') {return stripPng(input)}
return { buffer: input, changed: false, orientation: 1 }
}
+63
View File
@@ -0,0 +1,63 @@
import type { BasePayload, Config, DateField } from 'payload'
/**
* MongoDB TTL index for a plugin log (1.18.0; docs/performance.md §6): the database itself deletes records once
* they are older than the retention — also on a quiet site, where the purge after a new record never runs.
*
* Why a field of its own: Payload already keeps a plain index on `createdAt` (and the statistics on `lastAt`), and
* Mongoose recreates its indexes at every start — turning that index into a TTL one makes the start fail with
* IndexOptionsConflict. So the TTL counts from `iaplTtlFrom` (hidden; the record's `createdAt`, the visit's `lastAt`),
* with an index named `iapl_ttl` that only the plugin manages. At every start its time is set to the current
* `retentionDays` (collMod), so a changed retention applies at once; records written before 1.18.0 get the field
* from their own date once (a single updateMany). Postgres and SQLite: no field, no index — the purge does it.
* Opt-out: `ttlIndex: false` on the option; the index is then dropped at the next start (nothing more is deleted
* by it), the purge stays.
*/
export const TTL_FIELD = 'iaplTtlFrom'
export const TTL_INDEX = 'iapl_ttl'
export const isMongo = (config: Pick<Config, 'db'>) => (config.db as { name?: string } | undefined)?.name === 'mongoose'
/** The hidden date the TTL counts from. Not indexed by Payload (the plugin's own index is the TTL one). */
export const ttlField = (): DateField => ({
name: TTL_FIELD,
type: 'date',
admin: { disableBulkEdit: true, hidden: true },
})
type NativeCollection = {
collectionName: string
createIndex: (key: object, options: object) => Promise<string>
dropIndex: (name: string) => Promise<unknown>
indexes: () => Promise<Array<{ expireAfterSeconds?: number; name?: string }>>
updateMany: (filter: object, update: object[]) => Promise<{ modifiedCount?: number }>
}
export type TtlSyncResult = 'created' | 'dropped' | 'none' | 'updated'
/** Creates, updates or drops the TTL index of one collection (MongoDB only; anything else does nothing). */
export async function syncTtlIndex(
payload: BasePayload,
slug: string,
{ days, enabled, from }: { days: number; enabled: boolean; from: string },
): Promise<TtlSyncResult> {
const db = payload.db as unknown as { collections?: Record<string, { collection?: NativeCollection }>; connection?: { db?: { command: (c: object) => Promise<unknown> } }; name?: string }
const coll = db.collections?.[slug]?.collection
if (db.name !== 'mongoose' || !coll) {return 'none'}
const existing = (await coll.indexes()).find((i) => i.name === TTL_INDEX)
if (!enabled) {
if (!existing) {return 'none'}
await coll.dropIndex(TTL_INDEX)
return 'dropped'
}
// records from before 1.18.0 (or written by another path): the TTL counts from their own date
await coll.updateMany({ [from]: { $type: 'date' }, [TTL_FIELD]: { $exists: false } }, [{ $set: { [TTL_FIELD]: `$${from}` } }])
const seconds = Math.round(days * 86_400)
if (!existing) {
await coll.createIndex({ [TTL_FIELD]: 1 }, { name: TTL_INDEX, expireAfterSeconds: seconds })
return 'created'
}
if (existing.expireAfterSeconds === seconds) {return 'none'}
await db.connection!.db!.command({ collMod: coll.collectionName, index: { name: TTL_INDEX, expireAfterSeconds: seconds } })
return 'updated'
}
+19
View File
@@ -0,0 +1,19 @@
/**
* The plugin's own collections and globals turn versions on nowhere. When a project turns them on (globalOverrides,
* collectionOverrides, formOverrides…) without a limit, each keeps at most 20 versions per document (1.18.0;
* docs/performance.md §6) instead of Payload's 100 — a global like Site integrations is saved by the site itself on
* every status change. A limit the project writes wins (`max` for globals, `maxPerDoc` for collections, 0 =
* unlimited). Payload trims the oldest versions of a document on its next save.
*/
export const PLUGIN_VERSION_LIMIT = 20
type Versioned = { slug: string; versions?: unknown }
export function withVersionLimit<T extends Versioned>(entity: T, kind: 'collection' | 'global', limit = PLUGIN_VERSION_LIMIT): T {
const v = entity.versions
if (!v) {return entity}
const key = kind === 'global' ? 'max' : 'maxPerDoc'
if (v === true) {return { ...entity, versions: { [key]: limit } }}
if (typeof v === 'object' && typeof (v as Record<string, unknown>)[key] !== 'number') {return { ...entity, versions: { ...(v), [key]: limit } }}
return entity
}
+5
View File
@@ -30,6 +30,11 @@ export type StatsOptions = {
retentionDays?: number
/** Time zone that decides where a day starts. Default 'Europe/Warsaw'. */
timeZone?: string
/**
* MongoDB: a TTL index deletes visits whose last page view is older than `retentionDays`, also on a quiet site
* (1.18.0). Default true; `false` drops the index at the next start, the purge stays. Postgres / SQLite: not used.
*/
ttlIndex?: boolean
}
export type StatsPage = { p: string; t: string }
+3
View File
@@ -7,6 +7,7 @@ import { CONSENT_COOKIE, CONSENT_VERSION, readConsentRecord } from '../consent/s
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { readCappedBody } from '../shared/readCappedBody.js'
import { TTL_FIELD } from '../shared/ttl.js'
import { STATS_SLUG } from './collection.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js'
import { visitKey } from './visitKey.js'
@@ -121,6 +122,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
lastAt: now.toISOString(),
pageCount: pages.length,
pages,
[TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts)
...(visitorId && !visit.visitorId ? { visitorId } : {}),
} as never,
depth: 0,
@@ -140,6 +142,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
pages: [{ p: path, t: now.toISOString() }],
referrer: referrerHost(body.r, host),
startedAt: now.toISOString(),
[TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts)
visitKey: key,
...(typeof body.l === 'string' && /^[a-z]{2}(?:-[A-Za-z]{2})?$/.test(body.l) ? { locale: body.l } : {}),
...(country && /^[A-Z]{2}$/.test(country) && country !== 'XX' ? { country } : {}),
+23
View File
@@ -0,0 +1,23 @@
'use client'
import type { ComponentProps } from 'react'
import { lazy, Suspense } from 'react'
import type { Turnstile as TurnstileType } from './Turnstile.js'
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
const Impl = lazy(() => import('./Turnstile.js').then((m) => ({ default: m.Turnstile })))
/**
* The Turnstile widget, loaded where it is shown (1.18.0): `<Turnstile>` from `@intecion/ipal-kit/client` is this
* wrapper, so a page without a form carries none of its code. Same props; the eager one:
* `@intecion/ipal-kit/client/eager`.
*/
export function LazyTurnstile(props: ComponentProps<typeof TurnstileType>) {
return (
<Suspense fallback={(props.reserveHeight ?? TURNSTILE_HEIGHT) ? <div style={{ minHeight: props.reserveHeight ?? TURNSTILE_HEIGHT }} /> : null}>
<Impl {...props} />
</Suspense>
)
}
+8 -2
View File
@@ -2,6 +2,7 @@
import { useEffect, useRef } from 'react'
import { useTheme } from '../theme/useTheme.js'
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
declare global {
interface Window {
@@ -29,6 +30,11 @@ function ensureScript(): void {
export type TurnstileProps = {
/** Called with the token once solved, or null on expiry/error. */
onToken: (token: null | string) => void
/**
* Height kept free for the widget before Cloudflare draws it (1.18.0): the form below does not jump when it
* appears (layout shift). Default 73 (the standard widget as drawn); 0 for an invisible widget.
*/
reserveHeight?: number
/**
* Change this value to make the widget issue a NEW token (a token is
* single-use: after a submission the server refused, the next one needs a
@@ -60,7 +66,7 @@ export type TurnstileTheme = 'auto' | 'dark' | 'light' | 'page'
* The script is injected directly (no next/script dependency) so the widget
* stays framework-agnostic.
*/
export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }: TurnstileProps) {
export function Turnstile({ onToken, reserveHeight = TURNSTILE_HEIGHT, resetSignal = 0, siteKey, theme = 'page' }: TurnstileProps) {
const ref = useRef<HTMLDivElement>(null)
const widgetId = useRef<null | string>(null)
const pageTheme = useTheme().theme
@@ -115,5 +121,5 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }:
if (!siteKey) {return null}
return <div ref={ref} />
return <div ref={ref} style={reserveHeight ? { minHeight: reserveHeight } : undefined} />
}
+15 -7
View File
@@ -1,10 +1,13 @@
'use client'
import { createContext, use, useCallback, useState } from 'react'
import { createContext, lazy, Suspense, use, useCallback, useState } from 'react'
import type { TurnstileTheme } from './Turnstile.js'
import { Turnstile } from './Turnstile.js'
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
// The widget is loaded where a form shows it (1.18.0): the provider sits in the layout of every page.
const Turnstile = lazy(() => import('./Turnstile.js').then((m) => ({ default: m.Turnstile })))
type TurnstileContextValue = {
/** Clears the token and makes the widget issue a new one. */
@@ -69,7 +72,7 @@ export function useTurnstile(): {
enabled: boolean
reset: () => void
token: null | string
TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode
TurnstileWidget: (props?: { reserveHeight?: number; theme?: TurnstileTheme }) => React.ReactNode
} {
const ctx = use(TurnstileContext)
if (!ctx) {
@@ -93,9 +96,9 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
const { reset, siteKey, token } = ctx
const TurnstileWidget = useCallback(
(props?: { theme?: TurnstileTheme }) => {
(props?: { reserveHeight?: number; theme?: TurnstileTheme }) => {
if (!siteKey) {return null}
return <ProvidedTurnstile theme={props?.theme} />
return <ProvidedTurnstile reserveHeight={props?.reserveHeight} theme={props?.theme} />
},
[siteKey],
)
@@ -104,8 +107,13 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurn
}
/** The provider's widget: reads the key and the reset signal from the context, so `reset()` reaches it without a remount. */
function ProvidedTurnstile({ theme }: { theme?: TurnstileTheme }) {
function ProvidedTurnstile({ reserveHeight = TURNSTILE_HEIGHT, theme }: { reserveHeight?: number; theme?: TurnstileTheme }) {
const ctx = use(TurnstileContext)
if (!ctx?.siteKey) {return null}
return <Turnstile onToken={ctx.setToken} resetSignal={ctx.resetSignal} siteKey={ctx.siteKey} theme={theme} />
// the same reserved height while the widget's code loads: nothing below moves when it arrives
return (
<Suspense fallback={reserveHeight ? <div style={{ minHeight: reserveHeight }} /> : null}>
<Turnstile onToken={ctx.setToken} reserveHeight={reserveHeight} resetSignal={ctx.resetSignal} siteKey={ctx.siteKey} theme={theme} />
</Suspense>
)
}
+2 -1
View File
@@ -2,6 +2,7 @@
// 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'
// `Turnstile` is the lazy wrapper since 1.18.0 (same props): the widget's code loads where a form shows it
export { LazyTurnstile as Turnstile } from './LazyTurnstile.js'
export type { TurnstileProps, TurnstileTheme } from './Turnstile.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js'
+5
View File
@@ -0,0 +1,5 @@
/**
* Height kept free for the Turnstile widget before Cloudflare draws it: the widget measures 72.6 px in the browser
* (Cloudflare documents 300×65 for the frame; the container adds the rest). Measured 2026-12 on the reference site.
*/
export const TURNSTILE_HEIGHT = 73
+51 -3
View File
@@ -26,7 +26,7 @@ import { SIGN_IN_LOOK } from './modules/branding/signIn/brand.js'
import { lockBrandFields } from './modules/branding/signIn/brandAccess.js'
import { buildAdminLanguageEndpoint } from './modules/branding/signIn/languageEndpoint.js'
import { resolveSignInLook } from './modules/branding/signIn/options.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './modules/consent/consentLog.js'
import { addCookieScannerTabs } from './modules/consent/scanner/adminTabs.js'
import { buildCookieApprovalEndpoints, COOKIE_APPROVAL_VIEW_PATH } from './modules/consent/scanner/approval.js'
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
@@ -78,6 +78,8 @@ 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 { isMongo, syncTtlIndex, ttlField } from './modules/shared/ttl.js'
import { withVersionLimit } from './modules/shared/versionLimit.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.js'
@@ -133,6 +135,10 @@ export const iapl = (options: IaplOptions): Plugin => {
}
async function transform(incomingConfig: Config): Promise<Config> {
/** MongoDB TTL indexes to set at start (consent log, statistics): shared/ttl.ts. */
const ttlSyncs: Array<{ days: number; enabled: boolean; from: string; slug: string }> = []
/** Slugs of the plugin's own collections and globals (their versions get a limit: shared/versionLimit.ts). */
const pluginEntities = new Set<string>()
let config = { ...incomingConfig }
/** The project's own endpoints: the panel-action origin rule (adminSameOrigin) is for the plugin's only. */
@@ -811,6 +817,7 @@ export const iapl = (options: IaplOptions): Plugin => {
: pluginGlobals
// The project's globalOverrides win (access, admin, hooks merged; a function = full control).
config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)]
for (const g of pluginGlobals) {pluginEntities.add(g.slug)}
// The brand the sign-in screens show (name, logo, icon) is changed by admins only — with the sign-in look,
// unless the project says `brandAccess: 'editor'`; without the look only when it says `'admin'`.
const brandWl = options.whiteLabel === true ? {} : options.whiteLabel
@@ -873,7 +880,11 @@ export const iapl = (options: IaplOptions): Plugin => {
// --- consent log: proof of consent (on by default since 1.17.0; `consentLog: false` turns it off) ---
if (options.consentLog !== false) {
const logOptions = options.consentLog === true || options.consentLog === undefined ? {} : options.consentLog
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
const consentCollection = buildConsentLogCollection()
// MongoDB: the hidden date the TTL index counts from (shared/ttl.ts); SQL keeps its schema as it was
if (isMongo(config)) {consentCollection.fields = [...consentCollection.fields, ttlField()]}
config.collections = [...(config.collections ?? []), applyCollectionOverride(consentCollection, logOptions.collectionOverrides)]
ttlSyncs.push({ slug: CONSENT_LOG_SLUG, days: logOptions.retentionDays ?? 1095, enabled: logOptions.ttlIndex !== false, from: 'createdAt' })
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
config = withRetention(config, 'consent-records', logOptions.retentionDays ?? 1095)
}
@@ -955,7 +966,10 @@ export const iapl = (options: IaplOptions): Plugin => {
const statsOptions = options.stats === true ? {} : options.stats
const adminRoute = options.adminRoute ?? '/admin'
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)]
const statsCollection = buildStatsCollection()
if (isMongo(config)) {statsCollection.fields = [...statsCollection.fields, ttlField()]}
config.collections = [...(config.collections ?? []), applyCollectionOverride(statsCollection, statsOptions.collectionOverrides)]
ttlSyncs.push({ slug: 'stats-visits', days: statsOptions.retentionDays ?? 90, enabled: statsOptions.ttlIndex !== false, from: 'lastAt' })
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
config = withRetention(config, 'stats-visits', statsOptions.retentionDays ?? 90)
config.admin = {
@@ -1018,6 +1032,26 @@ export const iapl = (options: IaplOptions): Plugin => {
},
}
// --- unused media above the upload lists (opt-in; the notice only links, deleting stays manual) ---
if (options.unusedMedia && options.enabled !== false) {
const only = options.unusedMedia === true ? null : options.unusedMedia.collections
const adminRoute = options.adminRoute ?? '/admin'
config.collections = (config.collections ?? []).map((c) =>
c.upload && (!only || only.includes(c.slug))
? {
...c,
admin: {
...c.admin,
components: {
...c.admin?.components,
beforeListTable: [...(c.admin?.components?.beforeListTable ?? []), { path: '@intecion/ipal-kit/admin#UnusedMediaNotice', serverProps: { adminRoute, collection: c.slug } }],
},
},
}
: c,
)
}
// --- Payload's job queue over HTTP: an admin or the cron secret, unless the project wrote its own rule
config = withJobsRunAccess(config, options.jobsRunAccess ?? {})
@@ -1132,10 +1166,24 @@ export const iapl = (options: IaplOptions): Plugin => {
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
// MongoDB TTL indexes of the plugin's logs: created, kept at the current retention, or dropped when turned off
for (const { slug, ...ttl } of ttlSyncs) {
try {
const done = await syncTtlIndex(payload, slug, ttl)
if (done !== 'none') {payload.logger.info(`[iapl] ${slug}: TTL index ${done} (${ttl.enabled ? `${ttl.days} days` : 'off'})`)}
} catch (err) {
payload.logger.error(`[iapl] ${slug}: the TTL index could not be set (${err instanceof Error ? err.message : String(err)}); the purge after a new record still runs`)
}
}
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
payload.logger.info('[iapl] Plugin initialized.')
}
// The plugin's own entities whose versions a project turned on: at most 20 per document unless it set a limit
for (const slug of ['consent-records', 'cookie-review', 'cookie-crawl', 'stats-visits', 'forms', 'form-submissions']) {pluginEntities.add(slug)}
config.collections = (config.collections ?? []).map((c) => (pluginEntities.has(c.slug) ? withVersionLimit(c, 'collection') : c))
config.globals = (config.globals ?? []).map((g) => (pluginEntities.has(g.slug) ? withVersionLimit(g, 'global') : g))
// readVersions: readPublished() asks for `version._status` on version history (readPublishedVersions).
config.collections = withVersionReadRules(config.collections)
config.globals = withVersionReadRules(config.globals)
+10 -3
View File
@@ -154,7 +154,6 @@ export type IaplOptions = {
* factor: whoever the dashboard is drawn for sees the full text.
*/
dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' }
/**
* Host patterns of the project's development, preview and staging addresses (`*` = any characters).
* Default: `DEFAULT_DEVELOPMENT_HOSTS` — `['*.dev.netscale.pl']`, Intecion's own development domain,
@@ -184,6 +183,7 @@ export type IaplOptions = {
* onInit work or admin components.
*/
enabled?: boolean
/**
* Text written in one language fills the same field in every language that is
* still empty; a language with its own text is never overwritten. Default on
@@ -193,7 +193,6 @@ export type IaplOptions = {
* Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook.
*/
fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean
forms?: FormsOption
/**
@@ -276,6 +275,7 @@ export type IaplOptions = {
* over `seo.searchSettings`.
*/
searchSettings?: ((defaults: Field[]) => Field[]) | false
/**
* SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)
* and enables locale-aware metadata helpers.
@@ -297,7 +297,6 @@ export type IaplOptions = {
* follows the new server. docs/security.md "Stored secrets".
*/
secrets?: { reenterOnChange?: false; writeOnly?: false }
seo?: SeoOption
/** Additional fields injected into SiteSettings global */
@@ -470,6 +469,14 @@ export type IaplOptions = {
}
| false
/**
* Unused media in the panel (1.18.0; docs/media.md): above the list of every upload collection (or the ones
* named), how many files no page, entry or setting uses, with a link to Payload's list filtered to them — the
* editor checks and deletes them by hand (nothing is deleted by itself). Off by default: it adds an entry to the
* admin import map (`pnpm generate:importmap`). `true` or `{ collections: ['media'] }`.
*/
unusedMedia?: { collections?: string[] } | boolean
/**
* White-label the admin panel: show the CLIENT's brand (logo + name) in the
* admin — login screen and nav — pulled from SiteSettings, set by the editor
+4 -2
View File
@@ -1,7 +1,7 @@
import type { ReactElement, ReactNode } from 'react'
import { Children, cloneElement, createElement as h, isValidElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { prerender } from 'react-dom/static'
import { describe, expect, test, vi } from 'vitest'
import type { BlockContent, BlockRegistryOptions } from '../src/exports/blocks-rsc.js'
@@ -34,7 +34,9 @@ async function expand(node: ReactNode): Promise<ReactNode> {
return cloneElement(el, undefined, ...kids)
}
const render = async (node: ReactNode) => renderToStaticMarkup(h('div', null, (await expand(node)) as ReactNode))
// prerender waits for every lazy part, like Next's server render: the form's code is lazy since 1.18.0
const render = async (node: ReactNode) =>
(await new Response((await prerender(h('div', null, (await expand(node)) as ReactNode))).prelude).text()).replace(/<!--(?: |\$\??|\/\$)-->/g, '') // hydration markers out: the markup as before
const image = (alt = 'Photo') => ({ id: 1, alt, filename: 'a.jpg', height: 600, mimeType: 'image/jpeg', url: '/media/a.jpg', width: 900 })
const link = (label: string) => ({ type: 'internal' as const, appearance: 'primary', label, page: { id: 2, slug: 'kontakt' } })
+4 -4
View File
@@ -1,5 +1,6 @@
import { createElement, isValidElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { prerender } from 'react-dom/static'
import { describe, expect, test, vi } from 'vitest'
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
@@ -160,11 +161,10 @@ describe('page values (values prop) and prepareBuilderForm', () => {
expect(html).not.toContain('unknown')
})
test('RenderForm passes values through', () => {
test('RenderForm passes values through (the lazy form renders in full on the server)', async () => {
const action = async () => ({ message: 'ok', success: true })
const html = renderToStaticMarkup(
createElement(RenderForm, { action, form: withSubject, locale: 'pl', texts, values: { subject: 'Broszki' } }),
)
const { prelude } = await prerender(createElement(RenderForm, { action, form: withSubject, locale: 'pl', texts, values: { subject: 'Broszki' } }))
const html = await new Response(prelude).text()
expect(html).toContain('Broszki')
})
+2 -2
View File
@@ -420,8 +420,8 @@ describe('consent log: on by default, fails soft without its table', () => {
const lines = logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('consent-records table does not exist'))
expect(lines.length).toBeLessThanOrEqual(1)
expect(payload.create).toHaveBeenCalledTimes(2)
// the body's gpc never reaches the record (the shape is unchanged)
expect(Object.keys((payload.create.mock.calls[0] as unknown as [{ data: object }])[0].data).sort()).toEqual(['choices', 'consentId', 'version'])
// the body's gpc never reaches the record; iaplTtlFrom is the date a MongoDB TTL index counts from (1.18.0)
expect(Object.keys((payload.create.mock.calls[0] as unknown as [{ data: object }])[0].data).sort()).toEqual(['choices', 'consentId', 'iaplTtlFrom', 'version'])
})
describe('limits: body size and version', () => {
+9 -3
View File
@@ -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 () => {
+180
View File
@@ -0,0 +1,180 @@
// @vitest-environment happy-dom
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { act, createElement } from 'react'
import { createRoot } from 'react-dom/client'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { BackgroundVideo } from '../src/modules/block-library/ui/BackgroundVideo.js'
import { CARD_INTERACTIVE_CLASS, CARD_INTERACTIVE_SHADOW_CLASS } from '../src/modules/block-library/ui/Card.js'
import { Media } from '../src/modules/block-library/ui/Media.js'
import { runDoctor } from '../src/modules/doctor/run.js'
import { UnusedMediaNotice } from '../src/modules/media/UnusedMediaNotice.js'
import { syncTtlIndex, TTL_FIELD, TTL_INDEX } from '../src/modules/shared/ttl.js'
import { PLUGIN_VERSION_LIMIT, withVersionLimit } from '../src/modules/shared/versionLimit.js'
import { Turnstile } from '../src/modules/turnstile/Turnstile.js'
import { TURNSTILE_HEIGHT } from '../src/modules/turnstile/turnstileHeight.js'
const root = path.resolve(import.meta.dirname, '..')
const read = (rel: string) => readFileSync(path.join(root, rel), 'utf8')
describe('lazy form code (item 3)', () => {
test('the /client entry exports the lazy form and widget; /client/eager the eager ones; hooks are no client boundary', () => {
expect(read('src/exports/client.ts')).toMatch(/export \{ LazyBuilderForm as BuilderForm \} from '\.\.\/modules\/forms\/LazyBuilderForm\.js'/)
expect(read('src/modules/turnstile/client.ts')).toMatch(/export \{ LazyTurnstile as Turnstile \}/)
expect(read('src/exports/client-eager.ts')).toMatch(/export \{ BuilderForm \} from '\.\.\/modules\/forms\/BuilderForm\.js'/)
expect(JSON.parse(read('package.json')).exports['./client/eager']).toMatchObject({ import: './dist/exports/client-eager.js' })
for (const hook of ['useBuilderForm', 'useForm', 'useContactForm']) {expect(read(`src/modules/forms/${hook}.ts`)).not.toMatch(/^'use client'/m)}
// nothing imports the eager modules statically but the eager entry and the lazy wrappers' import()
expect(read('src/modules/forms/RenderForm.tsx')).not.toMatch(/^import \{ BuilderForm \}/m)
expect(read('src/modules/turnstile/TurnstileProvider.tsx')).toMatch(/lazy\(\(\) => import\('\.\/Turnstile\.js'\)/)
})
test('the Turnstile widget keeps its height free before Cloudflare draws it; 0 turns it off', () => {
expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, siteKey: 'k' }))).toBe(`<div style="min-height:${TURNSTILE_HEIGHT}px"></div>`)
expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, reserveHeight: 0, siteKey: 'k' }))).toBe('<div></div>')
})
})
describe('background video and reduced motion (item 4)', () => {
const video = { filename: 'loop.mp4', mimeType: 'video/mp4', url: '/api/media/file/loop.mp4' }
test('Media renders the background video through BackgroundVideo, same markup; opt-out keeps a plain <video>', () => {
const html = renderToStaticMarkup(createElement(Media, { resource: video, videoMode: 'background' }))
expect(html).toMatch(/^<video\b/)
expect(html).toMatch(/autoplay=""/i)
expect(html).toMatch(/\bloop=""/)
expect(renderToStaticMarkup(createElement(Media, { pauseForReducedMotion: false, resource: video, videoMode: 'background' }))).toBe(html)
})
test('paused for "reduce motion", played again when the setting changes', async () => {
let matches = true
const listeners: Array<() => void> = []
vi.stubGlobal('matchMedia', () => ({ addEventListener: (_: string, l: () => void) => listeners.push(l), get matches() { return matches }, removeEventListener: () => {} }))
const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
const play = vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve())
const host = document.createElement('div')
const r = createRoot(host)
await act(async () => r.render(createElement(BackgroundVideo, { autoPlay: true, loop: true, muted: true, src: '/v.mp4' })))
expect(pause).toHaveBeenCalledTimes(1)
matches = false
await act(async () => {for (const l of listeners) {l()}})
expect(play).toHaveBeenCalledTimes(1)
await act(async () => r.unmount())
vi.unstubAllGlobals()
})
})
describe('card hover (item 6)', () => {
test('the lift fades an ::after layer (opacity), the card shadow itself does not animate; the 1.17 class stays exported', () => {
expect(CARD_INTERACTIVE_CLASS).toMatch(/after:opacity-0/)
expect(CARD_INTERACTIVE_CLASS).toMatch(/hover:after:opacity-100/)
expect(CARD_INTERACTIVE_CLASS).not.toMatch(/transition-shadow/)
expect(CARD_INTERACTIVE_SHADOW_CLASS).toMatch(/transition-shadow/)
})
})
describe('TTL indexes (item 10)', () => {
const fake = (indexes: Array<{ expireAfterSeconds?: number; name: string }>) => {
const calls: string[] = []
const coll = {
collectionName: 'consent-records',
createIndex: async (key: object, options: { expireAfterSeconds: number; name: string }) => {
calls.push(`create ${JSON.stringify(key)} ${options.expireAfterSeconds}`)
return options.name
},
dropIndex: async (name: string) => void calls.push(`drop ${name}`),
indexes: async () => indexes,
updateMany: async (filter: object, update: object[]) => {
calls.push(`backfill ${JSON.stringify(filter)} ${JSON.stringify(update)}`)
return {}
},
}
const payload = { db: { name: 'mongoose', collections: { 'consent-records': { collection: coll } }, connection: { db: { command: async (c: object) => void calls.push(`collMod ${JSON.stringify(c)}`) } } } }
return { calls, payload: payload as never }
}
test('created on its own field (not Payload\'s createdAt index), old records backfilled from their date', async () => {
const { calls, payload } = fake([{ name: '_id_' }, { name: 'createdAt_1' }])
expect(await syncTtlIndex(payload, 'consent-records', { days: 1095, enabled: true, from: 'createdAt' })).toBe('created')
expect(calls).toEqual([
`backfill {"createdAt":{"$type":"date"},"${TTL_FIELD}":{"$exists":false}} [{"$set":{"${TTL_FIELD}":"$createdAt"}}]`,
`create {"${TTL_FIELD}":1} ${1095 * 86_400}`,
])
})
test('a changed retention moves the index (collMod); the same one does nothing; off drops it', async () => {
const changed = fake([{ name: TTL_INDEX, expireAfterSeconds: 90 * 86_400 }])
expect(await syncTtlIndex(changed.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('updated')
expect(changed.calls.at(-1)).toBe(`collMod {"collMod":"consent-records","index":{"name":"${TTL_INDEX}","expireAfterSeconds":${30 * 86_400}}}`)
const same = fake([{ name: TTL_INDEX, expireAfterSeconds: 30 * 86_400 }])
expect(await syncTtlIndex(same.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('none')
const off = fake([{ name: TTL_INDEX, expireAfterSeconds: 30 * 86_400 }])
expect(await syncTtlIndex(off.payload, 'consent-records', { days: 30, enabled: false, from: 'lastAt' })).toBe('dropped')
expect(off.calls).toEqual([`drop ${TTL_INDEX}`])
})
test('Postgres / SQLite: nothing (the purge after a new record does it); the field is MongoDB-only', async () => {
expect(await syncTtlIndex({ db: { name: 'drizzle' } } as never, 'consent-records', { days: 30, enabled: true, from: 'createdAt' })).toBe('none')
expect(read('src/plugin.ts')).toMatch(/if \(isMongo\(config\)\) \{consentCollection\.fields = \[\.\.\.consentCollection\.fields, ttlField\(\)\]\}/)
})
})
describe('versions (item 13)', () => {
test('the plugin\'s entities with versions on get 20 unless the project set a limit', () => {
expect(PLUGIN_VERSION_LIMIT).toBe(20)
expect(withVersionLimit({ slug: 'site-integrations', versions: true }, 'global').versions).toEqual({ max: 20 })
expect(withVersionLimit({ slug: 'forms', versions: { drafts: true } }, 'collection').versions).toEqual({ drafts: true, maxPerDoc: 20 })
expect(withVersionLimit({ slug: 'forms', versions: { maxPerDoc: 0 } }, 'collection').versions).toEqual({ maxPerDoc: 0 }) // the project's own (unlimited) wins
expect(withVersionLimit({ slug: 'forms' } as { slug: string; versions?: unknown }, 'collection').versions).toBeUndefined()
})
test('doctor hint for a project that turns versions on without a limit', async () => {
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-versions-'))
try {
const files: Record<string, string> = {
'package.json': '{"name":"x-web"}',
'src/collections/Pages.ts': "export const Pages = { slug: 'pages', versions: { drafts: { autosave: true } }, fields: [] }",
'src/collections/Posts.ts': "export const Posts = { slug: 'posts', versions: { drafts: true, maxPerDoc: 20 }, fields: [] }",
'src/globals/Header.ts': "export const Header = { slug: 'header', versions: true, fields: [] }",
}
for (const [rel, text] of Object.entries(files)) {
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
writeFileSync(path.join(dir, rel), text)
}
const report = await runDoctor({ offline: true, only: ['growth-versions-config'], packageRoot: root, root: dir, today: '2026-12-01', writeSeen: false })
expect(report.findings.map((f) => `${f.severity} ${f.file}: ${f.fix}`)).toEqual([
'info src/collections/Pages.ts: versions: { …, maxPerDoc: 20 }',
'info src/globals/Header.ts: versions: { max: 20 }',
])
} finally {
rmSync(dir, { force: true, recursive: true })
}
})
})
describe('unused media in the panel (item 12)', () => {
const payload = (docs: Record<string, object[]>) => ({
config: { admin: { user: 'users' }, collections: [{ slug: 'media', upload: true }, { slug: 'pages' }, { slug: 'users' }], custom: { ipal: { staffCollections: ['users'] } }, globals: [] },
find: async ({ collection }: { collection: string }) => ({ docs: docs[collection] ?? [] }),
findGlobal: async () => ({}),
})
const editor = { id: 1, collection: 'users', roles: ['editor'] }
test('a link to Payload\'s own list filtered to the unused files — nothing is deleted', async () => {
const p = payload({ media: [{ id: 'm1', filename: 'a.jpg' }, { id: 'm2', filename: 'plan.pdf' }, { id: 'm3', filename: 'b.jpg' }], pages: [{ hero: 'm1', text: 'see /api/media/file/plan.pdf' }] })
const html = renderToStaticMarkup(await UnusedMediaNotice({ adminRoute: '/admin', collection: 'media', i18n: { language: 'en' }, payload: p as never, user: editor }))
expect(html).toContain('1 file is not used on any page, entry or setting.')
expect(html).toContain('href="/admin/collections/media?where[id][in][0]=m3"')
expect(html).not.toMatch(/m1|m2/)
})
test('nothing for a visitor account or when every file is used; only a hint when the site is too big to check here', async () => {
const used = payload({ media: [{ id: 'm1', filename: 'a.jpg' }], pages: [{ hero: 'm1' }] })
expect(await UnusedMediaNotice({ collection: 'media', payload: used as never, user: editor })).toBeNull()
expect(await UnusedMediaNotice({ collection: 'media', payload: used as never, user: null })).toBeNull()
const broken = { ...used, find: async ({ collection }: { collection: string }) => { if (collection === 'pages') {throw new Error('no')} return { docs: [{ id: 'm1', filename: 'a.jpg' }] } } }
expect(renderToStaticMarkup(await UnusedMediaNotice({ collection: 'media', payload: broken as never, user: editor }))).toContain('too many documents to check')
})
})
+89
View File
@@ -0,0 +1,89 @@
import sharp from 'sharp'
import { describe, expect, test } from 'vitest'
import { buildOptimizeUploadHook } from '../src/modules/media/optimizeUpload.js'
import { exifOrientation, stripImageMetadata } from '../src/modules/media/stripMetadata.js'
/** A small JPEG with EXIF (camera, GPS-like comment, orientation) and an ICC profile. */
const jpegWith = (orientation = 1) =>
sharp({ create: { background: { b: 40, g: 120, r: 200 }, channels: 3, height: 24, width: 40 } })
.withMetadata({ exif: { IFD0: { Copyright: 'Example', Make: 'PhoneCo', Model: 'X1' } }, orientation })
.withIccProfile('srgb')
.jpeg({ quality: 90 })
.toBuffer()
const pngWithText = async () => {
const png = await sharp({ create: { background: '#336699', channels: 4, height: 8, width: 8 } }).png().toBuffer()
// a tEXt chunk after IHDR: "Comment\0secret place"
const data = Buffer.from('Comment\0secret place', 'latin1')
const chunk = Buffer.alloc(12 + data.length)
chunk.writeUInt32BE(data.length, 0)
chunk.write('tEXt', 4, 'latin1')
data.copy(chunk, 8)
chunk.writeUInt32BE(0, 8 + data.length) // CRC is not checked by the stripper (the chunk is dropped)
const ihdrEnd = 8 + 12 + png.readUInt32BE(8)
return Buffer.concat([png.subarray(0, ihdrEnd), chunk, png.subarray(ihdrEnd)])
}
describe('stripImageMetadata', () => {
test('JPEG: EXIF goes, the image data and the colour profile stay byte for byte', async () => {
const input = await jpegWith()
expect(input.includes(Buffer.from('PhoneCo'))).toBe(true)
const { buffer, changed, orientation } = stripImageMetadata(input, 'image/jpeg')
expect(changed).toBe(true)
expect(orientation).toBe(1)
expect(buffer.includes(Buffer.from('PhoneCo'))).toBe(false)
const before = await sharp(input).metadata()
const after = await sharp(buffer).metadata()
expect(after.exif).toBeUndefined()
expect(after.icc).toBeDefined() // the colour profile is kept
expect([after.width, after.height]).toEqual([before.width, before.height])
// same pixels: no re-encode
expect(await sharp(buffer).raw().toBuffer()).toEqual(await sharp(input).raw().toBuffer())
const sos = (b: Buffer) => b.subarray(b.indexOf(Buffer.from([0xff, 0xda])))
expect(sos(buffer).equals(sos(input))).toBe(true)
})
test('JPEG: the EXIF orientation is reported, so the caller can turn the pixels first', async () => {
expect(stripImageMetadata(await jpegWith(6), 'image/jpeg').orientation).toBe(6)
expect(exifOrientation(Buffer.from('not exif'))).toBe(1)
})
test('PNG: text chunks go, the pixels stay', async () => {
const input = await pngWithText()
expect(input.includes(Buffer.from('secret place'))).toBe(true)
const { buffer, changed } = stripImageMetadata(input, 'image/png')
expect(changed).toBe(true)
expect(buffer.includes(Buffer.from('secret place'))).toBe(false)
expect(await sharp(buffer).raw().toBuffer()).toEqual(await sharp(input).raw().toBuffer())
})
test('nothing to strip, another format or a broken file: returned unchanged', async () => {
const clean = await sharp({ create: { background: '#000', channels: 3, height: 4, width: 4 } }).jpeg().toBuffer()
expect(stripImageMetadata(clean, 'image/jpeg').changed).toBe(false)
const webp = await sharp(clean).webp().toBuffer()
expect(stripImageMetadata(webp, 'image/webp')).toEqual({ buffer: webp, changed: false, orientation: 1 })
const broken = Buffer.from([0xff, 0xd8, 0x00, 0x01, 0x02])
expect(stripImageMetadata(broken, 'image/jpeg').buffer).toBe(broken)
})
})
describe('buildOptimizeUploadHook: metadata on uploads that pass the limits', () => {
const run = async (data: Buffer, options = {}) => {
const file = { name: 'photo.jpg', data, mimetype: 'image/jpeg', size: data.length }
await buildOptimizeUploadHook(options)({ args: { data: {} }, operation: 'create', req: { file, i18n: { language: 'en' }, payload: { config: { sharp } } } } as never)
return file
}
test('stripped by default; an EXIF rotation is applied to the pixels; `stripMetadata: false` keeps the file', async () => {
const plain = await run(await jpegWith())
expect(plain.data.includes(Buffer.from('PhoneCo'))).toBe(false)
expect(plain.name).toBe('photo.jpg') // same format and name: only the metadata went
const turned = await run(await jpegWith(6)) // 40×24 stored, "rotate 90°" in EXIF
const meta = await sharp(turned.data).metadata()
expect([meta.width, meta.height, meta.orientation]).toEqual([24, 40, undefined])
const original = await jpegWith()
expect((await run(original, { stripMetadata: false })).data).toBe(original)
})
})