Merge commit '977872b' into claude/project-starter-build

This commit is contained in:
Radosław Smoliński
2026-10-29 15:51:32 +01:00
37 changed files with 518 additions and 39 deletions
+6
View File
@@ -15,6 +15,12 @@ export default async function LocaleLayout({ children, params }: Props) {
<body>
<SiteProviders banner={<CookieBanner controls="switch" equalChoice settings="detailed" />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
<main>{children}</main>
{/* A footer with links in the bottom-left corner: CookieButton must not cover them. */}
<footer style={{ borderTop: '1px solid #e5e5e5', display: 'flex', gap: '1.5rem', marginTop: '60vh', padding: '1.5rem 1rem' }}>
<a href={`/${locale}`}>Home</a>
<a href={`/${locale}/kontakt`}>Kontakt</a>
<a href={`/${locale}/polityka-prywatnosci`}>Polityka prywatności</a>
</footer>
</SiteProviders>
</body>
</html>
+22
View File
@@ -58,6 +58,26 @@ fifteen ready page sections and ten page templates. A new site in one command: `
- **Reference site for agents:** `docs/agent/reference-site/INDEX.md` (shipped) maps every plugin feature to a file
in a complete example site built on ipal-kit, so an agent can copy a working pattern. The site itself lives in the
plugin repo (`reference/`, not shipped) and is built, seeded and smoke-tested in the plugin's CI.
- **2FA screens in plain English and Polish:** `TOTP_TEXTS` (en, pl) go over `@clocklimited/payload-2fa`'s texts, and
the setup / verify screens get a tab title (`TOTP_VIEW_TITLE`, in the site's default language) instead of
"Payload". The project's own `i18n.translations.<lang>.totpPlugin` still wins, a view's own `meta.title` stays, and
`twoFactor: { …, texts: false }` keeps the package's texts. The admin language still follows the browser.
- **`<CookieButton>` stays clear of the footer:** when the footer scrolls into view the button moves up above it
(`avoid`, default `COOKIE_BUTTON_AVOID` = `footer, [role="contentinfo"]`; `avoid={false}` turns it off), `side`
(`'left'` default / `'right'`), position tokens `--ipal-cookie-button-inset`; `bottomOverlap` for your own widget.
Type `CookieButtonProps`.
### Fixed
- **Sitemap, llms.txt, the site index (MCP `list_pages`), search (`searchContent`, the search route, MCP
`search_content`):** the page assigned as the 404 page is no longer listed —
it answers 404 at its own address (`unlistedPageIds(settings)`). A 404 page that is also the homepage stays.
- **`buildImagesConfig` in production without R2:** with `R2_PUBLIC_URL` empty (the default: media served by the
app) the site's own `/api/media/file/**` on `NEXT_PUBLIC_SERVER_URL` is allowed, so next/image no longer answers
400. With R2 nothing changes; a production build on localhost still never opens private IPs.
- **`fillGlobal`:** a choice field (select, radio, checkbox, number, date) still at its `defaultValue` counts as
empty, so e.g. Theme → `defaultTheme: 'system'` can be seeded over the stored default `light`. Text is never
overwritten, even when it equals a default.
- **Docs:** `LanguageSwitcher` with `renderLabel` needs a `'use client'` wrapper (i18n.md, ipal-site).
### Changed
- The plugin's own dependencies are pinned to exact versions (`lucide-react` 0.400.0, `nodemailer` 10.3.1,
@@ -92,6 +112,8 @@ fifteen ready page sections and ten page templates. A new site in one command: `
Existing sites move block by block when they get work (an own block with the same slug and fields can be replaced by
the library block with `slug`, else a migration with **ipal-migrate-fields**). After turning blocks on:
`pnpm generate:types`, `pnpm payload generate:importmap`, Postgres/SQLite `pnpm payload migrate:create`.
6. **CookieButton:** it now lifts above the site footer when the footer is in view. A site with its own fixed footer
bar or a button placed by `className`: check it; `avoid={false}` keeps the old fixed position.
## 1.14.6
@@ -36,6 +36,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `twoFactor.collectionSlug` | the panel's login collection (`admin.user`, else the first auth collection) | collection with 2FA; startup fails with `[ipal] twoFactor…` when it is not an auth collection or differs from `admin.user` | point it at the login collection |
| `twoFactor.provider` | `'@intecion/ipal-kit/admin#TotpRedirectProvider'` | admin provider that sends users to `setup-totp` / `verify-totp` (path read in the browser); replaces the package's header-based one | own component path / `{ path, clientProps, serverProps }` (gets clientProps `forceSetup`); `false` keeps the package's (needs `x-pathname` on `/admin`, else `setup-totp?back=null` loops) |
| `twoFactor.texts` | ipal-kit's en/pl texts (`TOTP_TEXTS`) over the package's; 2FA screens titled "Two-step verification" / "Weryfikacja dwuetapowa" (site's language) | `false` = the package's texts; one text: `i18n.translations.<lang>.totpPlugin.<key>` (security.md) |
| `twoFactor.allowCollectionMismatch` | `false` | allows `collectionSlug` ≠ `admin.user` (panel users of the other collection then skip 2FA) | `true` only when you protect a second auth collection on purpose |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
@@ -144,7 +144,9 @@ Fifteen ready blocks and ten page templates. **Use a library block (or a variant
|---|---|---|
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint? }` — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Prop `className`. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Props `className`, `side` (`'left' \| 'right'`), `avoid` (selector it lifts above, default `COOKIE_BUTTON_AVOID` = footer; `false`). Tokens `--ipal-cookie-button-offset`, `--ipal-cookie-button-inset`. Type `CookieButtonProps`. |
| `COOKIE_BUTTON_AVOID`, `bottomOverlap(tops, viewportHeight)` | `@intecion/ipal-kit/client` | Default footer selector; pixels the footer covers at the bottom of the screen (how far the button moves up) |
| `TOTP_TEXTS`, `TOTP_VIEW_TITLE` | `@intecion/ipal-kit` | en/pl texts of the 2FA screens (`totpPlugin:*`, merged by `twoFactor`) and their tab title |
| `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels?, locale?, categories?, caption?, classNames?, storageColumn?, storageTypes? }`; `rows` from `getCookieTable()`; a **Type** column when a row is local / session storage (`storageColumn: 'auto' \| boolean`). |
| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, acceptAll, rejectAll, savePreferences, reopen }`. Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). |
@@ -346,7 +348,7 @@ Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders
| `DEFAULT_MIDDLEWARE_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | array `['/((?!api\|admin\|_next\|.*\\..*).*)']` (excludes `api`, `admin`, `_next`, files); paste into `config.matcher` as a literal — Next reads the matcher statically |
| `AlternateLinksProvider` | `@intecion/ipal-kit/client` | layout provider that holds the current page's addresses per language (for `LanguageSwitcher`); `SiteProviders` does not mount it |
| `AlternateLinksUpdater` | `@intecion/ipal-kit/client` | `<AlternateLinksUpdater links={{ pl, en }} />` on a page — reports its addresses in other languages |
| `LanguageSwitcher` | `@intecion/ipal-kit/client` | headless language switcher (`config`, `currentLocale`, `classNames`, `renderLabel`) linking to the addresses from context |
| `LanguageSwitcher` | `@intecion/ipal-kit/client` | headless language switcher (`config`, `currentLocale`, `classNames`, `renderLabel`) linking to the addresses from context. `renderLabel` is a function: pass it from a `'use client'` wrapper of your own, never from a server header (build fails) — i18n.md |
| `useAlternateLinks()` | `@intecion/ipal-kit/client` | hook: `{ [locale]: url }` of the current page — for your own switcher |
| `useSetAlternateLinks()` | `@intecion/ipal-kit/client` | setter hook used by `AlternateLinksUpdater` (usually not needed) |
@@ -512,6 +514,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
| Export | Import from | What it does / when |
|---|---|---|
| `unlistedPageIds(settings)` | `@intecion/ipal-kit` | Site settings → ids of pages with no URL of their own (the assigned 404 page, unless it is the homepage) — the sitemap, llms.txt and the site index skip them; use it in your own page lists |
| `getSystemPagePath({ page, locale, config, homeSlug? })` | `@intecion/ipal-kit` | Page assigned in Site settings (read with `locale: 'all'`) → path in the language (`/pl` for the homepage, `/en/privacy-policy`) or `undefined` |
| `ALL_SYSTEM_PAGE_ROLES` | `@intecion/ipal-kit` | Constant: all system page roles in a fixed order: `homepage`, `notFound`, `privacyPolicy`, `cookiePolicy`, `termsOfService` |
| `LocaleView({ views, defaultLocale })` | `@intecion/ipal-kit/client` | Picks, from ready per-language views, the one from the URL (`/en/...`) — in `not-found.tsx` without `headers()` (the route stays static); used by `createNotFoundPage` |
@@ -555,7 +558,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global (all seeded fields with `update` when untouched). |
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does (all seeded fields with `update` when untouched). |
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
+1 -1
View File
@@ -531,7 +531,7 @@ globals (the plugin's globals already refresh with `ipalKit({ revalidatePath })`
`/en/…`; the footer has legal links in the page language.
**Turn off / override.** Navigation is entirely project code (the plugin provides fields and resolvers); `buildLinkField({
relationTo, appearances: false, disableLabel })`, `LanguageSwitcher` (`classNames`, `renderLabel`) or your own on
relationTo, appearances: false, disableLabel })`, `LanguageSwitcher` (`classNames`, `renderLabel` — only inside a `'use client'` wrapper of your own, i18n.md) or your own on
`useAlternateLinks()`.
### Optional modules (outside the set; separate commit, entry in "Project decisions")
+4
View File
@@ -71,6 +71,10 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r
- Schema change with content in the database → **ipal-migrate-fields**, never "live".
## Phase 3 — Navigation and company data → **ipal-nav**
Language switcher in the header: `LanguageSwitcher` (`/client`). With `renderLabel` (e.g. `PL` / `EN`) wrap it in
your own `'use client'` file (`src/components/layout/LocaleSwitcher.tsx`) and render that from the server header —
a function can't cross from a server to a client component, and `next build` fails. Example: i18n.md
"Language switcher without 404".
## Phase 4 — Sections → **ipal-block** for every block
The reference site's Blocks page (`/pl/bloki` on the reference site, seed `src/seed/showcase.ts` in the index) shows
+6 -1
View File
@@ -105,7 +105,12 @@ takes `locale` and optional `labels`; defaults: `COOKIE_TABLE_LABELS` (`@intecio
| `controls` | `'checkbox'` | `'checkbox' \| 'switch'` |
| `settingsActions` | `['back', 'save']` | buttons under the categories (`'accept' \| 'back' \| 'reject' \| 'save'`) |
`CookieButton` takes only `className` (replaces the default).
`CookieButton` props: `className` (replaces the default classes; position is then yours too),
`side` (`'left'` default or `'right'`), `avoid` (CSS selector, default `COOKIE_BUTTON_AVOID` =
`'footer, [role="contentinfo"]'`; `false` = never move). While the footer is on screen the button
moves up by its visible part (`bottomOverlap`), so it never covers footer links. Position tokens:
`--ipal-cookie-button-offset` (from the bottom, default `1rem`), `--ipal-cookie-button-inset` (from the
side, default `1rem`); z-index `--ipal-z-header`. Type `CookieButtonProps`.
## Overriding the look (Level 2)
+3 -2
View File
@@ -390,7 +390,8 @@ Query: `?q=` (required), `?locale=`, `?limit=`. Response:
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
```
No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`),
No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`) and without the page assigned as the
404 page (Site settings → System pages, read through `settingsSlug`, default `site-settings`),
10 by default (`defaultLimit`), max 50 results. Under-construction mode:
pass `isPathVisible` from `createContentHelpers`, and hidden pages drop out of the results. Error/database
offline → empty result (200), not 500. **Rate limit:** 120/min per IP (in memory,
@@ -407,7 +408,7 @@ const results = await searchContent({ payload, query, config, locale, limit, bas
// SearchResult[] = { title, url, description?, slug }[]
```
`searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `locale`
`searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `settingsSlug` (`'site-settings'`, for the 404 page), `locale`
(default/invalid → `defaultLocale`), `limit` (10, clamped to 1–50),
`summaryField` (e.g. `'aiSummary'` — prefers the richer description from
`buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws
+1
View File
@@ -80,6 +80,7 @@ Use these terms everywhere: labels, descriptions, docs, toasts. Never a synonym.
| The whole website | site | `witryna` | website, page, domain |
| A blog/news entry | post | `wpis` | article (unless the project calls it so) |
| Electronic mail | e-mail | `e-mail` | email, mail |
| Code from an authenticator app at login | two-step verification (2FA in short labels) | `weryfikacja dwuetapowa` | TOTP, two-factor authentication |
| Cookie consent | consent | `zgoda` | permission, opt-in |
| Cookie consent banner | cookie banner | `baner cookies` | popup, consent bar, CookieBanner |
| Form entry sent by a visitor | submission | `zgłoszenie` | entry, response, lead |
+32 -2
View File
@@ -352,6 +352,32 @@ LanguageSwitcher has NO styles (classNames) — not `variant="light|dark"`, so t
fits any project design. A locale with no known alternate URL →
falls back to the root `/{code}`.
**`renderLabel` needs a client wrapper.** `LanguageSwitcher` is a client component and `renderLabel` is a
function; a server component (a header rendered on the server) cannot pass a function to a client
component — `next build` fails ("Functions cannot be passed directly to Client Components"). Put the
switcher with its `renderLabel` in a small client file of your own and render that from the server header:
```tsx
// src/components/layout/LocaleSwitcher.tsx — a client component of your own
'use client'
import type { I18nConfig } from '@intecion/ipal-kit'
import { LanguageSwitcher } from '@intecion/ipal-kit/client'
export function LocaleSwitcher({ config, locale }: { config: I18nConfig; locale: string }) {
return (
<LanguageSwitcher
classNames={{ root: 'relative', trigger: '…', menu: '…', item: '…', itemActive: '…' }}
config={config}
currentLocale={locale}
renderLabel={(l) => l.code.toUpperCase()}
/>
)
}
// header.tsx (server): <LocaleSwitcher config={i18nConfig} locale={locale} />
```
Without `renderLabel` (the config labels) the server header can render `LanguageSwitcher` directly.
> **Where the page gets alternates:** the RSC page already resolves the route (resolveRoute);
> from the same source compute the slugs per language (getLocalizedSlugs/buildLocalizedPath)
> and pass them to AlternateLinksUpdater. This removes the custom AlternateLinksContext
@@ -378,7 +404,10 @@ about the matcher — paste it inline. This is a Next limitation, not a plugin o
## Admin panel languages and texts
The site's content languages (`i18n.locales`) and the **admin panel's** language are
separate. The panel's language is what each user picks in *Account → Language*.
separate. The panel's language is what each user picks in *Account → Language*; until they pick one,
Payload takes the browser's language (English or Polish), else `i18n.fallbackLanguage` (Payload's
default `en`). An English browser therefore gets an English panel — 2FA screens included — on a
Polish site; set `i18n.fallbackLanguage: 'pl'` in your config to change the last step.
- **Default:** when the project's `buildConfig` has no `i18n.supportedLanguages`, ipal-kit
sets English and Polish. A project that sets its own list keeps it, untouched:
@@ -426,6 +455,7 @@ separate. The panel's language is what each user picks in *Account → Language*
- `i18n` is required — the module cannot be turned off; one language = mode without the `/pl` prefix.
- `config.localization` is currently always overridden from `i18n` (your own `localization` in payload.config does not survive); `fallback: false` turns off Payload's fallback.
- Proxy: `createProxy` with options (`consentCategory`, `cookieName`, `exposeHeaders`, `markdown`, `policyVersion`) or your own proxy on `createLocaleMiddleware` + `negotiateLocale` / `matchAcceptLanguage`.
- Switcher: `LanguageSwitcher` (`classNames`, `renderLabel`) or your own on `useAlternateLinks()`.
- Switcher: `LanguageSwitcher` (`classNames`, `renderLabel` — only from a client component: wrap it, see
"Language switcher without 404") or your own on `useAlternateLinks()`.
- Paths: `buildLocalizedPath` / `switchLocalePath` with `homeSlug` and `prefix` — for your own link helpers.
- Admin languages: your own `i18n.supportedLanguages` wins over the plugin's en + pl default; component texts via `i18n.translations.<lang>.ipal.<key>`.
+5
View File
@@ -50,6 +50,11 @@ locale — the caller decides the fallback (404, redirect). A slug equal to
`homeSlug` (default `'home'`; a string or a per-language map) collapses to the root — for a home page
with a different slug, pass `homeSlug`.
**Pages with no URL of their own:** `unlistedPageIds(settings)` (root) → the ids of pages assigned to a role that
renders elsewhere — today the 404 page (unless it is also the homepage). The sitemap, llms.txt, the site index
(MCP `list_pages`) and search (`searchContent`, `createSearchRoute`, MCP `search_content`) leave them out; use it in your
own lists of pages too.
## Typical case: `/{locale}` → home page
In the `[locale]/page.tsx` route you read `settings.homepage`, take its slug
+16
View File
@@ -402,6 +402,22 @@ pnpm generate:importmap
`src/app/(payload)/admin/importMap.js` must list `@intecion/ipal-kit/admin#TotpRedirectProvider` and
`@clocklimited/payload-2fa/rsc#TOTPSetup` / `#TOTPVerify` / `#TOTPField`. Commit the file.
### Texts of the 2FA screens (`twoFactor.texts`)
The setup and verify screens and the user field read their texts through Payload's i18n
(`totpPlugin:*`), in the user's admin language (*Account → Language*; without a choice, the
browser's language — an English browser sees English screens on a Polish site). The package's own texts are long and informal,
so ipal-kit merges `TOTP_TEXTS` (English and Polish, per `docs/dev/admin-ux.md`) over them, e.g.
"Two-step verification" / "Weryfikacja dwuetapowa", "Enter the 6-digit code from the app:" /
"Wpisz 6-cyfrowy kod z aplikacji:". The browser tab reads "Weryfikacja dwuetapowa — <site> | Panel"
(`TOTP_VIEW_TITLE` in the site's default language: Payload's view title is a plain string).
- **Override one text:** `i18n.translations.<lang>.totpPlugin.<key>` in your config — your keys win
over both sets.
- **Keep the package's texts:** `twoFactor: { …, texts: false }`.
- **Not translatable:** a network failure while sending the code shows the package's hardcoded
"Something went wrong" toast (rare: the server's own errors are translated).
### The redirect to the 2FA screens (`twoFactor.provider`)
The package's own admin provider decides on the server where to send the user, from an `x-pathname`
+1 -1
View File
@@ -203,7 +203,7 @@ is an error for that record, never an empty relation. Ready pages made of librar
|---|---|
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). With `update` and an untouched global: every seeded field |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
Each method prints one line per record (see [Running a seed](#running-a-seed)) and returns
+6 -4
View File
@@ -259,10 +259,12 @@ variable; the component follows automatically.
- `buildImagesConfig({ serverUrl?, production?, publicUrl?, extraHosts? })` → `images` in
`next.config.ts`: `formats` AVIF + WebP, `minimumCacheTTL` 31 days, `remotePatterns` from
`R2_PUBLIC_URL` (`publicUrl`) and `extraHosts` (https). Outside production (`production`, default
`NODE_ENV === 'production'`) also media served by the app — `/api/media/file/**` on
`NEXT_PUBLIC_SERVER_URL` (`serverUrl`) — and `dangerouslyAllowLocalIP: true` for localhost /
private networks (Next 16 rejects them otherwise). Spread the result and override:
`R2_PUBLIC_URL` (`publicUrl`) and `extraHosts` (https). Media served by the app — `/api/media/file/**` on
`NEXT_PUBLIC_SERVER_URL` (`serverUrl`) — are allowed outside production (`production`, default
`NODE_ENV === 'production'`) **and in production when `R2_PUBLIC_URL` is empty** (the default without R2:
Payload gives absolute URLs on the site's own host, which next/image would refuse with 400). Outside
production also `dangerouslyAllowLocalIP: true` for localhost / private networks (Next 16 rejects them
otherwise); a production build on localhost never gets it — set `production: false` for such a test run. Spread the result and override:
`images: { ...buildImagesConfig(), /* your own */ }`.
- `buildUploadSecurityHeaders({ collections? })` (default `['media']`) → headers for
`/api/<slug>/file/:path*`: sandbox CSP + `nosniff` (uploaded SVG without scripts). security.md.
+1 -4
View File
@@ -68,10 +68,7 @@ for (const l of LOCALES) {
test('every sitemap URL answers 200 with a title, canonical, hreflang and JSON-LD', async ({ page, request }) => {
const xml = await (await request.get('/sitemap.xml')).text()
// KNOWN plugin gap (reported 2026-10-29): the sitemap lists the page assigned as 404, which answers 404.
// Remove this filter when ipal-kit leaves the notFound page out of the sitemap.
const KNOWN_404 = ['/pl/nie-znaleziono', '/en/page-not-found']
const urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname).filter((p) => !KNOWN_404.includes(p))
const urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname)
expect(urls.length).toBeGreaterThan(20)
for (const path of urls) {
const res = await page.goto(path)
+3 -1
View File
@@ -15,14 +15,16 @@ export { shouldLoadGoogle } from '../modules/analytics/shouldLoadGoogle.js'
* client-only code.
*/
export {
bottomOverlap,
ConsentProvider,
ConsentScript,
COOKIE_BUTTON_AVOID,
CookieBanner,
CookieButton,
useConsent,
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from '../modules/consent/client.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieButtonProps, CookieSettingsAction } from '../modules/consent/client.js'
export { ConstructionNotice } from '../modules/construction/ConstructionNotice.js'
export type { ConstructionNoticeClassNames } from '../modules/construction/ConstructionNotice.js'
export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js'
+3 -2
View File
@@ -274,7 +274,7 @@ export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from '
export { getNotificationTexts, NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL, notificationFallback, resolveFormMessage } from './modules/notifications/index.js'
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath, unlistedPageIds } from './modules/pages/index.js'
export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
getGlobal,
@@ -316,8 +316,9 @@ export type {
TotpUser,
WithSecurityConfigOptions,
} from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
export {
+69 -5
View File
@@ -1,22 +1,42 @@
'use client'
import type { CSSProperties } from 'react'
import { Cookie } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useConsentContext } from './ConsentContext.js'
import { useIsMounted } from './useIsMounted.js'
/** Elements the button moves up for, so it never covers footer links. */
export const COOKIE_BUTTON_AVOID = 'footer, [role="contentinfo"]'
export type CookieButtonProps = {
/**
* CSS selector of elements the button lifts above while they are on screen
* (default: the site footer). `false` = never move.
*/
avoid?: false | string
/** Replaces the default classes (look and position). The lift above `avoid` still applies. */
className?: string
/** Corner. Default 'left'. */
side?: 'left' | 'right'
}
/**
* Floating "cookie settings" button — lets visitors reopen the consent panel
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
* Hidden while the banner is showing.
*
* Colours follow the same design tokens as CookieBanner (--ipal-surface,
* --ipal-border, --ipal-hover, --ipal-text), so a client's palette applies to
* both without touching either component. Pass className to
* replace the styling outright.
* --ipal-border, --ipal-hover, --ipal-text). Position: --ipal-cookie-button-offset
* (distance from the bottom, default 1rem), --ipal-cookie-button-inset (from the
* side, default 1rem), z-index --ipal-z-header. When the footer scrolls into
* view the button moves up by the visible part of it, so footer links stay free.
*/
export function CookieButton({ className }: { className?: string } = {}) {
export function CookieButton({ avoid = COOKIE_BUTTON_AVOID, className, side = 'left' }: CookieButtonProps = {}) {
const isMounted = useIsMounted()
const { decided, reopen, texts } = useConsentContext()
const lift = useLiftAbove(avoid, isMounted && decided)
// Render nothing until mounted — prevents hydration mismatch (no project
// ConsentWrapper workaround needed).
@@ -25,9 +45,18 @@ export function CookieButton({ className }: { className?: string } = {}) {
const cls =
className ??
'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] ' +
'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))] border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]'
const position: CSSProperties = className
? {}
: {
bottom: 'calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))',
position: 'fixed',
[side]: 'var(--ipal-cookie-button-inset, 1rem)',
zIndex: 'var(--ipal-z-header, 40)' as unknown as number,
}
return (
<button
// a11y label per locale: the panel's "settings title" (Cookie Settings global)
@@ -35,6 +64,7 @@ export function CookieButton({ className }: { className?: string } = {}) {
className={cls}
data-ipal="cookie-button"
onClick={reopen}
style={{ ...position, ...(lift ? { transform: `translateY(-${lift}px)` } : {}) }}
type="button"
>
<Cookie
@@ -44,3 +74,37 @@ export function CookieButton({ className }: { className?: string } = {}) {
</button>
)
}
/** Pixels of the `avoid` elements visible at the bottom of the viewport (0 when none). */
export function bottomOverlap(tops: number[], viewportHeight: number): number {
const top = Math.min(...tops, viewportHeight)
// Never push the button off the top of the screen.
return Math.max(0, Math.min(viewportHeight - top, viewportHeight - 96))
}
function useLiftAbove(selector: false | string, active: boolean): number {
const [lift, setLift] = useState(0)
const frame = useRef(0)
useEffect(() => {
if (!selector || !active) {return}
const measure = () => {
cancelAnimationFrame(frame.current)
frame.current = requestAnimationFrame(() => {
const tops = [...document.querySelectorAll(selector)].map((el) => el.getBoundingClientRect().top)
setLift(bottomOverlap(tops, window.innerHeight))
})
}
measure()
window.addEventListener('scroll', measure, { passive: true })
window.addEventListener('resize', measure)
const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure)
observer?.observe(document.body)
return () => {
cancelAnimationFrame(frame.current)
window.removeEventListener('scroll', measure)
window.removeEventListener('resize', measure)
observer?.disconnect()
}
}, [selector, active])
return selector ? lift : 0
}
+2 -1
View File
@@ -3,7 +3,8 @@ export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.js'
export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerAction, CookieBannerClassNames, CookieSettingsAction } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js'
export { bottomOverlap, COOKIE_BUTTON_AVOID, CookieButton } from './CookieButton.js'
export type { CookieButtonProps } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components.
export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
export type { ConsentCookieMap } from './useConsent.js'
+4 -1
View File
@@ -27,6 +27,8 @@ type CreateSearchRouteArgs = {
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
*/
rateLimit?: { max?: number; windowMs?: number } | false
/** SiteSettings global (the assigned 404 page is left out of results). Default 'site-settings'. */
settingsSlug?: string
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
summaryField?: string
}
@@ -50,7 +52,7 @@ type CreateSearchRouteArgs = {
* Uses the global Request/Response — no next/server import.
*/
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, summaryField } = args
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, settingsSlug, summaryField } = args
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
@@ -85,6 +87,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
locale,
payload,
query,
settingsSlug,
summaryField,
})
const shownLocale = locale ?? config.defaultLocale
+29 -3
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { unlistedPageIds } from '../pages/unlistedPages.js'
export type SearchResult = {
description?: string
@@ -27,6 +28,8 @@ type SearchContentArgs = {
payload: BasePayload
/** Keywords. */
query: string
/** SiteSettings global — the assigned 404 page is left out (unlistedPageIds). Default 'site-settings'. */
settingsSlug?: string
/**
* Field holding a richer AI summary (see buildSummaryField). When set and
* present on a doc, it's preferred over meta.description for the result's
@@ -64,6 +67,7 @@ export async function searchContent({
locale,
payload,
query,
settingsSlug,
summaryField,
}: SearchContentArgs): Promise<SearchResult[]> {
const q = query.trim()
@@ -89,7 +93,25 @@ export async function searchContent({
return []
}
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
const unlisted = await readUnlisted(payload, settingsSlug)
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField, unlisted })
}
/**
* Ids of pages with no URL of their own (the assigned 404 page), from Site settings — one small read
* (depth 0, two fields). A missing global means none.
*/
async function readUnlisted(payload: BasePayload, settingsSlug = 'site-settings'): Promise<Set<number | string>> {
try {
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
select: { homepage: true, notFound: true } as never,
})) as Record<string, unknown>
return unlistedPageIds(settings)
} catch {
return new Set()
}
}
type ToResultsArgs = {
@@ -99,13 +121,15 @@ type ToResultsArgs = {
max: number
origin: string
summaryField?: string
unlisted: Set<number | string>
}
/** Published, indexable docs → results. Shared by searchContent and listContent. */
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField }: ToResultsArgs): SearchResult[] {
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField, unlisted }: ToResultsArgs): SearchResult[] {
const results: SearchResult[] = []
for (const doc of docs) {
if (doc._status && doc._status !== 'published') {continue}
if (unlisted.has(doc.id)) {continue}
if (doc.noindex || doc.meta?.noindex) {continue}
const title = typeof doc.title === 'string' ? doc.title : undefined
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
@@ -145,6 +169,7 @@ export async function listContent({
limit = 50,
locale,
payload,
settingsSlug,
summaryField,
}: Omit<SearchContentArgs, 'query'>): Promise<SearchResult[]> {
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
@@ -164,5 +189,6 @@ export async function listContent({
} catch {
return []
}
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
const unlisted = await readUnlisted(payload, settingsSlug)
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField, unlisted })
}
+1
View File
@@ -246,6 +246,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
locale,
payload,
query,
settingsSlug,
summaryField,
}), locale)
if (results.length === 0) {return `No pages matched "${query}".`}
+1
View File
@@ -2,3 +2,4 @@ export { getSystemPagePath } from './getSystemPagePath.js'
export { buildSystemPagesFields } from './systemPagesFields.js'
export type { PagesOption, SystemPageRole } from './types.js'
export { ALL_SYSTEM_PAGE_ROLES } from './types.js'
export { unlistedPageIds } from './unlistedPages.js'
+21
View File
@@ -0,0 +1,21 @@
/** A relationship value (populated or an id) → its id. */
const idOf = (rel: unknown): number | string | undefined => {
if (typeof rel === 'string' || typeof rel === 'number') {return rel}
if (rel && typeof rel === 'object') {
const id = (rel as { id?: unknown }).id
return typeof id === 'string' || typeof id === 'number' ? id : undefined
}
return undefined
}
/**
* Pages that have no URL of their own, from Site settings → System pages: the page assigned as the
* 404 page renders through not-found.tsx and answers 404 at its own address, so the sitemap, llms.txt
* and the site index leave it out. A 404 page that is also the homepage stays listed.
*/
export function unlistedPageIds(settings: null | Record<string, unknown> | undefined): Set<number | string> {
const ids = new Set<number | string>()
const notFound = idOf(settings?.notFound)
if (notFound !== undefined && notFound !== idOf(settings?.homepage)) {ids.add(notFound)}
return ids
}
+51
View File
@@ -0,0 +1,51 @@
/**
* Texts of the 2FA screens and the user field (@clocklimited/payload-2fa reads
* them as `totpPlugin:*` through Payload's i18n). The package ships long,
* informal texts; these follow docs/dev/admin-ux.md. ipalKit merges them over
* the package's and under the project's own `i18n.translations`, so a project
* still overrides any key. `setup.description` is rendered as HTML by the package.
*/
const AUTHENTICATOR =
'<a href="https://support.google.com/accounts/answer/1066447" target="_blank" rel="nofollow noopener noreferrer">Google Authenticator</a>'
export const TOTP_TEXTS = {
en: {
totpPlugin: {
authApp: 'Authenticator app',
configured: 'Set up',
errors: { alreadySet: 'Two-step verification is already set up.' },
fieldDescription: 'Codes from an authenticator app protect this account.',
forceTotp: { description: 'The user must set up two-step verification.', label: 'Require 2FA' },
setup: {
addCodeManually: 'Enter the key manually',
button: 'Set up',
description: `Scan the QR code with an authenticator app, e.g. ${AUTHENTICATOR} or Microsoft Authenticator.`,
enterCode: 'Enter the {digits}-digit code from the app:',
incorrectCode: 'Incorrect code. Check the time on your phone or scan the QR code again.',
title: 'Set up two-step verification',
},
verify: { title: 'Two-step verification' },
},
},
pl: {
totpPlugin: {
authApp: 'Aplikacja uwierzytelniająca',
configured: 'Skonfigurowano',
errors: { alreadySet: 'Weryfikacja dwuetapowa jest już skonfigurowana.' },
fieldDescription: 'Kody z aplikacji uwierzytelniającej chronią to konto.',
forceTotp: { description: 'Użytkownik musi skonfigurować weryfikację dwuetapową.', label: 'Wymagaj 2FA' },
setup: {
addCodeManually: 'Wpisz klucz ręcznie',
button: 'Skonfiguruj',
description: `Zeskanuj kod QR aplikacją uwierzytelniającą, np. ${AUTHENTICATOR} lub Microsoft Authenticator.`,
enterCode: 'Wpisz {digits}-cyfrowy kod z aplikacji:',
incorrectCode: 'Nieprawidłowy kod. Sprawdź czas w telefonie lub zeskanuj kod QR ponownie.',
title: 'Konfiguracja weryfikacji dwuetapowej',
},
verify: { title: 'Weryfikacja dwuetapowa' },
},
},
}
/** Browser-tab title of the 2FA screens (Payload view meta is a plain string: the site's language). */
export const TOTP_VIEW_TITLE = { en: 'Two-step verification', pl: 'Weryfikacja dwuetapowa' }
+6 -3
View File
@@ -7,8 +7,8 @@ import {
defaultHashField,
defaultUntouchedSeconds,
editedSinceSeed,
hasContent,
isLocalizedValue,
isUnsetValue,
localesOf,
localize,
projectOnto,
@@ -426,9 +426,12 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
if (!listed(`global:${slug}`)) {return report(notListed(label))}
try {
const target = { global: slug }
const withHash = hasHashField(payload.config.globals.find((g) => g.slug === slug)?.fields as undefined | unknown[])
const global = payload.config.globals.find((g) => g.slug === slug)
const withHash = hasHashField(global?.fields as undefined | unknown[])
const fieldOf = (name: string) => (global?.flattenedFields as { defaultValue?: unknown; name?: string; type?: string }[] | undefined)?.find((f) => f.name === name)
const cur = await readSeedTarget(payload, target, defaultLocale)
const empty = Object.keys(data).filter((k) => !hasContent(cur[k]))
// Empty, or a choice still at its default value (e.g. Theme → light): never text an editor wrote.
const empty = Object.keys(data).filter((k) => isUnsetValue(cur[k], fieldOf(k)))
let keys = empty
let edited: null | string = null
if (update) {
+14
View File
@@ -175,6 +175,20 @@ export async function writeLocales(
}
/** True when a value has content (non-empty text, a number, true, or a nested one). */
/** Field types whose stored value is a choice, not text an editor wrote. */
const CHOICE_TYPES = new Set(['checkbox', 'date', 'number', 'point', 'radio', 'select'])
/**
* A global field nobody has set yet: empty, or — for a choice (select, radio, checkbox, number, date) —
* still holding the field's own `defaultValue`, which Payload stores on the first save of the global.
* Text an editor wrote is never "unset", even when it equals a default.
*/
export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; type?: string }): boolean {
if (!hasContent(value)) {return true}
if (!field || !CHOICE_TYPES.has(field.type ?? '') || field.defaultValue === undefined || typeof field.defaultValue === 'function') {return false}
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
}
export function hasContent(v: unknown): boolean {
if (typeof v === 'string') {return v.trim() !== ''}
if (typeof v === 'number' || v === true) {return true}
+3
View File
@@ -5,6 +5,7 @@ import type { I18nConfig } from '../i18n/index.js'
import { archiveFieldName } from '../content/index.js'
import { buildLocalizedPath, getLocaleCodes , getLocalizedSlugs } from '../i18n/index.js'
import { unlistedPageIds } from '../pages/unlistedPages.js'
import { buildHreflangAlternates } from './hreflang.js'
/**
@@ -264,6 +265,7 @@ export async function buildSitemapEntries({
}
const entries: SitemapEntry[] = []
const unlisted = unlistedPageIds(settings)
for (const collection of collections) {
// Read every doc once, across locales, so one row yields all its language
@@ -272,6 +274,7 @@ export async function buildSitemapEntries({
// loads every block of every post into memory at once.
for await (const raw of readAll(payload, collection.slug, select)) {
if (!isIndexable(raw)) {continue}
if (collection.slug === pagesSlug && unlisted.has(raw.id)) {continue}
const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))]
// Emit a separate <url> for EACH locale. Google's sitemap spec for
+3
View File
@@ -6,6 +6,7 @@ import type { I18nConfig } from '../i18n/index.js'
import { archiveFieldName } from '../content/index.js'
import { buildLocalizedPath, getLocaleCodes, isValidLocale } from '../i18n/index.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js'
import { unlistedPageIds } from '../pages/unlistedPages.js'
/** One public, indexable document in one language. */
export type SiteIndexEntry = {
@@ -154,6 +155,7 @@ export async function collectSiteIndex({
}
const entries: SiteIndexEntry[] = []
const unlisted = unlistedPageIds(settings)
for (const locale of wanted) {
for (const { slug: collection, prefix } of collections) {
// An archive collection without an archive page in this locale has no URLs there.
@@ -170,6 +172,7 @@ export async function collectSiteIndex({
for (const doc of docs) {
if (doc._status && doc._status !== 'published') {continue}
if (doc.noindex || doc.meta?.noindex) {continue}
if (collection === pagesSlug && unlisted.has(doc.id)) {continue}
const title = typeof doc.title === 'string' ? doc.title.trim() : ''
const slug = typeof doc.slug === 'string' ? doc.slug : ''
if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue}
+8 -5
View File
@@ -14,9 +14,11 @@ export type ImagesConfig = {
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
* optimize R2 files — otherwise it refuses them;
* - optimized images cached for 31 days (uploads get new names when replaced);
* - outside production, media served by the app itself (`/api/media/file/**` on
* NEXT_PUBLIC_SERVER_URL — local disk, no R2), including localhost, which
* Next 16 otherwise refuses as a private IP.
* - media served by the app itself (`/api/media/file/**` on NEXT_PUBLIC_SERVER_URL —
* local disk, no R2): always outside production, and in production whenever
* R2_PUBLIC_URL is empty (Payload then gives absolute URLs on the site's own host,
* which next/image refuses with 400 unless they are allowed); outside production
* also localhost, which Next 16 otherwise refuses as a private IP.
*
* import { buildImagesConfig } from '@intecion/ipal-kit'
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
@@ -39,7 +41,8 @@ export function buildImagesConfig({
}
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
let localMedia = false
if (!production && serverUrl && /^https?:\/\//i.test(serverUrl)) {
const r2 = remotePatterns.length > 0
if ((!production || !r2) && serverUrl && /^https?:\/\//i.test(serverUrl)) {
const u = new URL(serverUrl)
remotePatterns.push({
hostname: u.hostname,
@@ -47,7 +50,7 @@ export function buildImagesConfig({
...(u.port ? { port: u.port } : {}),
pathname: '/api/media/file/**',
})
localMedia = /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
localMedia = !production && /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
}
return {
formats: ['image/avif', 'image/webp'],
+31
View File
@@ -1,5 +1,7 @@
import type { Config, Plugin } from 'payload'
import { deepMergeSimple } from 'payload/shared'
import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js'
import type { IpalOptions, TotpPluginFactory } from './types.js'
@@ -30,6 +32,7 @@ import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.j
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
@@ -199,6 +202,34 @@ export const ipalKit = (options: IpalOptions): Plugin => {
totp: { issuer: tf.issuer },
})(config)
// The package's texts are long and informal: ipal-kit's (admin-ux.md) go over
// them, the project's own i18n.translations over both. The 2FA screens get a
// tab title instead of "Payload" (view meta is a plain string: the site's language).
if (tf.texts !== false) {
config.i18n = {
...config.i18n,
translations: deepMergeSimple(
deepMergeSimple((config.i18n?.translations ?? {}) as Record<string, unknown>, TOTP_TEXTS),
(incomingConfig.i18n?.translations ?? {}) as Record<string, unknown>,
),
}
const title = TOTP_VIEW_TITLE[options.i18n.defaultLocale.toLowerCase().startsWith('pl') ? 'pl' : 'en']
const views = config.admin?.components?.views ?? {}
config.admin = {
...config.admin,
components: {
...config.admin?.components,
views: Object.fromEntries(
Object.entries(views).map(([key, view]) =>
/^(?:Setup|Verify)TOTP/.test(key) && view && !view.meta?.title
? [key, { ...view, meta: { ...view.meta, title } }]
: [key, view],
),
),
},
}
}
// The package's TOTPProvider reads the path from an `x-pathname` header
// no proxy sets on /admin, so it redirected the setup screen to itself
// (`setup-totp?back=null`). Swap in ipal-kit's client-side provider, or
+6
View File
@@ -246,6 +246,12 @@ export type IpalOptions = {
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
*/
provider?: false | PayloadComponent
/**
* Texts of the 2FA screens and user field. Default: ipal-kit's English and
* Polish (`TOTP_TEXTS`), merged over the package's; your own
* `i18n.translations.<lang>.totpPlugin` still wins. `false` keeps the package's.
*/
texts?: false
}
| false
+16
View File
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { createSearchRoute } from '../src/modules/content/createSearchRoute.js'
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
const config: I18nConfig = {
@@ -86,6 +87,21 @@ describe('createMcpRoute', () => {
expect((await call('search_content', { query: 'nas' })).content[0].text).toContain('O nas')
})
test('search_content and the search route leave out the page assigned as the 404 page', async () => {
const withNotFound = [...pages, { id: 5, slug: 'nie-znaleziono', _status: 'published', title: 'Nie znaleziono nas' }]
;(payload.find as ReturnType<typeof vi.fn>).mockResolvedValue({ docs: withNotFound })
;(payload.findGlobal as ReturnType<typeof vi.fn>).mockResolvedValue({ homepage: 4, notFound: 5, siteName: 'Acme' })
const text = (await call('search_content', { query: 'nas' })).content[0].text
expect(text).toContain('O nas')
expect(text).not.toContain('nie-znaleziono')
// The site search route uses the same searchContent.
const search = createSearchRoute({ config, getCachedPayload: async () => payload, rateLimit: false })
const body = (await (await search(new Request('https://acme.pl/api/search?q=nas'))).json()) as { results: { slug: string }[] }
// (the fake find ignores the query, so every published page comes back — except the 404 page)
expect(body.results.map((r) => r.slug)).toEqual(['o-nas', 'strona-glowna'])
;(payload.find as ReturnType<typeof vi.fn>).mockResolvedValue({ docs: pages })
})
test('tool errors stay generic (no internals leak)', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
;(payload.find as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ECONNREFUSED db:5432'))
+8
View File
@@ -79,6 +79,14 @@ describe('buildImagesConfig', () => {
expect(config.dangerouslyAllowLocalIP).toBe(true)
expect(buildImagesConfig({ production: false, serverUrl: 'https://staging.acme.pl' }).dangerouslyAllowLocalIP).toBeUndefined()
})
test('production without R2 (the documented default): the site\'s own media are allowed', () => {
const config = buildImagesConfig({ production: true, publicUrl: '', serverUrl: 'https://acme.pl' })
expect(config.remotePatterns).toEqual([{ hostname: 'acme.pl', pathname: '/api/media/file/**', protocol: 'https' }])
expect(config.dangerouslyAllowLocalIP).toBeUndefined()
// A local production build (CI, `next start` on localhost) still never opens private IPs.
expect(buildImagesConfig({ production: true, serverUrl: 'http://localhost:3000' }).dangerouslyAllowLocalIP).toBeUndefined()
})
})
describe('buildMediaPlaceholderHook', () => {
+21
View File
@@ -108,6 +108,14 @@ describe('createSeeder', () => {
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
globals: [
{
slug: 'look',
fields: [
{ name: 'mode', type: 'select', defaultValue: 'light', options: ['light', 'dark', 'system'] },
{ name: 'toggle', type: 'checkbox', defaultValue: true },
{ name: 'greeting', type: 'text', defaultValue: 'Hello' },
],
},
{
slug: 'header',
fields: [
@@ -241,6 +249,19 @@ describe('createSeeder', () => {
expect((await seeder().fillGlobal('header', { tagline: { pl: 'Inne' } })).status).toBe('skip (exists)')
})
test('fillGlobal: a choice still at its default counts as unset; text is never overwritten', async () => {
await payload.updateGlobal({ slug: 'look' as never, data: {} as never }) // first save stores the defaults
const first = await seeder().fillGlobal('look', { greeting: 'Hi', mode: 'system', toggle: false })
expect(first).toMatchObject({ status: 'create' })
expect(first.note).toBe('empty fields filled: mode, toggle')
const look = (await payload.findGlobal({ slug: 'look' as never })) as { greeting: string; mode: string; toggle: boolean }
expect(look).toMatchObject({ greeting: 'Hello', mode: 'system', toggle: false })
// An editor's choice that differs from the default stays.
await payload.updateGlobal({ slug: 'look' as never, data: { mode: 'dark' } as never })
await seeder().fillGlobal('look', { mode: 'system' })
expect(((await payload.findGlobal({ slug: 'look' as never })) as { mode: string }).mode).toBe('dark')
})
test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => {
vi.stubEnv('NODE_ENV', 'production')
const only = ['pages:kontakt']
+27
View File
@@ -251,6 +251,33 @@ describe('sitemap route: split, cache, errors', () => {
})
})
describe('system pages without a URL of their own', () => {
const settings = { homepage: { id: 1, slug: { en: 'home', pl: 'start' } }, notFound: { id: 2, slug: { en: 'not-found-page', pl: 'nie-znaleziono' } } }
const pages = [
{ id: 1, slug: { en: 'home', pl: 'start' }, _status: 'published', title: 'Home' },
{ id: 2, slug: { en: 'not-found-page', pl: 'nie-znaleziono' }, _status: 'published', title: 'Not found' },
{ id: 3, slug: { en: 'contact', pl: 'kontakt' }, _status: 'published', title: 'Contact' },
]
test('the assigned 404 page is left out of the sitemap, the site index and llms.txt', async () => {
const payload = fakePayload({ pages })
payload.findGlobal.mockResolvedValue(settings)
const sitemap = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })
expect(sitemap.map((e) => e.url)).toEqual(['https://acme.pl/pl', 'https://acme.pl/en', 'https://acme.pl/pl/kontakt', 'https://acme.pl/en/contact'])
const flat = fakePayload({ pages: pages.map((p) => ({ ...p, slug: p.slug.pl })) })
flat.findGlobal.mockResolvedValue(settings)
expect((await collectSiteIndex({ config: single, payload: flat as never })).map((e) => e.path)).toEqual(['/', '/kontakt'])
expect(await buildLlmsTxt({ baseUrl: 'https://acme.pl', config: single, payload: flat as never })).not.toContain('nie-znaleziono')
})
test('a 404 page that is also the homepage stays listed', async () => {
const payload = fakePayload({ pages: pages.slice(0, 1) })
payload.findGlobal.mockResolvedValue({ homepage: { id: 1 }, notFound: 1 })
expect(await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })).toHaveLength(2)
})
})
describe('collectSiteIndex and llms.txt', () => {
const pages = Array.from({ length: 1205 }, (_, i) => ({ id: i, slug: `p${i}`, title: `Page ${i}` }))
+80
View File
@@ -0,0 +1,80 @@
import type { Config } from 'payload'
import { describe, expect, test } from 'vitest'
import { bottomOverlap } from '../src/modules/consent/CookieButton.js'
import { TOTP_TEXTS } from '../src/modules/security/totp/totpTexts.js'
import { ipalKit } from '../src/plugin.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
/** Stand-in for @clocklimited/payload-2fa: its own texts and the two views, as the package adds them. */
const fakeTotp = () => (config: Config) => ({
...config,
admin: {
...config.admin,
components: {
...config.admin?.components,
views: {
...config.admin?.components?.views,
SetupTOTP: { Component: { path: 'pkg#TOTPSetup' }, path: 'setup-totp' },
VerifyTOTP: { Component: { path: 'pkg#TOTPVerify' }, path: 'verify-totp' },
},
},
},
i18n: {
...config.i18n,
translations: {
...config.i18n?.translations,
en: { ...config.i18n?.translations?.en, totpPlugin: { verify: { title: 'Verification' } } },
pl: { ...config.i18n?.translations?.pl, totpPlugin: { verify: { title: 'Weryfikacja' } } },
},
},
})
const base = (translations?: Record<string, unknown>): Config =>
({ collections: [{ slug: 'users', auth: true, fields: [] }], i18n: translations ? { translations } : undefined, secret: 'test' }) as unknown as Config
type Translations = Record<string, { totpPlugin: { setup: Record<string, string>; verify: { title: string } } }>
describe('2FA texts', () => {
test('ipal-kit texts go over the package, the project over both; screens get a tab title', async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp } } as never)(
base({ en: { totpPlugin: { verify: { title: 'Project check' } } } }),
)
const t = config.i18n!.translations as Translations
expect(t.pl.totpPlugin.verify.title).toBe('Weryfikacja dwuetapowa')
expect(t.pl.totpPlugin.setup.enterCode).toBe('Wpisz {digits}-cyfrowy kod z aplikacji:')
expect(t.en.totpPlugin.verify.title).toBe('Project check')
const views = config.admin!.components!.views as Record<string, { meta?: { title?: string } }>
expect(views.VerifyTOTP.meta?.title).toBe('Weryfikacja dwuetapowa')
expect(views.SetupTOTP.meta?.title).toBe('Weryfikacja dwuetapowa')
})
test("texts: false keeps the package's", async () => {
const config = await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp, texts: false } } as never)(base())
expect((config.i18n!.translations as Translations).pl.totpPlugin.verify.title).toBe('Weryfikacja')
})
test('same keys in English and Polish, short and formal', () => {
const keys = (o: object, p = ''): string[] =>
Object.entries(o).flatMap(([k, v]) => (typeof v === 'object' ? keys(v as object, `${p}${k}.`) : [`${p}${k}`]))
expect(keys(TOTP_TEXTS.pl)).toEqual(keys(TOTP_TEXTS.en))
const all = [...Object.values(TOTP_TEXTS.pl.totpPlugin.setup), TOTP_TEXTS.pl.totpPlugin.fieldDescription]
expect(all.some((s) => /\b(?:Tw[oó]j|Będziesz|Masz)\b/.test(s))).toBe(false)
expect(TOTP_TEXTS.en.totpPlugin.forceTotp.label.split(' ').length).toBeLessThanOrEqual(3)
})
})
describe('CookieButton lift above the footer', () => {
test('moves up by the visible part of the footer', () => {
expect(bottomOverlap([], 800)).toBe(0)
expect(bottomOverlap([1200], 800)).toBe(0) // footer below the fold
expect(bottomOverlap([650], 800)).toBe(150)
expect(bottomOverlap([700, 650], 800)).toBe(150) // the highest one counts
})
test('never pushes the button off the screen', () => {
expect(bottomOverlap([-500], 800)).toBe(704)
})
})