Files
ipal-kit/test/performance1180.test.ts
T

181 lines
12 KiB
TypeScript

// @vitest-environment happy-dom
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { act, createElement } from 'react'
import { createRoot } from 'react-dom/client'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { BackgroundVideo } from '../src/modules/block-library/ui/BackgroundVideo.js'
import { CARD_INTERACTIVE_CLASS, CARD_INTERACTIVE_SHADOW_CLASS } from '../src/modules/block-library/ui/Card.js'
import { Media } from '../src/modules/block-library/ui/Media.js'
import { runDoctor } from '../src/modules/doctor/run.js'
import { UnusedMediaNotice } from '../src/modules/media/UnusedMediaNotice.js'
import { syncTtlIndex, TTL_FIELD, TTL_INDEX } from '../src/modules/shared/ttl.js'
import { PLUGIN_VERSION_LIMIT, withVersionLimit } from '../src/modules/shared/versionLimit.js'
import { Turnstile } from '../src/modules/turnstile/Turnstile.js'
import { TURNSTILE_HEIGHT } from '../src/modules/turnstile/turnstileHeight.js'
const root = path.resolve(import.meta.dirname, '..')
const read = (rel: string) => readFileSync(path.join(root, rel), 'utf8')
describe('lazy form code (item 3)', () => {
test('the /client entry exports the lazy form and widget; /client/eager the eager ones; hooks are no client boundary', () => {
expect(read('src/exports/client.ts')).toMatch(/export \{ LazyBuilderForm as BuilderForm \} from '\.\.\/modules\/forms\/LazyBuilderForm\.js'/)
expect(read('src/modules/turnstile/client.ts')).toMatch(/export \{ LazyTurnstile as Turnstile \}/)
expect(read('src/exports/client-eager.ts')).toMatch(/export \{ BuilderForm \} from '\.\.\/modules\/forms\/BuilderForm\.js'/)
expect(JSON.parse(read('package.json')).exports['./client/eager']).toMatchObject({ import: './dist/exports/client-eager.js' })
for (const hook of ['useBuilderForm', 'useForm', 'useContactForm']) {expect(read(`src/modules/forms/${hook}.ts`)).not.toMatch(/^'use client'/m)}
// nothing imports the eager modules statically but the eager entry and the lazy wrappers' import()
expect(read('src/modules/forms/RenderForm.tsx')).not.toMatch(/^import \{ BuilderForm \}/m)
expect(read('src/modules/turnstile/TurnstileProvider.tsx')).toMatch(/lazy\(\(\) => import\('\.\/Turnstile\.js'\)/)
})
test('the Turnstile widget keeps its height free before Cloudflare draws it; 0 turns it off', () => {
expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, siteKey: 'k' }))).toBe(`<div style="min-height:${TURNSTILE_HEIGHT}px"></div>`)
expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, reserveHeight: 0, siteKey: 'k' }))).toBe('<div></div>')
})
})
describe('background video and reduced motion (item 4)', () => {
const video = { filename: 'loop.mp4', mimeType: 'video/mp4', url: '/api/media/file/loop.mp4' }
test('Media renders the background video through BackgroundVideo, same markup; opt-out keeps a plain <video>', () => {
const html = renderToStaticMarkup(createElement(Media, { resource: video, videoMode: 'background' }))
expect(html).toMatch(/^<video\b/)
expect(html).toMatch(/autoplay=""/i)
expect(html).toMatch(/\bloop=""/)
expect(renderToStaticMarkup(createElement(Media, { pauseForReducedMotion: false, resource: video, videoMode: 'background' }))).toBe(html)
})
test('paused for "reduce motion", played again when the setting changes', async () => {
let matches = true
const listeners: Array<() => void> = []
vi.stubGlobal('matchMedia', () => ({ addEventListener: (_: string, l: () => void) => listeners.push(l), get matches() { return matches }, removeEventListener: () => {} }))
const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
const play = vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve())
const host = document.createElement('div')
const r = createRoot(host)
await act(async () => r.render(createElement(BackgroundVideo, { autoPlay: true, loop: true, muted: true, src: '/v.mp4' })))
expect(pause).toHaveBeenCalledTimes(1)
matches = false
await act(async () => {for (const l of listeners) {l()}})
expect(play).toHaveBeenCalledTimes(1)
await act(async () => r.unmount())
vi.unstubAllGlobals()
})
})
describe('card hover (item 6)', () => {
test('the lift fades an ::after layer (opacity), the card shadow itself does not animate; the 1.17 class stays exported', () => {
expect(CARD_INTERACTIVE_CLASS).toMatch(/after:opacity-0/)
expect(CARD_INTERACTIVE_CLASS).toMatch(/hover:after:opacity-100/)
expect(CARD_INTERACTIVE_CLASS).not.toMatch(/transition-shadow/)
expect(CARD_INTERACTIVE_SHADOW_CLASS).toMatch(/transition-shadow/)
})
})
describe('TTL indexes (item 10)', () => {
const fake = (indexes: Array<{ expireAfterSeconds?: number; name: string }>) => {
const calls: string[] = []
const coll = {
collectionName: 'consent-records',
createIndex: async (key: object, options: { expireAfterSeconds: number; name: string }) => {
calls.push(`create ${JSON.stringify(key)} ${options.expireAfterSeconds}`)
return options.name
},
dropIndex: async (name: string) => void calls.push(`drop ${name}`),
indexes: async () => indexes,
updateMany: async (filter: object, update: object[]) => {
calls.push(`backfill ${JSON.stringify(filter)} ${JSON.stringify(update)}`)
return {}
},
}
const payload = { db: { name: 'mongoose', collections: { 'consent-records': { collection: coll } }, connection: { db: { command: async (c: object) => void calls.push(`collMod ${JSON.stringify(c)}`) } } } }
return { calls, payload: payload as never }
}
test('created on its own field (not Payload\'s createdAt index), old records backfilled from their date', async () => {
const { calls, payload } = fake([{ name: '_id_' }, { name: 'createdAt_1' }])
expect(await syncTtlIndex(payload, 'consent-records', { days: 1095, enabled: true, from: 'createdAt' })).toBe('created')
expect(calls).toEqual([
`backfill {"createdAt":{"$type":"date"},"${TTL_FIELD}":{"$exists":false}} [{"$set":{"${TTL_FIELD}":"$createdAt"}}]`,
`create {"${TTL_FIELD}":1} ${1095 * 86_400}`,
])
})
test('a changed retention moves the index (collMod); the same one does nothing; off drops it', async () => {
const changed = fake([{ name: TTL_INDEX, expireAfterSeconds: 90 * 86_400 }])
expect(await syncTtlIndex(changed.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('updated')
expect(changed.calls.at(-1)).toBe(`collMod {"collMod":"consent-records","index":{"name":"${TTL_INDEX}","expireAfterSeconds":${30 * 86_400}}}`)
const same = fake([{ name: TTL_INDEX, expireAfterSeconds: 30 * 86_400 }])
expect(await syncTtlIndex(same.payload, 'consent-records', { days: 30, enabled: true, from: 'lastAt' })).toBe('none')
const off = fake([{ name: TTL_INDEX, expireAfterSeconds: 30 * 86_400 }])
expect(await syncTtlIndex(off.payload, 'consent-records', { days: 30, enabled: false, from: 'lastAt' })).toBe('dropped')
expect(off.calls).toEqual([`drop ${TTL_INDEX}`])
})
test('Postgres / SQLite: nothing (the purge after a new record does it); the field is MongoDB-only', async () => {
expect(await syncTtlIndex({ db: { name: 'drizzle' } } as never, 'consent-records', { days: 30, enabled: true, from: 'createdAt' })).toBe('none')
expect(read('src/plugin.ts')).toMatch(/if \(isMongo\(config\)\) \{consentCollection\.fields = \[\.\.\.consentCollection\.fields, ttlField\(\)\]\}/)
})
})
describe('versions (item 13)', () => {
test('the plugin\'s entities with versions on get 20 unless the project set a limit', () => {
expect(PLUGIN_VERSION_LIMIT).toBe(20)
expect(withVersionLimit({ slug: 'site-integrations', versions: true }, 'global').versions).toEqual({ max: 20 })
expect(withVersionLimit({ slug: 'forms', versions: { drafts: true } }, 'collection').versions).toEqual({ drafts: true, maxPerDoc: 20 })
expect(withVersionLimit({ slug: 'forms', versions: { maxPerDoc: 0 } }, 'collection').versions).toEqual({ maxPerDoc: 0 }) // the project's own (unlimited) wins
expect(withVersionLimit({ slug: 'forms' } as { slug: string; versions?: unknown }, 'collection').versions).toBeUndefined()
})
test('doctor hint for a project that turns versions on without a limit', async () => {
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-versions-'))
try {
const files: Record<string, string> = {
'package.json': '{"name":"x-web"}',
'src/collections/Pages.ts': "export const Pages = { slug: 'pages', versions: { drafts: { autosave: true } }, fields: [] }",
'src/collections/Posts.ts': "export const Posts = { slug: 'posts', versions: { drafts: true, maxPerDoc: 20 }, fields: [] }",
'src/globals/Header.ts': "export const Header = { slug: 'header', versions: true, fields: [] }",
}
for (const [rel, text] of Object.entries(files)) {
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
writeFileSync(path.join(dir, rel), text)
}
const report = await runDoctor({ offline: true, only: ['growth-versions-config'], packageRoot: root, root: dir, today: '2026-12-01', writeSeen: false })
expect(report.findings.map((f) => `${f.severity} ${f.file}: ${f.fix}`)).toEqual([
'info src/collections/Pages.ts: versions: { …, maxPerDoc: 20 }',
'info src/globals/Header.ts: versions: { max: 20 }',
])
} finally {
rmSync(dir, { force: true, recursive: true })
}
})
})
describe('unused media in the panel (item 12)', () => {
const payload = (docs: Record<string, object[]>) => ({
config: { admin: { user: 'users' }, collections: [{ slug: 'media', upload: true }, { slug: 'pages' }, { slug: 'users' }], custom: { ipal: { staffCollections: ['users'] } }, globals: [] },
find: async ({ collection }: { collection: string }) => ({ docs: docs[collection] ?? [] }),
findGlobal: async () => ({}),
})
const editor = { id: 1, collection: 'users', roles: ['editor'] }
test('a link to Payload\'s own list filtered to the unused files — nothing is deleted', async () => {
const p = payload({ media: [{ id: 'm1', filename: 'a.jpg' }, { id: 'm2', filename: 'plan.pdf' }, { id: 'm3', filename: 'b.jpg' }], pages: [{ hero: 'm1', text: 'see /api/media/file/plan.pdf' }] })
const html = renderToStaticMarkup(await UnusedMediaNotice({ adminRoute: '/admin', collection: 'media', i18n: { language: 'en' }, payload: p as never, user: editor }))
expect(html).toContain('1 file is not used on any page, entry or setting.')
expect(html).toContain('href="/admin/collections/media?where[id][in][0]=m3"')
expect(html).not.toMatch(/m1|m2/)
})
test('nothing for a visitor account or when every file is used; only a hint when the site is too big to check here', async () => {
const used = payload({ media: [{ id: 'm1', filename: 'a.jpg' }], pages: [{ hero: 'm1' }] })
expect(await UnusedMediaNotice({ collection: 'media', payload: used as never, user: editor })).toBeNull()
expect(await UnusedMediaNotice({ collection: 'media', payload: used as never, user: null })).toBeNull()
const broken = { ...used, find: async ({ collection }: { collection: string }) => { if (collection === 'pages') {throw new Error('no')} return { docs: [{ id: 'm1', filename: 'a.jpg' }] } } }
expect(renderToStaticMarkup(await UnusedMediaNotice({ collection: 'media', payload: broken as never, user: editor }))).toContain('too many documents to check')
})
})