Files

51 KiB
Raw Permalink Blame History

Reference site — file index

The reference site is one complete client site on IAPL 1.17.1 ("Example Studio", made up) that uses every convention in AGENT.md. It lives in the plugin repo (reference/, not in the npm package). Copy the PATTERN of the file you need; change only the project's content. Files up to 40 lines are below in full; open the rest in the repo at the tag of your plugin version: https://git.intecion.net/IntecionSoftware/ipal-kit/src/tag/v<version>/reference/<path>. If this index and AGENT.md disagree, report it with iapl-plugin-gap — it is a plugin bug.

Project files

Rules: AGENT.md §13, §0a.

File What it shows
.env.example every env var the site reads, with dev / test values and build vs runtime notes
.gitignore what a project never commits (below)
.npmrc the @intecion registry line (committed, no secret) (below)
.nvmrc Node 22, the same as engines and the Coolify build pack (below)
AGENTS.md the agent guide of the project: site map and filled "Project decisions" (AGENT.md §13)
CLAUDE.md one line @AGENTS.md (Claude Code reads CLAUDE.md)
DESIGN.md the human source of the look, matching src/design/tokens.ts
README.md how to run the reference site and what is where
docs/DEPLOY.md the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback
iapl-doctor.json the production domain and launch state for iapl-doctor (below)
next.config.ts security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By
package.json scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides
playwright.config.ts smoke tests against the built, seeded site (below)
postcss.config.mjs Tailwind 4 through PostCSS (below)
starter.manifest.json what iapl create keeps, drops and turns into placeholders
tsconfig.json paths @/ and @payload-config, .agents excluded (below)

.gitignore

node_modules
.next
.env
media
test-results
playwright-report
*.tsbuildinfo
!next-env.d.ts

.npmrc

legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/

.nvmrc

22

iapl-doctor.json

{
  "domain": "example-studio.pl",
  "launched": false,
  "rules": {
    "audit:collections-present": {
      "off": true,
      "reason": "Project decisions: posts and caseStudies with archive pages; entryFields.ts is their shared field helper, not a collection"
    },
    "i18n-literals": {
      "off": true,
      "files": [
        "src/components/design/**"
      ],
      "reason": "Approved exception (AGENTS.md → Project decisions): the /design styleguide has its labels in code"
    }
  }
}

playwright.config.ts

import { defineConfig, devices } from '@playwright/test'

// .env holds the E2E_* test values locally; CI passes them as env
try {
  process.loadEnvFile('.env')
} catch {
  // no .env (CI)
}

/**
 * Smoke tests against a built, seeded site: pnpm seed && pnpm build.
 * The 2FA verify limit (5 attempts per account in 10 minutes) is stored in the database; the global setup resets the
 * test admins and clears their counts before every run (e2e/global-setup.ts; E2E_SKIP_ADMIN_SETUP=1 for a run that
 * needs an EMPTY database, the fresh-site spec).
 * E2E_BASE_URL picks the port (default 3100). Playwright starts its own server there and fails when the port is
 * taken, so another project's dev server is never tested by mistake; E2E_REUSE_SERVER=1 uses a server you started.
 */
const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100'

export default defineConfig({
  forbidOnly: !!process.env.CI,
  // makes every run independent of the one before: test admins reset, stored 2FA attempt counts cleared
  globalSetup: './e2e/global-setup.ts',
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
  reporter: process.env.CI ? 'line' : 'list',
  retries: process.env.CI ? 1 : 0,
  testDir: './e2e',
  use: { baseURL, trace: 'retain-on-failure' },
  webServer: {
    command: 'pnpm start',
    // E2E_MAIL_RELAY_URL: the mail service's stand-in that e2e/mail-relay.spec.ts starts (nothing listens there otherwise,
    // and the other specs send through the SMTP sink, so the site never calls it)
    env: { E2E_MAIL_RELAY_URL: `http://127.0.0.1:${process.env.E2E_RELAY_PORT ?? 2527}/mail`, PORT: new URL(baseURL).port || '3000' },
    reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
    url: `${baseURL}/api/health`,
  },
  workers: 1,
})

postcss.config.mjs

export default { plugins: { '@tailwindcss/postcss': {} } }

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [{ "name": "next" }],
    "paths": {
      "@/*": ["./src/*"],
      "@payload-config": ["./src/payload.config.ts"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
  "exclude": ["node_modules", ".agents"]
}

Configuration

Rules: AGENT.md §3, iapl-setup stage 3.

File What it shows
src/content.config.ts collections with archive pages (below)
src/db.ts the database adapter, alone in one file (MongoDB) (below)
src/i18n.config.ts the ONLY source of languages (below)
src/instrumentation.ts env validation at startup (assertEnv, database name rule) (below)
src/payload.config.ts iapl with every module the site uses, R2, mail, 2FA, white-label
src/proxy.ts the locale proxy with Markdown negotiation (not middleware.ts) (below)

src/content.config.ts

import type { ContentOption } from '@intecion/ipal-kit'

/**
 * Collections with an archive page (docs/content.md). The archive page is picked in
 * Site settings → System pages, so `/pl/blog/<entry>` follows the page's slug.
 */
export const contentConfig: ContentOption = {
  collections: [
    // @starter:if posts
    { slug: 'posts', label: 'Blog', perPage: 9 },
    // @starter:endif
    // @starter:if caseStudies
    { slug: 'caseStudies', label: 'Case studies', perPage: 9 },
    // @starter:endif
  ],
}

src/db.ts

import { mongooseAdapter } from '@payloadcms/db-mongodb'

// MongoDB only (AGENTS.md → Project decisions). Database name from databaseNamesFor('example-studio.pl'):
// example-studiopl_dev locally, example-studiopl_prod in the Coolify MongoDB resource.
export const db = mongooseAdapter({ url: process.env.DATABASE_URI ?? '' })

src/i18n.config.ts

import type { I18nConfig } from '@intecion/ipal-kit'

/** The ONLY source of languages (AGENT.md §3). Every language has a URL prefix: /pl/…, /en/…. */
export const i18nConfig = {
  defaultLocale: 'pl',
  locales: [
    { code: 'pl', label: 'Polski' },
    { code: 'en', label: 'English' },
  ],
} as const satisfies I18nConfig

export type Locale = (typeof i18nConfig.locales)[number]['code']

src/instrumentation.ts

import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit/env'

export function register() {
  if (process.env.NEXT_RUNTIME !== 'nodejs') {return}
  // storage: R2 is required in production. ALLOW_LOCAL_MEDIA=1 lets a production build run on local disk for
  // local checks and CI only — never set it in Coolify.
  // @starter:if crawl
  // cookieCrawl: IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN in production (cookieScanner.crawl, the shared service).
  // @starter:endif
  // databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor).
  // R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md).
  assertEnv(
    iaplEnvRules({
      // @starter:if crawl
      cookieCrawl: true, // IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN in production — the shared cookie-crawler service
      // @starter:endif
      databaseName: { domain: 'example-studio.pl' },
      // @starter:if graph
      //: emailGraph: true, // GRAPH_* — e-mail through Microsoft Graph
      // @starter:endif
      ipHeader: true,
      // @starter:if r2
      storage: process.env.ALLOW_LOCAL_MEDIA !== '1',
      // @starter:else
      //: storage: false, // media on local disk — a Coolify persistent volume (AGENTS.md → Project decisions)
      // @starter:endif
    }).map((rule) => (rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule)),
  )
}

src/proxy.ts

import { createProxy } from '@intecion/ipal-kit'
import { NextResponse } from 'next/server'

import { i18nConfig } from '@/i18n.config'

// markdown: true (GEO) — /md/… passes without a locale redirect; `Accept: text/markdown` gets the Markdown page
export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse })

// Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin)
export const config = { matcher: ['/((?!(?:api|admin|_next)(?:/|$)|.*\\..*).*)'] }

Collections and globals

Rules: AGENT.md §5, iapl-nav, iapl-collection.

File What it shows
src/collections/CaseStudies.ts a project-specific archive collection (below)
src/collections/Media.ts the full media collection (media.md) (below)
src/collections/Pages.ts Pages: slug, blocks layout, AI summary, noindex, slug history, revalidation, system-page delete guard (below)
src/collections/Posts.ts the blog collection (archive in System pages) (below)
src/collections/entryFields.ts shared fields of archive collections (names the entry card reads) (below)
src/globals/Company.ts company data (PL market): footer, contact details, LocalBusiness JSON-LD (below)
src/globals/Footer.ts footer navigation global (below)
src/globals/Header.ts header navigation global (below)

src/collections/CaseStudies.ts

import type { CollectionConfig } from 'payload'

import { buildRevalidateHook } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'

import { i18nConfig } from '@/i18n.config'

import { entryFields } from './entryFields'

const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })

/** The project's own archive collection (skill iapl-collection) — the library has no case-study type. */
export const CaseStudies: CollectionConfig = {
  slug: 'caseStudies',
  admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
  access: { read: () => true },
  defaultSort: '-publishedAt',
  fields: entryFields,
  hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] },
  labels: { plural: { en: 'Case studies', pl: 'Realizacje' }, singular: { en: 'Case study', pl: 'Realizacja' } },
}

src/collections/Media.ts

import type { CollectionConfig } from 'payload'

import {
  buildMediaPlaceholderField,
  buildMediaPlaceholderHook,
  buildOptimizeUploadField,
  buildOptimizeUploadHook,
  normalizeFilenameHook,
} from '@intecion/ipal-kit'

/** media.md "Full collection", 1:1. */
export const Media: CollectionConfig = {
  slug: 'media',
  access: { read: () => true }, // public files; media are served by the app (/api/media/file/…)
  upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] },
  hooks: {
    beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()],
  },
  fields: [
    { name: 'alt', type: 'text', localized: true, required: true },
    buildOptimizeUploadField(),
    buildMediaPlaceholderField(),
  ],
}

src/collections/Pages.ts

import type { CollectionConfig } from 'payload'

import {
  buildNoindexField,
  buildPreventDeleteSystemPage,
  buildRevalidateHook,
  buildSlugField,
  buildSummaryField,
  rowLabel,
  trackSlugHistoryHook,
} from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'

import { pageBlocks } from '@/blocks/configs'
import { i18nConfig } from '@/i18n.config'

const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })

export const Pages: CollectionConfig = {
  slug: 'pages',
  admin: { defaultColumns: ['title', 'slug', 'updatedAt'], useAsTitle: 'title' },
  access: { read: () => true },
  fields: [
    { name: 'title', type: 'text', localized: true, required: true },
    buildSlugField({ from: 'title' }),
    { name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 },
    buildSummaryField(), // aiSummary — GEO (llms.txt, MCP)
    buildNoindexField(),
    { name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } },
  ],
  hooks: {
    afterChange: [revalidate.afterChange],
    afterDelete: [revalidate.afterDelete],
    beforeChange: [trackSlugHistoryHook],
    beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })],
  },
}

src/collections/Posts.ts

import type { CollectionConfig } from 'payload'

import { buildRevalidateHook } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'

import { i18nConfig } from '@/i18n.config'

import { entryFields } from './entryFields'

const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath })

/** Blog entries — listed on the page assigned in Site settings → System pages → Blog (content.config.ts). */
export const Posts: CollectionConfig = {
  slug: 'posts',
  admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' },
  access: { read: () => true },
  defaultSort: '-publishedAt',
  fields: entryFields,
  hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] },
  labels: { plural: { en: 'Blog posts', pl: 'Wpisy' }, singular: { en: 'Blog post', pl: 'Wpis' } },
}

src/collections/entryFields.ts

import type { Field } from 'payload'

import { buildNoindexField, buildSlugField, buildSummaryField } from '@intecion/ipal-kit'

import { pageBlocks } from '@/blocks/configs'

/**
 * Fields every archive collection shares (posts, case studies). The entry card of the entry list block
 * reads `title`, `excerpt`, `media` and `publishedAt` (defaultEntryCard), so the names follow it.
 */
export const entryFields: Field[] = [
  { name: 'title', type: 'text', localized: true, required: true },
  buildSlugField({ from: 'title' }),
  { name: 'excerpt', type: 'textarea', localized: true, admin: { description: 'One or two sentences on the card in lists.' } },
  { name: 'media', type: 'upload', relationTo: 'media', admin: { description: 'Card and share image.' } },
  { name: 'publishedAt', type: 'date', admin: { position: 'sidebar' }, defaultValue: () => new Date().toISOString() },
  { name: 'layout', type: 'blocks', blocks: pageBlocks },
  buildSummaryField(),
  buildNoindexField(),
]

src/globals/Company.ts

import type { GlobalConfig } from 'payload'

import { buildGlobalRevalidateHook, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'

/** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */
export const Company: GlobalConfig = {
  slug: 'company',
  access: { read: () => true },
  fields: [
    { name: 'name', type: 'text', required: true },
    { name: 'legalName', type: 'text' },
    { name: 'taxId', type: 'text', label: 'NIP' },
    { name: 'taxIdLabel', type: 'text', admin: { description: 'Shown before the tax ID in the footer.' }, defaultValue: 'NIP', label: 'Tax ID label', localized: true },
    {
      name: 'address',
      type: 'group',
      fields: [
        { name: 'street', type: 'text' },
        { name: 'postalCode', type: 'text' },
        { name: 'city', type: 'text' },
        { name: 'country', type: 'text', defaultValue: 'PL' },
      ],
    },
    { name: 'phone', type: 'text' },
    { name: 'email', type: 'email' },
    { name: 'hours', type: 'text', localized: true, admin: { description: 'Shown next to the contact form, e.g. "Mon–Fri 9:00–17:00".' } },
    {
      name: 'socials',
      type: 'array',
      admin: { components: rowLabel('label', 'Profile'), initCollapsed: true },
      labels: { plural: 'Profiles', singular: 'Profile' },
      fields: [
        { name: 'label', type: 'text', required: true },
        { name: 'url', type: 'text', required: true },
      ],
    },
  ],
  hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] },
}

src/globals/Footer.ts

import type { GlobalConfig } from 'payload'

import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'

/** iapl-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */
export const Footer: GlobalConfig = {
  slug: 'footer',
  access: { read: () => true },
  fields: [
    {
      name: 'columns',
      type: 'array',
      admin: { components: rowLabel('heading', 'Column'), initCollapsed: true },
      fields: [
        { name: 'heading', type: 'text', localized: true },
        {
          name: 'items',
          type: 'array',
          admin: { components: rowLabel('link.label', 'Link'), initCollapsed: true },
          fields: [buildLinkField({ appearances: false })],
          labels: { plural: 'Links', singular: 'Link' },
        },
      ],
      labels: { plural: 'Columns', singular: 'Column' },
      maxRows: 4,
    },
    { name: 'note', type: 'textarea', localized: true },
  ],
  hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] },
}

src/globals/Header.ts

import type { GlobalConfig } from 'payload'

import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
import { revalidatePath } from 'next/cache'

/** iapl-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */
export const Header: GlobalConfig = {
  slug: 'header',
  access: { read: () => true },
  fields: [
    {
      name: 'navItems',
      type: 'array',
      admin: { components: rowLabel('link.label', 'Menu item'), initCollapsed: true },
      fields: [
        buildLinkField({ appearances: false }),
        {
          name: 'subItems',
          type: 'array',
          admin: { components: rowLabel('link.label', 'Submenu item'), initCollapsed: true },
          fields: [buildLinkField({ appearances: false })],
          labels: { plural: 'Submenu', singular: 'Submenu item' },
          maxRows: 10,
        },
      ],
      labels: { plural: 'Menu items', singular: 'Menu item' },
      maxRows: 8,
    },
    buildLinksField({ maxRows: 1 }),
    { name: 'menuLabel', type: 'text', admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' }, localized: true },
  ],
  hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] },
}

Blocks

Rules: docs/block-library.md.

File What it shows
src/blocks/configs.ts the block library turned on in the Pages layout (libraryBlocks) (below)
src/blocks/registry.ts createBlockRegistry with next/image, next/link, the form action and contact details (below)

src/blocks/configs.ts

import { libraryBlocks, type LibraryBlocksOptions } from '@intecion/ipal-kit/blocks'

/**
 * Every library block is on, because the reference site shows all of them (the Blocks showcase page).
 * A client site turns on only what its site map needs (docs/block-library.md "Setup").
 */
export const blockOptions = {
  contact: true,
  cta: true,
  // @starter:if collections
  entryList: {
    collections: [
      // @starter:if posts
      { label: { en: 'Blog posts', pl: 'Wpisy' }, value: 'posts' },
      // @starter:endif
      // @starter:if caseStudies
      { label: { en: 'Case studies', pl: 'Realizacje' }, value: 'caseStudies' },
      // @starter:endif
    ],
  },
  // @starter:endif
  faq: true,
  featureGrid: true,
  gallery: true,
  hero: true,
  logos: true,
  pricing: true,
  richText: true,
  stats: true,
  steps: true,
  team: true,
  testimonials: true,
  textMedia: true,
} satisfies LibraryBlocksOptions

export const pageBlocks = [...libraryBlocks(blockOptions)]

src/blocks/registry.ts

import { createBlockRegistry } from '@intecion/ipal-kit/blocks/rsc'
import Image from 'next/image'
import Link from 'next/link'

import { sendForm } from '@/app/(frontend)/[locale]/actions'
import { formClasses } from '@/components/forms/formClasses'
import * as content from '@/lib/content'
import { getCompany } from '@/lib/globals'

/** Contact details beside the contact form — from the Company global, never from code. */
async function contactDetails(locale: string) {
  const company = await getCompany(locale)
  const labels = locale === 'pl' ? { address: 'Adres', email: 'E-mail', hours: 'Godziny', phone: 'Telefon' } : { address: 'Address', email: 'E-mail', hours: 'Hours', phone: 'Phone' }
  const address = [company.address?.street, [company.address?.postalCode, company.address?.city].filter(Boolean).join(' ')].filter(Boolean).join(', ')
  return [
    ...(company.phone ? [{ href: `tel:${company.phone.replace(/[^\d+]/g, '')}`, label: labels.phone, value: company.phone }] : []),
    ...(company.email ? [{ href: `mailto:${company.email}`, label: labels.email, value: company.email }] : []),
    ...(address ? [{ label: labels.address, value: address }] : []),
    ...(company.hours ? [{ label: labels.hours, value: company.hours }] : []),
  ]
}

/** blockType → component for every library block, bound to lib/content (docs/block-library.md "The registry"). */
export const blockRegistry = createBlockRegistry(content, {
  contactDetails,
  formClassNames: formClasses,
  Image,
  Link,
  noSnippet: ['cta'], // the same call to action closes most pages
  sendForm,
})

Design tokens

Rules: docs/design-tokens.md.

File What it shows
src/app/(frontend)/[locale]/design/page.tsx the design-token styleguide page (noindex) (below)
src/components/design/TokenPanel.tsx one styleguide panel built from IAPL_TOKENS
src/design/tokens.css GENERATED by pnpm tokens from tokens.ts — never edited by hand (below)
src/design/tokens.ts the brand: the ONLY file edited to rebrand the site (below)

src/app/(frontend)/[locale]/design/page.tsx

import type { Metadata } from 'next'

import { Container } from '@intecion/ipal-kit/blocks/rsc'

import { TokenPanel } from '@/components/design/TokenPanel'
import { i18nConfig } from '@/i18n.config'

// The styleguide: every design token, light and dark side by side. Technical page —
// noindex, not in the sitemap (it is not a Pages document), labels are token names (AGENTS.md → Project decisions).
export const metadata: Metadata = { robots: { follow: false, index: false }, title: 'Design tokens' }

export default function DesignPage() {
  return (
    <Container className="grid gap-10 py-section">
      <header className="grid gap-stack">
        <p className="text-sm uppercase tracking-heading text-fg-muted">IAPL</p>
        <h1 className="font-heading text-h1 leading-heading text-fg-strong">Design tokens</h1>
        <p className="max-w-measure text-lead text-fg-muted">
          src/design/tokens.ts → pnpm tokens → src/design/tokens.css. The panels set data-theme=&quot;light&quot; and data-theme=&quot;dark&quot;
          on themselves (the tokens switch on any element); the bottom row is the inverse scope (data-surface=&quot;inverse&quot;) in the page theme.
        </p>
      </header>
      <div className="grid gap-gap lg:grid-cols-2">
        <TokenPanel theme="light" title="Light" />
        <TokenPanel theme="dark" title="Dark" />
      </div>
      <TokenPanel inverse title="Inverse surface (data-surface=&quot;inverse&quot;)" />
    </Container>
  )
}

export const generateStaticParams = () => i18nConfig.locales.map(({ code }) => ({ locale: code }))

src/design/tokens.css

/*
 * GENERATED by `iapl-tokens` from src/design/tokens.ts — do not edit; change src/design/tokens.ts and run
 * `pnpm exec iapl-tokens`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css).
 */

:root {
  --ipal-fw-heading: 600;
  --ipal-radius: 0.25rem;
  --ipal-radius-card: 0.25rem;
}

:root, [data-theme="light"] {
  --ipal-bg: oklch(0.985 0.006 85);
  --ipal-primary: oklch(0.47 0.09 160);
  --ipal-surface-muted: oklch(0.955 0.012 85);
  --ipal-accent: oklch(0.55 0.13 50);
  --ipal-link-inverse: oklch(0.82 0.08 160);
  --ipal-primary-inverse: oklch(0.74 0.09 160);
  --ipal-primary-inverse-text: oklch(0.18 0.02 160);
}

:root[data-theme="dark"], [data-theme="dark"] {
  --ipal-bg: oklch(0.2 0.01 160);
  --ipal-primary: oklch(0.74 0.09 160);
  --ipal-surface-muted: oklch(0.25 0.012 160);
  --ipal-accent: oklch(0.76 0.12 55);
  --ipal-accent-text: oklch(0.18 0.02 55);
  --ipal-link-inverse: oklch(0.42 0.09 160);
  --ipal-primary-inverse: oklch(0.47 0.09 160);
  --ipal-primary-inverse-text: oklch(0.99 0 0);
  --ipal-primary-text: oklch(0.18 0.02 160);
}

src/design/tokens.ts

// src/design/tokens.ts — the ONLY file edited to rebrand the site (docs/design-tokens.md).
// After every change: `pnpm tokens` → writes src/design/tokens.css (commit it) and prints the WCAG contrast check.
// Leave out anything the brand does not change: the neutral defaults in @intecion/ipal-kit/tokens.css apply.
import { defineTokens } from '@intecion/ipal-kit/tokens'

export const tokens = defineTokens({
  theme: 'both', // must match Site settings → Theme (seeded: system, toggle on)
  fluid: 'wide',
  color: {
    light: {
      primary: 'oklch(0.47 0.09 160)', // deep sage green — the studio's brand colour (DESIGN.md §2)
      accent: 'oklch(0.55 0.13 50)', // terracotta, for highlights only
      'link-inverse': 'oklch(0.82 0.08 160)', // links and accents on inverted sections
      'primary-inverse': 'oklch(0.74 0.09 160)', // buttons on inverted (dark) sections
      'primary-inverse-text': 'oklch(0.18 0.02 160)',
      bg: 'oklch(0.985 0.006 85)', // warm paper white
      'surface-muted': 'oklch(0.955 0.012 85)',
    },
    dark: {
      primary: 'oklch(0.74 0.09 160)',
      'primary-text': 'oklch(0.18 0.02 160)', // dark text on the lighter dark-mode primary
      accent: 'oklch(0.76 0.12 55)',
      'accent-text': 'oklch(0.18 0.02 55)',
      'link-inverse': 'oklch(0.42 0.09 160)',
      'primary-inverse': 'oklch(0.47 0.09 160)', // inverted sections are light in dark mode
      'primary-inverse-text': 'oklch(0.99 0 0)',
      bg: 'oklch(0.2 0.01 160)',
      'surface-muted': 'oklch(0.25 0.012 160)',
    },
  },
  font: { fwHeading: 600 },
  radius: { card: '0.25rem', control: '0.25rem' }, // "sharp": architectural, precise
})

Data layer

Rules: AGENT.md §3, PROGRAMISTA §2.7.

File What it shows
src/lib/content.ts createContentHelpers: the ONLY access to Payload, routes, links, JSON-LD
src/lib/globals.ts cached getters for the project's own globals (below)

src/lib/globals.ts

import { cache } from 'react'

import type { Locale } from '@/i18n.config'

import { getCachedPayload } from './content'

/** Cached getters for the project's own globals — the layout passes them down as props (iapl-nav). */
export const getHeader = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'header', depth: 1, locale: locale as Locale }))
export const getFooter = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'footer', depth: 1, locale: locale as Locale }))
export const getCompany = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'company', locale: locale as Locale }))

Layout and components

Rules: AGENT.md §6.8, iapl-nav, iapl-form.

File What it shows
src/app/(frontend)/[locale]/[[...slug]]/page.tsx the catch-all page: createPageRoute, ISR, redirects, maintenance, the language switcher links (below)
src/app/(frontend)/[locale]/actions.ts the ONE form server action (createSubmitAction) (below)
src/app/(frontend)/[locale]/layout.tsx the locale layout: next/font slots, SiteProviders (theme, lightbox, consent), header, footer
src/app/(frontend)/[locale]/not-found.tsx 404 from the panel (createNotFoundPage) (below)
src/app/(frontend)/[locale]/notFoundView.ts the 404 view loaded only on a 404 (server action) (below)
src/app/(frontend)/styles.css the standard styles.css: Tailwind, fluid-wide, tokens, preset, brand (below)
src/components/forms/formClasses.ts the ONE place forms are styled, token utilities only (below)
src/components/layout/Footer.tsx footer: columns, company data, legal links from System pages, NoSnippet
src/components/layout/Header.tsx header: logo from Site settings, resolveNav menu, language and theme switch, CTA
src/components/layout/LocaleSwitcher.tsx the language switcher in a client wrapper (function props) (below)
src/components/layout/MobileNav.tsx the mobile menu (client, open state only) (below)

src/app/(frontend)/[locale]/[[...slug]]/page.tsx

import { AlternateLinksUpdater } from '@intecion/ipal-kit/client'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import { notFound, permanentRedirect, redirect } from 'next/navigation'

import { blockRegistry } from '@/blocks/registry'
import * as content from '@/lib/content'

// ISR — a literal in the file (Next reads it statically)
export const revalidate = 3600

// Archive pages (Blog, Case studies) list their entries with an entry list block in their own layout,
// so the editor decides where the list goes; entries render their own `layout` like pages.
const route = createPageRoute(content, {
  blocks: blockRegistry,
  notFound,
  permanentRedirect,
  redirect, // Site settings → Maintenance: hidden pages → homepage with a notice
  render: async ({ blocks, locale, segments }) => {
    // This page's address in every language → the language switcher never leads to a 404
    const { alternates } = await content.generatePageMetadata(locale, segments)
    const links = Object.fromEntries(
      Object.entries(alternates?.languages ?? {})
        .filter(([code]) => code !== 'x-default')
        .map(([code, href]) => [code, new URL(String(href)).pathname]),
    )
    return (
      <>
        <AlternateLinksUpdater links={links} />
        {blocks}
      </>
    )
  },
})

export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams

src/app/(frontend)/[locale]/actions.ts

'use server'
// ONE server action for every builder form: honeypot → client IP (IAPL_IP_HEADER) → submitForm
// (rate limit, Turnstile, validation, consent, save) → the message from Notifications.
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { headers } from 'next/headers'

import { getCachedPayload } from '@/lib/content'

export const sendForm = createSubmitAction({ getCachedPayload, headers })

src/app/(frontend)/[locale]/not-found.tsx

import { createNotFoundPage } from '@intecion/ipal-kit/rsc'

import * as content from '@/lib/content'

import { loadNotFoundView } from './notFoundView'

export default createNotFoundPage(content, { load: loadNotFoundView })

src/app/(frontend)/[locale]/notFoundView.ts

'use server'
import { renderNotFoundView } from '@intecion/ipal-kit/rsc'

import { blockRegistry } from '@/blocks/registry'
import * as content from '@/lib/content'

/** 404 content from the panel (System pages → 404), in the URL's language. */
export async function loadNotFoundView(locale: string) {
  return renderNotFoundView(content, { blocks: blockRegistry }, locale)
}

src/app/(frontend)/styles.css

/* The same on every site (design-tokens.md) — no brand values here; the brand lives in src/design/tokens.ts */
@import "tailwindcss";
@import "@intecion/ipal-kit/fluid-wide.css";
@import "@intecion/ipal-kit/tokens.css";
@import "@intecion/ipal-kit/tailwind.css";
@import "../../design/tokens.css";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";

src/components/forms/formClasses.ts

import type { BuilderFormClassNames } from '@intecion/ipal-kit/client'
import { buttonClass } from '@intecion/ipal-kit/blocks/rsc'

const control =
  'w-full rounded-control border border-border bg-surface px-3 py-2 text-fg placeholder:text-fg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus'

/** The ONLY place panel forms are styled (iapl-form). Token utilities only — no hex, no dark:. */
export const formClasses: BuilderFormClassNames = {
  actions: 'flex flex-wrap gap-3',
  back: buttonClass('secondary'),
  checkboxLabel: 'flex items-start gap-2 text-fg',
  choice: 'flex items-center gap-2',
  choices: 'grid gap-2',
  error: 'mt-1 text-sm text-danger',
  field: 'col-span-12',
  fieldHalf: 'md:col-span-6',
  fields: 'grid grid-cols-12 gap-4',
  form: 'grid gap-6',
  formError: 'rounded-control bg-danger-surface p-3 text-danger',
  file: 'block w-full text-fg file:mr-3 file:rounded-control file:border-0 file:bg-surface-muted file:px-3 file:py-2 file:text-fg-strong',
  fileItem: 'flex flex-wrap items-center gap-2',
  fileList: 'mt-2 grid gap-1 text-sm',
  fileRemove: 'underline underline-offset-2',
  help: 'mt-1 text-sm text-fg-muted',
  input: control,
  label: 'mb-1 block font-medium text-fg-strong',
  legend: 'mb-1 font-medium text-fg-strong',
  progress: 'text-sm text-fg-muted',
  select: control,
  step: 'grid gap-4',
  stepDescription: 'text-fg-muted',
  stepTitle: 'font-heading text-h4 text-fg-strong',
  submit: buttonClass('primary'),
  success: 'rounded-card bg-success-surface p-6 text-fg',
  textarea: `${control} min-h-32`,
}

src/components/layout/LocaleSwitcher.tsx

'use client'
import type { I18nConfig } from '@intecion/ipal-kit'

import { LanguageSwitcher } from '@intecion/ipal-kit/client'

/** Client wrapper: renderLabel is a function, which a server component cannot pass to a client component. */
export function LocaleSwitcher({ config, locale }: { config: I18nConfig; locale: string }) {
  return (
    <LanguageSwitcher
      classNames={{
        item: 'block px-3 py-2 text-fg hover:bg-hover',
        itemActive: 'font-semibold text-fg-strong',
        menu: 'absolute right-0 mt-2 min-w-32 rounded-card border border-border bg-surface-raised py-1 shadow-md',
        root: 'relative',
        trigger: 'rounded-control px-2 py-1 text-sm text-fg hover:bg-hover',
      }}
      config={config}
      currentLocale={locale}
      renderLabel={(l) => l.code.toUpperCase()}
    />
  )
}

src/components/layout/MobileNav.tsx

'use client'
import type { NavItem } from '@intecion/ipal-kit'

import Link from 'next/link'
import { useEffect, useState } from 'react'

/** Mobile menu: open state only, data via props (iapl-nav). Esc closes it. */
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
  const [open, setOpen] = useState(false)
  useEffect(() => {
    if (!open) {return}
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false)
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [open])
  return (
    <div className="md:hidden">
      <button
        aria-controls="mobile-nav"
        aria-expanded={open}
        className="rounded-control px-3 py-2 text-fg hover:bg-hover focus-visible:outline-2 focus-visible:outline-focus"
        onClick={() => setOpen(!open)}
        type="button"
      >
        {menuLabel}
      </button>
      {open ? (
        <ul className="absolute inset-x-0 top-full grid gap-1 border-b border-border bg-surface-raised p-4 shadow-md" id="mobile-nav">
          {items.map((item) => (
            <li key={item.href}>
              <Link className="block rounded-control px-3 py-2 text-fg hover:bg-hover" href={item.href} onClick={() => setOpen(false)}>
                {item.label}
              </Link>
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  )
}

SEO, GEO and ops routes

Rules: AGENT.md §0b, iapl-setup stages 7–8.

File What it shows
src/app/api/csp-report/route.ts CSP violation reports (below)
src/app/api/health/route.ts Coolify health check (below)
src/app/api/mcp/route.ts public MCP server (GEO) (below)
src/app/indexnow-key.txt/route.ts IndexNow key (below)
src/app/llms-full.txt/route.ts llms-full.txt (GEO) (below)
src/app/llms.txt/route.ts llms.txt (GEO) (below)
src/app/manifest.ts web app manifest from Site settings (below)
src/app/md/[locale]/[[...slug]]/route.ts every page as Markdown (GEO) (below)
src/app/robots.ts robots.txt with the AI crawler policy from the panel (below)
src/app/sitemap.xml/route.ts the one sitemap (below)

src/app/api/csp-report/route.ts

import { createCspReportRoute } from '@intecion/ipal-kit'

// CSP violation reports → `[csp]` lines in the logs (security.md)
export const POST = createCspReportRoute()

src/app/api/health/route.ts

// Coolify health check: 200, or 503 without the database
export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/api/mcp/route.ts

// GEO: public MCP server (read-only)
export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/indexnow-key.txt/route.ts

// IndexNow key (Site integrations or INDEXNOW_KEY)
export { indexNowKeyRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/llms-full.txt/route.ts

// GEO: full page content for AI assistants
export { llmsFullRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/llms.txt/route.ts

// GEO: site summary for AI assistants
export { llmsRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/manifest.ts

export { manifest as default } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/md/[locale]/[[...slug]]/route.ts

// GEO: every page as Markdown (noindex, canonical to the HTML)
export { markdownRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/robots.ts

// robots.txt from code + the AI crawler policy from Site settings → Search engines
export { getRobots as default } from '@/lib/content'
export const dynamic = 'force-dynamic'

src/app/sitemap.xml/route.ts

// sitemap: one only (no sitemap.ts), styled by the plugin
export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic'

Seeds

Rules: docs/seeding.md, docs/block-library.md "Page templates".

File What it shows
src/seed/base.ts BASE seed: templates, system pages, navigation, banner texts — kept by the starter
src/seed/demo.ts DEMO seed: the made-up company in pl and en — dropped by the starter
src/seed/forms.ts forms seed: fields, confirmation, e-mail to the company and to the sender
src/seed/index.ts the seed entry: layers, SEED_ONLY, the inbox rule
src/seed/lib.ts seed value helpers (both languages side by side, rich text) (below)
src/seed/media.ts generated placeholder images (no stock photos)
src/seed/showcase.ts the Blocks showcase page from blockLibraryManifest (every variant, inverted too)

src/seed/lib.ts

/** Seed value helpers — every text written once, both languages side by side (docs/seeding.md). */
export type L = { en: string; pl: string }

export const tx = (pl: string, en: string): L => ({ en, pl })

const textNode = (t: string) => ({ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: t, version: 1 })
const paragraph = (t: string) => ({ type: 'paragraph', children: [textNode(t)], direction: 'ltr', format: '', indent: 0, textFormat: 0, version: 1 })
const heading = (t: string, tag: 'h2' | 'h3') => ({ type: 'heading', children: [textNode(t)], direction: 'ltr', format: '', indent: 0, tag, version: 1 })
const root = (children: unknown[]) => ({ root: { type: 'root', children, direction: 'ltr', format: '', indent: 0, version: 1 } })

/** Rich text from paragraphs; a line starting with "## " is an h2, "### " an h3. One value per locale. */
export function rich(pl: string[], en: string[]) {
  const doc = (lines: string[]) =>
    root(lines.map((l) => (l.startsWith('### ') ? heading(l.slice(4), 'h3') : l.startsWith('## ') ? heading(l.slice(3), 'h2') : paragraph(l))))
  return { en: doc(en), pl: doc(pl) }
}

/** Plain text (blank-line paragraphs, single newlines as line breaks) → rich text, as form-builder messages expect. */
export function richMessage(text: string) {
  return root(
    text.split(/\n{2,}/).map((para) => ({
      ...paragraph(''),
      children: para.split('\n').flatMap((line, i) => [...(i ? [{ type: 'linebreak', version: 1 }] : []), textNode(line)]),
    })),
  )
}

export const header = (heading: L, intro?: L, eyebrow?: L) => ({ ...(eyebrow ? { eyebrow } : {}), heading, ...(intro ? { intro } : {}) })

/** A button / link to a page by its default-locale (pl) slug. */
export const pageLink = (label: L, slug: string, appearance: 'link' | 'primary' | 'secondary' = 'primary') => ({
  link: { type: 'internal', appearance, label, page: { $page: slug } },
})

Smoke tests

Rules: AGENT.md §8a.

File What it shows
e2e/closed-doors.spec.ts closed doors from outside (run by pnpm e2e:built in both bundlers): every door of e2e/closed-doors.ts asked on the production build as an anonymous visitor, a customer (the fixture's e2e-visitors) and an editor; doors still open while the owner decides are asserted open (test.fail)
e2e/closed-doors.ts the doors that must stay closed, who each is closed for and how a closed answer looks; a project adds its own (security.md "Closed doors from outside")
e2e/create-test-admin.ts two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests' mail sink (local / CI database only)
e2e/global-setup.ts Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order (below)
e2e/late-staff-fixture.ts test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin's roles, roles of the project's own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up)
e2e/late-staff.spec.ts the account rules on a BUILT site (run by pnpm e2e:built after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold admin, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin's rule
e2e/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) (below)
e2e/mail-relay-setup.ts for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below)
e2e/mail-relay.spec.ts the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives
e2e/routes.snapshot.json every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list routes:check compares with
e2e/routes.ts routes:check: the site's public routes against e2e/routes.snapshot.json (pnpm payload run e2e/routes.ts [update]; from the repository pnpm routes:check) (below)
e2e/sign-in-look.spec.ts browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named)
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/smtp-sink.ts a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)
e2e/totp.ts RFC 6238 code generator for the 2FA sign-in in the smoke test, and the addresses of the second test admin and the test editor (below)
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-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/global-setup.ts

import { execFileSync } from 'node:child_process'

/**
 * Before every Playwright run: the test admins are made (or reset) and their stored 2FA attempt counts cleared
 * (e2e/create-test-admin.ts). The count is kept in the database — 5 verify attempts per account in 10 minutes —
 * so without this a second run within ten minutes, or one spec run after the whole suite, would find the test
 * admin locked out: the result would depend on what ran before. Skipped when the test admin is not configured
 * (the specs that need it skip themselves) or with E2E_SKIP_ADMIN_SETUP=1.
 */
export default function globalSetup(): void {
  const { E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD, E2E_SKIP_ADMIN_SETUP, E2E_TOTP_SECRET } = process.env
  if (E2E_SKIP_ADMIN_SETUP === '1' || !E2E_ADMIN_EMAIL || !E2E_ADMIN_PASSWORD || !E2E_TOTP_SECRET) {return}
  execFileSync('pnpm', ['payload', 'run', 'e2e/create-test-admin.ts'], { env: { ...process.env, NODE_ENV: 'development' }, stdio: 'inherit' })
}

e2e/mail-relay-fixture.ts

/**
 * Test fixture, on only with E2E_MAIL_RELAY_URL (e2e/mail-relay.spec.ts): points the mail service's client at
 * a stand-in the spec starts on this machine, so the spec can watch a built site enrol through its own confirm
 * route and send — without the real service. Never part of a real site: the starter drops `e2e/` and the lines
 * that use this file; a real site names no address (the plugin's own is used).
 */
export const E2E_MAIL_RELAY_URL = process.env.E2E_MAIL_RELAY_URL || undefined

/** `iapl({ mail })` for the test, `undefined` (the plugin's defaults) otherwise. */
export const e2eMail = E2E_MAIL_RELAY_URL ? { relay: { retryBackoffMs: 50, url: E2E_MAIL_RELAY_URL } } : undefined

/**
 * `iapl({ developmentHosts })` for a test that plays a development address on this machine (the built-in
 * pattern, `*.dev.netscale.pl`, cannot be served from localhost): E2E_DEVELOPMENT_HOSTS, comma-separated
 * patterns. `undefined` (the plugin's built-in list) otherwise.
 */
export const e2eDevelopmentHosts = process.env.E2E_DEVELOPMENT_HOSTS ? process.env.E2E_DEVELOPMENT_HOSTS.split(',').map((p) => p.trim()).filter(Boolean) : undefined

e2e/mail-relay-setup.ts

/**
 * For e2e/mail-relay.spec.ts — LOCAL / CI database only:
 *   pnpm payload run e2e/mail-relay-setup.ts          the site has no SMTP server and no token: its next e-mail
 *                                                      goes to the mail service, enrolling first
 * Afterwards the spec runs e2e/create-test-admin.ts again, which points e-mail back at the tests' SMTP sink.
 */
import config from '@payload-config'
import { RELAY_KV_KEY } from '@intecion/ipal-kit'
import { isLocalDatabase } from '@intecion/ipal-kit/seed'
import { getPayload } from 'payload'

if (process.env.NODE_ENV === 'production' && !process.env.CI) {throw new Error('Refusing: NODE_ENV=production outside CI.')}
if (!isLocalDatabase(process.env.DATABASE_URI ?? '')) {throw new Error('Refusing: DATABASE_URI is not a local database.')}

const payload = await getPayload({ config })
await payload.updateGlobal({
  slug: 'site-integrations',
  context: { ipalIntegrationStatus: true },
  data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailMethod: 'relay', emailTransport: 'smtp', smtpFromAddress: '[email protected]', smtpFromName: 'Example Studio', smtpHost: null, smtpPassword: null, smtpUser: null } as never,
  overrideAccess: true,
})
for (const key of await payload.kv.keys()) {
  if (key === RELAY_KV_KEY || key.startsWith(`${RELAY_KV_KEY}:`)) {await payload.kv.delete(key)}
}
console.log('[e2e] no SMTP server and no mail-service token: the next e-mail enrols and goes through the mail service')
process.exit(0)

e2e/routes.ts

/**
 * routes:check — every public route of this site (REST, GraphQL, Next route files) against the judged list in
 * e2e/routes.snapshot.json (docs/security.md "Routes nobody has judged"). Reads the config only, never the database.
 *   pnpm payload run e2e/routes.ts           → fails on a route nobody has judged
 *   pnpm payload run e2e/routes.ts update    → adds new routes with an empty reason (judge them), drops gone ones
 * (`payload run` drops `--flags`, so the word is `update`.) From the plugin repository: pnpm routes:check [--update],
 * also the first step of pnpm e2e:built.
 */
import config from '@payload-config'
import { runRouteCheck } from '@intecion/ipal-kit/doctor'

process.exit(await runRouteCheck({ config: await config, update: process.argv.slice(2).includes('update') }))

e2e/totp.ts

import { createHmac } from 'node:crypto'

/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) — the code an authenticator app shows for `secret` (base32). */
export function totp(secret: string, now = Date.now()): string {
  const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
  let bits = ''
  for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')}
  const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
  const counter = Buffer.alloc(8)
  counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / 30)))
  const hmac = createHmac('sha1', key).update(counter).digest()
  const offset = hmac[hmac.length - 1] & 0xf
  const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000
  return code.toString().padStart(6, '0')
}

/** The second smoke-test admin (create-test-admin.ts makes both): `e2e-admin@…` → `e2e-admin-2@…`. */
export const secondTestAdmin = (email: string): string => email.replace('@', '-2@')

/** The smoke-test editor (create-test-admin.ts makes it): `e2e-admin@…` → `e2e-admin-editor@…`, role `editor`, the same password and secret. */
export const editorTestAccount = (email: string): string => email.replace('@', '-editor@')