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:
co-authored by
Claude Opus 5.5
parent
b61b753ec2
commit
cff76c2a69
+2
-1
@@ -36,7 +36,8 @@ the option or the exported builder (module docs §12, types in `dist/**/*.d.ts`)
|
||||
**Docs language:** all ipal-kit docs, this guide and the skills are written in English.
|
||||
Write new rules, AGENTS.md entries and plugin-gap reports in English.
|
||||
|
||||
**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`):
|
||||
**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:
|
||||
- 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 }`.
|
||||
|
||||
@@ -101,6 +101,8 @@ cp .agents/skills/ipal-form/resources/seed-form.template.ts scripts/seed-form-co
|
||||
# fill FORM from the brief (fields, labels, messages, email subjects — every language), NOTIFY = global/field with the company address
|
||||
pnpm payload run scripts/seed-form-contact.ts
|
||||
```
|
||||
The template writes the form with `createSeeder(...).upsertBy('forms', { title }, data)` from
|
||||
`@intecion/ipal-kit/seed` (every language, row ids kept, edited forms skipped).
|
||||
Without a notification address the script **stops** — ask the client which inbox should receive
|
||||
submissions (a question from the list in ipal-site), enter it in the panel and run again. Never put the address in code.
|
||||
Commit the script — in production run it after the migration: `SEED_DRY_RUN=1` first, back up the database, then
|
||||
|
||||
@@ -9,10 +9,12 @@
|
||||
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also updates it if nobody edited it since seeding
|
||||
* (`--dry-run` after the script path works too.)
|
||||
*
|
||||
* Safety: the form is matched by its title; nothing is ever deleted. SEED_UPDATE=1 is
|
||||
* refused when NODE_ENV=production or the database is not local, unless
|
||||
* IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set — back up the database first. A form an
|
||||
* editor changed is skipped and reported ("skip (edited)"); see SAFETY below.
|
||||
* Safety (createSeeder from @intecion/ipal-kit/seed): the form is matched by its
|
||||
* title; nothing is ever deleted. SEED_UPDATE=1 is refused when NODE_ENV=production
|
||||
* or the database is not local, unless IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set —
|
||||
* back up the database first. A form an editor changed is skipped and reported
|
||||
* ("skip (edited)"). Every language is written with `fallbackLocale: false` onto the
|
||||
* same row ids (fields, options, e-mails).
|
||||
*
|
||||
* Nothing about the company lives in this file. The notification address comes
|
||||
* from the panel — NOTIFY.global / NOTIFY.field below (the project's company
|
||||
@@ -21,13 +23,9 @@
|
||||
*
|
||||
* Safe to send to {{email}}: submitForm accepts exactly one address in an
|
||||
* `email` field (no extra recipients, no header injection).
|
||||
*
|
||||
* GOTCHA (Payload, localization.fallback: true): a read or update in locale X without
|
||||
* `fallbackLocale: false` merges the FALLBACK values into X — the default-locale
|
||||
* text gets saved as the X translation. Every non-default read and write below sets it.
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import config from '@payload-config'
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
// ─── fill from the brief ────────────────────────────────────────────────────
|
||||
@@ -82,65 +80,6 @@ const FORM = {
|
||||
const NOTIFY = { global: 'company', field: 'email' }
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ─── SAFETY — defaults the project may change here or through env (docs/seeding.md) ───
|
||||
/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */
|
||||
const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI'
|
||||
/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */
|
||||
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)]
|
||||
/**
|
||||
* "Untouched since seeding", primary method: updatedAt is at most this many seconds
|
||||
* after createdAt. After one seeded update the form counts as edited — add a hidden
|
||||
* SEED_HASH_FIELD (formOverrides) for repeated updates.
|
||||
*/
|
||||
const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120)
|
||||
/** Optional: hidden text field with a hash of the seeded values; used only if the forms collection has it. */
|
||||
const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash'
|
||||
/** SEED_FORCE=1 also overwrites an edited form — refused outside a local database. */
|
||||
const FORCE_ONLY_LOCAL = true
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1'
|
||||
const UPDATE = process.env.SEED_UPDATE === '1'
|
||||
const FORCE = UPDATE && process.env.SEED_FORCE === '1'
|
||||
|
||||
function dbIsLocal(): boolean {
|
||||
const url = (process.env[DB_URL_ENV] ?? '').trim()
|
||||
if (!url) return false
|
||||
if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file
|
||||
try {
|
||||
const u = new URL(url)
|
||||
if (u.protocol === 'mongodb+srv:') return false
|
||||
if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql
|
||||
const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '')
|
||||
if (!host || host.startsWith('/')) return true // postgres:///db = unix socket
|
||||
return LOCAL_HOSTS.includes(host)
|
||||
} catch {
|
||||
return false // unparsable (e.g. several Mongo hosts) = not local
|
||||
}
|
||||
}
|
||||
|
||||
const local = dbIsLocal()
|
||||
const prodLike = process.env.NODE_ENV === 'production' || !local
|
||||
if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') {
|
||||
console.error(
|
||||
`[seed-form] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` +
|
||||
' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' +
|
||||
' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' +
|
||||
' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. An edited form is still skipped.',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (FORCE && FORCE_ONLY_LOCAL && prodLike) {
|
||||
console.error('[seed-form] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.')
|
||||
process.exit(1)
|
||||
}
|
||||
if (UPDATE && prodLike) console.warn('[seed-form] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?')
|
||||
|
||||
// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip revalidation and IndexNow. ipalSeed: for project hooks.
|
||||
const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true }
|
||||
|
||||
type Localized = Readonly<Record<string, string>>
|
||||
|
||||
/** Plain text (with blank-line paragraphs) → Lexical rich text, as form-builder messages expect. */
|
||||
function richText(text: string) {
|
||||
return {
|
||||
@@ -166,9 +105,8 @@ function richText(text: string) {
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config })
|
||||
const locales = (payload.config.localization ? payload.config.localization.localeCodes : ['pl']) as string[]
|
||||
const defaultLocale = (payload.config.localization ? payload.config.localization.defaultLocale : locales[0]) as string
|
||||
const pick = (value: Localized, locale: string) => value[locale] ?? value[defaultLocale] ?? Object.values(value)[0]
|
||||
// Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file.
|
||||
const seed = createSeeder(payload, { label: '[seed-form]' })
|
||||
|
||||
// Notification address — from the panel, never from this file.
|
||||
let notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() ?? ''
|
||||
@@ -188,157 +126,25 @@ if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
/** A field with every per-language text ({ pl, en }) resolved: label, step title/description, option labels. */
|
||||
function localizeField(field: Record<string, unknown>, locale: string): Record<string, unknown> {
|
||||
const text = (v: unknown) => (v && typeof v === 'object' ? pick(v as Localized, locale) : v)
|
||||
return {
|
||||
...field,
|
||||
...('label' in field ? { label: text(field.label) } : {}),
|
||||
...('title' in field ? { title: text(field.title) } : {}),
|
||||
...('description' in field ? { description: text(field.description) } : {}),
|
||||
...(Array.isArray(field.options)
|
||||
? { options: (field.options as Record<string, unknown>[]).map((o) => ({ ...o, label: text(o.label) })) }
|
||||
: {}),
|
||||
}
|
||||
type Localized = Readonly<Record<string, string>>
|
||||
/** { pl: 'text', en: 'text' } → { pl: <rich text>, en: <rich text> } — still one value per locale. */
|
||||
const rich = (v: Localized) => Object.fromEntries(Object.entries(v).map(([l, text]) => [l, richText(text)]))
|
||||
|
||||
const result = await seed.upsertBy('forms', { title: FORM.title }, {
|
||||
title: FORM.title,
|
||||
fields: FORM.fields,
|
||||
submitButtonLabel: FORM.submitButtonLabel,
|
||||
confirmationType: 'message',
|
||||
confirmationMessage: rich(FORM.confirmation),
|
||||
emails: [
|
||||
{ emailTo: notifyTo, replyTo: '{{email}}', subject: FORM.notification.subject, message: rich(FORM.notification.message) },
|
||||
{ emailTo: '{{email}}', replyTo: notifyTo, subject: FORM.confirmationEmail.subject, message: rich(FORM.confirmationEmail.message) },
|
||||
],
|
||||
})
|
||||
|
||||
const { errors } = seed.summary()
|
||||
if (result.status === 'create' || result.status === 'update') {
|
||||
console.log(`Notifications to ${notifyTo}, confirmation to the sender.`)
|
||||
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
|
||||
}
|
||||
|
||||
/** Form data in one locale (localized fields resolved for it). */
|
||||
function dataFor(locale: string) {
|
||||
return {
|
||||
confirmationMessage: richText(pick(FORM.confirmation, locale)),
|
||||
confirmationType: 'message',
|
||||
emails: [
|
||||
{
|
||||
emailTo: notifyTo,
|
||||
replyTo: '{{email}}',
|
||||
message: richText(pick(FORM.notification.message, locale)),
|
||||
subject: pick(FORM.notification.subject, locale),
|
||||
},
|
||||
{
|
||||
emailTo: '{{email}}',
|
||||
replyTo: notifyTo,
|
||||
message: richText(pick(FORM.confirmationEmail.message, locale)),
|
||||
subject: pick(FORM.confirmationEmail.subject, locale),
|
||||
},
|
||||
],
|
||||
fields: FORM.fields.map((field) => localizeField(field as Record<string, unknown>, locale)),
|
||||
submitButtonLabel: pick(FORM.submitButtonLabel, locale),
|
||||
title: FORM.title,
|
||||
}
|
||||
}
|
||||
|
||||
/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */
|
||||
const stable = (v: unknown): string =>
|
||||
Array.isArray(v) ? `[${v.map(stable).join(',')}]`
|
||||
: v && typeof v === 'object'
|
||||
? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record<string, unknown>)[k] != null).sort()
|
||||
.map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`
|
||||
: JSON.stringify(v ?? null)
|
||||
const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32)
|
||||
/** The current values at the keys the seed writes (everything else in the form is ignored). */
|
||||
function project(seed: unknown, cur: unknown): unknown {
|
||||
if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((x, i) => project(x, cur[i])) : cur
|
||||
if (seed && typeof seed === 'object') {
|
||||
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur
|
||||
return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record<string, unknown>)[k], (cur as Record<string, unknown>)[k])]))
|
||||
}
|
||||
return cur
|
||||
}
|
||||
const seedHash = () => hashOf(Object.fromEntries(locales.map((l) => [l, dataFor(l)])))
|
||||
const hasHashField = !!HASH_FIELD && !!(payload.collections['forms' as never]?.config.fields as { name?: string }[] | undefined)?.some((f) => f.name === HASH_FIELD)
|
||||
|
||||
type FormDoc = Record<string, unknown> & { emails?: { id?: string }[]; fields?: { id?: string; options?: { id?: string }[] }[] }
|
||||
const readForm = async (formId: number | string, locale: string) =>
|
||||
(await payload.findByID({ collection: 'forms' as never, depth: 0, id: formId, locale: locale as never, fallbackLocale: false as never })) as FormDoc
|
||||
|
||||
/** null = untouched since seeding; a string = why it counts as edited. */
|
||||
async function editedReason(formId: number | string): Promise<string | null> {
|
||||
const doc = await readForm(formId, defaultLocale)
|
||||
const stored = hasHashField ? doc[HASH_FIELD] : undefined
|
||||
if (typeof stored === 'string' && stored) {
|
||||
const current: Record<string, unknown> = {}
|
||||
for (const l of locales) current[l] = project(dataFor(l), l === defaultLocale ? doc : await readForm(formId, l))
|
||||
return hashOf(current) === stored ? null : `${HASH_FIELD} differs`
|
||||
}
|
||||
const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt))
|
||||
if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt'
|
||||
const sec = Math.round((u - c) / 1000)
|
||||
return sec <= UNTOUCHED_SECONDS ? null : `updated ${sec}s after creation`
|
||||
}
|
||||
|
||||
/** Locale data onto the existing row ids (fields, their options, e-mails) — new ids would wipe the other languages' texts. */
|
||||
function withRowIds(d: ReturnType<typeof dataFor>, doc: FormDoc | undefined) {
|
||||
if (!doc) return d
|
||||
return {
|
||||
...d,
|
||||
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
|
||||
fields: d.fields.map((f, i) => ({
|
||||
...f,
|
||||
id: doc.fields?.[i]?.id,
|
||||
...(Array.isArray(f.options)
|
||||
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
|
||||
: {}),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
const summary = (status: string, errors = 0) => {
|
||||
console.log(`\n[seed-form] summary${DRY ? ' (dry run — nothing written)' : ''}`)
|
||||
console.table({
|
||||
created: status === 'create' ? 1 : 0,
|
||||
skipped: status === 'skip (exists)' ? 1 : 0,
|
||||
updated: status === 'update' ? 1 : 0,
|
||||
'skipped-edited': status === 'skip (edited)' ? 1 : 0,
|
||||
errors,
|
||||
})
|
||||
}
|
||||
|
||||
console.log(`[seed-form] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}`)
|
||||
const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } })
|
||||
let id = existing.docs[0]?.id as number | string | undefined
|
||||
let status: 'create' | 'skip (exists)' | 'update' | 'skip (edited)' = id ? 'update' : 'create'
|
||||
let note = ''
|
||||
if (id && !UPDATE) { status = 'skip (exists)'; note = 'SEED_UPDATE=1 updates it if nobody edited it' }
|
||||
if (id && UPDATE) {
|
||||
const why = await editedReason(id)
|
||||
if (why && !FORCE) { status = 'skip (edited)'; note = why }
|
||||
}
|
||||
if (DRY || status === 'skip (exists)' || status === 'skip (edited)') {
|
||||
console.log(`${status.padEnd(14)} form "${FORM.title}"${id ? ` (id ${id})` : ''}${note ? ` — ${note}` : ''}`)
|
||||
summary(status)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
try {
|
||||
const hash = hasHashField ? { [HASH_FIELD]: seedHash() } : {}
|
||||
if (!id) {
|
||||
const created = await payload.create({ collection: 'forms' as never, data: { ...dataFor(defaultLocale), ...hash } as never, locale: defaultLocale as never, context: CTX })
|
||||
id = created.id
|
||||
} else {
|
||||
const doc = await readForm(id, defaultLocale)
|
||||
await payload.update({ collection: 'forms' as never, data: { ...withRowIds(dataFor(defaultLocale), doc), ...hash } as never, id, locale: defaultLocale as never, context: CTX })
|
||||
}
|
||||
const formId = id
|
||||
|
||||
// Other languages: same rows (ids kept), localized texts per locale.
|
||||
for (const locale of locales.filter((l) => l !== defaultLocale)) {
|
||||
const doc = await readForm(formId, locale)
|
||||
await payload.update({
|
||||
collection: 'forms' as never,
|
||||
data: withRowIds(dataFor(locale), doc) as never,
|
||||
id: formId,
|
||||
locale: locale as never,
|
||||
fallbackLocale: false as never,
|
||||
context: CTX,
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`error form "${FORM.title}" — ${(e as Error).message}`)
|
||||
summary('', 1)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`${status.padEnd(14)} form "${FORM.title}" (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
|
||||
summary(status)
|
||||
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
|
||||
process.exit(0)
|
||||
process.exit(errors ? 1 : 0)
|
||||
|
||||
@@ -22,7 +22,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
| `i18n.defaultLocale` | — | `localization.defaultLocale`, `/` redirect in the proxy | must be in `locales` |
|
||||
| `i18n.fallback` | `true` | `localization.fallback` | `false` |
|
||||
| `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** |
|
||||
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: nobody is admin for Site Integrations, the e-mail test, stats, consent-records; `form-submissions` readable by editor+ only |
|
||||
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: every logged-in account passes the plugin's admin/editor checks (`userMeetsRole`): Site Integrations, the e-mail test, stats, consent-records, settings globals, `form-submissions`. Narrow them with `globalOverrides` / collection overrides |
|
||||
| `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins |
|
||||
| `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` |
|
||||
| `access.authAccess` | `{ create: adminOnly, delete: adminOnly, read: adminOrSelf, unlock: adminOnly, update: adminOrSelf }` | access of the auth collection the plugin **injects** (Payload's default lets any logged-in account edit or delete every other account) | your keys win, e.g. `{ read: authenticated }`; your own collection with that slug wins whole (give it `adminOrSelf` / `adminOnly` yourself) |
|
||||
@@ -48,6 +48,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
| `seo.autoFill` | `{ title: 'title', content: 'layout', descriptionLength: 155 }` | `beforeChange`: empty `meta.title/description` filled from document fields | `false`; object `{ title, description, content, descriptionLength }` |
|
||||
| `seo.descriptionCheck` | on (`settingsSlug: 'site-settings'`, `siteDescriptionField: 'siteDescription'`) | UI field `MetaDescriptionCheck` below the description (empty / duplicated) | `false`; object overrides slug/field |
|
||||
| `seo.fields` | `[]` | extra fields in the SEO group | — |
|
||||
| `seo.uploadsCollection` | `'media'` | upload collection `meta.image` relates to | any upload collection slug |
|
||||
| `seo.generateTitle` / `generateDescription` | plugin-seo | preview / generation in the panel | your own function `({ doc }) => string` |
|
||||
| `seo.searchSettings` | on (also without `seo`) | Site Settings → **Search & AI** tab: `searchVerification.google/bing/yandex` (→ `<meta>` via `generatePageMetadata`), `aiCrawlers.policy` + `aiCrawlers.rules[]` (→ robots.txt via `getRobots`), localized `llmsIntro` (→ top of `/llms.txt`); empty fields change nothing. Postgres: `migrate:create` after upgrading | `false` = no tab (without `seo`: `globalOverrides['site-settings']` function); `(fields) => fields` = your own set (keep the names `searchVerification`, `aiCrawlers`, `llmsIntro` or read your own fields in your routes) |
|
||||
| — (no option) | `uploadsCollection: 'media'` | meta image from the `media` collection | currently always `media` (gap) |
|
||||
@@ -189,7 +190,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba
|
||||
| `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) |
|
||||
| `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting |
|
||||
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env |
|
||||
| `R2_PUBLIC_URL` | as above; absolute URL in prod | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`; with `ipalEnvRules({ storage: true })` make the rule optional, env.md); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env |
|
||||
| `R2_PUBLIC_URL` | optional; required only with `ipalEnvRules({ storage: { requirePublicUrl: true } })` (then like the other `R2_*`); absolute URL in prod when set | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env |
|
||||
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | `emailGraph: true` / Graph transport in the panel | `mailAdapter` falls back to SMTP from the panel (logged) | env (agency Exchange) |
|
||||
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site Integrations → Turnstile; neither set → Turnstile off | panel (takes precedence) or env |
|
||||
| `INDEXNOW_KEY` | no | key from Site Integrations → IndexNow (generated) | env or panel |
|
||||
@@ -202,4 +203,16 @@ 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): 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`. 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): 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`.
|
||||
|
||||
| Seed env var (run time) | Effect |
|
||||
|---|---|
|
||||
| `SEED_DRY_RUN=1` (or `--dry-run`) | no writes, print the plan |
|
||||
| `SEED_UPDATE=1` | also update records nobody edited since seeding |
|
||||
| `IPAL_SEED_ALLOW_PROD_UPDATE=1` | allow `SEED_UPDATE=1` on production / a non-local database (back up first) |
|
||||
| `SEED_FORCE=1` | with `SEED_UPDATE=1`: overwrite edited records too — local database only |
|
||||
| `SEED_LOCAL_HOSTS` | extra hosts that count as a local database (comma-separated) |
|
||||
| `SEED_DB_URL_ENV` | name of the env var holding the database URL (default `DATABASE_URI`) |
|
||||
| `SEED_UNTOUCHED_SECONDS` | "untouched" window for the timestamp check (default 120) |
|
||||
| `SEED_HASH_FIELD` | hash field name (default `seedHash`; empty = timestamps only) |
|
||||
| `SEED_NOTIFY_EMAIL` | form seed: notification address on a first run |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# ipal-kit — export index
|
||||
|
||||
Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`,
|
||||
`/server`, `/next/middleware`, `/admin`, `/env`), grouped by module. Search with grep
|
||||
`/server`, `/seed`, `/next/middleware`, `/admin`, `/env`), grouped by module. Search with grep
|
||||
(`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself.
|
||||
"Import from" column — the first entry is preferred. Plugin options, env, routes and what the
|
||||
project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`.
|
||||
@@ -50,6 +50,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `hasMinimumRole(user, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
|
||||
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
|
||||
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
|
||||
| `userMeetsRole(req, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean` with `req` (`{ payload, user }`): role ≥ `minimum`, **or** any logged-in user when the user's auth collection has no `roles` field (the project omitted `access`). The plugin's staff features use it (Site Integrations, settings globals, test e-mail, stats, consent records, form submissions). Use it in your own access when the project may run without roles. |
|
||||
| `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). |
|
||||
| `buildRolesField(defaultRole?, { firstUserAdmin? })` | `@intecion/ipal-kit` | The `roles` select field the plugin injects (only admins set roles; `firstUserAdmin` default `true` = the account made on "Create first user" gets `admin`). The plugin wires it itself — use it only for an auth collection the plugin does not manage. |
|
||||
| `injectRoles(config, accessOption)` | `@intecion/ipal-kit` | Adds `roles` to `accessOption.authCollection` in a config. The plugin calls it itself with `access` — do not call. |
|
||||
@@ -180,7 +181,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error |
|
||||
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv` |
|
||||
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }` |
|
||||
|
||||
**Types:** `EnvRule`, `EnvKind` — variable rule (`name`, `required`, `kind`, `oneOf`, `validate`); `AssertEnvOptions` — `assertEnv` options; `IpalEnvFeatures` — `ipalEnvRules` argument (all from `/env` and root).
|
||||
|
||||
@@ -416,6 +417,25 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
|
||||
**Types:** `ExtractHeadingsOptions`, `HeadingItem`, `HeadingLevel` (root) — heading extraction options and result; `RenderRichTextProps` (`/rsc`) — renderer props; `TableOfContentsProps`, `TableOfContentsClassNames` (`/client`) — table of contents props and classes.
|
||||
|
||||
## Seeding (`seed`) — details: `node_modules/@intecion/ipal-kit/docs/seeding.md`
|
||||
|
||||
Server only (`pnpm payload run`); never import it from client code, the Payload config or a route.
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `createSeeder(payload, { dryRun?, update?, force?, guard?, editCheck?, context?, pagesCollection?, label?, log? })` | `@intecion/ipal-kit/seed` | The seed rules in one place → `{ upsertBySlug, upsertBy, fillGlobal, summary, dryRun, update, force, local }`. 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. |
|
||||
| `upsertBy(collection, key, data)` | (method) | Matches by other keys, e.g. a form by `{ title }`. |
|
||||
| `fillGlobal(slug, data)` | (method) | Fills only empty fields of a global (all seeded fields with `update` when untouched). |
|
||||
| `summary()` | (method) | Prints and returns `{ created, skipped, updated, skippedEdited, errors }`; exit 1 when `errors`. |
|
||||
| `isLocalDatabase(url, { localHosts? })` | `@intecion/ipal-kit/seed` | `true` for SQLite files, Unix sockets, localhost / 127.0.0.1 / ::1 (+ `SEED_LOCAL_HOSTS`). |
|
||||
| `writeLocales(payload, target, data, { context?, draft? })` | `@intecion/ipal-kit/seed` | Writes seed values (`{ pl, en }` per field) to `{ collection, id }` or `{ global }`: default locale first, then every other locale with `fallbackLocale: false` onto the same row ids. |
|
||||
| `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`).
|
||||
|
||||
## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|
||||
@@ -66,6 +66,8 @@ form with fields in JSX, an `api/contact` route, `nodemailer`, reCAPTCHA (AGENT.
|
||||
enter content from the brief: pages, blocks, links (`{ $page: 'slug' }`), globals —
|
||||
all languages side by side (`{ pl, en }`). Missing data → `[TO FILL: …]`.
|
||||
Never invent company data, prices, reviews, numbers, certificates, names.
|
||||
The template is a thin script over `createSeeder` (`@intecion/ipal-kit/seed`): keep the calls
|
||||
(`upsertBySlug`, `fillGlobal`, `summary`), change only CONTENT; options in docs/seeding.md.
|
||||
2. `pnpm payload run scripts/seed-content.ts` → the placeholder list goes into the report.
|
||||
On production (rules: `node_modules/@intecion/ipal-kit/docs/seeding.md`): `SEED_DRY_RUN=1` first, back up the
|
||||
database, then the real run. It only creates what is missing; `SEED_UPDATE=1` there is refused without
|
||||
|
||||
@@ -6,13 +6,15 @@
|
||||
* SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates records nobody edited since seeding
|
||||
* (`--dry-run` after the script path works too, e.g. `pnpm seed:content --dry-run`.)
|
||||
*
|
||||
* Safety (docs/seeding.md):
|
||||
* The rules live in createSeeder (@intecion/ipal-kit/seed), so fixes arrive with a
|
||||
* plugin upgrade:
|
||||
* - Create-only and idempotent. Pages match by their DEFAULT-locale slug; globals
|
||||
* get only the fields that are still empty. Nothing is ever deleted.
|
||||
* - SEED_UPDATE=1 is refused when NODE_ENV=production or the database is not local,
|
||||
* unless IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set. Back up the database first.
|
||||
* - An update skips every record an editor changed since seeding and reports it
|
||||
* ("skip (edited)"). How a record counts as untouched: see SAFETY below.
|
||||
* - An update skips every record an editor changed since seeding ("skip (edited)").
|
||||
* - Every locale is written with `fallbackLocale: false` onto the same row ids.
|
||||
* - Writes carry ipalSkipIndexNow, disableRevalidate and ipalSeed in `context`.
|
||||
* - Never seed users, passwords or secrets (SMTP, Turnstile, API keys) — panel / env.
|
||||
*
|
||||
* Write content ONCE, all languages side by side:
|
||||
@@ -20,23 +22,14 @@
|
||||
* heading: 'Nasze usługi' → same in every locale / non-localized field
|
||||
* page: { $page: 'kontakt' } → ID of the page whose DEFAULT-locale slug is 'kontakt'
|
||||
* Missing data: '[TO FILL: tax ID (NIP)]' — never invent company data, prices, reviews, numbers.
|
||||
*
|
||||
* The default locale creates the structure (blocks, array rows); other locales are
|
||||
* written onto the SAME row ids, so nothing is duplicated. Media: leave empty or
|
||||
* reference existing uploads by ID — the editor adds images. Never upload here.
|
||||
*
|
||||
* GOTCHA (Payload, localization.fallback: true): an update in locale X without
|
||||
* `fallbackLocale: false` merges the FALLBACK values into X — the default-locale
|
||||
* text gets saved as the X translation. Every non-default read and write below sets it.
|
||||
* Media: leave empty or reference existing uploads by ID — the editor adds images. Never upload here.
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import { getPayload } from 'payload'
|
||||
import config from '@payload-config'
|
||||
|
||||
type Json = string | number | boolean | null | Json[] | { [k: string]: Json }
|
||||
import { createSeeder } from '@intecion/ipal-kit/seed'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
// ------------------------------------------------------------------ CONTENT --
|
||||
const PAGES: { [k: string]: Json }[] = [
|
||||
const PAGES: Record<string, unknown>[] = [
|
||||
{
|
||||
title: { pl: 'Strona główna', en: 'Home' },
|
||||
slug: { pl: 'home', en: 'home' },
|
||||
@@ -50,269 +43,21 @@ const PAGES: { [k: string]: Json }[] = [
|
||||
},
|
||||
{ title: { pl: 'Kontakt', en: 'Contact' }, slug: { pl: 'kontakt', en: 'contact' }, layout: [] },
|
||||
]
|
||||
const GLOBALS: { slug: string; data: { [k: string]: Json } }[] = [
|
||||
const GLOBALS: { slug: string; data: Record<string, unknown> }[] = [
|
||||
// { slug: 'header', data: { links: [{ link: { type: 'internal', page: { $page: 'kontakt' }, label: { pl: 'Kontakt', en: 'Contact' } } }] } },
|
||||
]
|
||||
const COLLECTION = 'pages'
|
||||
// ----------------------------------------------------------------- /CONTENT --
|
||||
|
||||
// ------------------------------------------------------------------- SAFETY --
|
||||
// Defaults — the project may change them here or through env (docs/seeding.md).
|
||||
/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */
|
||||
const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI'
|
||||
/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */
|
||||
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)]
|
||||
/**
|
||||
* "Untouched since seeding", primary method: updatedAt is at most this many seconds
|
||||
* after createdAt (the seed's own writes in one run). After one seeded update the
|
||||
* record counts as edited — use SEED_HASH_FIELD for repeated updates.
|
||||
*/
|
||||
const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120)
|
||||
/**
|
||||
* Optional method: a hidden text field with a hash of the seeded values. Used only
|
||||
* when the collection/global has a top-level field with this name; it then decides
|
||||
* instead of the timestamps and allows repeated updates.
|
||||
*/
|
||||
const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash'
|
||||
/** SEED_FORCE=1 also overwrites edited records — refused outside a local database. */
|
||||
const FORCE_ONLY_LOCAL = true
|
||||
// ------------------------------------------------------------------ /SAFETY --
|
||||
// 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 }), { pagesCollection: COLLECTION })
|
||||
|
||||
const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1'
|
||||
const UPDATE = process.env.SEED_UPDATE === '1'
|
||||
const FORCE = UPDATE && process.env.SEED_FORCE === '1'
|
||||
// One call for all pages: missing ones are created first, so $page links work in any order.
|
||||
await seed.upsertBySlug(COLLECTION, PAGES)
|
||||
for (const g of GLOBALS) await seed.fillGlobal(g.slug, g.data)
|
||||
|
||||
function dbIsLocal(): boolean {
|
||||
const url = (process.env[DB_URL_ENV] ?? '').trim()
|
||||
if (!url) return false
|
||||
if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file
|
||||
try {
|
||||
const u = new URL(url)
|
||||
if (u.protocol === 'mongodb+srv:') return false
|
||||
if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql
|
||||
const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '')
|
||||
if (!host || host.startsWith('/')) return true // postgres:///db = unix socket
|
||||
return LOCAL_HOSTS.includes(host)
|
||||
} catch {
|
||||
return false // unparsable (e.g. several Mongo hosts) = not local
|
||||
}
|
||||
}
|
||||
|
||||
const local = dbIsLocal()
|
||||
const prodLike = process.env.NODE_ENV === 'production' || !local
|
||||
if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') {
|
||||
console.error(
|
||||
`[seed] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` +
|
||||
' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' +
|
||||
' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' +
|
||||
' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. Edited records are still skipped.',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (FORCE && FORCE_ONLY_LOCAL && prodLike) {
|
||||
console.error('[seed] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.')
|
||||
process.exit(1)
|
||||
}
|
||||
if (UPDATE && prodLike) console.warn('[seed] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?')
|
||||
|
||||
// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip cache revalidation and the
|
||||
// IndexNow ping for seeded (placeholder) content. ipalSeed: for the project's own hooks.
|
||||
const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true }
|
||||
const payload = await getPayload({ config })
|
||||
const loc = payload.config.localization
|
||||
const def = loc ? loc.defaultLocale : undefined
|
||||
const codes = loc ? loc.localeCodes : []
|
||||
const others = codes.filter((c) => c !== def)
|
||||
const ids = new Map<string, string | number>()
|
||||
|
||||
const isLocalized = (v: Json): boolean =>
|
||||
!!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0 && Object.keys(v).every((k) => codes.includes(k))
|
||||
|
||||
/** Value for one locale; arrays keep the ids of rows that already exist. undefined = omit. */
|
||||
function pick(v: Json, locale: string | undefined, existing: unknown): Json | undefined {
|
||||
if (isLocalized(v)) { const m = v as { [k: string]: Json }; return locale ? m[locale] : m[def as string] }
|
||||
if (Array.isArray(v)) {
|
||||
const ex = Array.isArray(existing) ? existing : []
|
||||
return v.map((item, i) => {
|
||||
const out = pick(item, locale, ex[i])
|
||||
const id = (ex[i] as { id?: string } | undefined)?.id
|
||||
return out && typeof out === 'object' && !Array.isArray(out) && id ? { ...out, id } : (out ?? null)
|
||||
})
|
||||
}
|
||||
if (v && typeof v === 'object') {
|
||||
if (typeof v.$page === 'string') {
|
||||
const id = ids.get(v.$page)
|
||||
if (id === undefined) throw new Error(`$page "${v.$page}" not found — seed that page earlier in PAGES or create it in the panel`)
|
||||
return id
|
||||
}
|
||||
const ex = (existing && typeof existing === 'object' ? existing : {}) as Record<string, unknown>
|
||||
const out: { [k: string]: Json } = {}
|
||||
for (const [k, val] of Object.entries(v) as [string, Json][]) {
|
||||
const r = pick(val, locale, ex[k])
|
||||
if (r !== undefined) out[k] = r
|
||||
}
|
||||
return out
|
||||
}
|
||||
return v
|
||||
}
|
||||
const defSlug = (p: { [k: string]: Json }) => String(isLocalized(p.slug) ? (p.slug as { [k: string]: Json })[def as string] : p.slug)
|
||||
const hasPageRef = (v: Json): boolean =>
|
||||
Array.isArray(v) ? v.some(hasPageRef) : !!v && typeof v === 'object' ? typeof v.$page === 'string' || Object.values(v).some(hasPageRef) : false
|
||||
const hasContent = (v: unknown): boolean =>
|
||||
typeof v === 'string' ? v.trim() !== '' : typeof v === 'number' || v === true ? true
|
||||
: Array.isArray(v) ? v.some(hasContent) : !!v && typeof v === 'object' ? Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x)) : false
|
||||
|
||||
// --- "edited since seeding" -------------------------------------------------
|
||||
/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */
|
||||
const stable = (v: unknown): string =>
|
||||
Array.isArray(v) ? `[${v.map(stable).join(',')}]`
|
||||
: v && typeof v === 'object'
|
||||
? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record<string, unknown>)[k] != null).sort()
|
||||
.map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`
|
||||
: JSON.stringify(v ?? null)
|
||||
const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32)
|
||||
/** The current values at the keys the seed writes (everything else in the record is ignored). */
|
||||
function project(seed: unknown, cur: unknown): unknown {
|
||||
if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((s, i) => project(s, cur[i])) : cur
|
||||
if (seed && typeof seed === 'object') {
|
||||
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur
|
||||
return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record<string, unknown>)[k], (cur as Record<string, unknown>)[k])]))
|
||||
}
|
||||
return cur
|
||||
}
|
||||
const localesOrDefault = codes.length ? codes : [undefined]
|
||||
/** Seed values per locale (refs resolved). */
|
||||
const seedPerLocale = (v: Json) => Object.fromEntries(localesOrDefault.map((l) => [l ?? '-', pick(v, l, undefined)]))
|
||||
const hasField = (fields: unknown[] | undefined) => !!HASH_FIELD && !!fields?.some((f) => (f as { name?: string }).name === HASH_FIELD)
|
||||
const pagesHaveHash = hasField(payload.collections[COLLECTION as never]?.config.fields as unknown[] | undefined)
|
||||
const globalHasHash = (slug: string) => hasField(payload.config.globals.find((g) => g.slug === slug)?.fields as unknown[] | undefined)
|
||||
|
||||
/** null = untouched; a string = why it counts as edited. */
|
||||
async function editedReason(
|
||||
doc: Record<string, unknown>,
|
||||
seed: Json,
|
||||
withHash: boolean,
|
||||
readLocale: (l: string | undefined) => Promise<unknown>,
|
||||
): Promise<string | null> {
|
||||
const stored = withHash ? doc[HASH_FIELD] : undefined
|
||||
if (typeof stored === 'string' && stored) {
|
||||
const seeded = seedPerLocale(seed)
|
||||
const current: Record<string, unknown> = {}
|
||||
for (const l of localesOrDefault) current[l ?? '-'] = project(seeded[l ?? '-'], await readLocale(l))
|
||||
return hashOf(current) === stored ? null : `${HASH_FIELD} differs`
|
||||
}
|
||||
const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt))
|
||||
if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt'
|
||||
const s = Math.round((u - c) / 1000)
|
||||
return s <= UNTOUCHED_SECONDS ? null : `updated ${s}s after creation`
|
||||
}
|
||||
|
||||
// --- report -----------------------------------------------------------------
|
||||
type Status = 'create' | 'skip (exists)' | 'update' | 'skip (edited)' | 'error'
|
||||
const counts: Record<Status, number> = { create: 0, 'skip (exists)': 0, update: 0, 'skip (edited)': 0, error: 0 }
|
||||
const report = (status: Status, what: string, note = '') => {
|
||||
counts[status]++
|
||||
console.log(`${status.padEnd(14)} ${what}${note ? ` — ${note}` : ''}`)
|
||||
}
|
||||
const readOpts = (l: string | undefined) => (l ? { locale: l as never, fallbackLocale: false as never } : {})
|
||||
console.log(`[seed] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}\n`)
|
||||
|
||||
// Existing pages first, so $page works regardless of order.
|
||||
const { docs: existingPages } = await payload.find({ collection: COLLECTION as never, depth: 0, limit: 0, pagination: false, ...readOpts(def) })
|
||||
const existingIds = new Set<string | number>()
|
||||
for (const d of existingPages as { id: string | number; slug?: string }[]) if (d.slug) { ids.set(d.slug, d.id); existingIds.add(d.id) }
|
||||
|
||||
// Plan: one status per page, decided before anything is written.
|
||||
const plan = new Map<string, 'create' | 'update'>()
|
||||
for (const p of PAGES) {
|
||||
const slug = defSlug(p)
|
||||
const id = ids.get(slug)
|
||||
if (id === undefined) { plan.set(slug, 'create'); if (DRY) ids.set(slug, `(new:${slug})`); continue }
|
||||
if (!UPDATE) { report('skip (exists)', `${COLLECTION} "${slug}"`, 'SEED_UPDATE=1 to update untouched records'); continue }
|
||||
try {
|
||||
const readDoc = (l: string | undefined) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, ...readOpts(l) })
|
||||
const why = await editedReason((await readDoc(def)) as Record<string, unknown>, p, pagesHaveHash, readDoc)
|
||||
if (why && !FORCE) { report('skip (edited)', `${COLLECTION}/${String(id)} "${slug}"`, why); continue }
|
||||
plan.set(slug, 'update')
|
||||
} catch (e) {
|
||||
report('error', `${COLLECTION} "${slug}"`, (e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 1: create missing pages without layout links (targets may not exist yet), pass 2: full content.
|
||||
for (const pass of [1, 2] as const) {
|
||||
for (const p of PAGES) {
|
||||
const slug = defSlug(p)
|
||||
const action = plan.get(slug)
|
||||
if (!action || (pass === 1 && action !== 'create')) continue
|
||||
if (DRY) {
|
||||
if (pass === 1) continue
|
||||
try { pick(p, def, undefined); report(action, `${COLLECTION} "${slug}"`, `[${codes.join(', ') || '-'}]`) } // resolves $page refs
|
||||
catch (e) { report('error', `${COLLECTION} "${slug}"`, (e as Error).message) }
|
||||
continue
|
||||
}
|
||||
try {
|
||||
if (pass === 1) {
|
||||
const data = pick(hasPageRef(p) ? { ...p, layout: [] } : p, def, undefined) as Record<string, unknown>
|
||||
const created = await payload.create({ collection: COLLECTION as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
|
||||
ids.set(slug, (created as { id: string | number }).id)
|
||||
continue
|
||||
}
|
||||
const id = ids.get(slug)
|
||||
if (id === undefined) continue // pass 1 failed — already reported
|
||||
const readDoc = (l: string) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, locale: l as never, fallbackLocale: false as never })
|
||||
const base = pick(p, def, undefined) as Record<string, unknown>
|
||||
const data = pagesHaveHash ? { ...base, [HASH_FIELD]: hashOf(seedPerLocale(p)) } : base
|
||||
await payload.update({ collection: COLLECTION as never, id: id as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
|
||||
for (const l of others) {
|
||||
await payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, l, await readDoc(def as string)) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX })
|
||||
}
|
||||
report(action, `${COLLECTION}/${String(id)} "${slug}"`, `[${codes.join(', ') || '-'}]`)
|
||||
} catch (e) {
|
||||
report('error', `${COLLECTION} "${slug}"`, (e as Error).message)
|
||||
plan.delete(slug)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Globals: only empty fields are filled. With SEED_UPDATE=1 an untouched global gets every seeded field.
|
||||
for (const g of GLOBALS) {
|
||||
try {
|
||||
const readG = (l: string | undefined) => payload.findGlobal({ slug: g.slug as never, depth: 0, ...readOpts(l) })
|
||||
const cur = (await readG(def)) as Record<string, unknown>
|
||||
const empty = Object.keys(g.data).filter((k) => !hasContent(cur[k]))
|
||||
let keys = empty
|
||||
let edited: string | null = null
|
||||
if (UPDATE) {
|
||||
edited = await editedReason(cur, g.data, globalHasHash(g.slug), readG)
|
||||
if (!edited || FORCE) keys = Object.keys(g.data)
|
||||
}
|
||||
if (!keys.length) {
|
||||
if (edited) report('skip (edited)', `global ${g.slug}`, edited)
|
||||
else report('skip (exists)', `global ${g.slug}`, 'every seeded field has content')
|
||||
continue
|
||||
}
|
||||
const all = keys.length === Object.keys(g.data).length
|
||||
const status: Status = keys !== empty ? 'update' : edited ? 'skip (edited)' : 'create'
|
||||
const note = keys !== empty ? `[${codes.join(', ') || '-'}]` : `${edited ? `${edited}; ` : ''}empty fields filled: ${keys.join(', ')}`
|
||||
if (!DRY) {
|
||||
const part = Object.fromEntries(keys.map((k) => [k, g.data[k]])) as { [k: string]: Json }
|
||||
const base = pick(part, def, cur) as Record<string, unknown>
|
||||
// The hash describes the whole seeded set — store it only when every seeded field was written.
|
||||
const data = all && globalHasHash(g.slug) ? { ...base, [HASH_FIELD]: hashOf(seedPerLocale(g.data)) } : base
|
||||
await payload.updateGlobal({ slug: g.slug as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
|
||||
for (const l of others) {
|
||||
await payload.updateGlobal({ slug: g.slug as never, data: pick(part, l, await readG(def)) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX })
|
||||
}
|
||||
}
|
||||
report(status, `global ${g.slug}`, note)
|
||||
} catch (e) {
|
||||
report('error', `global ${g.slug}`, (e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n[seed] summary${DRY ? ' (dry run — nothing written)' : ''}`)
|
||||
console.table({ created: counts.create, skipped: counts['skip (exists)'], updated: counts.update, 'skipped-edited': counts['skip (edited)'], errors: counts.error })
|
||||
const { errors } = seed.summary()
|
||||
const todo = JSON.stringify({ PAGES, GLOBALS }).match(/\[TO FILL:[^\]]*\]/g) ?? []
|
||||
if (todo.length) console.log(`\n${todo.length} placeholder(s) for the final report:\n ${[...new Set(todo)].join('\n ')}`)
|
||||
process.exit(counts.error ? 1 : 0)
|
||||
process.exit(errors ? 1 : 0)
|
||||
|
||||
+80
-18
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user