Admin link-preview hook never throws without a Payload instance

syncAdminMeta returned to payload.logger in its catch even when payload was
undefined, so the Site settings afterChange hook threw with req: {} (an
unhandled rejection that made vitest, and npm publish for 1.14.5, exit 1).
Return early without payload, log through payload?.logger, skip the call in the
hook without req.payload; the fillEmptyLocales hooks get the same guard. Tests:
sync without payload, and every plugin global afterChange hook with req: {}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 12:21:21 +01:00
co-authored by Claude Opus 5.5
parent 838a2f70b2
commit 71f7108cb8
4 changed files with 24 additions and 5 deletions
+3 -1
View File
@@ -171,6 +171,8 @@ export async function syncAdminMeta(
resolved: ResolvedAdminMeta,
{ nameField = 'siteName', settingsSlug = 'site-settings' }: { nameField?: string; settingsSlug?: string } = {},
): Promise<void> {
// A hook called without a Payload instance (tests, scripts) has nothing to read or write.
if (!payload) {return}
try {
const locale = payload.config.localization ? payload.config.localization.defaultLocale : undefined
const settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 0, ...(locale ? { locale: locale as never } : {}) })) as Record<string, unknown>
@@ -185,6 +187,6 @@ export async function syncAdminMeta(
if (!resolved.own.description && resolved.options.description !== false && description) {meta.description = description}
if (!resolved.own.titleSuffix && resolved.options.titleSuffix !== false && titleSuffix) {meta.titleSuffix = titleSuffix}
} catch (error) {
payload.logger.warn({ err: error, msg: '[ipal] admin meta: could not read Site settings; Payload defaults stay.' })
payload?.logger?.warn({ err: error, msg: '[ipal] admin meta: could not read Site settings; Payload defaults stay.' })
}
}
+6 -3
View File
@@ -85,7 +85,7 @@ async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
try {
await fn()
} catch (err) {
req.payload.logger.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
req.payload?.logger?.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
} finally {
req.locale = locale
req.fallbackLocale = fallbackLocale
@@ -96,6 +96,9 @@ async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
const skip = (context: Record<string, unknown> | undefined, locale: unknown) =>
Boolean(context?.ipalFillLocales || context?.ipalCookieScan) || typeof locale !== 'string' || locale === 'all' || locale === '*'
/** No Payload instance on the request (tests, scripts): nothing to read or write. */
const noPayload = (req: PayloadRequest | undefined) => !req?.payload
/**
* afterChange hook for a global: text saved in one language fills that field in
* every language where it is empty.
@@ -104,7 +107,7 @@ const skip = (context: Record<string, unknown> | undefined, locale: unknown) =>
*/
export function buildFillEmptyLocalesGlobalHook({ fields, global }: { fields: string[]; global: string }): GlobalAfterChangeHook {
return async ({ context, doc, req }) => {
if (skip(context, req.locale)) {return doc}
if (noPayload(req) || skip(context, req.locale)) {return doc}
await keepingLocale(req, () =>
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { global } }),
)
@@ -115,7 +118,7 @@ export function buildFillEmptyLocalesGlobalHook({ fields, global }: { fields: st
/** The same for a collection: the saved document's text fills its empty languages. */
export function buildFillEmptyLocalesCollectionHook({ collection, fields }: { collection: string; fields: string[] }): CollectionAfterChangeHook {
return async ({ context, doc, req }) => {
if (skip(context, req.locale) || doc?.id == null) {return doc}
if (noPayload(req) || skip(context, req.locale) || doc?.id == null) {return doc}
await keepingLocale(req, () =>
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { id: doc.id, collection } }),
)
+1 -1
View File
@@ -401,7 +401,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
afterChange: [
...(g.hooks?.afterChange ?? []),
async ({ doc, req }) => {
await syncAdminMeta(req.payload, resolved, { nameField: brandFields.nameField, settingsSlug })
if (req?.payload) {await syncAdminMeta(req.payload, resolved, { nameField: brandFields.nameField, settingsSlug })}
return doc
},
],
+14
View File
@@ -88,6 +88,11 @@ describe('admin meta defaults', () => {
await expect(syncAdminMeta(payload, resolved)).resolves.toBeUndefined()
expect(warn).toHaveBeenCalled()
})
test('sync without a Payload instance resolves (no logger to call)', async () => {
const { resolved } = buildAdminMeta({ agency: DEFAULT_AGENCY })
await expect(syncAdminMeta(undefined as unknown as Payload, resolved)).resolves.toBeUndefined()
})
})
describe('plugin wiring', () => {
@@ -102,6 +107,15 @@ describe('plugin wiring', () => {
expect(credit.serverProps).toMatchObject({ agency: 'Intecion.com', url: 'https://intecion.com', variant: 'login' })
})
test('every plugin global afterChange hook resolves with req: {} (no Payload instance)', async () => {
const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, whiteLabel: true } as never)(base())
const calls = (config.globals ?? []).flatMap((g) =>
(g.hooks?.afterChange ?? []).map((h) => h({ context: {}, doc: {}, global: g, previousDoc: {}, req: {} } as never)),
)
expect(calls.length).toBeGreaterThan(0)
await expect(Promise.all(calls)).resolves.toBeDefined()
})
test('adminMeta: false and agency: false switch the pieces off', async () => {
const config = await ipalKit({ adminMeta: false, agency: false, i18n, twoFactor: false, whiteLabel: true } as never)(base())
expect(config.admin?.meta?.robots).toBeUndefined()