diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1eadd3d..ef7af35 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,33 @@ 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. +## Unreleased + +Database names follow one rule, and seeding a live site touches only the records you name. + +### New +- **Database name rule:** `_prod` / `_dev` (e.g. `acmepl_prod`), docs/deployment.md. + `ipalEnvRules({ databaseName: true })` (domain from `NEXT_PUBLIC_SERVER_URL`, skipped on localhost) or + `{ databaseName: { domain, warn } }` checks `DATABASE_URI` and **warns only** — never fails startup. Default off. + Helpers: `databaseNamesFor(domain)`, `databaseNameFromUri(uri)`, `checkDatabaseName({ databaseUri, domain })`. +- **Seeding after launch:** `createSeeder(payload, { only })` / `SEED_ONLY="pages:kontakt,global:header"` (also + `forms:`, `pages:*`) — the run touches only the listed records; the rest are reported as + `skip (not listed)`. The seed templates (`ipal-site`, `ipal-form`) read it. + +### Changed +- **A full seed of a live database is refused:** a run without `only` / `SEED_ONLY` against `NODE_ENV=production` or + a non-local database now throws (with the steps to follow). Dry runs (`SEED_DRY_RUN=1`) are never refused. Allow it + only with the owner's explicit OK: `IPAL_SEED_ALLOW_FULL=1` or `guard: { allowFull: true }`; `guard: false` turns + every guard off. + +### Requires project changes +1. **Production seed scripts / Coolify jobs:** a seed run against production without a record list now stops. List + the records: `SEED_ONLY="pages:kontakt,global:header" pnpm seed` (check with `SEED_DRY_RUN=1` first, back up the + database). A deliberate full re-seed: `IPAL_SEED_ALLOW_FULL=1`, with the owner's OK. Local seeding is unchanged. +2. Optional: name the databases `<domain without dots>_prod` / `_dev` and add `ipalEnvRules({ databaseName: true })` + to see a warning when `DATABASE_URI` points elsewhere. Existing databases need not be renamed. +3. Seed scripts copied from older templates: take the new `SEED_ONLY` handling from `ipal-site` / `ipal-form`. + ## 1.14.6 The release of everything listed under 1.14.5. **1.14.5 was tagged but never published** (its pre-publish test run diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 7e2168a..d8304a6 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -36,6 +36,19 @@ patch `node_modules` or fork the package. **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. +> **VERY IMPORTANT — seeding after launch.** Once a site is live, **never run a full seed again**: the owner's +> edits on the live site must survive. Every later change targets **named records only** — specific pages, +> globals, forms or fields — listed in the seed (`only: [...]` / `SEED_ONLY="pages:kontakt,global:header"`). +> Never re-seed everything, not even in create-only mode, without the owner's explicit OK. `createSeeder` +> refuses a run with no record list against a production or non-local database unless `IPAL_SEED_ALLOW_FULL=1` +> (set it only after that OK). + +**Database names** (MongoDB and Postgres): the site's domain **with the dots removed**, plus `_prod` or `_dev` — +`intecion.com` → `intecioncom_prod` / `intecioncom_dev`, `architektimprez.pl` → `architektimprezpl_prod` / +`architektimprezpl_dev`. The name is the path of `DATABASE_URI`: `mongodb://…@mongo:27017/intecioncom_prod?authSource=admin`, +`postgres://…@db:5432/intecioncom_prod`. You derive the names from the domain and confirm them with the owner (ipal-setup +stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (deployment.md §4.2a). + **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. @@ -44,6 +57,7 @@ Write new rules, AGENTS.md entries and plugin-gap reports in English. - On production: dry run first (`SEED_DRY_RUN=1`), back up the database (Coolify **Backup now**), then the real run. - `SEED_UPDATE=1` on production / a non-local database only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`, after a backup; records an editor changed are always skipped and reported (`skip (edited)`) — never use `SEED_FORCE=1` there. +- After launch: named records only (`only` / `SEED_ONLY`); a full run of a live database is refused without `IPAL_SEED_ALLOW_FULL=1`. - Schema and one-off data fixes → Payload migrations; field renames with content → **ipal-migrate-fields**; content → seeds. ## Ask before you build — architecture questions @@ -60,7 +74,7 @@ the ready-to-send list is in **ipal-setup** stage 0 (ipal-site phase 0 uses the | Forms | which forms, who receives them, e-mail provider (SMTP from the panel or Microsoft Graph) | | Analytics and consent | GA4 / GTM / pixels, Consent Mode basic or advanced, cookie banner mode, cookie scan | | SEO / GEO | market and local business data, AI crawler policy (llms.txt, Markdown, MCP, AI bots) | -| Data and media | database (Postgres or MongoDB), media storage (R2 or local disk) | +| Data and media | database (Postgres or MongoDB) and its names (`<domain without dots>_prod` / `_dev` — derive, then confirm), media storage (R2 or local disk) | | Admin | 2FA, white-label (client brand in the panel), agency credit | | Hosting | Coolify, the production domain(s), who adds the DNS records (deployment.md §6) | @@ -1290,10 +1304,12 @@ Write everything in this file in English. ## Project decisions - Architecture answers (AGENT.md "Ask before you build"), one line each: languages + default + URLs · - styling · pages/collections · forms + e-mail · analytics/consent/cookie scan · SEO/GEO · database + media · + styling · pages/collections · forms + e-mail · analytics/consent/cookie scan · SEO/GEO · database (+ names + `<domain>_prod` / `<domain>_dev`, e.g. `intecioncom_prod`) + media · 2FA/white-label/credit · hosting + domains + DNS - <client-specific decisions, e.g. "blog without authors", "404 = homepage"> - <approved workarounds: what, why, plugin-request file, owner's approval> +- Launch date: <date> — from then on seeds touch named records only (AGENT.md "seeding after launch") - <exceptions to the rules — with the reason> - <only on a client decision> ipal-audit-skip: <keys from AGENT.md §0b> — <reason, source of the decision> ``` diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/ipal-form/SKILL.md index 4ed447a..a856036 100644 --- a/docs/agent/skills/ipal-form/SKILL.md +++ b/docs/agent/skills/ipal-form/SKILL.md @@ -114,6 +114,8 @@ Commit the script — in production run it after the migration: `SEED_DRY_RUN=1` the real run (rules: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Changing the form: fix FORM, `SEED_UPDATE=1 pnpm payload run …` — it updates the form only if nobody edited it since seeding (otherwise `skip (edited)`); on production / a non-local database it also needs `IPAL_SEED_ALLOW_PROD_UPDATE=1`. +**After launch** a form seed touches only its own form (`only: ['forms:<title>']` in the template) — never re-run +every form seed or the content seed to change one form (AGENT.md "seeding after launch"). Details the seed already covers, which you check after every manual change in the panel: 1. **Forms → the form**: fields from the brief, `name` in English, lowercase diff --git a/docs/agent/skills/ipal-form/resources/seed-form.template.ts b/docs/agent/skills/ipal-form/resources/seed-form.template.ts index 2998ca4..d842f54 100644 --- a/docs/agent/skills/ipal-form/resources/seed-form.template.ts +++ b/docs/agent/skills/ipal-form/resources/seed-form.template.ts @@ -106,7 +106,9 @@ function richText(text: string) { const payload = await getPayload({ config }) // Options (docs/seeding.md § Turn off, override, extend) — env vars work without editing this file. -const seed = createSeeder(payload, { label: '[seed-form]' }) +// A form seed touches exactly one record — this form (matched by its title). After launch that stays true: +// it never re-seeds other forms, and an edited form is skipped (docs/seeding.md, "after launch"). +const seed = createSeeder(payload, { label: '[seed-form]', only: [`forms:${FORM.title}`] }) // Notification address — from the panel, never from this file. let notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() ?? '' diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 24b23a3..38f8e44 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -149,7 +149,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip | languages | `src/i18n.config.ts` | `export const i18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const satisfies I18nConfig` | `curl -sI $U/` → 3xx to `/pl` | i18n.md | | proxy | `src/proxy.ts` | `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })` + `export const config = { matcher: ['/((?!api\|admin\|_next\|.*\\..*).*)'] }` (a literal!) | `curl -sI $U/` → `/pl`; `curl -s -H 'Accept: text/markdown' $U/pl` → Markdown | i18n.md, PROGRAMISTA §2.6 | | proxy (Next 15 / custom) | `middleware`/`proxy.ts` | `createLocaleMiddleware({ config, … })` (`/next/middleware` or the main entry) | as above | i18n.md | -| env validation | `src/instrumentation.ts` | `if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` from `@intecion/ipal-kit/env` | remove a variable → startup fails with the list of missing ones | env.md | +| env validation | `src/instrumentation.ts` | `if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true, ipHeader: true, databaseName: true }))` from `@intecion/ipal-kit/env` | remove a variable → startup fails with the list of missing ones; a database not named `<domain>_prod`/`_dev` → a warning | env.md, deployment.md §4.2a | | Next config | `next.config.ts` | `withPayload(withSecurityConfig({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts, csp }) }, { source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, ...buildUploadSecurityHeaders()] }))` | `curl -sI $U/pl \| grep -iE 'x-content-type\|strict-transport\|x-powered-by'` (no `x-powered-by`) | security.md, storage.md, PROGRAMISTA §2.9 | | CSP | `next.config.ts`, `src/app/api/csp-report/route.ts` | `csp = { mode: 'report-only', reportUri: '/api/csp-report', r2Url, <flags> }` in `buildSecurityHeaders` + `buildAdminCspHeaders`; route `export const POST = createCspReportRoute()`; after clean reports `mode: 'enforce'` | `curl -sI $U/pl \| grep -i content-security-policy-report-only`; browser console and `[csp]` log lines without violations | security.md | | data / routes | `src/lib/content.ts` | `export const { … } = createContentHelpers({ config, content, i18n: i18nConfig, baseUrl, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName } })` | `pnpm tsc --noEmit` | frontend.md, PROGRAMISTA §2.7 | @@ -218,7 +218,7 @@ and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `ba | variable | required when | effect when missing | where to set | |---|---|---|---| -| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`) | +| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`); the database is named `<domain without dots>_prod` / `_dev` (`intecioncom_prod`), checked by `databaseName: true` | | `PAYLOAD_SECRET` | always | Payload does not start; `assertEnv` throws | env, ≥32 characters, different in prod (`secretVar`) | | `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 | @@ -237,13 +237,15 @@ 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`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`. +**Seeding** (content in pages, forms, globals) — **VERY IMPORTANT: after launch never re-seed everything; named records only** (`only` / `SEED_ONLY`; a full run of a live database needs the owner's OK and `IPAL_SEED_ALLOW_FULL=1`). Create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Helper: `createSeeder` from `@intecion/ipal-kit/seed` (resources/api.md → Seeding). 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_ONLY` | the records a run may touch (`pages:kontakt,global:header`) — required after launch | +| `IPAL_SEED_ALLOW_FULL=1` | allow a run without `SEED_ONLY` on production / a non-local database — owner's explicit OK only (in code: `createSeeder(payload, { guard: { allowFull: true } })`; `guard: false` turns every guard off) | | `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`) | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index b2a6112..6e0bf68 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -254,7 +254,10 @@ Opt-in with `ipalKit({ cookieScanner: true })`; the plugin wires the collection, | 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`; `R2_PUBLIC_URL` optional unless `storage: { requirePublicUrl: true }` | +| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar?, databaseName? })` | `@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 }`; `databaseName: true \| { domain?, warn? }` only warns when the `DATABASE_URI` database is not `<domain without dots>_prod` / `_dev` | +| `databaseNamesFor(domainOrUrl)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the two database names for a site: `intecion.com` → `{ prod: 'intecioncom_prod', dev: 'intecioncom_dev' }` (`www.` dropped, dots removed) | +| `databaseNameFromUri(uri)` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | the database name (URI path) of a Mongo / Postgres `DATABASE_URI`; null for SQLite files or no name | +| `checkDatabaseName({ databaseUri, domain })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | warning text when the name breaks the rule, else null (skips localhost / no domain) — what `databaseName` uses | **Types:** `EnvRule`, `EnvKind` — variable rule (`name`, `required`, `kind`, `oneOf`, `validate`); `AssertEnvOptions` — `assertEnv` options; `IpalEnvFeatures` — `ipalEnvRules` argument (all from `/env` and root). @@ -520,7 +523,7 @@ 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?, 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. | +| `createSeeder(payload, { dryRun?, update?, force?, only?, guard?, editCheck?, context?, pagesCollection?, 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. | | `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). | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 3b11471..7282e9a 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -43,13 +43,19 @@ Before I set up the site I need your decisions on: 5. Analytics and consent: GA4 / GTM / Meta / other pixels? Consent Mode basic or advanced? Cookie dialog inline / modal / detailed? Cookie scan of the finished site? 6. SEO/GEO: market, local business (address, opening hours)? AI access (llms.txt, Markdown, MCP, AI bots) — on? -7. Database: Postgres or MongoDB? Media: Cloudflare R2 or local disk (Coolify volume)? +7. Database: Postgres or MongoDB? Names (rule: domain without dots + _prod / _dev) — for <domain> I will use + <domainnodots>_prod and <domainnodots>_dev, OK? Media: Cloudflare R2 or local disk (Coolify volume)? 8. Admin: 2FA (on by default), white-label with the client's logo, agency credit in the panel? 9. Hosting: Coolify — which server/project? Production domain(s), www or apex? Who adds the DNS records? ``` **Code.** None — write every answer into `AGENTS.md` → "Project decisions" (one line per topic; template: AGENT.md §13). -**Check.** All nine topics have an answer in "Project decisions"; nothing in it says "assumed" or "default". +**Database names** (VERY IMPORTANT, deployment.md §4.2a): derive them from the production domain — dots removed, +plus `_prod` / `_dev` (`intecion.com` → `intecioncom_prod`, `intecioncom_dev`; `architektimprez.pl` → +`architektimprezpl_prod`, `architektimprezpl_dev`) — and confirm them in question 7. Never `payload`, `test` or a guess. + +**Check.** All nine topics have an answer in "Project decisions" (including both database names); nothing in it +says "assumed" or "default". **Turn off / override.** Never skipped. If the owner says "you decide" for a topic, write that down as their answer, propose a concrete choice and get a yes before you build it. @@ -403,7 +409,7 @@ export function register() { if (process.env.NEXT_RUNTIME !== 'nodejs') return // R2_PUBLIC_URL optional: media served through the app by default (storage.md, env.md) assertEnv( - ipalEnvRules({ storage: true, ipHeader: true /* , emailGraph: true with Graph */ }).map((r) => + ipalEnvRules({ storage: true, ipHeader: true, databaseName: true /* , emailGraph: true with Graph */ }).map((r) => r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r, ), ) diff --git a/docs/agent/skills/ipal-site/SKILL.md b/docs/agent/skills/ipal-site/SKILL.md index 73b73ad..f1f9237 100644 --- a/docs/agent/skills/ipal-site/SKILL.md +++ b/docs/agent/skills/ipal-site/SKILL.md @@ -80,6 +80,9 @@ 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. + **VERY IMPORTANT — after launch never run the whole seed again** (the owner's edits must survive): a later + change lists exactly the records it touches in `ONLY` / `SEED_ONLY` (e.g. `pages:kontakt,global:header`), + checked with a dry run; a full re-seed only with the owner's explicit OK (`IPAL_SEED_ALLOW_FULL=1`). 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. diff --git a/docs/agent/skills/ipal-site/resources/seed-content.template.ts b/docs/agent/skills/ipal-site/resources/seed-content.template.ts index 5f58ede..e44fab5 100644 --- a/docs/agent/skills/ipal-site/resources/seed-content.template.ts +++ b/docs/agent/skills/ipal-site/resources/seed-content.template.ts @@ -4,6 +4,7 @@ * SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts # no writes: prints create / skip / update per record * pnpm payload run scripts/seed-content.ts # creates what's missing, never overwrites * SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates records nobody edited since seeding + * SEED_ONLY="pages:kontakt" pnpm payload run … # only the listed records (or set ONLY below) * (`--dry-run` after the script path works too, e.g. `pnpm seed:content --dry-run`.) * * The rules live in createSeeder (@intecion/ipal-kit/seed), so fixes arrive with a @@ -16,6 +17,10 @@ * - 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. + * - VERY IMPORTANT — after launch: never run the whole seed again. The owner's edits on the live + * site must survive. List exactly the records this run may touch in ONLY (or SEED_ONLY); the rest + * is reported as "skip (not listed)". A run without a list against a production / non-local + * database is refused unless IPAL_SEED_ALLOW_FULL=1 — only with the owner's explicit OK. * * Write content ONCE, all languages side by side: * heading: { pl: 'Nasze usługi', en: 'Our services' } → localized value @@ -47,11 +52,14 @@ 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' +// Before launch: undefined (the whole site). After launch: ONLY the records the owner asked for, e.g. +// ['pages:kontakt', 'global:header'] — `collection:<default-locale slug>`, `global:<slug>`, `collection:*`. +const ONLY: string[] | undefined = undefined // ----------------------------------------------------------------- /CONTENT -- // 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 seed = createSeeder(await getPayload({ config }), { only: ONLY, pagesCollection: COLLECTION }) // One call for all pages: missing ones are created first, so $page links work in any order. await seed.upsertBySlug(COLLECTION, PAGES) diff --git a/docs/deployment.md b/docs/deployment.md index 99e3529..e92ca47 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -19,8 +19,9 @@ Related: [PROGRAMISTA.md](./dev/PROGRAMISTA.md) (from zero to a working site, § ### Core (REQUIRED — the project will not start without them) ```bash -# Database (Mongo or Postgres — depending on the project) -DATABASE_URI=mongodb://... # or postgres://... / file:./dev.db (dev) +# Database (Mongo or Postgres — depending on the project); name = <domain without dots>_prod / _dev (§4.2a) +DATABASE_URI=mongodb://user:pass@mongo:27017/intecioncom_prod?authSource=admin # or postgres://user:pass@db:5432/intecioncom_prod +# dev: …/intecioncom_dev, or file:./dev.db # Payload secret (signs sessions/tokens) — random, long PAYLOAD_SECRET=<random-string-min-32-chars> @@ -244,6 +245,27 @@ One Coolify **application** per project (built from the Git repo) plus a Coolify - **Redirect** www ↔ apex in the app's domain/redirect setting (Direction) so the canonical host is the one in `NEXT_PUBLIC_SERVER_URL` — canonical, hreflang and sitemap URLs use that variable, the redirect must agree with it. +### 4.2a Database names (VERY IMPORTANT) + +Every project uses the same names, on MongoDB and Postgres: the site's domain **with the dots removed**, plus +`_prod` (production) or `_dev` (development / staging). No other suffixes, no `payload`, `test` or `db1`. + +| Site | Production | Development | +|---|---|---| +| `intecion.com` | `intecioncom_prod` | `intecioncom_dev` | +| `architektimprez.pl` | `architektimprezpl_prod` | `architektimprezpl_dev` | + +- The name is the path of `DATABASE_URI`: `mongodb://user:pass@mongo:27017/intecioncom_prod?authSource=admin`, + `postgres://user:pass@db:5432/intecioncom_prod` (the Postgres database name, not the user or the schema). +- In Coolify: create the database resource with that database name (Postgres "Initial database", or the name in the + Mongo connection string), and set `DATABASE_URI` on the app to it. +- A leading `www.` is not part of the name; a hyphen in the domain stays (quote the name in SQL: + `CREATE DATABASE "my-sitepl_prod"`). +- **Check:** `ipalEnvRules({ databaseName: true })` warns at startup (never fails) when the name in `DATABASE_URI` + does not match the domain in `NEXT_PUBLIC_SERVER_URL` (skipped for localhost). `{ domain: 'intecion.com' }` sets the + domain, `{ warn }` replaces the console warning; leave the option out to turn the check off. Helpers: + `databaseNamesFor`, `databaseNameFromUri`, `checkDatabaseName` from `@intecion/ipal-kit/env` (env.md). + ### 4.2 Environment variables — where and when Coolify → the application → **Environment Variables**. Each variable can be available at **build time**, diff --git a/docs/env.md b/docs/env.md index 2d28820..236e31a 100644 --- a/docs/env.md +++ b/docs/env.md @@ -67,6 +67,8 @@ ipalEnvRules({ serverUrlVar?: string, // default 'NEXT_PUBLIC_SERVER_URL' secretVar?: string, // default 'PAYLOAD_SECRET' databaseVar?: string, // default 'DATABASE_URI' + databaseName?: boolean | { domain?: string; warn?: (message: string) => void }, + // WARN (never fail) when the DATABASE_URI database is not <domain without dots>_prod / _dev }) ``` @@ -101,6 +103,21 @@ assertEnv([ ]) ``` +### Database names — `databaseName` + +The naming rule (deployment.md §4.2a): the site's domain with the dots removed, plus `_prod` / `_dev` — +`intecion.com` → `intecioncom_prod` / `intecioncom_dev`. `ipalEnvRules({ databaseName: true })` adds a check that +only **warns** (console, or your `warn`) when the database in `DATABASE_URI` breaks it. The domain comes from +`NEXT_PUBLIC_SERVER_URL` in `process.env` (localhost and dotless hosts are skipped) or from `{ domain }`. + +```ts +import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '@intecion/ipal-kit/env' + +databaseNamesFor('https://www.intecion.com') // { prod: 'intecioncom_prod', dev: 'intecioncom_dev' } +databaseNameFromUri('postgres://u:p@db:5432/intecioncom_prod') // 'intecioncom_prod' (null for file:/no name) +checkDatabaseName({ databaseUri: process.env.DATABASE_URI, domain: 'intecion.com' }) // warning text or null +``` + ## assertEnv — the validator ```ts @@ -151,7 +168,7 @@ redeploys. ## Exports ```ts -import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' +import { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from '@intecion/ipal-kit/env' import type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from '@intecion/ipal-kit/env' ``` diff --git a/docs/seeding.md b/docs/seeding.md index eece364..37a5a9b 100644 --- a/docs/seeding.md +++ b/docs/seeding.md @@ -1,5 +1,12 @@ # seeding — content seeds that never overwrite production +> **VERY IMPORTANT — the first rule of seeding.** Once a site is live, **never run a full seed again**: the owner's +> edits on the live site must survive. Every later change targets **named records only** — specific pages, +> globals, forms or fields — listed in the seed (`only: [...]` / `SEED_ONLY="pages:kontakt,global:header"`). +> Never re-seed everything, not even in create-only mode, without the owner's explicit OK. `createSeeder` +> refuses a run with no record list against a production or non-local database unless `IPAL_SEED_ALLOW_FULL=1` +> (set it only after that OK). + A seed is a script that puts content into the database: pages, forms, globals. ipal-kit ships two templates. Copy them into the project and fill them from the brief: @@ -26,13 +33,17 @@ should use it too; if it does not, it must follow the rules by hand. 3. **Never delete.** No `payload.delete`, no "clean up first". A record that should go away is removed by a person in the panel. -4. **Never seed users, passwords or secrets.** SMTP, Turnstile, API keys and tokens stay in the panel or in +4. **After launch, named records only.** Before launch the seed may build the whole site. After launch a seed + lists exactly the records it may touch (`only`, `SEED_ONLY`) — everything else is reported as + `skip (not listed)` and never read for writing. A full run against a live database needs the owner's explicit + OK and `IPAL_SEED_ALLOW_FULL=1`. Record the launch date in `AGENTS.md` → "Project decisions". +5. **Never seed users, passwords or secrets.** SMTP, Turnstile, API keys and tokens stay in the panel or in env vars. The first admin is created on the first-user screen. -5. **Globals: fill only empty fields.** A field that already has content is kept. -6. **Media: leave upload fields empty or reference existing uploads by ID.** Never upload files in a +6. **Globals: fill only empty fields.** A field that already has content is kept. +7. **Media: leave upload fields empty or reference existing uploads by ID.** Never upload files in a production seed. The editor adds images. -7. **Write each locale separately, with `fallbackLocale: false`.** See [Locales](#locales). -8. **Pass the context flags** the plugin reads. See [Context flags](#context-flags). +8. **Write each locale separately, with `fallbackLocale: false`.** See [Locales](#locales). +9. **Pass the context flags** the plugin reads. See [Context flags](#context-flags). ## Running a seed @@ -41,6 +52,7 @@ should use it too; if it does not, it must follow the rules by hand. | `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts` | no writes; prints the plan | | `pnpm payload run scripts/seed-content.ts` | creates what is missing, never overwrites | | `SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts` | also updates records nobody edited since seeding | +| `SEED_ONLY="pages:kontakt,global:header" pnpm payload run scripts/seed-content.ts` | after launch: only the listed records (`collection:slug`, `forms:<title>`, `global:<slug>`, `collection:*`) | `--dry-run` after the script path does the same as `SEED_DRY_RUN=1`, for example with a package script: `"seed:content": "payload run scripts/seed-content.ts"` → `pnpm seed:content --dry-run`. @@ -53,19 +65,20 @@ Every run prints one line per record and a summary: | `skip (exists)` | the record exists; nothing changes | | `update` | `SEED_UPDATE=1` and nobody edited the record since seeding; the seed overwrites the seeded fields | | `skip (edited)` | `SEED_UPDATE=1`, but an editor changed the record; it is kept (the line says why) | +| `skip (not listed)` | the record is not on the run's list (`only` / `SEED_ONLY`); it is not touched | | `error` | the write failed; the script exits with code 1 | -The summary table counts `created`, `skipped`, `updated`, `skipped-edited` and `errors`. +The summary table counts `created`, `skipped`, `updated`, `skipped-edited`, `not listed` and `errors`. ## Before you run a seed on production -1. **Dry run.** Run the seed with `SEED_DRY_RUN=1` and read every line. Expect `create` and `skip (exists)`. -2. **Test on a copy.** Run it on staging or on a local copy of the production database first. -3. **Back up the database.** +2. **Dry run.** Run the seed with `SEED_DRY_RUN=1` and read every line. Expect `create` and `skip (exists)`. +3. **Test on a copy.** Run it on staging or on a local copy of the production database first. +4. **Back up the database.** - Coolify: the database resource → **Backups** → **Backup now** ([deployment.md §4.6](./deployment.md)). - Postgres by hand: `pg_dump -Fc "$DATABASE_URI" > before-seed.dump` - MongoDB by hand: `mongodump --uri="$DATABASE_URI" --archive=before-seed.archive` -4. **Run it for real.** Check the panel and the site. +5. **Run it for real.** Check the panel and the site. **Restore, if something went wrong:** @@ -135,13 +148,15 @@ Pass them in `context` on every `create`, `update` and `updateGlobal` (`createSe ## Running a seed on Coolify 1. Coolify → the application → **Terminal** → the app container ([deployment.md §4.7](./deployment.md)). -2. Dry run: `SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts`. +2. Dry run with the record list: `SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts` + — the plan must name only the records the owner asked for. 3. Back up the database (**Backup now**). 4. The real run, without `SEED_DRY_RUN`. The seed script and its dependencies must be in the image. Env vars (`DATABASE_URI`, `PAYLOAD_SECRET`, …) must be available at runtime, not only at build time. The container already has `NODE_ENV=production`, so -`SEED_UPDATE=1` is refused there unless you add `IPAL_SEED_ALLOW_PROD_UPDATE=1`. +`SEED_UPDATE=1` is refused there unless you add `IPAL_SEED_ALLOW_PROD_UPDATE=1`, and a run without `SEED_ONLY` +is refused unless you add `IPAL_SEED_ALLOW_FULL=1` (only with the owner's explicit OK). ## Seeds or migrations? @@ -218,6 +233,8 @@ the script: |---|---|---|---| | `SEED_DRY_RUN=1` / `--dry-run` | `dryRun` | off | no writes, print the plan | | `SEED_UPDATE=1` | `update` | off | update records nobody edited since seeding | +| `SEED_ONLY` | `only` | all records | the records the run may touch: `pages:kontakt`, `forms:Contact form`, `global:header`, `pages:*` (comma-separated in env) | +| `IPAL_SEED_ALLOW_FULL=1` | `guard.allowFull` | off | allow a run without `only` on production or a non-local database (a full re-seed — owner's OK only) | | `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) | diff --git a/src/exports/env.ts b/src/exports/env.ts index 7d54929..2b8992a 100644 --- a/src/exports/env.ts +++ b/src/exports/env.ts @@ -13,5 +13,5 @@ * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true })) * } */ -export { assertEnv, ipalEnvRules } from '../modules/env/index.js' +export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from '../modules/env/index.js' export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js' diff --git a/src/index.ts b/src/index.ts index 448b979..1de0439 100644 --- a/src/index.ts +++ b/src/index.ts @@ -181,7 +181,7 @@ export type { MailAdapterArgs } from './modules/email/mailAdapter.js' export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js' export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js' // Boot-time environment validation (fail fast on misconfigured deploys). -export { assertEnv, ipalEnvRules } from './modules/env/index.js' +export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from './modules/env/index.js' export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js' export { checkboxGroupBlock, placeholderField, stepBlock, timeBlock, withPlaceholder } from './modules/forms/builderBlocks.js' export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './modules/forms/builderLogic.js' diff --git a/src/modules/env/databaseName.ts b/src/modules/env/databaseName.ts new file mode 100644 index 0000000..c27f713 --- /dev/null +++ b/src/modules/env/databaseName.ts @@ -0,0 +1,44 @@ +/** + * Database naming rule (docs/deployment.md): the site's domain with the dots + * removed, plus `_prod` or `_dev` — intecion.com → intecioncom_prod / intecioncom_dev, + * architektimprez.pl → architektimprezpl_prod / architektimprezpl_dev. + * The same for MongoDB and Postgres; the name is the path of DATABASE_URI. + */ + +/** Hosts that are not a site domain (dev / Docker) — no expectation is derived from them. */ +const NOT_A_DOMAIN = /^(?:localhost|127\.0\.0\.1|\[?::1\]?|0\.0\.0\.0)$|^[^.]+$/ + +/** The two database names for a site domain or URL (`https://www.intecion.com/` → intecioncom_*). */ +export function databaseNamesFor(domainOrUrl: string): { dev: string; prod: string } { + const host = domainOrUrl.trim().toLowerCase().replace(/^[a-z][a-z\d+.-]*:\/\//, '').replace(/[/:?#].*$/, '').replace(/^www\./, '') + const base = host.replace(/\./g, '') + return { dev: `${base}_dev`, prod: `${base}_prod` } +} + +/** The database name in a connection string (the URI path), or null (SQLite file, no name). */ +export function databaseNameFromUri(uri: null | string | undefined): null | string { + const value = (uri ?? '').trim() + if (!value || /^file:/i.test(value)) {return null} + try { + const name = decodeURIComponent(new URL(value).pathname.replace(/^\//, '').split('/')[0] ?? '') + return name || null + } catch { + return null + } +} + +/** + * A warning when the database in `databaseUri` breaks the naming rule, else null. + * `domain` is the site's production domain; without one (or for localhost) nothing is checked. + */ +export function checkDatabaseName({ databaseUri, domain }: { databaseUri?: null | string; domain?: null | string }): null | string { + if (!domain) {return null} + const host = domain.trim().toLowerCase().replace(/^[a-z][a-z\d+.-]*:\/\//, '').replace(/[/:?#].*$/, '') + if (NOT_A_DOMAIN.test(host)) {return null} + const name = databaseNameFromUri(databaseUri) + if (!name) {return null} + const { dev, prod } = databaseNamesFor(host) + return name === prod || name === dev + ? null + : `database "${name}" does not follow the naming rule for ${host.replace(/^www\./, '')}: expected "${prod}" (production) or "${dev}" (development) — docs/deployment.md` +} diff --git a/src/modules/env/index.ts b/src/modules/env/index.ts index 3ad7ab5..37ffc10 100644 --- a/src/modules/env/index.ts +++ b/src/modules/env/index.ts @@ -1,4 +1,5 @@ export { assertEnv } from './assertEnv.js' export type { AssertEnvOptions, EnvKind, EnvRule } from './assertEnv.js' +export { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from './databaseName.js' export { ipalEnvRules } from './ipalEnvRules.js' export type { IpalEnvFeatures } from './ipalEnvRules.js' diff --git a/src/modules/env/ipalEnvRules.ts b/src/modules/env/ipalEnvRules.ts index d9878c3..ab088d4 100644 --- a/src/modules/env/ipalEnvRules.ts +++ b/src/modules/env/ipalEnvRules.ts @@ -2,12 +2,21 @@ import type { EnvRule } from './assertEnv.js' type TurnstileNames = { secretVar?: string; siteKeyVar?: string } +import { checkDatabaseName } from './databaseName.js' + export type IpalEnvFeatures = { /** * Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared * token (at least 16 characters). Required in production only. */ cookieCrawl?: boolean + /** + * Warn (never fail) when the database name in DATABASE_URI breaks the naming rule + * `<domain without dots>_prod` / `_dev` (docs/deployment.md). `true` takes the domain from + * NEXT_PUBLIC_SERVER_URL (skipped for localhost); `{ domain }` sets it; `{ warn }` replaces + * the console.warn. Default off. + */ + databaseName?: { domain?: string; warn?: (message: string) => void } | boolean /** Override the database var. Default 'DATABASE_URI'. */ databaseVar?: string /** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */ @@ -62,6 +71,7 @@ export type IpalEnvFeatures = { export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { const { cookieCrawl = false, + databaseName = false, databaseVar = 'DATABASE_URI', emailGraph = false, ipHeader = false, @@ -158,5 +168,20 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { ) } + if (databaseName) { + const { domain, warn = (message: string) => console.warn(`[ipal] ${message}`) } = databaseName === true ? {} : databaseName + rules.push({ + name: databaseVar, + description: 'Database name: <domain without dots>_prod / _dev (warning only)', + required: false, + // A warning, never an error: the project may have a reason (an old database, a shared server). + validate: (value) => { + const message = checkDatabaseName({ databaseUri: value, domain: domain ?? process.env[serverUrlVar] }) + if (message) {warn(`${databaseVar}: ${message}`)} + return true + }, + }) + } + return rules } diff --git a/src/modules/seed/seeder.ts b/src/modules/seed/seeder.ts index 6308e5b..c2ef33a 100644 --- a/src/modules/seed/seeder.ts +++ b/src/modules/seed/seeder.ts @@ -29,6 +29,8 @@ import { * - `update: true` overwrites only records nobody edited since seeding; * - `update: true` is refused on production / a non-local database unless * IPAL_SEED_ALLOW_PROD_UPDATE=1; + * - after launch a seed touches named records only (`only` / SEED_ONLY): a run with no + * record list is refused on production / a non-local database unless IPAL_SEED_ALLOW_FULL=1; * - every write carries `context` (ipalSkipIndexNow, disableRevalidate, ipalSeed); * - one line per record and summary() with the counts. * @@ -36,7 +38,7 @@ import { * package throws outside a bundled server, and `payload run` is plain Node. */ -export type SeedStatus = 'create' | 'error' | 'skip (edited)' | 'skip (exists)' | 'update' +export type SeedStatus = 'create' | 'error' | 'skip (edited)' | 'skip (exists)' | 'skip (not listed)' | 'update' export type SeedResult = { /** Record id; a placeholder `(new:<key>)` for a planned create in a dry run. */ @@ -50,6 +52,8 @@ export type SeedResult = { export type SeedSummary = { created: number errors: number + /** Records left out because they are not in `only`. */ + notListed: number skipped: number skippedEdited: number updated: number @@ -83,6 +87,11 @@ export type SeederOptions = { */ guard?: | { + /** + * A run without `only` on production / a non-local database (a full seed of a live site). + * Default IPAL_SEED_ALLOW_FULL=1 — only with the owner's explicit OK. + */ + allowFull?: boolean /** Default IPAL_SEED_ALLOW_PROD_UPDATE=1. */ allowProdUpdate?: boolean /** Database URL checked for "local". Default the var SEED_DB_URL_ENV names (DATABASE_URI). */ @@ -99,6 +108,14 @@ export type SeederOptions = { label?: string /** Where lines go. Default stdout. */ log?: (line: string) => void + /** + * The records this run may touch — everything else is reported as `skip (not listed)`. + * `'pages:kontakt'` (collection + default-locale slug, or the `upsertBy` key values joined + * with `|`), `'forms:Contact form'`, `'global:header'`, or `'pages:*'` for a whole collection. + * Default SEED_ONLY (comma-separated). Undefined = every record (a full seed — refused on a + * live database, see `guard.allowFull`). + */ + only?: string[] /** Collection `{ $page: '<slug>' }` references resolve in. Default 'pages'. */ pagesCollection?: string /** Also update records nobody edited since seeding. Default SEED_UPDATE=1. */ @@ -120,6 +137,8 @@ export type Seeder = { fillGlobal: (slug: string, data: Record<string, unknown>) => Promise<SeedResult> readonly force: boolean readonly local: boolean + /** The record list (`only`), or null for a full seed. */ + readonly only: null | string[] /** Ends the run: prints the summary and returns the counts (errors > 0 → exit 1). */ summary: () => SeedSummary readonly update: boolean @@ -142,7 +161,7 @@ const defaultLog = (line: string) => { process.stdout.write(`${line}\n`) } -type Item = { data: Record<string, unknown>; key: Record<string, number | string>; label: string } +type Item = { data: Record<string, unknown>; key: Record<string, number | string>; label: string; ref: string } type Planned = { action?: 'create' | 'update'; id?: number | string; result?: SeedResult } & Item const hasRef = (v: unknown): boolean => @@ -162,12 +181,24 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): const untouchedSeconds = options.editCheck?.untouchedSeconds ?? defaultUntouchedSeconds() const pagesCollection = options.pagesCollection ?? 'pages' const context = { ...DEFAULT_CONTEXT, ...options.context } + const onlyList = options.only ?? (env.SEED_ONLY ? env.SEED_ONLY.split(',') : undefined) + const only = onlyList ? onlyList.map((r) => r.trim()).filter(Boolean) : null const local = isLocalDatabase(guard ? (guard.databaseUrl ?? seedDatabaseUrl()) : seedDatabaseUrl(), guard ? { ...(guard.localHosts && { localHosts: guard.localHosts }) } : {}) if (guard) { const production = guard.production ?? env.NODE_ENV === 'production' const prodLike = production || !local const allowProdUpdate = guard.allowProdUpdate ?? env.IPAL_SEED_ALLOW_PROD_UPDATE === '1' + const allowFull = guard.allowFull ?? env.IPAL_SEED_ALLOW_FULL === '1' + if (!dryRun && !only?.length && prodLike && !allowFull) { + throw new Error( + `${label} full seed refused: ${production ? 'NODE_ENV=production' : 'the database is not local'} and no record list.\n` + + ' A live site keeps the owner\'s edits — after launch a seed touches named records only.\n' + + ' 1. List them: SEED_ONLY="pages:kontakt,global:header" (or createSeeder(payload, { only: [...] })).\n' + + ' 2. Run with SEED_DRY_RUN=1 and read the plan; back up the database.\n' + + ' 3. A full seed of a live database only with the owner\'s explicit OK: IPAL_SEED_ALLOW_FULL=1.', + ) + } if (update && prodLike && !allowProdUpdate) { throw new Error( `${label} update refused: ${production ? 'NODE_ENV=production' : 'the database is not local'}.\n` + @@ -184,11 +215,11 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): const { codes, defaultLocale } = localesOf(payload) const localeKeys = codes.length ? codes : [undefined] - const counts: Record<SeedStatus, number> = { create: 0, error: 0, 'skip (edited)': 0, 'skip (exists)': 0, update: 0 } + 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>() log( - `${label} ${dryRun ? 'DRY RUN — nothing is written' : 'writing'} · ${update ? `updates on${force ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}\n`, + `${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`, ) const report = (result: SeedResult): SeedResult => { @@ -197,6 +228,10 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): return result } + /** Is this record on the run's list? `collection:*` lists a whole collection. */ + const listed = (ref: string) => !only || only.includes(ref) || only.includes(`${ref.slice(0, ref.indexOf(':'))}:*`) + const notListed = (label: string): SeedResult => ({ label, note: 'not in the record list (only / SEED_ONLY)', status: 'skip (not listed)' }) + const collectionConfig = (slug: string) => payload.collections[slug as never]?.config const hasHashField = (fields: undefined | unknown[]) => !!hashField && !!fields?.some((f) => (f as { name?: string }).name === hashField) @@ -262,7 +297,8 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): return editedSinceSeed({ currentHash, doc, hashField: withHash ? hashField : false, untouchedSeconds }) } - const upsertMany = async (collection: string, items: Item[]): Promise<SeedResult[]> => { + const upsertMany = async (collection: string, all: Item[]): Promise<SeedResult[]> => { + const items = all.filter((item) => listed(item.ref)) const withHash = hasHashField(collectionConfig(collection)?.fields as undefined | unknown[]) const draft = hasDrafts(collection) const trackPages = collection === pagesCollection @@ -334,7 +370,9 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): } } } - return plan.map((p) => report(p.result!)) + // Results in the caller's order; records off the list are reported, never touched. + const done = new Map(plan.map((p) => [p.ref, p.result!])) + return all.map((item) => report(done.get(item.ref) ?? notListed(item.label))) } const slugOf = (data: Record<string, unknown>, slugField: string) => { @@ -354,17 +392,21 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): const list = Array.isArray(data) ? data : [data] const items = list.map((d) => { const slug = slugOf(d, slugField) - return { data: d, key: { [slugField]: slug }, label: `${collection} "${slug}"` } + return { data: d, key: { [slugField]: slug }, label: `${collection} "${slug}"`, ref: `${collection}:${slug}` } }) const results = await upsertMany(collection, items) return Array.isArray(data) ? results : results[0] } const upsertBy: Seeder['upsertBy'] = async (collection, key, data) => - (await upsertMany(collection, [{ data, key, label: `${collection} ${Object.values(key).map((v) => `"${String(v)}"`).join(' ')}` }]))[0] + (await upsertMany(collection, [{ + data, key, label: `${collection} ${Object.values(key).map((v) => `"${String(v)}"`).join(' ')}`, + ref: `${collection}:${Object.values(key).map(String).join('|')}`, + }]))[0] const fillGlobal: Seeder['fillGlobal'] = async (slug, data) => { const label = `global ${slug}` + if (!listed(`global:${slug}`)) {return report(notListed(label))} try { const target = { global: slug } const withHash = hasHashField(payload.config.globals.find((g) => g.slug === slug)?.fields as undefined | unknown[]) @@ -398,16 +440,17 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): const result: SeedSummary = { created: counts.create, errors: counts.error, + notListed: counts['skip (not listed)'], skipped: counts['skip (exists)'], skippedEdited: counts['skip (edited)'], updated: counts.update, } log(`\n${label} summary${dryRun ? ' (dry run — nothing written)' : ''}`) log( - ` created ${result.created} · skipped ${result.skipped} · updated ${result.updated} · skipped-edited ${result.skippedEdited} · errors ${result.errors}`, + ` created ${result.created} · skipped ${result.skipped} · updated ${result.updated} · skipped-edited ${result.skippedEdited} · not listed ${result.notListed} · errors ${result.errors}`, ) return result } - return { dryRun, fillGlobal, force, local, summary, update, upsertBy, upsertBySlug } + return { dryRun, fillGlobal, force, local, only, summary, update, upsertBy, upsertBySlug } } diff --git a/test/env.test.ts b/test/env.test.ts index e9d7fb6..16adeed 100644 --- a/test/env.test.ts +++ b/test/env.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { assertEnv } from '../src/modules/env/assertEnv.js' +import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '../src/modules/env/databaseName.js' import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js' const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 's' } @@ -52,3 +53,40 @@ describe('ipalEnvRules({ storage })', () => { expect(check({ ...base, NODE_ENV: 'development', R2_BUCKET: 'b' })).toThrow(/R2_ACCESS_KEY_ID is required/) }) }) + +describe('database naming rule', () => { + test('names come from the domain without dots', () => { + expect(databaseNamesFor('intecion.com')).toEqual({ dev: 'intecioncom_dev', prod: 'intecioncom_prod' }) + expect(databaseNamesFor('https://www.architektimprez.pl/')).toEqual({ dev: 'architektimprezpl_dev', prod: 'architektimprezpl_prod' }) + }) + + test('the name is read from Mongo and Postgres URIs', () => { + expect(databaseNameFromUri('mongodb://u:p@mongo:27017/intecioncom_prod?authSource=admin')).toBe('intecioncom_prod') + expect(databaseNameFromUri('mongodb+srv://u:p@cluster.example.net/intecioncom_dev')).toBe('intecioncom_dev') + expect(databaseNameFromUri('postgres://u:p@db:5432/intecioncom_prod')).toBe('intecioncom_prod') + expect(databaseNameFromUri('file:./dev.db')).toBeNull() + expect(databaseNameFromUri('postgres://u:p@db:5432')).toBeNull() + }) + + test('checkDatabaseName warns on a mismatch and skips local or unknown domains', () => { + expect(checkDatabaseName({ databaseUri: 'postgres://db/intecioncom_prod', domain: 'https://intecion.com' })).toBeNull() + expect(checkDatabaseName({ databaseUri: 'postgres://db/payload', domain: 'intecion.com' })).toMatch(/expected "intecioncom_prod"/) + expect(checkDatabaseName({ databaseUri: 'postgres://db/payload', domain: 'http://localhost:3000' })).toBeNull() + expect(checkDatabaseName({ databaseUri: 'postgres://db/payload' })).toBeNull() + }) + + test('ipalEnvRules({ databaseName }) only warns — assertEnv still passes', () => { + const warn = vi.fn() + const env = { DATABASE_URI: 'mongodb://mongo/payload', NEXT_PUBLIC_SERVER_URL: 'https://intecion.com', PAYLOAD_SECRET: 's' } + expect(() => assertEnv(ipalEnvRules({ databaseName: { domain: 'intecion.com', warn } }), { env })).not.toThrow() + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/DATABASE_URI: database "payload"[\s\S]*intecioncom_prod/)) + warn.mockClear() + assertEnv(ipalEnvRules({ databaseName: { domain: 'www.intecion.com', warn } }), { env: { ...env, DATABASE_URI: 'mongodb://mongo/intecioncom_dev' } }) + expect(warn).not.toHaveBeenCalled() + // true: the domain comes from NEXT_PUBLIC_SERVER_URL in process.env + vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://architektimprez.pl') + assertEnv(ipalEnvRules({ databaseName: { warn } }), { env: { ...env, DATABASE_URI: 'postgres://db/architektimprez_prod' } }) + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/expected "architektimprezpl_prod"/)) + vi.unstubAllEnvs() + }) +}) diff --git a/test/seed.test.ts b/test/seed.test.ts index 4f273c9..1ac2504 100644 --- a/test/seed.test.ts +++ b/test/seed.test.ts @@ -165,7 +165,7 @@ describe('createSeeder', () => { const again = seeder() expect((await again.upsertBySlug('pages', PAGES)).map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)']) - expect(again.summary()).toEqual({ created: 0, errors: 0, skipped: 2, skippedEdited: 0, updated: 0 }) + expect(again.summary()).toEqual({ created: 0, errors: 0, notListed: 0, skipped: 2, skippedEdited: 0, updated: 0 }) expect(lines.join('\n')).toMatch(/skip \(exists\)\s+pages "start"/) }) @@ -243,19 +243,55 @@ describe('createSeeder', () => { test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => { vi.stubEnv('NODE_ENV', 'production') - expect(() => seeder({ update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/) - expect(() => seeder()).not.toThrow() // create-only is always allowed + const only = ['pages:kontakt'] + expect(() => seeder({ only, update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/) + expect(() => seeder({ only })).not.toThrow() // create-only of listed records is always allowed vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') - expect(seeder({ update: true }).update).toBe(true) + expect(seeder({ only, update: true }).update).toBe(true) expect(lines.join('\n')).toMatch(/Did you back it up/) vi.unstubAllEnvs() vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app') - expect(() => seeder({ update: true })).toThrow(/the database is not local/) + expect(() => seeder({ only, update: true })).toThrow(/update refused: the database is not local/) expect(() => seeder({ guard: { localHosts: ['db'] }, update: true })).not.toThrow() expect(() => seeder({ guard: false, update: true })).not.toThrow() vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') - expect(() => seeder({ force: true, update: true })).toThrow(/force refused/) + expect(() => seeder({ force: true, only, update: true })).toThrow(/force refused/) + }) + + test('after launch: a full seed of a live database is refused without a record list', () => { + vi.stubEnv('NODE_ENV', 'production') + expect(() => seeder()).toThrow(/full seed refused: NODE_ENV=production[\s\S]*SEED_ONLY/) + expect(() => seeder({ dryRun: true })).not.toThrow() // a dry run only prints the plan + expect(() => seeder({ only: ['global:header'] })).not.toThrow() + vi.stubEnv('SEED_ONLY', 'pages:kontakt, global:header') + expect(seeder().only).toEqual(['pages:kontakt', 'global:header']) + vi.unstubAllEnvs() + vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app') + expect(() => seeder()).toThrow(/full seed refused: the database is not local/) + expect(() => seeder({ guard: { allowFull: true } })).not.toThrow() + vi.stubEnv('IPAL_SEED_ALLOW_FULL', '1') + expect(() => seeder()).not.toThrow() + expect(() => seeder({ guard: false })).not.toThrow() + }) + + test('only: records off the list are reported and never touched', async () => { + const seed = seeder({ only: ['posts:listed', 'global:header'] }) + const [listed, other] = await seed.upsertBySlug('posts', [ + { slug: 'listed', title: 'Listed' }, + { slug: 'not-listed', title: 'Not listed' }, + ]) + expect(listed.status).toBe('create') + expect(other.status).toBe('skip (not listed)') + expect((await seed.upsertBy('posts', { slug: 'other' }, { title: 'X' })).status).toBe('skip (not listed)') + expect((await seed.fillGlobal('header', { phone: '+48 2' })).status).not.toBe('skip (not listed)') + const { docs } = await payload.find({ collection: 'posts', where: { slug: { in: ['not-listed', 'other'] } } }) + expect(docs).toHaveLength(0) + expect(seed.summary().notListed).toBe(2) + + const whole = seeder({ only: ['posts:*'] }) + expect((await whole.upsertBySlug('posts', { slug: 'any-post', title: 'Any' })).status).toBe('create') + expect((await whole.fillGlobal('header', { tagline: 'x' })).status).toBe('skip (not listed)') }) test('env defaults: SEED_DRY_RUN, SEED_UPDATE', () => { @@ -273,7 +309,7 @@ describe('createSeeder', () => { vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl') vi.stubEnv('INDEXNOW_KEY', 'k123') - const seed = seeder({ update: true }) + const seed = seeder({ only: ['pages:*', 'global:header'], update: true }) await seed.upsertBySlug('pages', [ { slug: { en: 'news', pl: 'aktualnosci' }, _status: 'published', title: { en: 'News', pl: 'Aktualności' } }, { slug: { pl: 'oferta' }, _status: 'published', title: { pl: 'Oferta po aktualizacji' } },