Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration

buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.

R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.

Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.

Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-21 16:45:03 +02:00
co-authored by Claude Opus 5.5
parent 2c3195c4e1
commit e1431a7c49
25 changed files with 511 additions and 23 deletions
+49
View File
@@ -0,0 +1,49 @@
import type { BasePayload } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import { migrateCookieSettingsSaveButton } from '../src/globals/CookieSettings/migrateSaveButton.js'
import { getConsentTexts } from '../src/modules/consent/getConsentTexts.js'
function payloadWith(db: Record<string, unknown>, cookieSettings: Record<string, unknown> = {}) {
return {
db,
findGlobal: vi.fn(async () => cookieSettings),
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },
} as unknown as BasePayload
}
describe('Cookie Settings buttons.save → savePreferences (1.12.2)', () => {
test('MongoDB: copies the old value for every locale, only when the new field is missing', async () => {
const updateOne = vi.fn(async () => ({ modifiedCount: 1 }))
const payload = payloadWith({ name: 'mongoose', globals: { collection: { updateOne } } })
await migrateCookieSettingsSaveButton(payload)
expect(updateOne).toHaveBeenCalledWith(
{ 'buttons.save': { $exists: true }, 'buttons.savePreferences': { $exists: false }, globalType: 'cookie-settings' },
[{ $set: { 'buttons.savePreferences': '$buttons.save' } }],
)
expect(payload.logger.info).toHaveBeenCalled()
})
test('other adapters: nothing (the SQL migration renames the column)', async () => {
const updateOne = vi.fn()
await migrateCookieSettingsSaveButton(payloadWith({ name: 'sqlite', globals: { collection: { updateOne } } }))
expect(updateOne).not.toHaveBeenCalled()
})
test('a failing update is logged, start continues', async () => {
const payload = payloadWith({
name: 'mongoose',
globals: { collection: { updateOne: vi.fn(async () => { throw new Error('no rights') }) } },
})
await expect(migrateCookieSettingsSaveButton(payload)).resolves.toBeUndefined()
expect(payload.logger.error).toHaveBeenCalled()
})
test('getConsentTexts: old field as the raw locale map (Mongo, not in the schema) → this locale', async () => {
const payload = payloadWith({}, { buttons: { save: { de: 'Einstellungen speichern', pl: 'Zapisz ustawienia' } } })
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'de', label: 'DE' }] } as const
const texts = await getConsentTexts({ config, locale: 'de', payload, privacyPolicy: false })
expect(texts.buttons.save).toBe('Einstellungen speichern')
})
})
+4
View File
@@ -30,6 +30,10 @@ describe('ipalEnvRules({ storage })', () => {
expect(check({ ...base, NODE_ENV: 'development' })).not.toThrow()
})
test('development: R2_PUBLIC_URL alone is the read-only media mode', () => {
expect(check({ ...base, NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl' })).not.toThrow()
})
test('development: a partial R2 set is an error (all or nothing)', () => {
expect(check({ ...base, NODE_ENV: 'development', R2_BUCKET: 'b' })).toThrow(/R2_ACCESS_KEY_ID is required/)
})
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, test, vi } from 'vitest'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
const thrower = (code: string) => vi.fn((url?: string) => { throw new Error(`${code}${url ? ` ${url}` : ''}`) }) as unknown as (url?: string) => never
const helpers = (locales = ['pl', 'en']) =>
({
getHomeSlug: vi.fn(async () => 'home'),
getPageJsonLd: vi.fn(async () => []),
getSystemLinks: vi.fn(async (locale: string) => [{ href: `/${locale}`, role: 'homepage' }]),
i18n: { defaultLocale: 'pl', locales: locales.map((code) => ({ code })) },
resolvePageRedirect: vi.fn(async () => null),
resolveRoute: vi.fn(async (_locale: string, segments: string[]) => ({
type: segments.length ? 'page' : 'home',
doc: { id: segments.length ? 'p1' : 'home', layout: [] },
})),
}) as never
const page = (segments: string[], locale = 'pl') => ({ params: Promise.resolve({ slug: segments, locale }) })
const opts = { blocks: {}, notFound: thrower('NOT_FOUND'), permanentRedirect: thrower('308') }
describe('createPageRoute homeAlias (1.12.2)', () => {
test('/pl/home → 308 /pl', async () => {
await expect(createPageRoute(helpers(), opts).Page(page(['home']))).rejects.toThrow('308 /pl')
})
test('the root and other pages render', async () => {
await expect(createPageRoute(helpers(), opts).Page(page([]))).resolves.toBeTruthy()
await expect(createPageRoute(helpers(), opts).Page(page(['kontakt']))).resolves.toBeTruthy()
})
test('homeAlias: false renders the alias', async () => {
await expect(createPageRoute(helpers(), { ...opts, homeAlias: false }).Page(page(['home']))).resolves.toBeTruthy()
})
})
+30
View File
@@ -0,0 +1,30 @@
import type { FieldHook } from 'payload'
import { describe, expect, test } from 'vitest'
import { buildAutoFillMetaHook } from '../src/modules/seo/autoFillMeta.js'
import { buildSummaryField } from '../src/modules/seo/buildSummaryField.js'
import { SKIP_AUTO_FILL } from '../src/modules/seo/skipAutoFill.js'
const layout = [{ blockType: 'content', body: 'Rekrutujemy pracowników do pracy w Holandii od ponad dziesięciu lat.' }]
describe('context.ipalSkipAutoFill (1.12.2)', () => {
const summaryHook = (buildSummaryField() as { hooks: { beforeChange: FieldHook[] } }).hooks.beforeChange[0]
const metaHook = buildAutoFillMetaHook()
const run = (context: Record<string, unknown>) => ({
meta: (metaHook({ context, data: { layout, meta: {}, title: 'Kontakt' } } as never) as { meta: Record<string, unknown> }).meta,
summary: summaryHook({ context, data: { layout }, value: undefined } as never),
})
test('default: summary and meta are generated', () => {
const { meta, summary } = run({})
expect(summary).toMatch(/Rekrutujemy/)
expect(meta.title).toBe('Kontakt')
})
test('skipped: nothing generated', () => {
const { meta, summary } = run({ [SKIP_AUTO_FILL]: true })
expect(summary).toBeUndefined()
expect(meta).toEqual({})
})
})
+101
View File
@@ -0,0 +1,101 @@
import type { Config } from 'payload'
import { s3Storage } from '@payloadcms/storage-s3'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { buildR2Storage } from '../src/modules/storage/buildR2Storage.js'
const r2 = {
R2_ACCESS_KEY_ID: 'k',
R2_BUCKET: 'b',
R2_ENDPOINT: 'https://acc.r2.cloudflarestorage.com',
R2_PUBLIC_URL: 'https://media.acme.pl',
R2_SECRET_ACCESS_KEY: 's',
}
const HANDLER = '@payloadcms/storage-s3/client#S3ClientUploadHandler'
function stub(env: Record<string, string>) {
vi.unstubAllEnvs()
for (const key of Object.keys(r2)) {vi.stubEnv(key, '')}
for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)}
}
const baseConfig = (): Config =>
({ collections: [{ slug: 'media', fields: [], upload: true }] }) as unknown as Config
/** Admin component paths the import map is generated from. */
function adminDependencies(config: Config): string[] {
const deps = (config.admin?.dependencies ?? {}) as Record<string, { path?: string }>
return Object.values(deps).map((d) => d.path ?? '')
}
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
describe('buildR2Storage — import map independent of env (1.12.2)', () => {
test('no R2 env: storage-s3 registered disabled, its client handler still in admin dependencies', async () => {
stub({ NODE_ENV: 'development' })
const config = await buildR2Storage(['media'], { s3Storage })(baseConfig())
expect(adminDependencies(config)).toContain(HANDLER)
// still local disk: no adapter, no disableLocalStorage
const media = config.collections?.find((c) => c.slug === 'media')
expect((media?.upload as { disableLocalStorage?: boolean }).disableLocalStorage).toBeUndefined()
})
test('full R2 env: same handler (the import maps match)', async () => {
stub({ ...r2, NODE_ENV: 'production' })
const config = await buildR2Storage(['media'], { s3Storage })(baseConfig())
expect(adminDependencies(config)).toContain(HANDLER)
})
test('no adapter injected and no R2 env: plain passthrough (local-disk projects)', async () => {
stub({ NODE_ENV: 'development' })
const config = await buildR2Storage(['media'])(baseConfig())
expect(adminDependencies(config)).not.toContain(HANDLER)
})
})
describe('buildR2Storage — read-only media (R2_PUBLIC_URL only, outside production)', () => {
type Hooks = {
afterRead: ((a: { doc: Record<string, unknown> }) => Record<string, unknown>)[]
beforeOperation: ((a: { args: { req?: { file?: unknown } }; operation: string }) => unknown)[]
}
async function mediaHooks(env: Record<string, string>): Promise<Hooks | undefined> {
vi.spyOn(console, 'warn').mockImplementation(() => {})
stub(env)
const config = await buildR2Storage(['media'], { s3Storage })(baseConfig())
return config.collections?.find((c) => c.slug === 'media')?.hooks as unknown as Hooks | undefined
}
test('URLs point at the public domain, sizes included', async () => {
const hooks = await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl/' })
const doc = hooks!.afterRead[0]({
doc: {
filename: 'logo plik.png',
sizes: { thumbnail: { filename: 'logo-400x300.png', url: '/api/media/file/logo-400x300.png' } },
thumbnailURL: '/api/media/file/logo-400x300.png',
url: '/api/media/file/logo plik.png',
},
})
expect(doc.url).toBe('https://media.acme.pl/logo%20plik.png')
expect(doc.thumbnailURL).toBe('https://media.acme.pl/logo-400x300.png')
expect((doc.sizes as Record<string, { url: string }>).thumbnail.url).toBe('https://media.acme.pl/logo-400x300.png')
})
test('uploads and deletes are refused, metadata edits pass', async () => {
const hooks = await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: 'https://media.acme.pl' })
const guard = hooks!.beforeOperation[0]
expect(() => guard({ args: { req: { file: {} } }, operation: 'create' })).toThrow(/read-only/)
expect(() => guard({ args: { req: {} }, operation: 'delete' })).toThrow(/read-only/)
expect(() => guard({ args: { req: {} }, operation: 'update' })).not.toThrow()
})
test('not in production, not with credentials, not with a relative URL', async () => {
expect(await mediaHooks({ NODE_ENV: 'production', R2_PUBLIC_URL: 'https://media.acme.pl' })).toBeUndefined()
expect(await mediaHooks({ NODE_ENV: 'development', R2_PUBLIC_URL: '/media' })).toBeUndefined()
const partial = await mediaHooks({ NODE_ENV: 'development', R2_BUCKET: 'b', R2_PUBLIC_URL: 'https://media.acme.pl' })
expect(partial).toBeUndefined()
})
})