Replaced by an explicit list of forms only (ten exported names, runtime env names, project file names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are not touched. package.json keeps the five old bin names beside the five new ones. The old names stop working in this commit and come back as aliases in the next; docs follow. Co-Authored-By: Claude Fable 5.2 <[email protected]>
189 lines
10 KiB
TypeScript
189 lines
10 KiB
TypeScript
import type { Block, Payload } from 'payload'
|
||
|
||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||
import os from 'node:os'
|
||
import path from 'node:path'
|
||
import { getPayload } from 'payload'
|
||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||
|
||
import type { SeedResult } from '../src/exports/seed.js'
|
||
|
||
import { createSeeder } from '../src/exports/seed.js'
|
||
import { buildLinksField, buildSectionHeaderField } from '../src/index.js'
|
||
import { iapl } from '../src/plugin.js'
|
||
import { buildTestConfig } from './helpers.js'
|
||
|
||
vi.mock('server-only', () => ({}))
|
||
|
||
/**
|
||
* Regression (vanstevpl-web, 1.15.4): a page whose REQUIRED layout holds a { $page } / { $form } reference
|
||
* could not be created — pass 1 left the whole field out and validation rejected the record, while the dry
|
||
* run reported a create. Now pass 1 resolves references to existing records, retries records whose required
|
||
* fields wait for pages created later in the same call, and reports cycles and unknown targets as errors
|
||
* with nothing written. The dry run reports the same outcome.
|
||
*/
|
||
const LOCALES = ['pl', 'en', 'de'] as const
|
||
|
||
const callToAction: Block = { slug: 'callToAction', fields: [buildSectionHeaderField(), buildLinksField()] }
|
||
const formBlock: Block = { slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms', required: true }] }
|
||
// A block whose link to another page is required — forward references to it must wait.
|
||
const teaser: Block = { slug: 'teaser', fields: [{ name: 'target', type: 'relationship', relationTo: 'pages', required: true }] }
|
||
|
||
const confirmation = {
|
||
root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 },
|
||
}
|
||
|
||
/** A page with a required layout of one block. */
|
||
const page = (slug: string, title: string, layout: Record<string, unknown>[]) => ({
|
||
slug: { de: `${slug}-de`, en: `${slug}-en`, pl: slug },
|
||
layout,
|
||
title: { de: `${title} DE`, en: `${title} EN`, pl: title },
|
||
})
|
||
const teaserTo = (slug: string) => ({ blockType: 'teaser', target: { $page: slug } })
|
||
|
||
describe('createSeeder: required fields with references', () => {
|
||
let payload: Payload
|
||
|
||
beforeAll(async () => {
|
||
vi.stubEnv('DATABASE_URI', 'file::memory:')
|
||
const config = buildTestConfig({
|
||
collections: [
|
||
{ slug: 'users', auth: true, fields: [] },
|
||
{
|
||
slug: 'pages',
|
||
fields: [
|
||
{ name: 'title', type: 'text', localized: true, required: true },
|
||
{ name: 'slug', type: 'text', index: true, localized: true },
|
||
{ name: 'layout', type: 'blocks', blocks: [callToAction, formBlock, teaser], required: true },
|
||
],
|
||
},
|
||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seed-refs') } },
|
||
],
|
||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||
editor: lexicalEditor(),
|
||
localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] },
|
||
plugins: [
|
||
iapl({
|
||
forms: {},
|
||
i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) },
|
||
pages: { slug: 'pages' },
|
||
twoFactor: false,
|
||
} as never),
|
||
],
|
||
secret: 'seed-required-refs',
|
||
telemetry: false,
|
||
})
|
||
payload = await getPayload({ config })
|
||
// The existing records the references point at.
|
||
const seed = createSeeder(payload, { log: () => {} })
|
||
await seed.upsertBySlug('pages', page('kontakt', 'Kontakt', [{ blockType: 'callToAction', header: { heading: { de: 'Hallo', en: 'Hello', pl: 'Cześć' } } }]))
|
||
await seed.upsertBy('forms', { title: 'Contact form' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [{ name: 'name', blockType: 'text', label: 'Name' }], title: 'Contact form' })
|
||
}, 60_000)
|
||
|
||
afterAll(async () => {
|
||
vi.unstubAllEnvs()
|
||
await payload?.destroy()
|
||
})
|
||
|
||
const seeder = (dryRun = false) => createSeeder(payload, { dryRun, log: () => {}, update: false })
|
||
const idOf = async (slug: string) => (await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: slug } } })).docs[0]?.id
|
||
const count = async () => (await payload.count({ collection: 'pages' })).totalDocs
|
||
|
||
/** Runs the same seed as a dry run, then for real: both must report the same statuses. */
|
||
const both = async (run: (seed: ReturnType<typeof seeder>) => Promise<SeedResult | SeedResult[]>) => {
|
||
const planned = [await run(seeder(true))].flat().map((r) => r.status)
|
||
const done = [await run(seeder())].flat()
|
||
expect(done.map((r) => r.status)).toEqual(planned)
|
||
return done
|
||
}
|
||
|
||
test('the report’s careers page: a required layout linking to an existing page, in pl, en and de', async () => {
|
||
const careers = {
|
||
slug: { de: 'karriere', en: 'careers', pl: 'kariera' },
|
||
layout: [
|
||
{
|
||
blockType: 'callToAction',
|
||
header: { heading: { de: 'Kontakt', en: 'Contact', pl: 'Kontakt' } },
|
||
links: [{ link: { type: 'internal', page: { $page: 'kontakt' } } }],
|
||
},
|
||
],
|
||
title: { de: 'Karriere', en: 'Careers', pl: 'Kariera' },
|
||
}
|
||
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', careers)])
|
||
expect(result).toMatchObject({ status: 'create' })
|
||
|
||
const all = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false as never, locale: 'all' as never })) as unknown as {
|
||
layout: { header: { heading: Record<string, string> }; id: string; links: { link: { page: unknown } }[] }[]
|
||
}
|
||
expect(all.layout).toHaveLength(1)
|
||
expect(all.layout[0].header.heading).toEqual({ de: 'Kontakt', en: 'Contact', pl: 'Kontakt' })
|
||
expect(all.layout[0].links[0].link.page).toBe(await idOf('kontakt'))
|
||
// One set of rows in every locale (1.15.4).
|
||
for (const locale of LOCALES) {
|
||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 0, fallbackLocale: false, locale })) as unknown as { layout: { id: string }[] }
|
||
expect(doc.layout[0].id).toBe(all.layout[0].id)
|
||
}
|
||
|
||
// Create-only: a second run changes nothing.
|
||
expect(await seeder().upsertBySlug('pages', careers)).toMatchObject({ status: 'skip (exists)' })
|
||
})
|
||
|
||
test('a required layout with a form block pointing at an existing form', async () => {
|
||
const [result] = await both(async (seed) => [await seed.upsertBySlug('pages', page('formularz', 'Formularz', [{ blockType: 'formBlock', form: { $form: 'Contact form' } }]))])
|
||
expect(result).toMatchObject({ status: 'create' })
|
||
const doc = (await payload.findByID({ id: result.id!, collection: 'pages', depth: 1, locale: 'pl' })) as unknown as { layout: { form: { title: string } }[] }
|
||
expect(doc.layout[0].form.title).toBe('Contact form')
|
||
})
|
||
|
||
test('forward references in one call: an optional link is filled in pass 2, a required one waits for its page', async () => {
|
||
const results = await both((seed) =>
|
||
seed.upsertBySlug('pages', [
|
||
// Optional link (CTA) to a page later in the list.
|
||
page('o-nas', 'O nas', [{ blockType: 'callToAction', links: [{ link: { type: 'internal', page: { $page: 'oferta' } } }] }]),
|
||
// Required link to a page later in the list: created once that page exists.
|
||
page('start', 'Start', [teaserTo('oferta')]),
|
||
page('oferta', 'Oferta', [{ blockType: 'callToAction', header: { heading: { de: 'Angebot', en: 'Offer', pl: 'Oferta' } } }]),
|
||
]),
|
||
)
|
||
expect(results.map((r) => r.status)).toEqual(['create', 'create', 'create'])
|
||
const oferta = await idOf('oferta')
|
||
const about = (await payload.findByID({ id: (await idOf('o-nas')), collection: 'pages', depth: 0, locale: 'en' })) as unknown as { layout: { links: { link: { page: unknown } }[] }[] }
|
||
expect(about.layout[0].links[0].link.page).toBe(oferta)
|
||
const start = (await payload.findByID({ id: (await idOf('start')), collection: 'pages', depth: 0, locale: 'de' })) as unknown as { layout: { target: unknown }[] }
|
||
expect(start.layout[0].target).toBe(oferta)
|
||
|
||
// Second run: everything exists, nothing written.
|
||
const again = await seeder().upsertBySlug('pages', [page('o-nas', 'O nas', []), page('start', 'Start', []), page('oferta', 'Oferta', [])])
|
||
expect(again.map((r) => r.status)).toEqual(['skip (exists)', 'skip (exists)', 'skip (exists)'])
|
||
})
|
||
|
||
test('required references in a cycle: a clear error, nothing written', async () => {
|
||
const before = await count()
|
||
const results = await seeder().upsertBySlug('pages', [page('jeden', 'Jeden', [teaserTo('dwa')]), page('dwa', 'Dwa', [teaserTo('jeden')])])
|
||
expect(results.map((r) => r.status)).toEqual(['error', 'error'])
|
||
expect(results[0].note).toMatch(/required references to pages not created yet \("dwa"\) — a cycle of required links/)
|
||
expect(await count()).toBe(before)
|
||
})
|
||
|
||
test('a reference to a page that never appears: an error in the dry run and the real run, nothing written', async () => {
|
||
const before = await count()
|
||
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('sierota', 'Sierota', [teaserTo('nie-ma-takiej')]))])
|
||
expect(results[0]).toMatchObject({ status: 'error' })
|
||
expect(results[0].note).toMatch(/\$page "nie-ma-takiej" not found/)
|
||
expect(await count()).toBe(before)
|
||
})
|
||
|
||
test('a reference to a form that does not exist: an error in the dry run too', async () => {
|
||
const results = await both(async (seed) => [await seed.upsertBySlug('pages', page('bez-formularza', 'Bez', [{ blockType: 'formBlock', form: { $form: 'Missing form' } }]))])
|
||
expect(results[0]).toMatchObject({ status: 'error' })
|
||
expect(results[0].note).toMatch(/\$form "Missing form" not found/)
|
||
})
|
||
|
||
test('dry run: a form planned earlier in the same run counts as there', async () => {
|
||
const seed = seeder(true)
|
||
expect(await seed.upsertBy('forms', { title: 'Newsletter' }, { confirmationMessage: confirmation, confirmationType: 'message', fields: [], title: 'Newsletter' })).toMatchObject({ status: 'create' })
|
||
expect(await seed.upsertBySlug('pages', page('newsletter', 'Newsletter', [{ blockType: 'formBlock', form: { $form: 'Newsletter' } }]))).toMatchObject({ status: 'create' })
|
||
})
|
||
})
|