1.18.0 performance items: reference 404 placeholder and heading font without preload, lazy form and Turnstile code (eager entry /client/eager), Turnstile space kept, background video paused for reduced motion, card hover on opacity, metadata stripped on upload, MongoDB TTL indexes for the consent log and statistics, unused-media notice, version limit for the plugin's entities

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 15:38:38 +01:00
co-authored by Claude Opus 5.5
parent 076b3ef707
commit d628839235
47 changed files with 2546 additions and 78 deletions
+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`
+768
View File
@@ -0,0 +1,768 @@
{
"client": {
"mobile": {
"home": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 19948,
"image": 9544,
"js": 188341,
"other": 0
},
"cls": 0.036,
"fcp": 768,
"inp": 32,
"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": 2432,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 22,
"scriptMs": 126,
"status": 200,
"tbt": 14,
"thirdParty": [],
"ttfb": 151,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17081,
"image": 8457,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 756,
"inp": 32,
"interaction": "PL",
"lcp": 756,
"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": 2435,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 126,
"status": 200,
"tbt": 12,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16640,
"image": 5322,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 740,
"inp": 40,
"interaction": "PL",
"lcp": 740,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2437,
"prefetches": 3,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 130,
"status": 200,
"tbt": 14,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17135,
"image": 5322,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 752,
"inp": 40,
"interaction": "PL",
"lcp": 752,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2435,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 137,
"status": 200,
"tbt": 15,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16540,
"image": 4376,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 772,
"inp": 40,
"interaction": "PL",
"lcp": 772,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2442,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 18,
"scriptMs": 129,
"status": 200,
"tbt": 15,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16793,
"image": 0,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 776,
"inp": 40,
"interaction": "PL",
"lcp": 776,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2380,
"prefetches": 2,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 16,
"scriptMs": 215,
"status": 200,
"tbt": 13,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 37303,
"image": 2018,
"js": 216609,
"other": 0
},
"cls": 0,
"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": 2459,
"prefetches": 4,
"profile": "mobile",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 21,
"scriptMs": 205,
"status": 200,
"tbt": 21,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 151,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 7711,
"image": 0,
"js": 188341,
"other": 2472
},
"cls": 0,
"fcp": 1900,
"inp": 40,
"interaction": "PL",
"lcp": 1900,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 2845,
"prefetches": 10,
"profile": "mobile",
"renderBlocking": [],
"requests": 17,
"scriptMs": 172,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 151,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"desktop": {
"home": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 19948,
"image": 9286,
"js": 188341,
"other": 0
},
"cls": 0.001,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 477,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 22,
"scriptMs": 51,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl",
"runs": 3
},
"page": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17081,
"image": 10684,
"js": 188341,
"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": 476,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 20,
"scriptMs": 47,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/o-nas",
"runs": 3
},
"archive": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16640,
"image": 4815,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 284,
"inp": 40,
"interaction": "PL",
"lcp": 284,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 469,
"prefetches": 11,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 51,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog",
"runs": 3
},
"post": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 17135,
"image": 4815,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 276,
"inp": 40,
"interaction": "PL",
"lcp": 276,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 472,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 19,
"scriptMs": 46,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/blog/zanim-kupisz-dzialke",
"runs": 3
},
"caseStudy": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16540,
"image": 9286,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 292,
"inp": 40,
"interaction": "PL",
"lcp": 292,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 471,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 20,
"scriptMs": 40,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/realizacje/dom-pod-lasem",
"runs": 3
},
"form": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 16793,
"image": 0,
"js": 188341,
"other": 0
},
"cls": 0,
"fcp": 280,
"inp": 40,
"interaction": "PL",
"lcp": 280,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 439,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 16,
"scriptMs": 51,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/wycena",
"runs": 3
},
"showcase": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 37303,
"image": 5267,
"js": 216587,
"other": 0
},
"cls": 0,
"fcp": 304,
"inp": 40,
"interaction": "PL",
"lcp": 304,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "p"
},
"load": 493,
"prefetches": 8,
"profile": "desktop",
"renderBlocking": [
"/_next/static/css/b2d8ea1877879cf5.css"
],
"requests": 22,
"scriptMs": 60,
"status": 200,
"tbt": 0,
"thirdParty": [
"https://challenges.cloudflare.com"
],
"ttfb": 41,
"url": "/pl/bloki",
"runs": 3
},
"notFound": {
"bytes": {
"css": 11177,
"font": 209501,
"html": 7711,
"image": 0,
"js": 188341,
"other": 2472
},
"cls": 0,
"fcp": 428,
"inp": 40,
"interaction": "PL",
"lcp": 480,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "h1"
},
"load": 412,
"prefetches": 14,
"profile": "desktop",
"renderBlocking": [],
"requests": 17,
"scriptMs": 44,
"status": 404,
"tbt": 0,
"thirdParty": [],
"ttfb": 41,
"url": "/pl/nie-ma-takiej-strony",
"runs": 3
}
},
"admin": {
"bytes": {
"css": 98168,
"font": 0,
"html": 24047,
"image": 0,
"js": 843378,
"other": 1690
},
"cls": 0,
"fcp": 1040,
"inp": null,
"interaction": null,
"lcp": 1040,
"lcpElement": {
"fetchpriority": null,
"loading": null,
"src": null,
"tag": "a"
},
"load": 962,
"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": 351,
"status": 200,
"tbt": 0,
"thirdParty": [],
"ttfb": 89,
"url": "/admin/login",
"runs": 3
}
},
"date": "2026-12-01T14:09:30.949Z",
"label": "webpack-1180-after",
"method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs",
"runs": 3,
"server": {
"coldStartHealthMs": 1197,
"coldStartFirstPageMs": 1221,
"firstPageMs": 22,
"ttfb_home": {
"median": 3.5,
"p95": 6.8
},
"ttfb_md": {
"median": 30.7,
"p95": 37.1
},
"ttfb_sitemap": {
"median": 1.8,
"p95": 2.4
},
"ttfb_llms": {
"median": 44.6,
"p95": 56.7
},
"render": {
"home": {
"medianMs": 68.1,
"queries": 24,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 33,
"media": 9,
"forms": 3
}
},
"page": {
"medianMs": 53.1,
"queries": 21,
"queryMs": 1,
"byCollection": {
"globals": 27,
"media": 6,
"pages": 27,
"forms": 3
}
},
"archive": {
"medianMs": 62,
"queries": 23,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6,
"forms": 3,
"posts": 6
}
},
"post": {
"medianMs": 65.3,
"queries": 26,
"queryMs": 0,
"byCollection": {
"globals": 27,
"media": 9,
"pages": 24,
"posts": 15,
"forms": 3
}
},
"caseStudy": {
"medianMs": 50.2,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 21,
"media": 6,
"casestudies": 9,
"forms": 3
}
},
"form": {
"medianMs": 31.4,
"queries": 19,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 24,
"media": 3,
"forms": 3
}
},
"showcase": {
"medianMs": 48.8,
"queries": 27,
"queryMs": 0,
"byCollection": {
"globals": 24,
"pages": 33,
"media": 12,
"forms": 6,
"posts": 6
}
},
"notFound": {
"medianMs": 21.3,
"queries": 20,
"queryMs": 0,
"byCollection": {
"globals": 27,
"pages": 27,
"media": 6
}
},
"md": {
"medianMs": 29,
"queries": 16,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 5,
"pages": 6,
"forms": 1
}
},
"sitemap": {
"medianMs": 3,
"queries": 0,
"queryMs": 0,
"byCollection": {}
},
"llms": {
"medianMs": 42,
"queries": 22,
"queryMs": 0,
"byCollection": {
"globals": 4,
"media": 3,
"pages": 7,
"posts": 4,
"casestudies": 4
}
},
"llmsFull": {
"medianMs": 55,
"queries": 38,
"queryMs": 0,
"byCollection": {
"globals": 6,
"media": 9,
"pages": 13,
"forms": 2,
"posts": 4,
"casestudies": 4
}
}
},
"rssMiB": 305
}
}
+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
}
}
+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",
+33 -4
View File
@@ -37,10 +37,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 +108,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)
+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
@@ -22,6 +22,7 @@ export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js
export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTab.js'
export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { UNUSED_MEDIA_LINK_LIMIT, UnusedMediaNotice } from '../modules/media/UnusedMediaNotice.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js'
export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.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,9 @@ 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'
// `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 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'
+2 -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,
@@ -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
@@ -1,5 +1,6 @@
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { TTL_FIELD } from '../shared/ttl.js'
import type { CollectionOverride } from '../shared/collectionOverride.js'
import { userMeetsRole } from '../access/predicates.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), { filename: d.filename ?? null, id: d.id, slug: u.slug })
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({ filename: f.filename, id: f.id })}}
return { byCollection, checked, complete, total: files.size }
}
+34
View File
@@ -4,6 +4,8 @@ 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
@@ -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)
+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 = (
@@ -24,6 +24,11 @@ export type RenderFormProps = {
/** The project's `sendForm` server action (createSubmitAction). */
action: SendFormAction
classNames?: BuilderFormClassNames
/**
* 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>
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
converters?: JSXConvertersFunction
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
@@ -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({ [TTL_FIELD]: { $exists: false }, [from]: { $type: 'date' } }, [{ $set: { [TTL_FIELD]: `$${from}` } }])
const seconds = Math.round(days * 86_400)
if (!existing) {
await coll.createIndex({ [TTL_FIELD]: 1 }, { expireAfterSeconds: seconds, name: TTL_INDEX })
return 'created'
}
if (existing.expireAfterSeconds === seconds) {return 'none'}
await db.connection!.db!.command({ collMod: coll.collectionName, index: { expireAfterSeconds: seconds, name: TTL_INDEX } })
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 as object), [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
@@ -1,5 +1,6 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { TTL_FIELD } from '../shared/ttl.js'
import type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
import { gpcFromHeaders, resolveConsent } from '../consent/gpc.js'
@@ -119,6 +120,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
data: {
exit: path,
lastAt: now.toISOString(),
[TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts)
pageCount: pages.length,
pages,
...(visitorId && !visit.visitorId ? { visitorId } : {}),
@@ -136,6 +138,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
entry: path,
exit: path,
lastAt: now.toISOString(),
[TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts)
pageCount: 1,
pages: [{ p: path, t: now.toISOString() }],
referrer: referrerHost(body.r, host),
+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
@@ -1,4 +1,5 @@
'use client'
import { TURNSTILE_HEIGHT } from './turnstileHeight.js'
import { useEffect, useRef } from 'react'
import { useTheme } from '../theme/useTheme.js'
@@ -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, resetSignal = 0, siteKey, theme = 'page', reserveHeight = TURNSTILE_HEIGHT }: 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'
@@ -77,6 +77,8 @@ import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { withRetention } from './modules/shared/retention.js'
import { isMongo, syncTtlIndex, ttlField } from './modules/shared/ttl.js'
import { withVersionLimit } from './modules/shared/versionLimit.js'
import { assertPluginSwitches } from './modules/shared/switches.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({ days: logOptions.retentionDays ?? 1095, enabled: logOptions.ttlIndex !== false, from: 'createdAt', slug: CONSENT_LOG_SLUG })
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({ days: statsOptions.retentionDays ?? 90, enabled: statsOptions.ttlIndex !== false, from: 'lastAt', slug: 'stats-visits' })
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)
+7
View File
@@ -154,6 +154,13 @@ export type IaplOptions = {
* factor: whoever the dashboard is drawn for sees the full text.
*/
dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' }
/**
* 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?: boolean | { collections?: string[] }
/**
* Host patterns of the project's development, preview and staging addresses (`*` = any characters).
+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: { collections: { 'consent-records': { collection: coll } }, connection: { db: { command: async (c: object) => void calls.push(`collMod ${JSON.stringify(c)}`) } }, name: 'mongoose' } }
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 {"${TTL_FIELD}":{"$exists":false},"createdAt":{"$type":"date"}} [{"$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([{ expireAfterSeconds: 90 * 86_400, name: TTL_INDEX }])
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":{"expireAfterSeconds":${30 * 86_400},"name":"${TTL_INDEX}"}}`)
const same = fake([{ expireAfterSeconds: 30 * 86_400, name: TTL_INDEX }])
expect(await syncTtlIndex(same.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('none')
const off = fake([{ expireAfterSeconds: 30 * 86_400, name: TTL_INDEX }])
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' }, '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 = { collection: 'users', id: 1, roles: ['editor'] }
test('a link to Payload\'s own list filtered to the unused files — nothing is deleted', async () => {
const p = payload({ media: [{ filename: 'a.jpg', id: 'm1' }, { filename: 'plan.pdf', id: 'm2' }, { filename: 'b.jpg', id: 'm3' }], 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: [{ filename: 'a.jpg', id: 'm1' }], 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: [{ filename: 'a.jpg', id: 'm1' }] } } }
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 = { data, mimetype: 'image/jpeg', name: 'photo.jpg', 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)
})
})