Seed helper: @intecion/ipal-kit/seed (createSeeder + building blocks)

createSeeder(payload, { dryRun, update, force, guard, editCheck, context, ... })
returns upsertBySlug, upsertBy, fillGlobal and summary(); building blocks
isLocalDatabase, writeLocales, seedHash, projectOnto, editedSinceSeed.
Behaviour follows docs/seeding.md: create-only by default, natural keys,
never deletes, globals get empty fields only, every locale written with
fallbackLocale: false onto the same row ids, records edited since seeding
skipped, update refused on production / non-local DB unless
IPAL_SEED_ALLOW_PROD_UPDATE=1, context.ipalSkipIndexNow on every write.

Both seed templates now use the helper. Node-only entry (no 'server-only',
which throws under `payload run`). SQLite integration tests cover the
production guard, the edited-record skip, the hash field, row ids and
the IndexNow skip. Agent guide (AGENT.md, ipal-reference, ipal-site,
ipal-form) and seeding.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 18:33:34 +02:00
co-authored by Claude Opus 5.5
parent b61b753ec2
commit cff76c2a69
16 changed files with 1155 additions and 521 deletions
+80 -18
View File
@@ -8,7 +8,9 @@ templates. Copy them into the project and fill them from the brief:
| `docs/agent/skills/ipal-site/resources/seed-content.template.ts` | `scripts/seed-content.ts` | pages (or another collection with a slug) and globals, every language |
| `docs/agent/skills/ipal-form/resources/seed-form.template.ts` | `scripts/seed-form-<name>.ts` | one form: fields, confirmation, both e-mails, every language |
Both follow the rules below. A seed you write yourself must follow them too.
Both are thin scripts over the seed helper `createSeeder` from `@intecion/ipal-kit/seed`
([The seed helper](#the-seed-helper)), which implements every rule below. A seed you write yourself
should use it too; if it does not, it must follow the rules by hand.
## Rules
@@ -97,7 +99,7 @@ host is `localhost`, `127.0.0.1` or `::1`. Everything else is not local, includi
Timestamps are simple and safe, but they allow **one** update per record: after a seeded update
`updatedAt` moves on, so the next run reports `skip (edited)`. When you need repeated updates, add the
hash field. The templates use it automatically when the collection or global has a top-level field with
hash field. The seed helper uses it automatically when the collection or global has a top-level field with
that name; the stored hash then decides instead of the timestamps.
```ts
@@ -122,7 +124,7 @@ English version. See also [i18n.md](./i18n.md).
## Context flags
Pass them in `context` on every `create`, `update` and `updateGlobal`:
Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSeeder` does it on every write):
| Flag | Read by | Effect |
|---|---|---|
@@ -152,22 +154,82 @@ must be available at runtime, not only at build time. The container already has
A seed never changes the schema. A migration never fills editorial content from a brief.
## The seed helper
`@intecion/ipal-kit/seed` is a server-only entry for seed scripts (plain Node via `pnpm payload run`).
Never import it from client code, the Payload config or a route. It does not import `server-only`,
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 { getPayload } from 'payload'
const seed = createSeeder(await getPayload({ config }))
await seed.upsertBySlug('pages', [
{ title: { pl: 'Start', en: 'Home' }, slug: { pl: 'start', en: 'home' }, layout: [/* … { $page: 'kontakt' } … */] },
{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' } },
])
await seed.upsertBy('forms', { title: 'Contact form' }, { title: 'Contact form', fields: [/* … */] })
await seed.fillGlobal('header', { phone: '[TO FILL: phone]' })
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.
`{ $page: 'kontakt' }` becomes the ID of the page whose default-locale slug is `kontakt`.
| 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` links), then every record gets its full content, so pages can link to each other in any order |
| `upsertBy(collection, key, data)` | matches by other natural keys, e.g. `{ title: 'Contact form' }` (all keys must match, default locale) |
| `fillGlobal(slug, data)` | fills only the global's empty fields (the default locale decides). With `update` and an untouched global: every seeded field |
| `summary()` | prints the summary and returns `{ created, skipped, updated, skippedEdited, errors }` |
Each method prints one line per record (see [Running a seed](#running-a-seed)) and returns
`{ status, label, id, note }`. A failed write is reported as `error` and the run goes on; exit
with code 1 when `summary().errors` is not 0. `createSeeder` itself throws when the production
guard refuses the run.
On a collection with drafts the helper reads the latest draft, both to match records and to tell
whether an editor changed them.
### Building blocks
| Export | Use |
|---|---|
| `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`,
`UpsertOptions`, `WriteLocalesOptions`, `EditedSinceSeedArgs`.
## Turn off, override, extend
The guards are defaults in the templates. The project can change them — at the top of each template
(`SAFETY` block) or through env:
Every guard is a default. Change it with an env var at run time or with a `createSeeder` option in
the script:
| Env var / constant | Default | What it does |
|---|---|---|
| `SEED_DRY_RUN=1` / `--dry-run` | off | no writes, print the plan |
| `SEED_UPDATE=1` | off | update records nobody edited since seeding |
| `IPAL_SEED_ALLOW_PROD_UPDATE=1` | off | allow `SEED_UPDATE=1` on production or a non-local database |
| `SEED_FORCE=1` | off | with `SEED_UPDATE=1`: overwrite edited records too. Local database only (`FORCE_ONLY_LOCAL`) |
| `SEED_LOCAL_HOSTS` | — | extra hosts that count as local, comma-separated (e.g. a Docker Compose `db` service) |
| `SEED_DB_URL_ENV` | `DATABASE_URI` | the env var that holds the database URL |
| `SEED_UNTOUCHED_SECONDS` | `120` | the timestamp window for "untouched since creation" |
| `SEED_HASH_FIELD` | `seedHash` | the hash field name; empty = timestamps only |
| `SEED_NOTIFY_EMAIL` | — | form seed: notification address for a first run when the company global is still empty |
| Env var | `createSeeder` option | Default | What it does |
|---|---|---|---|
| `SEED_DRY_RUN=1` / `--dry-run` | `dryRun` | off | no writes, print the plan |
| `SEED_UPDATE=1` | `update` | off | update records nobody edited since seeding |
| `IPAL_SEED_ALLOW_PROD_UPDATE=1` | `guard.allowProdUpdate` | off | allow `update` on production or a non-local database |
| `SEED_FORCE=1` | `force` | off | with `update`: overwrite edited records too. Local database only (`guard.forceOnlyLocal: false` lifts that) |
| `SEED_LOCAL_HOSTS` | `guard.localHosts` | — | extra hosts that count as local, comma-separated (e.g. a Docker Compose `db` service) |
| `SEED_DB_URL_ENV` | `guard.databaseUrl` | `DATABASE_URI` | the env var that holds the database URL / the URL itself |
| `NODE_ENV` | `guard.production` | `NODE_ENV === 'production'` | whether this run counts as production |
| — | `guard: false` | on | turn the production guard off (the project takes the risk) |
| `SEED_UNTOUCHED_SECONDS` | `editCheck.untouchedSeconds` | `120` | the timestamp window for "untouched since creation" |
| `SEED_HASH_FIELD` | `editCheck.hashField` | `seedHash` | the hash field name; empty / `false` = timestamps only |
| — | `context` | `{ ipalSeed, disableRevalidate, ipalSkipIndexNow }` all `true` | merged over the defaults; set a key to `false` to drop it |
| — | `pagesCollection` | `pages` | the collection `{ $page }` links resolve in |
| — | `label`, `log` | `[seed]`, stdout | line prefix and where lines go |
| `SEED_NOTIFY_EMAIL` | — | — | form seed: notification address for a first run when the company global is still empty |
The plugin itself has no seed option and no seed code. The templates are plain project scripts: edit
them freely, but keep the rules above.
The plugin has no seed option and runs no seed by itself. The templates are plain project scripts:
edit them freely, but keep the rules above.