Compare commits

..
8 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 755f510c9f 1.15.5 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.5" section. PROGRAMISTA §6: item 60. Reference site: skills
and the AGENTS.md pointer on 1.15.5; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 970307f3ab 1.15.5
Version bump; the Unreleased section becomes 1.15.5: required fields with
references are seeded complete; a stricter dry run (missing $form / $page is an
error there too). What projects must update: nothing required; a required reference
cycle now fails clearly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław Smoliński c7e198fd92 Merge claude/seeder-required-refs: required fields with references are created complete
createSeeder's first pass resolves { $page } / { $form } references to existing
records, so a required layout is created complete; a forward $page is filled in
pass 2 and a record whose required field needs it waits for that page. Required
cycles and never-appearing targets are an error with nothing written; the dry run
reports the same, including a missing $form. Guards, create-only, the edit check
and SEED_ONLY are unchanged. Reported from vanstevpl-web.
2026-11-13 14:31:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 748ef9286f Seeder: required fields with references are created complete (1.15.5)
A page whose required layout holds a { $page } / { $form } reference could not be
created: pass 1 left the whole field out, validation rejected the record, and the
dry run reported a create (vanstevpl-web, 1.15.4).

- pass 1 resolves references to records that exist (or were created earlier in
  the run), so the field is written complete
- a { $page } to a page later in the same call is null in pass 1 and filled in
  pass 2; a record whose required field needs it is retried once that page exists
- required links in a cycle and references to pages or forms that never appear
  are an error with nothing written; unknown page targets are found while
  planning, so the dry run reports them too
- dry run: a missing form is an error (was a placeholder); a form planned earlier
  in the same dry run counts as existing
- real-Payload tests (pl, en, de): the report's careers page, an existing form
  target, optional and required forward links, a cycle, missing page and form,
  create-only second runs, dry-run parity
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:29:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 179d5b0d79 1.15.4 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.4" section (repair with SEED_UPDATE, live site with SEED_ONLY,
edited records and global arrays by hand). PROGRAMISTA §6: item 59. Reference site:
skills and the AGENTS.md pointer on 1.15.4; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f00fe3ad6 1.15.4
Version bump; the Unreleased section becomes 1.15.4: seeding whole localized arrays
keeps every language. What projects must update: nothing required; repairing records
an earlier seed wrote needs SEED_UPDATE=1 (locally first; on production with SEED_ONLY
and IPAL_SEED_ALLOW_PROD_UPDATE=1 after a backup), edited records and global arrays
by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:26 +01:00
Radosław Smoliński a79740cd44 Merge claude/seeder-localized-arrays: whole localized arrays keep every language
createSeeder / writeLocales: a value seeded per language as a whole (form fields,
nested select options, page layouts, global arrays) keeps the stored row ids in
every locale instead of only the last language surviving; localized: true fields
keep rows per locale. Seed guards, the edit check and SEED_ONLY are unchanged.
Reported from vanstevpl-web.
2026-11-12 15:35:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 00e814e3ca Seeder: whole localized arrays keep every language (1.15.4)
createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:33:35 +01:00
14 changed files with 699 additions and 45 deletions
+42
View File
@@ -8,6 +8,48 @@ 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.5
### Fixed
- **Seeding a required field with references** (`createSeeder`, `upsertBySlug` / `upsertBy`): a page whose required
`layout` holds a `{ $page }` or `{ $form }` reference can be created. The first pass used to leave the whole field out,
so validation rejected the record ("The following field is invalid: … > Layout") while the dry run reported a create.
Now references to records that exist are resolved in the first pass, so the field is written complete. A link to a
page created later in the same call is filled in the second pass, and a record whose required field needs that page
waits until it exists. Required links in a cycle, and links to a page or form that never appears, are an error with
nothing written. The dry run now reports the same outcome, including a missing form. Seed scripts need no change.
### Changed
- **A stricter dry run:** `SEED_DRY_RUN=1` with a `{ $form }` to a form that neither exists nor is seeded earlier in the
same run is now an error, as the real run would be (before, the dry run printed a placeholder and reported a create).
The same holds for a `{ $page }` that never appears.
### What projects must update
- Nothing is required: seed scripts need no change.
- A seed with a required reference cycle (two new pages whose required fields link to each other) now stops with a
clear error naming the pages, and nothing is written for them; make one of the links optional or seed one page
first. Before, such a run could look successful in the dry run and fail on validation in the real one.
- A dry run that now reports a missing form or page: seed that record first (or create it in the panel), then run again.
## 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
+1 -1
View File
@@ -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.3 ("Example Studio", made up) that uses
The reference site is one complete client site on ipal-kit 1.15.5 ("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:
@@ -558,13 +558,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `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`). |
+18
View File
@@ -236,6 +236,24 @@ and the browser tab shows the same separator.
**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.
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
an error. Seed that record first or create it in the panel.
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
## 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):
+2
View File
@@ -666,6 +666,8 @@ Do one item at a time, build, check. Order by importance:
| 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 |
| 60 | **1.15.5** — a seeded page with a required layout linking to a page or form fails validation ("… > Layout") | nothing to change in the seed; run it again (dry run first); a missing `$form` / `$page` is now an error in the dry run too; a required link cycle: make one link optional | CHANGELOG 1.15.5, 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`.
+18 -2
View File
@@ -197,14 +197,30 @@ 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:
is an error for that record, never an empty relation.
**References and required fields.** A new record is created complete, so a required field (a `layout` whose block
links to a page or form) passes validation:
- a reference to a record that exists — or was created earlier in the run — becomes its ID in the first write;
- a `{ $page }` to a page created later **in the same `upsertBySlug` call** is filled in the second pass; when the
field that holds it is required, the record waits until that page exists. Pages that link to each other belong in
one call (an array);
- required links in a cycle (A needs B, B needs A) and a reference to a page or form that does not exist and is not
planned are an **error** for those records, and nothing is written for them. Make one of the links optional, or seed
one of the pages first;
- the dry run reports the same outcome. A form planned earlier in the same dry run counts as existing. Only a required
cycle shows up first in the real run, because the dry run does not validate fields. Ready pages made of library blocks:
`pageTemplates` in [block-library.md](./block-library.md#page-templates).
| Method | What it does |
|---|---|
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (without fields that hold `$page` / `$form` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBySlug(collection, data \| data[], { slugField })` | matches by the default-locale slug (`slugField`, default `slug`). With an array, missing records are created first (references to existing records resolved, links to pages later in the call filled in pass 2; a required one waits for its page), then every record gets its full content, so pages can link to each other in any order. Unknown targets and required cycles: error, nothing written |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). A choice — select, radio, checkbox, number, date — still at the field's `defaultValue` counts as empty (Payload stores defaults on the first save, so `defaultTheme: 'system'` can be seeded over `light`); text is never treated so, even when it equals a default. A field that already holds exactly the seeded value is not written (`skip (exists)`), so re-running a seed of defaults changes nothing. With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.15.3",
"version": "1.15.5",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -558,13 +558,13 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
| Export | Import from | What it does / when |
|---|---|---|
| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, formsCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local, only }`. `only` (or `SEED_ONLY`) = the records the run may touch (`pages:kontakt`, `forms:<title>`, `global:<slug>`, `pages:*`), the rest → `skip (not listed)`; a run without it against production / a non-local database throws unless `IPAL_SEED_ALLOW_FULL=1` / `guard.allowFull: true` (after launch: named records only; dry runs are never refused; `guard: false` turns every guard off). Create-only by default, natural keys, never deletes, globals: empty fields only, every locale with `fallbackLocale: false` onto the same row ids, skips records edited since seeding, writes with `context` `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }`. Throws when `update` runs on production / a non-local database without `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Both seed templates use it. |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). |
| `upsertBySlug(collection, data \| data[], { slugField? })` | (method of `createSeeder`) | Matches by the default-locale slug; an array creates missing records first, so `{ $page: 'slug' }` links work in any order; `{ $form: 'title' }` = the form's id (`formsCollection`, default `forms`). A required field (layout) with references is written complete in the first write; a link to a page later in the same call waits for it; required cycles and unknown targets are an error with nothing written; the dry run reports the same. |
| `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`). |
@@ -236,6 +236,24 @@ and the browser tab shows the same separator.
**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.
**→ 1.15.5 (PROGRAMISTA §6, item 60; required fields with references in seeds; seeding.md) — nothing required:**
1. A seed that failed with "The following field is invalid: … > Layout" for a page whose required layout links to
another page or a form: run it again — the record is now created complete (`SEED_DRY_RUN=1` first).
2. The dry run is stricter: a `{ $form }` / `{ $page }` to a record that neither exists nor is seeded earlier in the run is
an error. Seed that record first or create it in the panel.
3. A "cycle of required links" error: make one of the two links optional, or seed one of the pages first.
**Check:** `SEED_DRY_RUN=1 pnpm seed` reports 0 errors; the real run creates the same records.
## 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
View File
@@ -47,7 +47,7 @@ Write everything in this file in English.
<!-- /starter:decisions -->
<!-- ipal-kit:start -->
## ipal-kit 1.15.3 — agent guide
## ipal-kit 1.15.5 — 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:
+107 -26
View File
@@ -172,11 +172,22 @@ const formRef = (v: object): string | undefined => {
return typeof ref === 'string' ? ref : undefined
}
/** True when the value holds a { $page } or { $form } reference — such fields are written once refs resolve. */
const hasRef = (v: unknown): boolean =>
Array.isArray(v)
? v.some(hasRef)
: !!v && typeof v === 'object' && (typeof (v as { $page?: unknown }).$page === 'string' || formRef(v) !== undefined || Object.values(v).some(hasRef))
const pageRef = (v: object): string | undefined => {
const ref = (v as { $page?: unknown }).$page
return typeof ref === 'string' ? ref : undefined
}
/** The default-locale slugs of the { $page } references a value holds. */
const pageRefsIn = (v: unknown, out = new Set<string>()): Set<string> => {
if (Array.isArray(v)) {v.forEach((x) => pageRefsIn(x, out))}
else if (v && typeof v === 'object') {
const ref = pageRef(v)
if (ref !== undefined) {out.add(ref)}
else {Object.values(v).forEach((x) => pageRefsIn(x, out))}
}
return out
}
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()
@@ -229,6 +240,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
const localeKeys = codes.length ? codes : [undefined]
const counts: Record<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, 'skip (not listed)': 0, update: 0 }
const pageIds = new Map<string, number | string>()
/** Forms planned for creation in a dry run, by title — a later { $form } to them is not an error. */
const plannedForms = new Set<string>()
log(
`${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'} · ${only ? `only: ${only.join(', ')}` : 'all records'}\n`,
@@ -278,11 +291,12 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
if (form !== undefined) {
const id = await findId(formsCollection, { title: form })
if (id !== undefined) {return id}
if (lenient || dryRun) {return `(form:${form})`}
// A dry run reports what the real run would do: a form planned earlier in this run will exist.
if (lenient || (dryRun && plannedForms.has(form))) {return `(form:${form})`}
throw new Error(`$form "${form}" not found — seed that form first or create it in the panel`)
}
const ref = (v as { $page?: unknown }).$page
if (typeof ref === 'string') {
const ref = pageRef(v)
if (ref !== undefined) {
let id = pageIds.get(ref)
if (id === undefined) {
id = await findId(pagesCollection, { slug: ref })
@@ -299,6 +313,34 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
return out
}
/**
* The first-pass value of a record being created: references to records that exist now become their ids,
* so a required field (a layout whose block links to a page) is written complete. A { $page } to a page
* planned in the same call and not created yet (`forward`) becomes null and is collected; pass 2 writes it.
* Any other unknown target throws — nothing is written for that record.
*/
const resolveForCreate = async (v: unknown, forward: Set<string>, planned: Set<string>): Promise<unknown> => {
if (Array.isArray(v)) {return Promise.all(v.map((x) => resolveForCreate(x, forward, planned)))}
if (!v || typeof v !== 'object') {return v}
if (formRef(v) !== undefined) {return resolveRefs(v)}
const ref = pageRef(v)
if (ref !== undefined) {
const known = pageIds.get(ref) ?? (await findId(pagesCollection, { slug: ref }))
if (known !== undefined) {
pageIds.set(ref, known)
return known
}
if (planned.has(ref)) {
forward.add(ref)
return null
}
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
}
const out: Record<string, unknown> = {}
for (const [k, x] of Object.entries(v)) {out[k] = await resolveForCreate(x, forward, planned)}
return out
}
/** Per-locale seed values (refs resolved) — what the hash describes. */
const perLocale = (data: unknown) => Object.fromEntries(localeKeys.map((l) => [l ?? '-', localize(data, l, undefined, codes)]))
@@ -325,6 +367,7 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
// Plan: one status per record, decided before anything is written.
const plan: Planned[] = []
const plannedHere = new Set(trackPages ? items.map((i) => i.key.slug).filter((s): s is string => typeof s === 'string') : [])
for (const item of items) {
const p: Planned = { ...item }
plan.push(p)
@@ -332,8 +375,14 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
p.id = await findId(collection, item.key)
const slug = typeof item.key.slug === 'string' ? item.key.slug : undefined
if (p.id === undefined) {
// Every { $page } must exist already or be planned in this call — otherwise nothing is written (dry run too).
for (const ref of pageRefsIn(item.data)) {
if (plannedHere.has(ref) || pageIds.has(ref) || (await findId(pagesCollection, { slug: ref })) !== undefined) {continue}
throw new Error(`$page "${ref}" not found — seed that page first or create it in the panel`)
}
p.action = 'create'
if (dryRun && trackPages && slug) {pageIds.set(slug, `(new:${slug})`)}
if (dryRun && collection === formsCollection && typeof item.key.title === 'string') {plannedForms.add(item.key.title)}
continue
}
if (trackPages && slug) {pageIds.set(slug, p.id)}
@@ -352,27 +401,59 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}):
}
}
// Pass 1: create missing records without fields that reference other pages (they may not exist yet).
// Pass 1: create missing records complete — references to existing records resolved. A forward { $page }
// (a page created later in this call) is null for now; a record whose required field needs it is retried
// once that page exists. Required references in a cycle, or to a page that never appears, are an error
// and nothing is written for those records.
if (!dryRun) {
for (const p of plan) {
if (p.action !== 'create') {continue}
try {
const first = Object.fromEntries(Object.entries(p.data).filter(([, v]) => !hasRef(v)))
const created = await payload.create({
collection: collection as never,
context,
data: localize(first, defaultLocale, undefined, codes) as never,
depth: 0,
...(defaultLocale ? { locale: defaultLocale as never } : {}),
})
p.id = (created as { id: number | string }).id
const slug = p.key.slug
if (trackPages && typeof slug === 'string') {pageIds.set(slug, p.id)}
} catch (e) {
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
p.action = undefined
const waiting = plan.filter((p) => p.action === 'create' && !p.result)
const planned = new Set(trackPages ? waiting.map((p) => p.key.slug).filter((s): s is string => typeof s === 'string') : [])
const blocked = new Map<Planned, { error: string; forward: Set<string> }>()
let progress = true
while (waiting.length && progress) {
progress = false
for (const p of [...waiting]) {
const forward = new Set<string>()
try {
const first = (await resolveForCreate(p.data, forward, planned)) as Record<string, unknown>
const created = await payload.create({
collection: collection as never,
context,
data: localize(first, defaultLocale, undefined, codes) as never,
depth: 0,
...(defaultLocale ? { locale: defaultLocale as never } : {}),
})
p.id = (created as { id: number | string }).id
const slug = p.key.slug
if (trackPages && typeof slug === 'string') {
pageIds.set(slug, p.id)
planned.delete(slug)
}
waiting.splice(waiting.indexOf(p), 1)
blocked.delete(p)
progress = true
} catch (e) {
if (forward.size) {
// Valid only once the pages it links to exist — try again after the others.
blocked.set(p, { error: (e as Error).message, forward })
continue
}
p.result = { label: p.label, note: (e as Error).message, status: 'error' }
p.action = undefined
waiting.splice(waiting.indexOf(p), 1)
}
}
}
for (const p of waiting) {
const why = blocked.get(p)
const targets = [...(why?.forward ?? [])].map((s) => `"${s}"`).join(', ')
p.result = {
label: p.label,
note: `required references to pages not created yet (${targets}) — a cycle of required links; make one link optional or seed that page first${why ? ` (${why.error})` : ''}`,
status: 'error',
}
p.action = undefined
}
}
// Pass 2: full content in every locale (dry run: resolve refs to report broken ones).
+87 -10
View File
@@ -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}
+212
View File
@@ -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' }] })
})
})
+188
View File
@@ -0,0 +1,188 @@
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 type { SeedResult } from '../src/exports/seed.js'
import { createSeeder } from '../src/exports/seed.js'
import { buildLinksField, buildSectionHeaderField } from '../src/index.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
/**
* Regression (vanstevpl-web, 1.15.4): a page whose REQUIRED layout holds a { $page } / { $form } reference
* could not be created — pass 1 left the whole field out and validation rejected the record, while the dry
* run reported a create. Now pass 1 resolves references to existing records, retries records whose required
* fields wait for pages created later in the same call, and reports cycles and unknown targets as errors
* with nothing written. The dry run reports the same outcome.
*/
const LOCALES = ['pl', 'en', 'de'] as const
const callToAction: Block = { slug: 'callToAction', fields: [buildSectionHeaderField(), buildLinksField()] }
const formBlock: Block = { slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms', required: true }] }
// A block whose link to another page is required — forward references to it must wait.
const teaser: Block = { slug: 'teaser', fields: [{ name: 'target', type: 'relationship', relationTo: 'pages', required: true }] }
const confirmation = {
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
}
/** A page with a required layout of one block. */
const page = (slug: string, title: string, layout: Record<string, unknown>[]) => ({
slug: { de: `${slug}-de`, en: `${slug}-en`, pl: slug },
layout,
title: { de: `${title} DE`, en: `${title} EN`, pl: title },
})
const teaserTo = (slug: string) => ({ blockType: 'teaser', target: { $page: slug } })
describe('createSeeder: required fields with references', () => {
let payload: Payload
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
const config = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text', localized: true, required: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{ name: 'layout', type: 'blocks', blocks: [callToAction, formBlock, teaser], required: true },
],
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-refs') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
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-required-refs',
telemetry: false,
})
payload = await getPayload({ config })
// The existing records the references point at.
const seed = createSeeder(payload, { log: () => {} })
await seed.upsertBySlug('pages', page('kontakt', 'Kontakt', [{ blockType: 'callToAction', header: { heading: { de: 'Hallo', en: 'Hello', pl: 'Cześć' } } }]))
await seed.upsertBy('forms', { title: 'Contact form' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'Contact form' })
}, 60_000)
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
const seeder = (dryRun = false) => createSeeder(payload, { dryRun, log: () => {}, update: false })
const idOf = async (slug: string) => (await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: slug } } })).docs[0]?.id
const count = async () => (await payload.count({ collection: 'pages' })).totalDocs
/** Runs the same seed as a dry run, then for real: both must report the same statuses. */
const both = async (run: (seed: ReturnType<typeof seeder>) => Promise<SeedResult | SeedResult[]>) => {
const planned = [await run(seeder(true))].flat().map((r) => r.status)
const done = [await run(seeder())].flat()
expect(done.map((r) => r.status)).toEqual(planned)
return done
}
test('the report’s careers page: a required layout linking to an existing page, in pl, en and de', async () => {
const careers = {
slug: { de: 'karriere', en: 'careers', pl: 'kariera' },
layout: [
{
blockType: 'callToAction',
header: { heading: { de: 'Kontakt', en: 'Contact', pl: 'Kontakt' } },
links: [{ link: { type: 'internal', page: { $page: 'kontakt' } } }],
},
],
title: { de: 'Karriere', en: 'Careers', pl: 'Kariera' },
}
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', careers)])
expect(result).toMatchObject({ status: 'create' })
const all = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as unknown as {
layout: { header: { heading: Record<string, string> }; id: string; links: { link: { page: unknown } }[] }[]
}
expect(all.layout).toHaveLength(1)
expect(all.layout[0].header.heading).toEqual({ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' })
expect(all.layout[0].links[0].link.page).toBe(await idOf('kontakt'))
// One set of rows in every locale (1.15.4).
for (const locale of LOCALES) {
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { layout: { id: string }[] }
expect(doc.layout[0].id).toBe(all.layout[0].id)
}
// Create-only: a second run changes nothing.
expect(await seeder().upsertBySlug('pages', careers)).toMatchObject({ status: 'skip (exists)' })
})
test('a required layout with a form block pointing at an existing form', async () => {
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', page('formularz', 'Formularz', [{ blockType: 'formBlock', form: { $form: 'Contact form' } }]))])
expect(result).toMatchObject({ status: 'create' })
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 1, locale: 'pl' })) as unknown as { layout: { form: { title: string } }[] }
expect(doc.layout[0].form.title).toBe('Contact form')
})
test('forward references in one call: an optional link is filled in pass 2, a required one waits for its page', async () => {
const results = await both((seed) =>
seed.upsertBySlug('pages', [
// Optional link (CTA) to a page later in the list.
page('o-nas', 'O nas', [{ blockType: 'callToAction', links: [{ link: { type: 'internal', page: { $page: 'oferta' } } }] }]),
// Required link to a page later in the list: created once that page exists.
page('start', 'Start', [teaserTo('oferta')]),
page('oferta', 'Oferta', [{ blockType: 'callToAction', header: { heading: { de: 'Angebot', en: 'Offer', pl: 'Oferta' } } }]),
]),
)
expect(results.map((r) => r.status)).toEqual(['create', 'create', 'create'])
const oferta = await idOf('oferta')
const about = (await payload.findByID({ id: (await idOf('o-nas')), collection: 'pages', depth: 0, locale: 'en' })) as unknown as { layout: { links: { link: { page: unknown } }[] }[] }
expect(about.layout[0].links[0].link.page).toBe(oferta)
const start = (await payload.findByID({ id: (await idOf('start')), collection: 'pages', depth: 0, locale: 'de' })) as unknown as { layout: { target: unknown }[] }
expect(start.layout[0].target).toBe(oferta)
// Second run: everything exists, nothing written.
const again = await seeder().upsertBySlug('pages', [page('o-nas', 'O nas', []), page('start', 'Start', []), page('oferta', 'Oferta', [])])
expect(again.map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)', 'skip (exists)'])
})
test('required references in a cycle: a clear error, nothing written', async () => {
const before = await count()
const results = await seeder().upsertBySlug('pages', [page('jeden', 'Jeden', [teaserTo('dwa')]), page('dwa', 'Dwa', [teaserTo('jeden')])])
expect(results.map((r) => r.status)).toEqual(['error', 'error'])
expect(results[0].note).toMatch(/required references to pages not created yet \("dwa"\) — a cycle of required links/)
expect(await count()).toBe(before)
})
test('a reference to a page that never appears: an error in the dry run and the real run, nothing written', async () => {
const before = await count()
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('sierota', 'Sierota', [teaserTo('nie-ma-takiej')]))])
expect(results[0]).toMatchObject({ status: 'error' })
expect(results[0].note).toMatch(/\$page "nie-ma-takiej" not found/)
expect(await count()).toBe(before)
})
test('a reference to a form that does not exist: an error in the dry run too', async () => {
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('bez-formularza', 'Bez', [{ blockType: 'formBlock', form: { $form: 'Missing form' } }]))])
expect(results[0]).toMatchObject({ status: 'error' })
expect(results[0].note).toMatch(/\$form "Missing form" not found/)
})
test('dry run: a form planned earlier in the same run counts as there', async () => {
const seed = seeder(true)
expect(await seed.upsertBy('forms', { title: 'Newsletter' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [], title: 'Newsletter' })).toMatchObject({ status: 'create' })
expect(await seed.upsertBySlug('pages', page('newsletter', 'Newsletter', [{ blockType: 'formBlock', form: { $form: 'Newsletter' } }]))).toMatchObject({ status: 'create' })
})
})