Compare commits
@@ -8,6 +8,87 @@ versions at once, go through every "Requires project changes" section in order,
|
||||
version you have. A new release = a new section at the top; we remove the oldest ones only
|
||||
once there are more than 20.
|
||||
|
||||
## 1.15.4
|
||||
|
||||
### Fixed
|
||||
- **Seeding whole localized arrays** (`createSeeder`, `writeLocales`): a value written per language as a whole —
|
||||
`fields: { pl: [...], en: [...], de: [...] }`, a page `layout`, a global array — now keeps the stored row ids in every
|
||||
language. Before, each locale write made new shared rows and only the last language survived (form fields, nested
|
||||
select options, layouts, global arrays); an editor's later save could then fail validation. Fields that are
|
||||
themselves `localized: true` (a localized layout) keep rows per language, as before. Seed scripts need no change;
|
||||
repairing records an earlier seed already wrote: "What projects must update".
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required: seed scripts need no change.
|
||||
- A project that seeded whole localized arrays (form fields with options, a page `layout`, a global array written as
|
||||
`{ pl: [...], en: [...] }`) and lost languages: a plain re-run skips existing records (create-only), so rewrite them
|
||||
with `SEED_UPDATE=1` — **locally first**, then check every language in the panel. On a live site only for the named
|
||||
records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1 IPAL_SEED_ALLOW_PROD_UPDATE=1`, `SEED_DRY_RUN=1` first,
|
||||
after a backup (Coolify). Records an editor changed since seeding are skipped — fix those in the panel. A global
|
||||
array: `fillGlobal` fills empty fields only, so clear the field in the panel before the run, or fix it by hand.
|
||||
|
||||
## 1.15.3
|
||||
|
||||
### Fixed
|
||||
- **ipal-audit and ipal-doctor no longer report the panel's own bilingual labels as hardcoded text.** "Hardcoded Polish
|
||||
text in code" (`i18n-literals` in the doctor) flagged `adminText('Title', 'Tytuł')` and `{ en: 'Title', pl: 'Tytuł' }`,
|
||||
the labels AGENT.md §6.5a asks for. The check now reads the syntax tree (`polish-literals.mjs`, with the project's
|
||||
TypeScript; a plain grep without it). In a schema file — a `.ts` file under `collections/`, `globals/`, `fields/` or
|
||||
`blocks/`, or one importing Payload's schema types — it accepts `adminText()`, `{ en, pl }` as `label`, `singular`,
|
||||
`plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback and a `const x: AdminText`, also over several
|
||||
lines. Still reported: every `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required.
|
||||
- Run `pnpm ipal:skills` after upgrading, so the updated audit scripts reach the project: the **ipal-audit** skill runs
|
||||
the project's own copy in `.agents/skills/ipal-audit/scripts` (`audit.sh`, `polish-literals.mjs`); `ipal-doctor` already
|
||||
uses the plugin's.
|
||||
|
||||
## 1.15.2
|
||||
|
||||
### Fixed
|
||||
- **ipal-doctor finds the frontend by structure, not by the name `(frontend)`.** A site with its pages in another route
|
||||
group (`src/app/(site)/[locale]`) was treated as single-language: false "missing" routes and a demand for the
|
||||
single-language Markdown route. `layout-required` now takes any `app/(<group>)` (or `app` itself) that holds the
|
||||
catch-all page, a localized one first; two candidates give a warning naming both. The lazy 404's server action may be
|
||||
`notFoundView.ts` or `notFoundView.tsx` (pages.md), and the other required files accept their usual extensions
|
||||
(`.ts`/`.tsx`, route `.js`). New: `ipal-doctor.json` `"layout": { "frontend": "src/app/(site)" }` for a layout the
|
||||
doctor cannot tell; new export `findFrontend`.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required.
|
||||
- After upgrading, remove any temporary `layout-required` silence in `ipal-doctor.json` that was added for a route group
|
||||
with another name (e.g. `(site)`) or a `notFoundView.tsx`, then run `pnpm exec ipal-doctor` again. Only if the doctor
|
||||
reports two frontend candidates: set `"layout": { "frontend": "src/app/(<group>)" }`.
|
||||
- `pnpm ipal:skills` for the updated `ipal-doctor` and `ipal-reference` skills.
|
||||
|
||||
## 1.15.1
|
||||
|
||||
A seed run that stops early now fails loudly instead of looking like a success.
|
||||
|
||||
### New
|
||||
- `guardSeedExit()` in `@intecion/ipal-kit/seed` ([seeding.md](./seeding.md)): call it first in a seed script. A run that
|
||||
ends before Payload initializes or before `summary()` — `payload run` exits with code 0 and no output when the
|
||||
script's top-level await is left without anything that keeps Node running — now prints `[seed] ended before Payload
|
||||
initialized` / `… before the seed finished` and exits 1. `createSeeder` and `summary()` report to it; normal runs, dry
|
||||
runs, write errors and the production refusals keep their exit codes and messages. Also `activeSeedExitGuard()` and
|
||||
the types `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`.
|
||||
- The seed templates (`ipal-site`, `ipal-form`) and the reference site call it, so sites made with `ipal-kit create` have it.
|
||||
|
||||
### Changed
|
||||
- Reference site (not shipped): the Playwright smoke tests start their own server and fail when the port is taken
|
||||
(`reuseExistingServer` only with `E2E_REUSE_SERVER=1`), so another project's dev server is never tested by mistake.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required.
|
||||
- Recommended: add `guardSeedExit()` (imported from `@intecion/ipal-kit/seed`) as the first statement of every seed
|
||||
script, before `getPayload()`; without it nothing changes. A guarded script must end with `seed.summary()` (the seed
|
||||
templates do), otherwise it exits 1 as "ended before the seed finished".
|
||||
- **Check in Coolify:** after a seed in the app's Terminal, `echo $?` must print `0`; `1` with a `[seed] ended …` line
|
||||
means the run stopped early and nothing after that point was written — run it again.
|
||||
- `pnpm ipal:skills` for the updated `ipal-site` / `ipal-form` seed templates and `ipal-reference`.
|
||||
|
||||
|
||||
## 1.15.0
|
||||
|
||||
A new site in one command (`ipal-kit create`), built from a complete reference site; `ipal-doctor`, which checks any site
|
||||
|
||||
+5
-2
@@ -51,6 +51,8 @@ stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (d
|
||||
|
||||
**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Write seeds with
|
||||
`createSeeder` from `@intecion/ipal-kit/seed` (the templates do) — it enforces every rule below:
|
||||
- Call `guardSeedExit()` first in every seed script (before `getPayload`): a run that ends early exits 1 with the reason
|
||||
instead of a silent 0 that looks like success in Coolify's Terminal.
|
||||
- Seeds are create-only and idempotent: match by the default-locale slug / form title / the global, skip what exists.
|
||||
- Never delete; never seed users, passwords or secrets; globals: fill only empty fields; no media uploads.
|
||||
- Every locale written separately with `fallbackLocale: false`; `context: { disableRevalidate: true, ipalSkipIndexNow: true }`.
|
||||
@@ -420,7 +422,7 @@ CDN preconnect: `<MediaPreconnect />` (from env). Media: `normalizeFilenameHook`
|
||||
```
|
||||
src/
|
||||
app/
|
||||
(frontend)/
|
||||
(frontend)/ # any route group name works ((site) …); ipal-doctor finds it by structure
|
||||
styles.css # Tailwind + @source on node_modules/@intecion/ipal-kit/dist
|
||||
[locale]/ # single-language: no [locale] (see i18n.md)
|
||||
layout.tsx # no <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
|
||||
@@ -746,7 +748,8 @@ empty fields, without guessing, without numbered slots. You design the schema fo
|
||||
(`ctaUrl` → "Cta Url"). Label 1–3 words, ≤ 30 characters.
|
||||
- Texts are `{ en: '…', pl: '…' }` (one key per admin language of the project):
|
||||
`label`, `admin.description`, option `label`, tab `label`, `labels.singular/plural`,
|
||||
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`.
|
||||
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`; shorthand `adminText('Title', 'Tytuł')` from
|
||||
`@intecion/ipal-kit/blocks`. In a schema file `ipal-audit` accepts both; the same words in a component are an error.
|
||||
- `admin.description` only when the label is not enough — one sentence ≤ 120 characters:
|
||||
what it does / where it shows, with a format example (`'Section id for #links, e.g. "pricing".'`),
|
||||
never how the code works (no component, function, env-var or package names).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<!-- Generated by scripts/reference-index.mjs from reference/ — do not edit by hand (pnpm reference:index). -->
|
||||
|
||||
The reference site is one complete client site on ipal-kit 1.15.0 ("Example Studio", made up) that uses
|
||||
The reference site is one complete client site on ipal-kit 1.15.4 ("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:
|
||||
@@ -92,7 +92,11 @@ try {
|
||||
// no .env (CI)
|
||||
}
|
||||
|
||||
/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */
|
||||
/**
|
||||
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
|
||||
* 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({
|
||||
@@ -105,7 +109,7 @@ export default defineConfig({
|
||||
webServer: {
|
||||
command: 'pnpm start',
|
||||
env: { PORT: new URL(baseURL).port || '3000' },
|
||||
reuseExistingServer: true,
|
||||
reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
|
||||
url: `${baseURL}/api/health`,
|
||||
},
|
||||
workers: 1,
|
||||
|
||||
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
|
||||
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
|
||||
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
|
||||
|
||||
## Polish text and panel labels (AGENT.md §2, §6.5a)
|
||||
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
|
||||
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
|
||||
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
|
||||
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
|
||||
|
||||
## Design tokens (AGENT.md §6.11)
|
||||
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
|
||||
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
|
||||
|
||||
@@ -238,8 +238,10 @@ fi
|
||||
if [ -n "$FRONT" ]; then
|
||||
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
|
||||
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
|
||||
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
|
||||
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
|
||||
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
|
||||
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
|
||||
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
|
||||
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
|
||||
fi
|
||||
GLOBALS=$(dirs src/globals)
|
||||
if [ -n "$GLOBALS" ]; then
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env node
|
||||
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
|
||||
// node polish-literals.mjs <dir> [<dir> …]
|
||||
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
|
||||
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
|
||||
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
|
||||
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
|
||||
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
|
||||
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
|
||||
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
|
||||
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
|
||||
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const load = (from) => {
|
||||
try {
|
||||
return createRequire(from)('typescript')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
|
||||
if (!ts) process.exit(3)
|
||||
|
||||
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
|
||||
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
|
||||
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
|
||||
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
|
||||
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
|
||||
|
||||
const files = []
|
||||
const walk = (p) => {
|
||||
let st
|
||||
try { st = statSync(p) } catch { return }
|
||||
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
|
||||
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
|
||||
}
|
||||
process.argv.slice(2).forEach(walk)
|
||||
|
||||
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
|
||||
|
||||
for (const file of files) {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
if (!POLISH.test(text)) continue
|
||||
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
|
||||
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
|
||||
|
||||
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
|
||||
const helpers = new Map()
|
||||
for (const st of source.statements) {
|
||||
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
|
||||
const named = st.importClause?.namedBindings
|
||||
if (!named || !ts.isNamedImports(named)) continue
|
||||
for (const el of named.elements) {
|
||||
const name = (el.propertyName ?? el.name).text
|
||||
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
|
||||
}
|
||||
}
|
||||
|
||||
const isBilingual = (node) =>
|
||||
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
|
||||
|
||||
// Is this literal one of the panel's own labels? Walks up from the literal.
|
||||
const isAdminLabel = (literal) => {
|
||||
let inside = false
|
||||
for (let node = literal; node.parent; node = node.parent) {
|
||||
const parent = node.parent
|
||||
if (keyName(parent) === 'defaultValue') return false
|
||||
if (inside) continue
|
||||
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
|
||||
const helper = helpers.get(parent.expression.text)
|
||||
if (helper === 'adminText') inside = true
|
||||
// rowLabel(fields, fallback): the fallback only, as { en, pl }
|
||||
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
|
||||
}
|
||||
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
|
||||
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
|
||||
}
|
||||
return inside
|
||||
}
|
||||
|
||||
const seen = new Set()
|
||||
const visit = (node) => {
|
||||
if (ts.isImportDeclaration(node)) return
|
||||
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
|
||||
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
|
||||
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
|
||||
if (!seen.has(line)) {
|
||||
seen.add(line)
|
||||
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(source)
|
||||
}
|
||||
@@ -27,7 +27,8 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
{ "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } }
|
||||
```
|
||||
Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`,
|
||||
`layout.allow`, `seen` (written by the doctor), `extraRules`.
|
||||
`layout.allow`, `layout.frontend` (the pages' folder, e.g. `src/app/(site)` — found by structure otherwise; any route
|
||||
group name works), `seen` (written by the doctor), `extraRules`.
|
||||
5. Run again until it reports what the project expects (a new site: `--strict` → `0 error(s), 0 warning(s), 0 info`).
|
||||
|
||||
## Options and exit codes
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
* `email` field (no extra recipients, no header injection).
|
||||
*/
|
||||
import config from '@payload-config'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
// ─── fill from the brief ────────────────────────────────────────────────────
|
||||
@@ -104,6 +104,8 @@ function richText(text: string) {
|
||||
}
|
||||
}
|
||||
|
||||
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
|
||||
guardSeedExit({ label: '[seed-form]' })
|
||||
const payload = await getPayload({ config })
|
||||
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file.
|
||||
// A form seed touches exactly one record — this form (matched by its title). After launch that stays true:
|
||||
|
||||
@@ -144,7 +144,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
|
||||
## 3. What the project wires itself
|
||||
|
||||
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason, docs/doctor.md).
|
||||
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason; the pages may sit in any route group — `layout.frontend` names it when two qualify; docs/doctor.md).
|
||||
`$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`).
|
||||
|
||||
| element | file | minimal example | how to check | details |
|
||||
@@ -248,7 +248,7 @@ Details: env.md, deployment.md, PROGRAMISTA §3.
|
||||
|
||||
**DNS** (A/AAAA, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From domain, R2 domain): the plugin sets nothing — list of records to check with `dig`: `deployment.md` §6, summary in **ipal-setup** stage 11.
|
||||
|
||||
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
|
||||
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding), with `guardSeedExit()` called first (an early exit → exit 1 with the reason, never a silent 0). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
|
||||
|
||||
| Seed env var (run time) | Effect |
|
||||
|---|---|
|
||||
|
||||
@@ -562,13 +562,14 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `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 — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
|
||||
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
|
||||
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
|
||||
| `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. |
|
||||
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
|
||||
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
|
||||
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
|
||||
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
|
||||
|
||||
**Types:** `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
|
||||
**Types:** `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess` — the early-exit guard; `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
|
||||
|
||||
## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
|
||||
|
||||
@@ -809,13 +810,14 @@ Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `planSkills({ dest, source })` | `@intecion/ipal-kit/doctor` | What `ipal-skills` would change: `missing`, `stale`, `retired` ipal-* folders. |
|
||||
| `parseToolOutput(text)`, `AUDIT_RULE_MAP` | `@intecion/ipal-kit/doctor` | Reads `[ERROR] title (n) — rule` output of `audit.sh` / `seo-check.mjs`; audit titles that are a doctor rule. |
|
||||
| `DEFAULT_SRC_ALLOW` | `@intecion/ipal-kit/doctor` | Top-level `src/` entries the convention allows (`layout.allow` extends it). |
|
||||
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `ipal-doctor.json` wins. |
|
||||
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
|
||||
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
|
||||
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
|
||||
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IPAL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `ipalKit` unless `doctor: false`. |
|
||||
|
||||
**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
|
||||
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`.
|
||||
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
|
||||
|
||||
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
*/
|
||||
import config from '@payload-config'
|
||||
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
import { pageTemplates } from '@intecion/ipal-kit/templates'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
|
||||
const ONLY: string[] | undefined = undefined
|
||||
// ----------------------------------------------------------------- /CONTENT --
|
||||
|
||||
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
|
||||
guardSeedExit()
|
||||
|
||||
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file:
|
||||
// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } })
|
||||
const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION })
|
||||
|
||||
@@ -217,6 +217,35 @@ and the browser tab shows the same separator.
|
||||
**Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without
|
||||
`SEED_ONLY` stops with "full seed refused".
|
||||
|
||||
**→ 1.15.1 (PROGRAMISTA §6, item 56; seed exit guard; seeding.md) — nothing required, recommended:**
|
||||
1. Every seed script: `import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'` and `guardSeedExit()` as
|
||||
the first statement, before `getPayload()`; the script ends with `seed.summary()` (the `ipal-site` / `ipal-form`
|
||||
templates show it). `pnpm ipal:skills` for the updated templates.
|
||||
2. **Check:** run the seed with `SEED_DRY_RUN=1` locally → exit 0; in Coolify's Terminal after a seed, `echo $?` → `0`
|
||||
(a `1` with `[seed] ended …` means the run stopped early — run it again).
|
||||
|
||||
**→ 1.15.2 (PROGRAMISTA §6, item 57; ipal-doctor route groups; doctor.md) — nothing required:**
|
||||
1. `pnpm ipal:skills`; remove a temporary `layout-required` silence in `ipal-doctor.json` added for a route group with
|
||||
another name or a `notFoundView.tsx`.
|
||||
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
|
||||
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
|
||||
|
||||
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
|
||||
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
|
||||
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
|
||||
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
|
||||
text in a `.tsx` component is still reported.
|
||||
|
||||
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
|
||||
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
|
||||
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
|
||||
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
|
||||
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
|
||||
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
|
||||
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
|
||||
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
|
||||
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
+4
-1
@@ -387,7 +387,10 @@ For a seed (script, flags and data format: [seeding.md](./seeding.md)):
|
||||
|
||||
1. **dry run** — `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts`, read the planned changes;
|
||||
2. **Backup now** on the database (§4.6);
|
||||
3. the real run; check the panel and the site.
|
||||
3. the real run; check the panel and the site;
|
||||
4. `echo $?` — `0` after the summary means done. `1` with `[seed] ended before Payload initialized` (or `… before the
|
||||
seed finished`) means the run stopped early and silently would have looked like a success — the seed's
|
||||
`guardSeedExit()` caught it (seeding.md); run it again.
|
||||
|
||||
The seed script and its dependencies must be in the image (they are when Coolify builds from the whole repo).
|
||||
|
||||
|
||||
@@ -663,6 +663,10 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 53 | **1.14.4** — cookie texts retyped in every language; three cookie entries in the admin navigation | `pnpm payload generate:importmap` (`CookieReviewTab`, `CookieSiteCheckTab`); empty languages fill themselves (`fillEmptyLocales: false` to keep them empty); with `cookieScanner` one **Cookies** entry with tabs (`cookieScanner: { adminLayout: 'separate' }` for the old entries); Cookie banner is now called Cookies — update editor instructions; no migration | consent.md, cookie-scanner.md, hooks.md, CHANGELOG 1.14.4 |
|
||||
| 54 | **1.14.6** (1.14.5 never published) — `/api/graphql` answers 500; graphql-scalars high advisory; theme stored as `ipal-theme`; hand-written `admin.meta` for the panel preview | Postgres: `migrate:create` for the title separator **plus `${sql.raw(titleSeparatorSql())}` after the first `SET DATA TYPE text;`**, and the cookie storage type; `graphql-scalars` override (Node 22 recommended); `THEME_STORAGE_KEY` instead of `'ipal-theme'`; `titleSeparatorChar()` for a raw `settings.titleSeparator`; remove hand-written panel `admin.meta`; `pnpm ipal:skills` (`--external` optional) | CHANGELOG 1.14.6 + 1.14.5, seo.md, theme.md, white-label.md, consent.md |
|
||||
| 55 | **1.15.0** — a production seed runs everything; no design tokens / block library; no site check | `SEED_ONLY` for production seeds (full seed refused, `IPAL_SEED_ALLOW_FULL=1` with the owner's OK); optional tokens.css + the block library (block by block, `migrate:create`); CookieButton above the footer (`avoid={false}`); `pnpm ipal:skills`; `pnpm exec ipal-doctor` (`--url`); new sites with `ipal-kit create` | CHANGELOG 1.15.0, seeding.md, design-tokens.md, block-library.md, doctor.md, project-starter.md |
|
||||
| 56 | **1.15.1** — a seed in Coolify's Terminal ends with exit 0 and no output (it stopped before Payload started) | `guardSeedExit()` first in every seed script, `seed.summary()` at the end; check `echo $?` after a seed; `pnpm ipal:skills` | CHANGELOG 1.15.1, seeding.md |
|
||||
| 57 | **1.15.2** — ipal-doctor reports missing routes for a site whose pages live in `app/(site)` (not `(frontend)`), or a `notFoundView.tsx` | nothing to change; remove the temporary `layout-required` silence; two candidates → `layout.frontend` in `ipal-doctor.json`; `pnpm ipal:skills` | CHANGELOG 1.15.2, doctor.md |
|
||||
| 58 | **1.15.3** — ipal-audit / ipal-doctor report `adminText()` or `{ en, pl }` panel labels as hardcoded Polish text | `pnpm ipal:skills`; remove a temporary `i18n-literals` silence added for such labels; public text is still reported | CHANGELOG 1.15.3, ipal-audit skill |
|
||||
| 59 | **1.15.4** — a seeded form / layout / global array shows only the last language (whole localized arrays) | nothing to change in the seed; repair: `SEED_UPDATE=1` locally, on production `SEED_ONLY` + `SEED_UPDATE=1` + `IPAL_SEED_ALLOW_PROD_UPDATE=1` after a backup; edited records and global arrays by hand | CHANGELOG 1.15.4, seeding.md |
|
||||
|
||||
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
|
||||
`node_modules/@intecion/ipal-kit/dist`.
|
||||
|
||||
+6
-5
@@ -84,7 +84,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
|
||||
| | `node-22` | warning | `engines.node` only 22 (`">=22 <23"`), `.nvmrc` / `.node-version` = 22; with `--deep`, the running Node |
|
||||
| | `pnpm-pinned` | info | `packageManager` is set |
|
||||
| | `deps-audit` | error on critical/high, info on moderate/low | `pnpm audit --prod` (registry) |
|
||||
| layout | `layout-required` | error | the AGENT.md §3 files (proxy, i18n config, instrumentation, `lib/content`, every route, the `(frontend)` files, `blocks/registry.ts`, `collections/{Pages,Media}.ts`, `components/layout`, `components/forms/formClasses.ts`); an `ipal-audit-skip` key (`llms`, `llms-full`, `markdown`, `mcp`, `indexnow`) drops its file |
|
||||
| layout | `layout-required` | error | the AGENT.md §3 files (proxy, i18n config, instrumentation, `lib/content`, every route, the frontend files — `layout`, `actions`, `not-found`, `notFoundView` (`.ts` or `.tsx`), the catch-all page — in the route group found by structure: any `app/(<group>)` (or `app` itself) holding `[locale]/[[...slug]]/page.tsx` or `[[...slug]]/page.tsx`, a localized one first, `(frontend)` on a tie (two matches → a warning naming both); `layout.frontend` sets it, `blocks/registry.ts`, `collections/{Pages,Media}.ts`, `components/layout`, `components/forms/formClasses.ts`); an `ipal-audit-skip` key (`llms`, `llms-full`, `markdown`, `mcp`, `indexnow`) drops its file |
|
||||
| | `layout-forbidden` | error | no `middleware.ts`, no `lib/{pages,locales,navigation}.ts`, `fields/{link,sectionHeader,sectionSettings}.ts` |
|
||||
| | `layout-extra` | info | `src/` entries outside the allow list (AGENT.md §3 + `seed/`, `design/`, `db.ts`, `env.rules.ts`, `content.config.ts`; extend with `layout.allow`) |
|
||||
| | `naming` | warning | block folders, collection and global files PascalCase, `scripts/*` kebab-case, no `index.ts` barrels |
|
||||
@@ -110,7 +110,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M
|
||||
| | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` |
|
||||
| | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` |
|
||||
| | `blocks-tokens` | error / warning | from `ipal-audit`: hex colours, the token standard not wired, `ipal-tokens --check` |
|
||||
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code |
|
||||
| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `ipal-audit` skill) |
|
||||
| | `audit:<title>` | as reported | every other `ipal-audit --quick` finding, one per file |
|
||||
| live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `ipal-seo-check` error and warning |
|
||||
| deep | `deep-status` | error | the deep check could not finish |
|
||||
@@ -128,7 +128,7 @@ Every rule can be silenced, lowered or raised — **with a reason** — in `ipal
|
||||
{
|
||||
"domain": "example-studio.pl",
|
||||
"launched": false,
|
||||
"layout": { "allow": ["scripts"] },
|
||||
"layout": { "allow": ["scripts"], "frontend": "src/app/(site)" },
|
||||
"rules": {
|
||||
"csp": { "off": true, "reason": "new site: report-only until the reports are clean", "until": "2026-12-01" },
|
||||
"i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: the styleguide labels" },
|
||||
@@ -144,6 +144,7 @@ Every rule can be silenced, lowered or raised — **with a reason** — in `ipal
|
||||
| `domain` | the production domain (dots allowed) — the base of the database names. Without it: a non-local `NEXT_PUBLIC_SERVER_URL`, else the folder name minus `-web` |
|
||||
| `launched` | the site is live: seeds must then name their records. Also true when "Project decisions" has a line with "launch" and a date |
|
||||
| `layout.allow` | more top-level `src/` entries the convention allows |
|
||||
| `layout.frontend` | the folder that holds the site's pages, e.g. `src/app/(site)` — only for a layout the doctor cannot tell (two route groups with pages); the route group's name is otherwise free |
|
||||
| `rules.<id>` | `off` (silence), `severity` (`error` / `warning` / `info`), `reason` (**required** — an entry without one is ignored and reported), `until` (ISO date; after it the entry stops applying and the report says so), `files` (globs: only findings in those files). The id is the rule (`csp`) or an audit finding (`audit:collections-present`); `audit` covers all audit findings |
|
||||
| `seen` | first-seen dates the doctor stores itself (`csp-report-only`, for the 4-week CSP rule). It writes this key only outside CI (`CI` unset), not with `--json`, and only when the file exists |
|
||||
| `extraRules` | your own rule modules (paths relative to the project), each exporting `rules: DoctorRule[]` |
|
||||
@@ -199,10 +200,10 @@ console.log(formatReport(report))
|
||||
|
||||
`runDoctor`, `runDoctorCli`, `doctorRules`, `applySettings`, `runDeepProbe`, `createDoctorContext`, `loadDoctorConfig`,
|
||||
`formatReport`, `formatDriftTable`, `planSkills`, `parseToolOutput`, `AUDIT_RULE_MAP`, `AUDIT_SKIP_RULES`,
|
||||
`DEFAULT_SRC_ALLOW`, `createLiveFetcher`, `buildDoctorEndpoint`, `collectDoctorStatus`, `globToRegExp`, `parseEnvFile`,
|
||||
`DEFAULT_SRC_ALLOW`, `findFrontend`, `createLiveFetcher`, `buildDoctorEndpoint`, `collectDoctorStatus`, `globToRegExp`, `parseEnvFile`,
|
||||
`readAuditSkips`, `bareHost`, `expandSites`, `parseDoctorArgs`, `DOCTOR_USAGE`; types `DoctorRule`, `DoctorFinding`,
|
||||
`DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`, `DoctorSource`, `DoctorStatus`, `DoctorContext`,
|
||||
`RuleFinding`, `RunDoctorOptions`, `DoctorEndpointOptions`.
|
||||
`RuleFinding`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
|
||||
|
||||
## Environment variables
|
||||
|
||||
|
||||
+30
-2
@@ -152,6 +152,8 @@ Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSe
|
||||
— the plan must name only the records the owner asked for.
|
||||
3. Back up the database (**Backup now**).
|
||||
4. The real run, without `SEED_DRY_RUN`.
|
||||
5. Check the exit code (`echo $?`): `0` with the summary means done. A run that stops early prints
|
||||
`[seed] ended before …` and exits `1` (`guardSeedExit`, below) — run it again; nothing after that point was written.
|
||||
|
||||
The seed script and its dependencies must be in the image. Env vars (`DATABASE_URI`, `PAYLOAD_SECRET`, …)
|
||||
must be available at runtime, not only at build time. The container already has `NODE_ENV=production`, so
|
||||
@@ -178,9 +180,10 @@ because that package throws outside a bundled server.
|
||||
```ts
|
||||
// scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
|
||||
import config from '@payload-config'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
guardSeedExit() // first — an early exit becomes exit 1 with the reason, never a silent 0
|
||||
const seed = createSeeder(await getPayload({ config }))
|
||||
await seed.upsertBySlug('pages', [
|
||||
{ title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] },
|
||||
@@ -194,6 +197,10 @@ process.exit(seed.summary().errors ? 1 : 0)
|
||||
**Seed values.** Write each value once, every language side by side. An object whose keys are all
|
||||
locale codes is one value per locale (`{ pl: 'Kontakt', en: 'Contact' }`); anything else is the same
|
||||
in every locale. A locale missing from such an object is left untouched in that locale.
|
||||
This works at any level: a text (`label: { pl, en }`) or a whole array, layout or group (`fields: { pl: [...], en: [...] }`).
|
||||
Rows of a field that is not localized are shared by every language — the helper reuses their ids, so give each
|
||||
language the same rows in the same order (its texts differ; non-localized values such as an option's `value` come
|
||||
from the last language written). A field with `localized: true` keeps its own rows per language.
|
||||
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`;
|
||||
`{ $form: 'Contact form' }` becomes the ID of the form with that title (seed the form first). A missing form
|
||||
is an error for that record, never an empty relation. Ready pages made of library blocks:
|
||||
@@ -211,6 +218,26 @@ Each method prints one line per record (see [Running a seed](#running-a-seed)) a
|
||||
with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production
|
||||
guard refuses the run.
|
||||
|
||||
### A run that ends early fails loudly — `guardSeedExit()`
|
||||
|
||||
`payload run` starts the CLI with `void start()` and then imports the script. When the script's top-level
|
||||
`await getPayload()` (or a later await) is left with nothing that keeps Node's event loop alive, Node simply exits:
|
||||
**code 0, no output** — in Coolify's Terminal that looks exactly like a successful seed. Call `guardSeedExit()` first
|
||||
in every seed script (the templates and the reference site do):
|
||||
|
||||
| The run | Exit | What you see |
|
||||
|---|---|---|
|
||||
| ends before Payload initialized | 1 | `[seed] ended before Payload initialized — the run stopped early …` |
|
||||
| ends after `createSeeder` but before `summary()` | 1 | `[seed] ended before the seed finished — …` |
|
||||
| finishes: `summary()`, then `process.exit(errors ? 1 : 0)` (or ends naturally after the summary, e.g. a dry run) | 0 / 1 | the summary, as before |
|
||||
| a write fails | 1 | the `error` lines and the summary, as before |
|
||||
| the production guard refuses (`full seed refused`, `update refused`) or the script throws | 1 | the error, as before (`payload run` prints it) |
|
||||
|
||||
`createSeeder` marks the run initialized and `summary()` marks it finished, so the guard needs nothing else.
|
||||
`guardSeedExit({ label: '[seed-form]', log, process })` — label of the message, where it goes (default stderr), and
|
||||
the process (tests). `dispose()` stops watching. Check: `pnpm seed` with a reachable database prints the summary as
|
||||
before; an interrupted run prints the line above and `echo $?` shows `1`.
|
||||
|
||||
On a collection with drafts the helper reads the latest draft, both to match records and to tell
|
||||
whether an editor changed them.
|
||||
|
||||
@@ -218,13 +245,14 @@ whether an editor changed them.
|
||||
|
||||
| Export | Use |
|
||||
|---|---|
|
||||
| `guardSeedExit({ label, log, process })` | the early-exit guard above → `{ initialized, finished, dispose, state }`; `activeSeedExitGuard()` returns the current one (`createSeeder` and `summary()` report to it) |
|
||||
| `isLocalDatabase(url, { localHosts })` | the "local database" test of [Updates on production](#updates-on-production) |
|
||||
| `writeLocales(payload, target, data, { context, draft })` | writes seed values to an existing record (`{ collection, id }` or `{ global }`) in every locale: the default locale first, then the others with `fallbackLocale: false` onto the same row ids |
|
||||
| `seedHash(value)` | the hash stored in the hash field: key order, row ids and `null`s don't change it |
|
||||
| `projectOnto(seed, current)` | the current values at the keys the seed writes, the input for `seedHash` on a re-run |
|
||||
| `editedSinceSeed({ doc, currentHash, hashField, untouchedSeconds })` | `null` when untouched, otherwise why the record counts as edited |
|
||||
|
||||
Types: `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`,
|
||||
Types: `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`, `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `SeedTarget`, `SeedValue`,
|
||||
`UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`.
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.15.0",
|
||||
"version": "1.15.4",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on
|
||||
a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys
|
||||
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
|
||||
|
||||
## Polish text and panel labels (AGENT.md §2, §6.5a)
|
||||
`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`,
|
||||
`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`,
|
||||
`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a
|
||||
`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
|
||||
|
||||
## Design tokens (AGENT.md §6.11)
|
||||
The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in
|
||||
classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated),
|
||||
|
||||
@@ -238,8 +238,10 @@ fi
|
||||
if [ -n "$FRONT" ]; then
|
||||
report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \
|
||||
"$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')"
|
||||
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \
|
||||
"$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')"
|
||||
# The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep.
|
||||
POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \
|
||||
POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')
|
||||
report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH"
|
||||
fi
|
||||
GLOBALS=$(dirs src/globals)
|
||||
if [ -n "$GLOBALS" ]; then
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env node
|
||||
// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0.
|
||||
// node polish-literals.mjs <dir> [<dir> …]
|
||||
// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work.
|
||||
// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under
|
||||
// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file:
|
||||
// - adminText('Title', 'Tytuł') from @intecion/ipal-kit
|
||||
// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group
|
||||
// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit
|
||||
// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
|
||||
// Anything under defaultValue is public content, so it is reported. So is a Polish-only label.
|
||||
// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep).
|
||||
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const load = (from) => {
|
||||
try {
|
||||
return createRequire(from)('typescript')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url)
|
||||
if (!ts) process.exit(3)
|
||||
|
||||
const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/
|
||||
const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group'])
|
||||
const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\//
|
||||
const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/
|
||||
const IPAL = /^@intecion\/ipal-kit(?:\/|$)/
|
||||
|
||||
const files = []
|
||||
const walk = (p) => {
|
||||
let st
|
||||
try { st = statSync(p) } catch { return }
|
||||
if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n))
|
||||
else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p)
|
||||
}
|
||||
process.argv.slice(2).forEach(walk)
|
||||
|
||||
const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null)
|
||||
|
||||
for (const file of files) {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
if (!POLISH.test(text)) continue
|
||||
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
|
||||
const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text))
|
||||
|
||||
// Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count.
|
||||
const helpers = new Map()
|
||||
for (const st of source.statements) {
|
||||
if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue
|
||||
const named = st.importClause?.namedBindings
|
||||
if (!named || !ts.isNamedImports(named)) continue
|
||||
for (const el of named.elements) {
|
||||
const name = (el.propertyName ?? el.name).text
|
||||
if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name)
|
||||
}
|
||||
}
|
||||
|
||||
const isBilingual = (node) =>
|
||||
ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k))
|
||||
|
||||
// Is this literal one of the panel's own labels? Walks up from the literal.
|
||||
const isAdminLabel = (literal) => {
|
||||
let inside = false
|
||||
for (let node = literal; node.parent; node = node.parent) {
|
||||
const parent = node.parent
|
||||
if (keyName(parent) === 'defaultValue') return false
|
||||
if (inside) continue
|
||||
if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) {
|
||||
const helper = helpers.get(parent.expression.text)
|
||||
if (helper === 'adminText') inside = true
|
||||
// rowLabel(fields, fallback): the fallback only, as { en, pl }
|
||||
if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true
|
||||
}
|
||||
if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true
|
||||
if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true
|
||||
}
|
||||
return inside
|
||||
}
|
||||
|
||||
const seen = new Set()
|
||||
const visit = (node) => {
|
||||
if (ts.isImportDeclaration(node)) return
|
||||
const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)
|
||||
if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) {
|
||||
const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line
|
||||
if (!seen.has(line)) {
|
||||
seen.add(line)
|
||||
console.log(`${file}:${line + 1}:${text.split('\n')[line]}`)
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(source)
|
||||
}
|
||||
@@ -27,7 +27,8 @@ Full reference: `node_modules/@intecion/ipal-kit/docs/doctor.md`.
|
||||
{ "rules": { "i18n-literals": { "off": true, "files": ["src/components/design/**"], "reason": "approved exception: styleguide labels" } } }
|
||||
```
|
||||
Keys: `off`, `severity`, `reason` (required), `until` (ISO date), `files` (globs). Top level: `domain`, `launched`,
|
||||
`layout.allow`, `seen` (written by the doctor), `extraRules`.
|
||||
`layout.allow`, `layout.frontend` (the pages' folder, e.g. `src/app/(site)` — found by structure otherwise; any route
|
||||
group name works), `seen` (written by the doctor), `extraRules`.
|
||||
5. Run again until it reports what the project expects (a new site: `--strict` → `0 error(s), 0 warning(s), 0 info`).
|
||||
|
||||
## Options and exit codes
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
* `email` field (no extra recipients, no header injection).
|
||||
*/
|
||||
import config from '@payload-config'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
// ─── fill from the brief ────────────────────────────────────────────────────
|
||||
@@ -104,6 +104,8 @@ function richText(text: string) {
|
||||
}
|
||||
}
|
||||
|
||||
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
|
||||
guardSeedExit({ label: '[seed-form]' })
|
||||
const payload = await getPayload({ config })
|
||||
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file.
|
||||
// A form seed touches exactly one record — this form (matched by its title). After launch that stays true:
|
||||
|
||||
@@ -144,7 +144,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
|
||||
## 3. What the project wires itself
|
||||
|
||||
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason, docs/doctor.md).
|
||||
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**, **ipal-doctor** (`pnpm exec ipal-doctor` — the whole site against the team standard; `ipal-doctor.json` silences a rule with a reason; the pages may sit in any route group — `layout.frontend` names it when two qualify; docs/doctor.md).
|
||||
`$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`).
|
||||
|
||||
| element | file | minimal example | how to check | details |
|
||||
@@ -248,7 +248,7 @@ Details: env.md, deployment.md, PROGRAMISTA §3.
|
||||
|
||||
**DNS** (A/AAAA, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From domain, R2 domain): the plugin sets nothing — list of records to check with `dig`: `deployment.md` §6, summary in **ipal-setup** stage 11.
|
||||
|
||||
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
|
||||
**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding), with `guardSeedExit()` called first (an early exit → exit 1 with the reason, never a silent 0). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
|
||||
|
||||
| Seed env var (run time) | Effect |
|
||||
|---|---|
|
||||
|
||||
@@ -562,13 +562,14 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `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 — a choice (select, radio, checkbox, number, date) still at its `defaultValue` counts as empty, text never does; a field already holding the seeded value is skipped (all seeded fields with `update` when untouched). |
|
||||
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
|
||||
| `guardSeedExit({ label?, log?, process? })`, `activeSeedExitGuard()` | `@intecion/ipal-kit/seed` | Call first in a seed script: a run that ends before Payload initializes or before `summary()` (Node exiting through an empty event loop under `payload run`) prints `[seed] ended before …` and exits 1 instead of a silent 0. `createSeeder` / `summary()` report to it; `dispose()` stops it. |
|
||||
| `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. |
|
||||
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field, or a whole array per locale) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids (shared rows of non-localized arrays and blocks; a `localized: true` field keeps rows per locale). |
|
||||
| `seedHash(value)` | `@intecion/ipal-kit/seed` | Stable hash for the hidden `seedHash` field (key order, row ids, nulls ignored). |
|
||||
| `projectOnto(seed, current)` | `@intecion/ipal-kit/seed` | Current values at the keys the seed writes — hash them to compare with the stored hash. |
|
||||
| `editedSinceSeed({ doc, currentHash?, hashField?, untouchedSeconds? })` | `@intecion/ipal-kit/seed` | `null` = untouched; otherwise the reason (stored hash differs / `updatedAt` too late after `createdAt`). |
|
||||
|
||||
**Types:** `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
|
||||
**Types:** `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess` — the early-exit guard; `Seeder`, `SeederOptions`, `SeedResult`, `SeedStatus`, `SeedSummary`, `UpsertOptions` — the seeder, its options and results; `SeedValue`, `SeedTarget`, `WriteLocalesOptions`, `EditedSinceSeedArgs` — building-block inputs (all `/seed`).
|
||||
|
||||
## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
|
||||
|
||||
@@ -809,13 +810,14 @@ Bin: `ipal-doctor` (`pnpm exec ipal-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `planSkills({ dest, source })` | `@intecion/ipal-kit/doctor` | What `ipal-skills` would change: `missing`, `stale`, `retired` ipal-* folders. |
|
||||
| `parseToolOutput(text)`, `AUDIT_RULE_MAP` | `@intecion/ipal-kit/doctor` | Reads `[ERROR] title (n) — rule` output of `audit.sh` / `seo-check.mjs`; audit titles that are a doctor rule. |
|
||||
| `DEFAULT_SRC_ALLOW` | `@intecion/ipal-kit/doctor` | Top-level `src/` entries the convention allows (`layout.allow` extends it). |
|
||||
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `ipal-doctor.json` wins. |
|
||||
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
|
||||
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
|
||||
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
|
||||
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IPAL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `ipalKit` unless `doctor: false`. |
|
||||
|
||||
**Types:** `DoctorRule`, `DoctorFinding`, `RuleFinding`, `DoctorReport`, `DoctorConfig`, `DoctorRuleSetting`, `DoctorSeverity`,
|
||||
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`.
|
||||
`DoctorSource`, `DoctorStatus`, `DoctorContext`, `RunDoctorOptions`, `DoctorEndpointOptions`, `FrontendLayout`.
|
||||
|
||||
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
*/
|
||||
import config from '@payload-config'
|
||||
import { libraryBlockSlugs } from '@intecion/ipal-kit/blocks'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
import { pageTemplates } from '@intecion/ipal-kit/templates'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
@@ -67,6 +67,9 @@ const COLLECTION = 'pages'
|
||||
const ONLY: string[] | undefined = undefined
|
||||
// ----------------------------------------------------------------- /CONTENT --
|
||||
|
||||
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (docs/seeding.md).
|
||||
guardSeedExit()
|
||||
|
||||
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file:
|
||||
// createSeeder(payload, { editCheck: { hashField: false }, guard: { localHosts: ['db'] }, context: { … } })
|
||||
const seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION })
|
||||
|
||||
@@ -217,6 +217,35 @@ and the browser tab shows the same separator.
|
||||
**Check:** `pnpm exec ipal-doctor --strict` → 0 errors, 0 warnings; `pnpm build`; a production seed without
|
||||
`SEED_ONLY` stops with "full seed refused".
|
||||
|
||||
**→ 1.15.1 (PROGRAMISTA §6, item 56; seed exit guard; seeding.md) — nothing required, recommended:**
|
||||
1. Every seed script: `import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'` and `guardSeedExit()` as
|
||||
the first statement, before `getPayload()`; the script ends with `seed.summary()` (the `ipal-site` / `ipal-form`
|
||||
templates show it). `pnpm ipal:skills` for the updated templates.
|
||||
2. **Check:** run the seed with `SEED_DRY_RUN=1` locally → exit 0; in Coolify's Terminal after a seed, `echo $?` → `0`
|
||||
(a `1` with `[seed] ended …` means the run stopped early — run it again).
|
||||
|
||||
**→ 1.15.2 (PROGRAMISTA §6, item 57; ipal-doctor route groups; doctor.md) — nothing required:**
|
||||
1. `pnpm ipal:skills`; remove a temporary `layout-required` silence in `ipal-doctor.json` added for a route group with
|
||||
another name or a `notFoundView.tsx`.
|
||||
2. Two frontend candidates reported → `"layout": { "frontend": "src/app/(<group>)" }` in `ipal-doctor.json`.
|
||||
**Check:** `pnpm exec ipal-doctor --strict` → no `layout-required` finding for the site's own route group.
|
||||
|
||||
**→ 1.15.3 (PROGRAMISTA §6, item 58; ipal-audit, bilingual panel labels; ipal-audit skill) — nothing required:**
|
||||
1. `pnpm ipal:skills`, so the updated `audit.sh` and `polish-literals.mjs` reach the project.
|
||||
2. Remove a temporary `i18n-literals` silence or `ipal-audit-skip` added because of `adminText()` / `{ en, pl }` labels.
|
||||
**Check:** `pnpm exec ipal-doctor --strict` → no `i18n-literals` finding for a schema file's bilingual labels; Polish
|
||||
text in a `.tsx` component is still reported.
|
||||
|
||||
**→ 1.15.4 (PROGRAMISTA §6, item 59; seeding whole localized arrays; seeding.md) — nothing required:**
|
||||
1. Did a seed write a whole localized array (`{ pl: [...], en: [...] }` for form fields, a page `layout`, a global
|
||||
array) and the panel shows only the last language? A plain re-run skips existing records (create-only): rewrite
|
||||
them locally with `SEED_UPDATE=1 pnpm seed` and check every language in the panel.
|
||||
2. Live site, only the affected records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1
|
||||
IPAL_SEED_ALLOW_PROD_UPDATE=1 SEED_DRY_RUN=1 pnpm seed`, back up the database (Coolify), then the same without
|
||||
`SEED_DRY_RUN`. Records an editor changed since seeding are skipped (`skip (edited)`) — fix them in the panel.
|
||||
3. A global array: `fillGlobal` fills empty fields only — clear the field in the panel before the run, or fix it by hand.
|
||||
**Check:** the panel shows the seeded rows in every language; a second run reports `skip`, not new rows.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ Write everything in this file in English.
|
||||
<!-- /starter:decisions -->
|
||||
|
||||
<!-- ipal-kit:start -->
|
||||
## ipal-kit 1.15.0 — agent guide
|
||||
## ipal-kit 1.15.4 — agent guide
|
||||
|
||||
<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->
|
||||
This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:
|
||||
|
||||
+3
-2
@@ -17,8 +17,9 @@ cp .env.example .env # then fill PAYLOAD_SECRET; DATABASE
|
||||
pnpm seed # demo + base content, every language
|
||||
pnpm dev # http://localhost:3000/pl
|
||||
```
|
||||
Production check: `pnpm build && ALLOW_LOCAL_MEDIA=1 PORT=3100 pnpm start`, then
|
||||
`pnpm payload run e2e/create-test-admin.ts && pnpm test:e2e`.
|
||||
Production check: `pnpm build && pnpm payload run e2e/create-test-admin.ts && ALLOW_LOCAL_MEDIA=1 pnpm test:e2e`
|
||||
(Playwright starts the built site on port 3100 itself; another port: `E2E_BASE_URL=http://localhost:3200`, built with
|
||||
the same `NEXT_PUBLIC_SERVER_URL`; a server you started yourself: `E2E_REUSE_SERVER=1`).
|
||||
|
||||
## What is where
|
||||
| Convention | Files |
|
||||
|
||||
@@ -7,7 +7,11 @@ try {
|
||||
// no .env (CI)
|
||||
}
|
||||
|
||||
/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */
|
||||
/**
|
||||
* Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts.
|
||||
* 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({
|
||||
@@ -20,7 +24,7 @@ export default defineConfig({
|
||||
webServer: {
|
||||
command: 'pnpm start',
|
||||
env: { PORT: new URL(baseURL).port || '3000' },
|
||||
reuseExistingServer: true,
|
||||
reuseExistingServer: process.env.E2E_REUSE_SERVER === '1',
|
||||
url: `${baseURL}/api/health`,
|
||||
},
|
||||
workers: 1,
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
* only with the owner's explicit OK). Pages are create-only; an edited record is skipped.
|
||||
*/
|
||||
import config from '@payload-config'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import { seedBaseGlobals, seedBaseNavigation, seedBasePages, seedBaseTexts } from './base'
|
||||
@@ -33,6 +33,8 @@ const withBase = layer === 'all' || layer === 'base'
|
||||
//: const withBase = true // a new site has only the base layer (the reference site's demo is not copied)
|
||||
// @starter:endif
|
||||
|
||||
// An early exit (Payload never up, the run cut short) fails with exit 1 instead of a silent 0 (seeding.md).
|
||||
guardSeedExit()
|
||||
const payload = await getPayload({ config })
|
||||
const seed = createSeeder(payload)
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ export { formatDriftTable, formatReport } from '../modules/doctor/format.js'
|
||||
export { bareHost, createDoctorContext, loadDoctorConfig, parseEnvFile, readAuditSkips } from '../modules/doctor/project.js'
|
||||
export type { DoctorContext } from '../modules/doctor/project.js'
|
||||
export { planSkills } from '../modules/doctor/rules/agents.js'
|
||||
export { DEFAULT_SRC_ALLOW } from '../modules/doctor/rules/layout.js'
|
||||
export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.js'
|
||||
export type { FrontendLayout } from '../modules/doctor/rules/layout.js'
|
||||
export { createLiveFetcher } from '../modules/doctor/rules/live.js'
|
||||
export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js'
|
||||
export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js'
|
||||
|
||||
+7
-1
@@ -6,8 +6,9 @@
|
||||
* // scripts/seed-content.ts — pnpm payload run scripts/seed-content.ts
|
||||
* import config from '@payload-config'
|
||||
* import { getPayload } from 'payload'
|
||||
* import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
* import { createSeeder, guardSeedExit } from '@intecion/ipal-kit/seed'
|
||||
*
|
||||
* guardSeedExit() // first: an early exit (no Payload, unfinished run) becomes exit 1, not a silent 0
|
||||
* const seed = createSeeder(await getPayload({ config }))
|
||||
* await seed.upsertBySlug('pages', [{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } }])
|
||||
* await seed.fillGlobal('header', { links: [] })
|
||||
@@ -18,8 +19,10 @@
|
||||
* package throws in plain Node, and `payload run` is plain Node.
|
||||
*/
|
||||
export {
|
||||
activeSeedExitGuard,
|
||||
createSeeder,
|
||||
editedSinceSeed,
|
||||
guardSeedExit,
|
||||
isLocalDatabase,
|
||||
projectOnto,
|
||||
seedHash,
|
||||
@@ -29,6 +32,9 @@ export type {
|
||||
EditedSinceSeedArgs,
|
||||
Seeder,
|
||||
SeederOptions,
|
||||
SeedExitGuard,
|
||||
SeedExitGuardOptions,
|
||||
SeedExitProcess,
|
||||
SeedResult,
|
||||
SeedStatus,
|
||||
SeedSummary,
|
||||
|
||||
@@ -33,35 +33,72 @@ export const DEFAULT_SRC_ALLOW = [
|
||||
/** The project renders blocks through the library registry — then components/ui/ only holds overrides. */
|
||||
export const usesBlockRegistry = (ctx: DoctorContext) => /createBlockRegistry\s*\(/.test(stripComments(ctx.read(`${ctx.src}blocks/registry.ts`)))
|
||||
|
||||
/** Files AGENT.md §3 expects, with the `ipal-audit-skip` key that drops each one. */
|
||||
function requiredFiles(ctx: DoctorContext): Array<[string, string?]> {
|
||||
const multi = ctx.exists(`${ctx.src}app/(frontend)/[locale]`)
|
||||
const fe = multi ? 'app/(frontend)/[locale]' : 'app/(frontend)'
|
||||
/** Where the site's pages live: the route group (any name) and whether it has a `[locale]` segment. */
|
||||
export type FrontendLayout = {
|
||||
/** Other folders that look like the frontend too (set `layout.frontend` to choose). */
|
||||
ambiguous: string[]
|
||||
/** Folder relative to src/, e.g. `app/(site)`, `app/(frontend)` or `app` (no route group). */
|
||||
dir: string
|
||||
/** `layout.frontend` names a folder that does not exist. */
|
||||
missingOverride?: string
|
||||
multi: boolean
|
||||
}
|
||||
|
||||
const PAGE = ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
|
||||
const has = (ctx: DoctorContext, dir: string, names: string[]) => names.some((n) => ctx.exists(`${ctx.src}${dir}/${n}`))
|
||||
|
||||
/**
|
||||
* The frontend folder, found by structure rather than by name (a route group's name never reaches the URL):
|
||||
* `ipal-doctor.json` `layout.frontend` wins; else every `app/(<group>)` except `(payload)`, and `app` itself,
|
||||
* holding the catch-all page — one with a `[locale]` page first. No match → `app/(frontend)` (the convention).
|
||||
*/
|
||||
export function findFrontend(ctx: DoctorContext): FrontendLayout {
|
||||
const override = ctx.config.layout?.frontend?.trim()
|
||||
if (override) {
|
||||
const dir = override.replace(/^\.?\//, '').replace(/^src\//, '').replace(/\/+$/, '')
|
||||
return { ambiguous: [], dir, missingOverride: ctx.exists(`${ctx.src}${dir}`) ? undefined : override, multi: ctx.exists(`${ctx.src}${dir}/[locale]`) }
|
||||
}
|
||||
const groups = ['app', ...ctx.list(`${ctx.src}app`).filter((n) => /^\(.+\)$/.test(n) && n !== '(payload)').map((n) => `app/${n}`)]
|
||||
const localized = groups.filter((g) => has(ctx, `${g}/[locale]/[[...slug]]`, PAGE))
|
||||
const single = groups.filter((g) => has(ctx, `${g}/[[...slug]]`, PAGE))
|
||||
const best = localized.length ? localized : single
|
||||
if (!best.length) {return { ambiguous: [], dir: 'app/(frontend)', multi: ctx.exists(`${ctx.src}app/(frontend)/[locale]`) }}
|
||||
const dir = best.includes('app/(frontend)') ? 'app/(frontend)' : best[0]
|
||||
return { ambiguous: best.filter((g) => g !== dir), dir, multi: localized.length > 0 }
|
||||
}
|
||||
|
||||
/** Files AGENT.md §3 expects — each as its accepted names — with the `ipal-audit-skip` key that drops it. */
|
||||
function requiredFiles(ctx: DoctorContext, frontend: FrontendLayout): Array<[string[], string?]> {
|
||||
const fe = frontend.multi ? `${frontend.dir}/[locale]` : frontend.dir
|
||||
const ts = (base: string) => [`${base}.ts`, `${base}.tsx`]
|
||||
const tsx = (base: string) => [`${base}.tsx`, `${base}.ts`, `${base}.jsx`, `${base}.js`]
|
||||
const route = (dir: string) => [`${dir}/route.ts`, `${dir}/route.js`]
|
||||
return [
|
||||
['proxy.ts'],
|
||||
['i18n.config.ts'],
|
||||
['instrumentation.ts'],
|
||||
['payload.config.ts'],
|
||||
['lib/content.ts'],
|
||||
['app/manifest.ts'],
|
||||
['app/robots.ts'],
|
||||
['app/sitemap.xml/route.ts'],
|
||||
['app/llms.txt/route.ts', 'llms'],
|
||||
['app/llms-full.txt/route.ts', 'llms-full'],
|
||||
[multi ? 'app/md/[locale]/[[...slug]]/route.ts' : 'app/md/[[...slug]]/route.ts', 'markdown'],
|
||||
['app/api/mcp/route.ts', 'mcp'],
|
||||
['app/api/health/route.ts'],
|
||||
['app/indexnow-key.txt/route.ts', 'indexnow'],
|
||||
[`${fe}/layout.tsx`],
|
||||
[`${fe}/actions.ts`],
|
||||
[`${fe}/not-found.tsx`],
|
||||
[`${fe}/notFoundView.ts`],
|
||||
[`${fe}/[[...slug]]/page.tsx`],
|
||||
['blocks/registry.ts'],
|
||||
['collections/Pages.ts'],
|
||||
['collections/Media.ts'],
|
||||
['components/layout'],
|
||||
['components/forms/formClasses.ts'],
|
||||
[ts('proxy')],
|
||||
[ts('i18n.config')],
|
||||
[ts('instrumentation')],
|
||||
[ts('payload.config')],
|
||||
[ts('lib/content')],
|
||||
[tsx('app/manifest')],
|
||||
[tsx('app/robots')],
|
||||
[route('app/sitemap.xml')],
|
||||
[route('app/llms.txt'), 'llms'],
|
||||
[route('app/llms-full.txt'), 'llms-full'],
|
||||
[route(frontend.multi ? 'app/md/[locale]/[[...slug]]' : 'app/md/[[...slug]]'), 'markdown'],
|
||||
[route('app/api/mcp'), 'mcp'],
|
||||
[route('app/api/health')],
|
||||
[route('app/indexnow-key.txt'), 'indexnow'],
|
||||
[tsx(`${fe}/layout`)],
|
||||
[ts(`${fe}/actions`)],
|
||||
[tsx(`${fe}/not-found`)],
|
||||
// the lazy 404's server action: .tsx when its fallback holds JSX (pages.md)
|
||||
[ts(`${fe}/notFoundView`)],
|
||||
[tsx(`${fe}/[[...slug]]/page`)],
|
||||
[ts('blocks/registry')],
|
||||
[ts('collections/Pages')],
|
||||
[ts('collections/Media')],
|
||||
[['components/layout']],
|
||||
[ts('components/forms/formClasses')],
|
||||
// components/ui/: blocks-ui-required (only without createBlockRegistry)
|
||||
]
|
||||
}
|
||||
@@ -74,10 +111,19 @@ export const layoutRules: DoctorRule[] = [
|
||||
id: 'layout-required',
|
||||
check: (ctx) => {
|
||||
if (!ctx.src) {return [{ message: 'no src/ folder (AGENT.md §3)', severity: 'error' }]}
|
||||
const missing = requiredFiles(ctx).filter(([file, key]) => !(key && ctx.auditSkips.has(key)) && !ctx.exists(`${ctx.src}${file}`))
|
||||
return missing.length
|
||||
? [{ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([f]) => `${ctx.src}${f}`).join(', ')}`, severity: 'error' }]
|
||||
: []
|
||||
const frontend = findFrontend(ctx)
|
||||
const out: RuleFinding[] = []
|
||||
if (frontend.missingOverride) {
|
||||
out.push({ file: 'ipal-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' })
|
||||
}
|
||||
if (frontend.ambiguous.length) {
|
||||
out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in ipal-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' })
|
||||
}
|
||||
const missing = requiredFiles(ctx, frontend).filter(([names, key]) => !(key && ctx.auditSkips.has(key)) && !names.some((n) => ctx.exists(`${ctx.src}${n}`)))
|
||||
if (missing.length) {
|
||||
out.push({ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
|
||||
group: 'layout',
|
||||
|
||||
@@ -42,7 +42,11 @@ export type DoctorConfig = {
|
||||
extraRules?: string[]
|
||||
/** true once the site is live: seeds must then name their records. */
|
||||
launched?: boolean
|
||||
layout?: { allow?: string[] }
|
||||
/**
|
||||
* `allow`: more top-level src/ entries. `frontend`: the folder that holds the site's pages, e.g. `src/app/(site)` —
|
||||
* by default the doctor finds it by structure (any route group with the catch-all page).
|
||||
*/
|
||||
layout?: { allow?: string[]; frontend?: string }
|
||||
rules?: Record<string, DoctorRuleSetting>
|
||||
/** First time a condition was seen (ISO date), e.g. `{ "csp-report-only": "2026-10-29" }`. */
|
||||
seen?: Record<string, string>
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* A seed run that ends early must fail loudly. `payload run` starts the CLI with `void start()` and then
|
||||
* `await import(script)`: when a seed script's top-level `await getPayload()` (or a later await) is left with
|
||||
* nothing that keeps Node's event loop alive, Node simply exits — code 0, no output. In Coolify's Terminal
|
||||
* that looks exactly like a successful run. The guard turns it into exit 1 with the reason.
|
||||
*
|
||||
* Dependency-free on purpose: no Payload, no Node imports — safe to import first in any seed script.
|
||||
*/
|
||||
|
||||
type ExitListener = () => void
|
||||
|
||||
/** The bits of `process` the guard uses — injectable for tests. */
|
||||
export type SeedExitProcess = {
|
||||
exit: (code: number) => void
|
||||
exitCode?: null | number | string
|
||||
off: (event: 'beforeExit', listener: ExitListener) => unknown
|
||||
on: (event: 'beforeExit', listener: ExitListener) => unknown
|
||||
}
|
||||
|
||||
export type SeedExitGuardOptions = {
|
||||
/** Prefix of the message. Default '[seed]'. */
|
||||
label?: string
|
||||
/** Where the message goes. Default stderr. */
|
||||
log?: (line: string) => void
|
||||
/** Default the real `process`. */
|
||||
process?: SeedExitProcess
|
||||
}
|
||||
|
||||
export type SeedExitGuard = {
|
||||
/** Stops watching (the run decides its exit code itself). */
|
||||
dispose: () => void
|
||||
/** The seed ended: `summary()` calls it. */
|
||||
finished: () => void
|
||||
/** Payload is up: `createSeeder` calls it. */
|
||||
initialized: () => void
|
||||
readonly state: 'finished' | 'initialized' | 'waiting'
|
||||
}
|
||||
|
||||
let active: null | SeedExitGuard = null
|
||||
|
||||
/** The guard of the current run, if the script started one (`createSeeder` and `summary()` report to it). */
|
||||
export function activeSeedExitGuard(): null | SeedExitGuard {
|
||||
return active
|
||||
}
|
||||
|
||||
/**
|
||||
* Call it first in a seed script, before `getPayload()`. Until `summary()` runs, an exit through an empty
|
||||
* event loop prints "[seed] ended before Payload initialized" (or "… before the seed finished") and exits 1.
|
||||
* A normal `process.exit(code)` — after the summary, on an error, or the guard's own refusal — is untouched.
|
||||
*/
|
||||
export function guardSeedExit(options: SeedExitGuardOptions = {}): SeedExitGuard {
|
||||
const proc: SeedExitProcess = options.process ?? process
|
||||
const label = options.label ?? '[seed]'
|
||||
const log = options.log ?? ((line: string) => {process.stderr.write(`${line}\n`)})
|
||||
let state: SeedExitGuard['state'] = 'waiting'
|
||||
|
||||
const onBeforeExit = () => {
|
||||
if (state === 'finished') {return}
|
||||
const when = state === 'waiting' ? 'before Payload initialized' : 'before the seed finished'
|
||||
log(
|
||||
`${label} ended ${when} — the run stopped early and nothing after that point was written. ` +
|
||||
'Exit code 1. Run it again; if it repeats, check the database connection and the seed script.',
|
||||
)
|
||||
proc.exitCode = 1
|
||||
proc.exit(1)
|
||||
}
|
||||
|
||||
const guard: SeedExitGuard = {
|
||||
dispose: () => {
|
||||
proc.off('beforeExit', onBeforeExit)
|
||||
if (active === guard) {active = null}
|
||||
},
|
||||
finished: () => {
|
||||
state = 'finished'
|
||||
},
|
||||
initialized: () => {
|
||||
if (state === 'waiting') {state = 'initialized'}
|
||||
},
|
||||
get state() {
|
||||
return state
|
||||
},
|
||||
}
|
||||
active?.dispose()
|
||||
proc.on('beforeExit', onBeforeExit)
|
||||
active = guard
|
||||
return guard
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
export { activeSeedExitGuard, guardSeedExit } from './exitGuard.js'
|
||||
export type { SeedExitGuard, SeedExitGuardOptions, SeedExitProcess } from './exitGuard.js'
|
||||
export { isLocalDatabase } from './guard.js'
|
||||
export { createSeeder } from './seeder.js'
|
||||
export type { Seeder, SeederOptions, SeedResult, SeedStatus, SeedSummary, UpsertOptions } from './seeder.js'
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { SeedTarget } from './values.js'
|
||||
|
||||
import { activeSeedExitGuard } from './exitGuard.js'
|
||||
import { isLocalDatabase, seedDatabaseUrl } from './guard.js'
|
||||
import {
|
||||
defaultHashField,
|
||||
@@ -178,6 +179,8 @@ const hasRef = (v: unknown): boolean =>
|
||||
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
|
||||
|
||||
export function createSeeder(payload: BasePayload, options: SeederOptions = {}): Seeder {
|
||||
// Payload is up (the caller passed it in) — the run's exit guard, if any, now waits for summary()
|
||||
activeSeedExitGuard()?.initialized()
|
||||
const env = process.env
|
||||
const dryRun = options.dryRun ?? (process.argv.includes('--dry-run') || env.SEED_DRY_RUN === '1')
|
||||
const update = options.update ?? env.SEED_UPDATE === '1'
|
||||
@@ -459,6 +462,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
|
||||
}
|
||||
|
||||
const summary = (): SeedSummary => {
|
||||
activeSeedExitGuard()?.finished()
|
||||
const result: SeedSummary = {
|
||||
created: counts.create,
|
||||
errors: counts.error,
|
||||
|
||||
+87
-10
@@ -25,19 +25,81 @@ export function isLocalizedValue(v: unknown, codes: string[]): v is Record<strin
|
||||
return isPlainObject(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
|
||||
}
|
||||
|
||||
/** The schema of the value being localized: its fields, or its block types (`blocks` field rows). */
|
||||
export type SeedSchema = { blocks?: Record<string, readonly SeedField[]>; fields?: readonly SeedField[] }
|
||||
|
||||
/** The slice of a Payload field config the seed helper reads. */
|
||||
export type SeedField = {
|
||||
blocks?: readonly ({ fields: readonly SeedField[]; slug: string } | string)[]
|
||||
fields?: readonly SeedField[]
|
||||
localized?: boolean
|
||||
name?: string
|
||||
tabs?: readonly { fields: readonly SeedField[]; name?: string }[]
|
||||
type: string
|
||||
}
|
||||
|
||||
/** Named fields at one level: rows, collapsibles and unnamed tabs add no path segment. */
|
||||
function namedFields(fields: readonly SeedField[] = []): Map<string, SeedField> {
|
||||
const out = new Map<string, SeedField>()
|
||||
for (const f of fields) {
|
||||
if (f.type === 'tabs') {
|
||||
for (const tab of f.tabs ?? []) {
|
||||
if (tab.name) {out.set(tab.name, { name: tab.name, type: 'group', fields: tab.fields })}
|
||||
else {for (const [k, v] of namedFields(tab.fields)) {out.set(k, v)}}
|
||||
}
|
||||
} else if (f.name) {out.set(f.name, f)}
|
||||
else if (f.fields) {for (const [k, v] of namedFields(f.fields)) {out.set(k, v)}}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The schema below a field: a group's or array's fields, or a blocks field's block types. */
|
||||
function schemaOf(field: SeedField | undefined, blockConfigs?: (slug: string) => readonly SeedField[] | undefined): SeedSchema | undefined {
|
||||
if (!field) {return undefined}
|
||||
if (field.type === 'blocks') {
|
||||
const blocks: Record<string, readonly SeedField[]> = {}
|
||||
for (const b of field.blocks ?? []) {
|
||||
if (typeof b === 'string') {
|
||||
const fields = blockConfigs?.(b)
|
||||
if (fields) {blocks[b] = fields}
|
||||
} else {blocks[b.slug] = b.fields}
|
||||
}
|
||||
return { blocks }
|
||||
}
|
||||
return field.fields ? { fields: field.fields } : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The value for one locale. Arrays (array fields, blocks) keep the ids of the
|
||||
* rows already stored at the same index — new ids would wipe the other
|
||||
* locales' texts. A block row keeps its id only when its blockType matches.
|
||||
* The value for one locale. Rows of arrays and blocks keep the ids of the rows
|
||||
* already stored at the same index — new ids would wipe the other locales' texts.
|
||||
* A block row keeps its id only when its blockType matches. A whole localized
|
||||
* value (`fields: { pl: [...], en: [...] }`) is localized again after its locale
|
||||
* is picked, so its rows keep the stored ids too.
|
||||
*
|
||||
* With `schema` (writeLocales passes the collection's or global's fields), a field
|
||||
* that is itself localized (`localized: true` array, blocks or group) gets no
|
||||
* stored ids: its rows belong to one locale and are never shared.
|
||||
* undefined = leave the field out.
|
||||
*/
|
||||
export function localize(value: unknown, locale: string | undefined, existing: unknown, codes: string[]): unknown {
|
||||
if (isLocalizedValue(value, codes)) {return locale ? value[locale] : undefined}
|
||||
export function localize(
|
||||
value: unknown,
|
||||
locale: string | undefined,
|
||||
existing: unknown,
|
||||
codes: string[],
|
||||
schema?: SeedSchema,
|
||||
blockConfigs?: (slug: string) => readonly SeedField[] | undefined,
|
||||
): unknown {
|
||||
if (isLocalizedValue(value, codes)) {
|
||||
const picked = locale ? value[locale] : undefined
|
||||
return picked === undefined ? undefined : localize(picked, locale, existing, codes, schema, blockConfigs)
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const rows = Array.isArray(existing) ? (existing as unknown[]) : []
|
||||
return value.map((item, i) => {
|
||||
const row = rows[i] as Record<string, unknown> | undefined
|
||||
const out = localize(item, locale, row, codes)
|
||||
const type = isPlainObject(item) && typeof item.blockType === 'string' ? item.blockType : undefined
|
||||
const rowSchema = schema?.blocks ? (type && schema.blocks[type] ? { fields: schema.blocks[type] } : undefined) : schema
|
||||
const out = localize(item, locale, row, codes, rowSchema, blockConfigs)
|
||||
if (!isPlainObject(out) || !row?.id) {return out ?? null}
|
||||
if (out.blockType !== undefined && row.blockType !== undefined && out.blockType !== row.blockType) {return out}
|
||||
return { ...out, id: row.id }
|
||||
@@ -45,9 +107,12 @@ export function localize(value: unknown, locale: string | undefined, existing: u
|
||||
}
|
||||
if (isPlainObject(value)) {
|
||||
const ex = isPlainObject(existing) ? existing : {}
|
||||
const fields = schema?.fields ? namedFields(schema.fields) : undefined
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const [k, v] of Object.entries(value)) {
|
||||
const r = localize(v, locale, ex[k], codes)
|
||||
const field = fields?.get(k)
|
||||
// A localized field's stored rows belong to another locale — never reuse their ids.
|
||||
const r = localize(v, locale, field?.localized ? undefined : ex[k], codes, schemaOf(field, blockConfigs), blockConfigs)
|
||||
if (r !== undefined) {out[k] = r}
|
||||
}
|
||||
return out
|
||||
@@ -132,6 +197,16 @@ export function editedSinceSeed({
|
||||
|
||||
export type SeedTarget = { collection: string; id: number | string } | { global: string }
|
||||
|
||||
/** The fields of a seed target (collection or global) and the config's shared blocks, for localize. */
|
||||
export function seedSchemaOf(payload: BasePayload, target: SeedTarget): { blockConfigs: (slug: string) => readonly SeedField[] | undefined; schema?: SeedSchema } {
|
||||
const config = payload.config as { blocks?: { fields: SeedField[]; slug: string }[]; collections?: { fields: SeedField[]; slug: string }[]; globals?: { fields: SeedField[]; slug: string }[] }
|
||||
const owner = 'global' in target ? config.globals?.find((g) => g.slug === target.global) : config.collections?.find((c) => c.slug === target.collection)
|
||||
return {
|
||||
blockConfigs: (slug) => config.blocks?.find((b) => b.slug === slug)?.fields,
|
||||
...(owner ? { schema: { fields: owner.fields } } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export type WriteLocalesOptions = {
|
||||
/** Passed to every write — see docs/seeding.md § Context flags. */
|
||||
context?: Record<string, unknown>
|
||||
@@ -161,20 +236,21 @@ export async function writeLocales(
|
||||
{ context = {}, draft = false }: WriteLocalesOptions = {},
|
||||
): Promise<void> {
|
||||
const { codes, defaultLocale } = localesOf(payload)
|
||||
const { blockConfigs, schema } = seedSchemaOf(payload, target)
|
||||
const local = (locale: string | undefined, rows: unknown) => localize(data, locale, rows, codes, schema, blockConfigs)
|
||||
const write = (value: unknown, locale: string | undefined) => {
|
||||
const loc = locale ? { fallbackLocale: false as never, locale: locale as never } : {}
|
||||
return 'global' in target
|
||||
? payload.updateGlobal({ slug: target.global as never, context, data: value as never, depth: 0, ...loc })
|
||||
: payload.update({ id: target.id, collection: target.collection as never, context, data: value as never, depth: 0, ...loc })
|
||||
}
|
||||
await write(localize(data, defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft), codes), defaultLocale)
|
||||
await write(local(defaultLocale, await readSeedTarget(payload, target, defaultLocale, draft)), defaultLocale)
|
||||
const others = codes.filter((c) => c !== defaultLocale)
|
||||
if (!others.length) {return}
|
||||
const rows = await readSeedTarget(payload, target, defaultLocale, draft)
|
||||
for (const locale of others) {await write(localize(data, locale, rows, codes), locale)}
|
||||
for (const locale of others) {await write(local(locale, rows), locale)}
|
||||
}
|
||||
|
||||
/** 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'])
|
||||
|
||||
@@ -189,6 +265,7 @@ export function isUnsetValue(value: unknown, field?: { defaultValue?: unknown; t
|
||||
return JSON.stringify(value) === JSON.stringify(field.defaultValue)
|
||||
}
|
||||
|
||||
/** True when a value has content (non-empty text, a number, true, or a nested one). */
|
||||
export function hasContent(v: unknown): boolean {
|
||||
if (typeof v === 'string') {return v.trim() !== ''}
|
||||
if (typeof v === 'number' || v === true) {return true}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, test } from 'vitest'
|
||||
|
||||
import { parseToolOutput } from '../src/modules/doctor/rules/tooling.js'
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
|
||||
const packageRoot = path.resolve(import.meta.dirname, '..')
|
||||
const scripts = path.join(packageRoot, 'docs/agent/skills/ipal-audit/scripts')
|
||||
let dirs: string[] = []
|
||||
|
||||
function project(files: Record<string, string>): string {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'ipal-polish-'))
|
||||
dirs.push(root)
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
const file = path.join(root, rel)
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
writeFileSync(file, content)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
/** `file:line` of every finding of the check. */
|
||||
function polish(files: Record<string, string>): string[] {
|
||||
const root = project(files)
|
||||
const out = execFileSync(process.execPath, [path.join(scripts, 'polish-literals.mjs'), 'src'], { cwd: root, encoding: 'utf8' })
|
||||
return out.split('\n').filter(Boolean).map((l) => l.match(/^(.+?:\d+):/)?.[1] ?? l)
|
||||
}
|
||||
|
||||
const HELPER = "import { adminText, rowLabel } from '@intecion/ipal-kit/blocks'\n"
|
||||
|
||||
afterEach(() => {
|
||||
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
|
||||
dirs = []
|
||||
})
|
||||
|
||||
describe('hardcoded Polish text: the panel labels are not public text', () => {
|
||||
test('adminText() in a schema file, on one line and over several', () => {
|
||||
expect(polish({
|
||||
'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [
|
||||
{ name: 'title', type: 'text', label: adminText('Title', 'Tytuł') },
|
||||
{ name: 'heading', type: 'text', label: adminText(
|
||||
'Heading',
|
||||
'Nagłówek',
|
||||
) },
|
||||
] }\n`,
|
||||
'src/globals/Header.ts': `${HELPER}export const Header = { slug: 'header', label: adminText('Header', 'Nagłówek') }\n`,
|
||||
})).toEqual([])
|
||||
})
|
||||
|
||||
test('{ en, pl } as label, singular, plural, description, placeholder, group, option label — one line and several', () => {
|
||||
expect(polish({
|
||||
'src/globals/Company.ts': `export const Company = { slug: 'company', admin: { group: { en: 'Company', pl: 'Dane firmy żółć' } }, fields: [
|
||||
{ name: 'areas', type: 'array', labels: { singular: { en: 'Area', pl: 'Obszar działania' }, plural: {
|
||||
en: 'Areas',
|
||||
pl: 'Obszary działania',
|
||||
} }, fields: [] },
|
||||
{ name: 'kind', type: 'select', label: {
|
||||
en: 'Social profiles',
|
||||
pl: 'Profile społecznościowe',
|
||||
}, admin: { description: { en: 'Where it shows', pl: 'Gdzie się wyświetla' }, placeholder: { en: 'Pick', pl: 'Wybierz coś ładnego ł' } }, options: [{ label: { en: 'Title', pl: 'Tytuł' }, value: 't' }] },
|
||||
] }\n`,
|
||||
})).toEqual([])
|
||||
})
|
||||
|
||||
test('an aliased import, rowLabel fallback, a typed AdminText constant, a file importing Payload types', () => {
|
||||
expect(polish({
|
||||
'src/fields/title.ts': `import { adminText as t, rowLabel } from '@intecion/ipal-kit/blocks'
|
||||
export const a = { label: t('Title', 'Tytuł'), admin: { components: rowLabel('x', { en: 'Item', pl: 'Pozycja ż' }) } }\n`,
|
||||
'src/lib/schema.ts': `import type { AdminText } from '@intecion/ipal-kit'
|
||||
import type { Field } from 'payload'
|
||||
const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' }
|
||||
export const f: Field = { name: 'title', type: 'text', label: { en: 'Title', pl: 'Tytuł' } }
|
||||
export const g = TITLE\n`,
|
||||
})).toEqual([])
|
||||
})
|
||||
|
||||
test('comments never count', () => {
|
||||
expect(polish({ 'src/components/A.tsx': "// 'Nagłówek'\n/* \"Tytuł\" */\nexport const A = () => null\n" })).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('hardcoded Polish text: public strings are still reported', () => {
|
||||
test('a public component with the same words, whichever form it uses', () => {
|
||||
expect(polish({
|
||||
'src/components/Hero.tsx': `${HELPER}export const Hero = () => (
|
||||
<section aria-label="Nagłówek">
|
||||
<Title text={'Tytuł'} label={adminText('Title', 'Tytuł')} other={{ label: { en: 'Heading', pl: 'Nagłówek' } }} />
|
||||
<Multi
|
||||
caption={{
|
||||
en: 'Social profiles',
|
||||
pl: 'Profile społecznościowe',
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
)\n`,
|
||||
})).toEqual(['src/components/Hero.tsx:3', 'src/components/Hero.tsx:4', 'src/components/Hero.tsx:8'])
|
||||
})
|
||||
|
||||
test('a block component next to its schema; a helper in lib without schema types', () => {
|
||||
expect(polish({
|
||||
'src/blocks/Hero/Component.tsx': "export const Hero = () => <h1 title=\"Nagłówek\" />\n",
|
||||
'src/blocks/Hero/config.ts': `${HELPER}export const Hero = { slug: 'hero', label: adminText('Heading', 'Nagłówek') }\n`,
|
||||
'src/lib/texts.ts': "export const labels = { label: { en: 'Title', pl: 'Tytuł' } }\n",
|
||||
})).toEqual(['src/blocks/Hero/Component.tsx:1', 'src/lib/texts.ts:1'])
|
||||
})
|
||||
|
||||
test('in a schema file: Polish only, another key, defaultValue, a lookalike helper, a client file', () => {
|
||||
expect(polish({
|
||||
'src/collections/Bad.ts': `${HELPER}export const Bad = { slug: 'bad', fields: [
|
||||
{ name: 'a', label: 'Tytuł' },
|
||||
{ name: 'b', label: { pl: 'Tytuł' } },
|
||||
{ name: 'c', heading: { en: 'Title', pl: 'Tytuł' } },
|
||||
{ name: 'd', defaultValue: 'Nagłówek' },
|
||||
{ name: 'e', defaultValue: adminText('Heading', 'Nagłówek') },
|
||||
{ name: 'f', defaultValue: {
|
||||
en: 'Heading',
|
||||
pl: 'Nagłówek',
|
||||
} },
|
||||
] }\n`,
|
||||
'src/globals/Client.ts': `'use client'\n${HELPER}export const x = { label: adminText('Title', 'Tytuł') }\n`,
|
||||
'src/globals/Lookalike.ts': "const adminText = (a: string, b: string) => b\nexport const x = { label: adminText('Title', 'Tytuł') }\n",
|
||||
})).toEqual([
|
||||
'src/collections/Bad.ts:3', 'src/collections/Bad.ts:4', 'src/collections/Bad.ts:5', 'src/collections/Bad.ts:6', 'src/collections/Bad.ts:7', 'src/collections/Bad.ts:10',
|
||||
'src/globals/Client.ts:3',
|
||||
'src/globals/Lookalike.ts:2',
|
||||
])
|
||||
})
|
||||
|
||||
test('adminText outside a schema file is reported; rowLabel only spares its { en, pl } fallback', () => {
|
||||
expect(polish({
|
||||
'src/fields/row.ts': `${HELPER}export const a = rowLabel('x', 'Pozycja ż')\nexport const b = rowLabel('Żółć', { en: 'Item', pl: 'Pozycja ż' })\n`,
|
||||
'src/lib/text.ts': `${HELPER}export const t = adminText('Title', 'Tytuł')\n`,
|
||||
})).toEqual(['src/fields/row.ts:2', 'src/fields/row.ts:3', 'src/lib/text.ts:2'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ipal-audit and ipal-doctor agree', () => {
|
||||
const files = {
|
||||
'package.json': JSON.stringify({ name: 'examplepl-web' }),
|
||||
'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [
|
||||
{ name: 'title', label: adminText('Title', 'Tytuł') },
|
||||
{ name: 'heading', label: {
|
||||
en: 'Heading',
|
||||
pl: 'Nagłówek',
|
||||
} },
|
||||
] }\n`,
|
||||
'src/components/Public.tsx': `${HELPER}export const Public = () => <p title="Nagłówek">{adminText('Title', 'Tytuł')}</p>\n`,
|
||||
}
|
||||
test('audit.sh and the i18n-literals rule report the public component only', async () => {
|
||||
const root = project(files)
|
||||
const audit = spawnSync('bash', [path.join(scripts, 'audit.sh'), '--quick'], { cwd: root, encoding: 'utf8' })
|
||||
const line = parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')
|
||||
expect(line?.level).toBe('error')
|
||||
expect(line?.items).toEqual([`src/components/Public.tsx:2:export const Public = () => <p title="Nagłówek">{adminText('Title', 'Tytuł')}</p>`])
|
||||
|
||||
const report = await runDoctor({ offline: true, only: ['audit'], packageRoot, root, writeSeen: false })
|
||||
const polishFindings = report.findings.filter((f) => f.rule === 'i18n-literals' && f.message.startsWith('hardcoded Polish'))
|
||||
expect(polishFindings.map((f) => f.file)).toEqual(['src/components/Public.tsx'])
|
||||
})
|
||||
|
||||
test('without TypeScript in reach the check still runs, as a plain grep', () => {
|
||||
const copy = project({ 'x.txt': '' })
|
||||
cpSync(scripts, path.join(copy, 'scripts'), { recursive: true })
|
||||
const root = project(files)
|
||||
const env = { ...process.env, NODE_PATH: '' } // pnpm's bin shims put its store on NODE_PATH
|
||||
const alone = spawnSync(process.execPath, [path.join(copy, 'scripts/polish-literals.mjs'), 'src'], { cwd: root, encoding: 'utf8', env })
|
||||
expect(alone.status).toBe(3)
|
||||
const audit = spawnSync('bash', [path.join(copy, 'scripts/audit.sh'), '--quick'], { cwd: root, encoding: 'utf8', env })
|
||||
expect(parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')?.items.join('\n')).toContain('src/components/Public.tsx')
|
||||
})
|
||||
|
||||
test('audit.sh passes when only schema labels hold Polish', () => {
|
||||
const { 'src/components/Public.tsx': _, ...schemaOnly } = files
|
||||
const audit = spawnSync('bash', [path.join(scripts, 'audit.sh'), '--quick'], { cwd: project(schemaOnly), encoding: 'utf8' })
|
||||
expect(parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -145,6 +145,44 @@ describe('db-name', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/** Every AGENT.md §3 file outside the frontend folder; `frontend` lists the files inside it. */
|
||||
function layoutProject(group: string, frontend: Record<string, string>, extra: Record<string, object | string> = {}) {
|
||||
const files: Record<string, object | string> = { ...base() }
|
||||
for (const f of ['proxy.ts', 'i18n.config.ts', 'instrumentation.ts', 'payload.config.ts', 'lib/content.ts', 'app/manifest.ts', 'app/robots.ts', 'app/sitemap.xml/route.ts', 'app/llms.txt/route.ts', 'app/llms-full.txt/route.ts', 'app/md/[locale]/[[...slug]]/route.ts', 'app/api/mcp/route.ts', 'app/api/health/route.ts', 'app/indexnow-key.txt/route.ts', 'blocks/registry.ts', 'collections/Pages.ts', 'collections/Media.ts', 'components/layout/Header.tsx', 'components/forms/formClasses.ts']) {files[`src/${f}`] = ''}
|
||||
for (const [f, content] of Object.entries(frontend)) {files[`src/app/${group}/${f}`] = content}
|
||||
return project({ ...files, ...extra })
|
||||
}
|
||||
const localizedFrontend = { '[locale]/[[...slug]]/page.tsx': '', '[locale]/actions.ts': '', '[locale]/layout.tsx': '', '[locale]/not-found.tsx': '', '[locale]/notFoundView.tsx': '' }
|
||||
|
||||
describe('frontend route group (layout-required)', () => {
|
||||
test('a (site) group with [locale] and notFoundView.tsx passes — the group name does not matter', async () => {
|
||||
const report = await doctor(layoutProject('(site)', localizedFrontend), ['layout-required'])
|
||||
expect(report.findings).toEqual([])
|
||||
})
|
||||
test('pages without a route group (app/[locale]) are found too', async () => {
|
||||
expect((await doctor(layoutProject('', localizedFrontend), ['layout-required'])).findings).toEqual([])
|
||||
})
|
||||
test('layout.frontend wins; a folder that does not exist is reported', async () => {
|
||||
const root = layoutProject('(web)', localizedFrontend, { 'src/app/(other)/[[...slug]]/page.tsx': '' })
|
||||
expect((await doctor(root, ['layout-required'], { config: { layout: { frontend: 'src/app/(web)' } } })).findings).toEqual([])
|
||||
const wrong = await doctor(root, ['layout-required'], { config: { layout: { frontend: 'src/app/(nope)' } } })
|
||||
expect(wrong.findings.map((f) => f.message)[0]).toBe('layout.frontend "src/app/(nope)" does not exist')
|
||||
})
|
||||
test('two localized groups: the ambiguity is reported, (frontend) is checked', async () => {
|
||||
const root = layoutProject('(site)', localizedFrontend, Object.fromEntries(Object.keys(localizedFrontend).map((f) => [`src/app/(frontend)/${f}`, ''])))
|
||||
const report = await doctor(root, ['layout-required'])
|
||||
expect(report.findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([
|
||||
'warning: several folders hold the site\'s pages: src/app/(frontend), src/app/(site) — checked src/app/(frontend)',
|
||||
])
|
||||
})
|
||||
test('a localized group wins over a single-language one; a missing page names the group it checked', async () => {
|
||||
const { '[locale]/actions.ts': _, ...withoutActions } = localizedFrontend
|
||||
const root = layoutProject('(site)', withoutActions, { 'src/app/(landing)/[[...slug]]/page.tsx': '' })
|
||||
const report = await doctor(root, ['layout-required'])
|
||||
expect(report.findings.map((f) => f.message)).toEqual(['missing: src/app/(site)/[locale]/actions.ts'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('layout, blocks, seeds, agents', () => {
|
||||
test('missing convention files and forbidden copies', async () => {
|
||||
const root = project({ ...base(), 'src/middleware.ts': '', 'src/payload.config.ts': '', 'src/scripts/x.ts': '' })
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import path from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { activeSeedExitGuard, createSeeder, guardSeedExit, type SeedExitProcess } from '../src/exports/seed.js'
|
||||
|
||||
const guardFile = pathToFileURL(path.resolve(import.meta.dirname, '../src/modules/seed/exitGuard.ts')).href
|
||||
|
||||
/** A `process` stand-in: `beforeExit` is emitted by the test, `exit` is recorded. */
|
||||
function fakeProcess() {
|
||||
const emitter = new EventEmitter()
|
||||
const exits: number[] = []
|
||||
const proc: { exitCode?: null | number | string } & SeedExitProcess = {
|
||||
exit: (code) => {exits.push(code)},
|
||||
off: (event, listener) => emitter.off(event, listener),
|
||||
on: (event, listener) => emitter.on(event, listener),
|
||||
}
|
||||
return { emit: () => emitter.emit('beforeExit'), exits, listeners: () => emitter.listenerCount('beforeExit'), proc }
|
||||
}
|
||||
|
||||
afterEach(() => activeSeedExitGuard()?.dispose())
|
||||
|
||||
describe('guardSeedExit', () => {
|
||||
it('fails a run that ends before Payload initialized', () => {
|
||||
const fake = fakeProcess()
|
||||
const lines: string[] = []
|
||||
guardSeedExit({ log: (l) => lines.push(l), process: fake.proc })
|
||||
fake.emit()
|
||||
expect(fake.exits).toEqual([1])
|
||||
expect(fake.proc.exitCode).toBe(1)
|
||||
expect(lines[0]).toMatch(/^\[seed\] ended before Payload initialized/)
|
||||
})
|
||||
|
||||
it('fails a run that ends after createSeeder but before summary()', () => {
|
||||
const fake = fakeProcess()
|
||||
const lines: string[] = []
|
||||
const guard = guardSeedExit({ label: '[seed-form]', log: (l) => lines.push(l), process: fake.proc })
|
||||
createSeeder({ config: { localization: false } } as never, { guard: false, log: () => {} })
|
||||
expect(guard.state).toBe('initialized')
|
||||
fake.emit()
|
||||
expect(fake.exits).toEqual([1])
|
||||
expect(lines[0]).toMatch(/^\[seed-form\] ended before the seed finished/)
|
||||
})
|
||||
|
||||
it('leaves a finished run alone (summary() ends it), and dispose() removes the listener', () => {
|
||||
const fake = fakeProcess()
|
||||
const guard = guardSeedExit({ log: () => {}, process: fake.proc })
|
||||
const seed = createSeeder({ config: { localization: false } } as never, { guard: false, log: () => {} })
|
||||
seed.summary()
|
||||
expect(guard.state).toBe('finished')
|
||||
fake.emit()
|
||||
expect(fake.exits).toEqual([])
|
||||
guard.dispose()
|
||||
expect(fake.listeners()).toBe(0)
|
||||
expect(activeSeedExitGuard()).toBeNull()
|
||||
})
|
||||
|
||||
it('a second guard replaces the first (one listener)', () => {
|
||||
const fake = fakeProcess()
|
||||
guardSeedExit({ log: () => {}, process: fake.proc })
|
||||
const second = guardSeedExit({ log: () => {}, process: fake.proc })
|
||||
expect(fake.listeners()).toBe(1)
|
||||
expect(activeSeedExitGuard()).toBe(second)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The real thing in a child process, started the way `payload run` starts a script: `void start()` and
|
||||
* `await import(script)`. Exit codes and messages must match what an operator sees in Coolify's Terminal.
|
||||
*/
|
||||
describe('guardSeedExit in a real process', () => {
|
||||
const run = (body: string) => {
|
||||
const script = `import { guardSeedExit } from '${guardFile}'
|
||||
const start = async () => {
|
||||
try {
|
||||
${body}
|
||||
} catch (error) {
|
||||
console.error('Error running script:', error.message)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
void start()`
|
||||
return spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20_000 })
|
||||
}
|
||||
|
||||
it('an await that never settles: exit 1 with the reason, not a silent 0', () => {
|
||||
const r = run(`guardSeedExit()\n await new Promise(() => {}) // getPayload() left with nothing keeping the loop alive`)
|
||||
expect(r.status).toBe(1)
|
||||
expect(r.stderr).toMatch(/\[seed\] ended before Payload initialized/)
|
||||
})
|
||||
|
||||
it('without the guard the same script exits 0 silently (the failure the guard exists for)', () => {
|
||||
const r = run(`await new Promise(() => {})`)
|
||||
expect(r.status).toBe(0)
|
||||
expect(`${r.stdout}${r.stderr}`).toBe('')
|
||||
})
|
||||
|
||||
it('a finished run exits with its own code; an error and a refusal keep exit 1 and their message', () => {
|
||||
expect(run(`const g = guardSeedExit()\n g.initialized(); g.finished()\n console.log('summary')\n process.exit(0)`)).toMatchObject({ status: 0, stdout: 'summary\n' })
|
||||
const failed = run(`const g = guardSeedExit()\n g.initialized(); g.finished()\n process.exit(1)`)
|
||||
expect(failed.status).toBe(1)
|
||||
expect(failed.stderr).not.toMatch(/ended before/)
|
||||
const refused = run(`guardSeedExit()\n throw new Error('[seed] full seed refused: NODE_ENV=production and no record list.')`)
|
||||
expect(refused.status).toBe(1)
|
||||
expect(refused.stderr).toMatch(/full seed refused/)
|
||||
expect(refused.stderr).not.toMatch(/ended before/)
|
||||
})
|
||||
|
||||
it('a dry run that ends naturally after summary() exits 0', () => {
|
||||
const r = run(`const g = guardSeedExit()\n g.initialized(); g.finished()`)
|
||||
expect(r.status).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { Block, Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { createSeeder } from '../src/exports/seed.js'
|
||||
import { localize } from '../src/modules/seed/values.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
/**
|
||||
* Regression (vanstevpl-web, 1.15.3): a whole localized value — `fields: { pl: [...], en: [...], de: [...] }` —
|
||||
* must keep the stored row ids in every locale. Before the fix each locale write made new shared rows and only
|
||||
* the last language survived (forms, nested select options, page layouts, global arrays).
|
||||
*/
|
||||
const LOCALES = ['pl', 'en', 'de'] as const
|
||||
const confirmation = (text: string) => ({
|
||||
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
|
||||
})
|
||||
|
||||
/** One form, written per locale as whole localized arrays — shared blocks with nested options. */
|
||||
const formFields = (lang: { name: string; topic: string; topics: [string, string] }) => [
|
||||
{ name: 'name', blockType: 'text', label: lang.name, required: true },
|
||||
{
|
||||
name: 'topic',
|
||||
blockType: 'select',
|
||||
label: lang.topic,
|
||||
options: [
|
||||
{ label: lang.topics[0], value: 'offer' },
|
||||
{ label: lang.topics[1], value: 'other' },
|
||||
],
|
||||
},
|
||||
]
|
||||
const FORM = {
|
||||
confirmationMessage: { de: confirmation('Danke'), en: confirmation('Thanks'), pl: confirmation('Dziękujemy') },
|
||||
confirmationType: 'message',
|
||||
fields: {
|
||||
de: formFields({ name: 'Vorname', topic: 'Thema', topics: ['Angebot', 'Sonstiges'] }),
|
||||
en: formFields({ name: 'First name', topic: 'Topic', topics: ['Offer', 'Other'] }),
|
||||
pl: formFields({ name: 'Imię', topic: 'Temat', topics: ['Oferta', 'Inne'] }),
|
||||
},
|
||||
submitButtonLabel: { de: 'Senden', en: 'Send', pl: 'Wyślij' },
|
||||
title: 'Contact form',
|
||||
}
|
||||
|
||||
const section = (heading: string, items: string[]) => ({ blockType: 'section', heading, items: items.map((text) => ({ text })) })
|
||||
|
||||
describe('createSeeder: whole localized arrays keep every language', () => {
|
||||
let payload: Payload
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv('DATABASE_URI', 'file::memory:')
|
||||
const sectionBlock: Block = {
|
||||
slug: 'section',
|
||||
fields: [
|
||||
{ name: 'heading', type: 'text', localized: true },
|
||||
{ name: 'items', type: 'array', fields: [{ name: 'text', type: 'text', localized: true }] },
|
||||
],
|
||||
}
|
||||
const config = buildTestConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', localized: true },
|
||||
{ name: 'slug', type: 'text', index: true, localized: true },
|
||||
// Shared rows, text per locale (the block library's default).
|
||||
{ name: 'layout', type: 'blocks', blocks: [sectionBlock] },
|
||||
// Rows per locale (the block library's `localization: 'layout'`).
|
||||
{ name: 'localizedLayout', type: 'blocks', blocks: [sectionBlock], localized: true },
|
||||
],
|
||||
},
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-arrays') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
globals: [
|
||||
{
|
||||
slug: 'footer',
|
||||
fields: [{ name: 'links', type: 'array', fields: [{ name: 'label', type: 'text', localized: true }, { name: 'url', type: 'text' }] }],
|
||||
},
|
||||
],
|
||||
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
|
||||
plugins: [
|
||||
ipalKit({
|
||||
forms: {},
|
||||
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
|
||||
pages: { slug: 'pages' },
|
||||
twoFactor: false,
|
||||
} as never),
|
||||
],
|
||||
secret: 'seed-localized-arrays',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
vi.unstubAllEnvs()
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
const seeder = () => createSeeder(payload, { dryRun: false, log: () => {}, update: false })
|
||||
const readAll = (collection: string, id: number | string) =>
|
||||
payload.findByID({ id, collection: collection as never, depth: 0, fallbackLocale: false as never, locale: 'all' as never }) as Promise<Record<string, unknown>>
|
||||
|
||||
test('a form: blocks and nested select options keep every language and one set of row ids', async () => {
|
||||
const result = await seeder().upsertBy('forms', { title: 'Contact form' }, FORM)
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
|
||||
const all = await readAll('forms', result.id!)
|
||||
const fields = all.fields as { id: string; label: Record<string, string>; options?: { id: string; label: Record<string, string> }[] }[]
|
||||
expect(fields).toHaveLength(2)
|
||||
expect(fields[0].label).toEqual({ de: 'Vorname', en: 'First name', pl: 'Imię' })
|
||||
expect(fields[1].label).toEqual({ de: 'Thema', en: 'Topic', pl: 'Temat' })
|
||||
expect(fields[1].options?.map((o) => o.label)).toEqual([
|
||||
{ de: 'Angebot', en: 'Offer', pl: 'Oferta' },
|
||||
{ de: 'Sonstiges', en: 'Other', pl: 'Inne' },
|
||||
])
|
||||
expect(all.submitButtonLabel).toEqual({ de: 'Senden', en: 'Send', pl: 'Wyślij' })
|
||||
|
||||
// Every locale reads the same rows.
|
||||
const ids = async (locale: string) => {
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'forms', depth: 0, fallbackLocale: false, locale: locale as never })) as unknown as { fields: { id: string; options?: { id: string }[] }[] }
|
||||
return doc.fields.flatMap((f) => [f.id, ...(f.options ?? []).map((o) => o.id)])
|
||||
}
|
||||
const pl = await ids('pl')
|
||||
expect(await ids('en')).toEqual(pl)
|
||||
expect(await ids('de')).toEqual(pl)
|
||||
|
||||
// An editor's later save in Polish validates (no missing option labels).
|
||||
const plDoc = await payload.findByID({ id: result.id!, collection: 'forms', depth: 0, fallbackLocale: false, locale: 'pl' })
|
||||
await expect(payload.update({ id: result.id!, collection: 'forms', data: { ...plDoc, submitButtonLabel: 'Wyślij teraz' } as never, locale: 'pl' })).resolves.toBeTruthy()
|
||||
const after = await readAll('forms', result.id!)
|
||||
expect((after.fields as { label: Record<string, string> }[])[0].label).toEqual({ de: 'Vorname', en: 'First name', pl: 'Imię' })
|
||||
})
|
||||
|
||||
test('a page: a shared layout keeps one set of rows; a localized layout keeps rows per locale', async () => {
|
||||
const page = {
|
||||
slug: { de: 'ueber-uns', en: 'about', pl: 'o-nas' },
|
||||
layout: {
|
||||
de: [section('Leistungen', ['Planung', 'Bau'])],
|
||||
en: [section('Services', ['Design', 'Build'])],
|
||||
pl: [section('Usługi', ['Projekt', 'Budowa'])],
|
||||
},
|
||||
localizedLayout: {
|
||||
de: [section('Nur Deutsch', ['Eins'])],
|
||||
en: [section('English only', ['One', 'Two', 'Three'])],
|
||||
pl: [section('Tylko polski', ['Jeden', 'Dwa'])],
|
||||
},
|
||||
title: { de: 'Über uns', en: 'About', pl: 'O nas' },
|
||||
}
|
||||
const [result] = await seeder().upsertBySlug('pages', [page])
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
|
||||
const all = await readAll('pages', result.id!)
|
||||
const layout = all.layout as { heading: Record<string, string>; id: string; items: { text: Record<string, string> }[] }[]
|
||||
expect(layout).toHaveLength(1)
|
||||
expect(layout[0].heading).toEqual({ de: 'Leistungen', en: 'Services', pl: 'Usługi' })
|
||||
expect(layout[0].items.map((i) => i.text)).toEqual([
|
||||
{ de: 'Planung', en: 'Design', pl: 'Projekt' },
|
||||
{ de: 'Bau', en: 'Build', pl: 'Budowa' },
|
||||
])
|
||||
|
||||
// Localized layout: each language has its own rows, with its own length.
|
||||
for (const [locale, heading, count] of [['pl', 'Tylko polski', 2], ['en', 'English only', 3], ['de', 'Nur Deutsch', 1]] as const) {
|
||||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { localizedLayout: { heading: string; items: unknown[] }[] }
|
||||
expect(doc.localizedLayout[0]).toMatchObject({ heading })
|
||||
expect(doc.localizedLayout[0].items).toHaveLength(count)
|
||||
}
|
||||
})
|
||||
|
||||
test('a global array (fillGlobal) keeps every language', async () => {
|
||||
const links = (labels: [string, string]) => [
|
||||
{ label: labels[0], url: '/kontakt' },
|
||||
{ label: labels[1], url: '/blog' },
|
||||
]
|
||||
const result = await seeder().fillGlobal('footer', {
|
||||
links: { de: links(['Kontakt', 'Blog']), en: links(['Contact', 'Blog']), pl: links(['Kontakt', 'Wpisy']) },
|
||||
})
|
||||
expect(result).toMatchObject({ status: 'create' })
|
||||
const all = (await payload.findGlobal({ slug: 'footer' as never, depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as { links: { label: Record<string, string>; url: string }[] }
|
||||
expect(all.links.map((l) => l.label)).toEqual([
|
||||
{ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' },
|
||||
{ de: 'Blog', en: 'Blog', pl: 'Wpisy' },
|
||||
])
|
||||
expect(all.links.map((l) => l.url)).toEqual(['/kontakt', '/blog'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('localize', () => {
|
||||
test('a whole localized value keeps the stored row ids, nested arrays included', () => {
|
||||
const stored = [{ id: 'a', options: [{ id: 'o1', label: 'Oferta' }] }]
|
||||
const value = { en: [{ options: [{ label: 'Offer' }] }], pl: [{ options: [{ label: 'Oferta' }] }] }
|
||||
expect(localize(value, 'en', stored, ['pl', 'en'])).toEqual([{ id: 'a', options: [{ id: 'o1', label: 'Offer' }] }])
|
||||
expect(localize(value, 'de', stored, ['pl', 'en', 'de'])).toBeUndefined()
|
||||
})
|
||||
|
||||
test('with a schema, a localized field never reuses another locale’s rows', () => {
|
||||
const schema = { fields: [{ name: 'layout', type: 'array', fields: [{ name: 'text', type: 'text' }], localized: true }] }
|
||||
const stored = { layout: [{ id: 'pl-row', text: 'Polski' }] }
|
||||
expect(localize({ layout: { en: [{ text: 'English' }] } }, 'en', stored, ['pl', 'en'], schema)).toEqual({ layout: [{ text: 'English' }] })
|
||||
expect(localize({ layout: { en: [{ text: 'English' }] } }, 'en', stored, ['pl', 'en'])).toEqual({ layout: [{ id: 'pl-row', text: 'English' }] })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user