Added more agent skills

This commit is contained in:
2026-10-13 19:07:03 +02:00
parent 0ccc7e5064
commit 80d8b7102c
80 changed files with 2802 additions and 390 deletions
+2 -1
View File
@@ -1,7 +1,8 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
/**
* Entry point: @intecion/ipal-kit/admin
*
* Admin-panel UI components (white-label branding). Separate export so Payload's
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/
+125 -161
View File
@@ -1,3 +1,20 @@
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export type { AccessOption, Role } from './modules/access/index.js'
export {
adminOnly,
@@ -13,208 +30,155 @@ export {
requireRoleField,
ROLE_HIERARCHY,
} from './modules/access/index.js'
export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
A11Y_COOKIE,
A11Y_DEFAULT,
a11yAttributes,
parseA11y,
serializeA11y,
} from './modules/accessibility/index.js'
export type { A11yState } from './modules/accessibility/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
getGlobal,
getSiteSettings,
getSiteIntegrations,
SITE_SETTINGS_SLUG,
SITE_INTEGRATIONS_SLUG,
} from './modules/payload/index.js'
export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js'
export {
ACCEPT_ALL_CONSENT,
CONSENT_CATEGORIES,
CONSENT_COOKIE,
CONSENT_MAX_AGE,
CONSENT_VERSION,
DEFAULT_CONSENT,
getConsentTexts,
parseConsent,
REJECT_ALL_CONSENT,
serializeConsent,
setDefaultConsent,
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'
export type {
ContentCollectionOption,
ContentOption,
ResolvedRoute,
} from './modules/content/index.js'
composeTitle,
buildHreflangAlternates,
buildMetadata,
readSiteMetaConfig,
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js'
export { createContentHelpers } from './modules/frontend/index.js'
export {
archiveFieldName,
resolveRoute,
resolveRedirect,
resolveNotFoundPage,
blocksToMarkdown,
createMarkdownRenderer,
markdownResponse,
prefersMarkdown,
markdownHref,
MARKDOWN_PREFIX,
searchContent,
createSearchRoute,
archiveFieldName,
getArchiveEntries,
buildArchivePath,
buildEntryPath,
createMarkdownRenderer,
createSearchRoute,
getArchiveEntries,
MARKDOWN_PREFIX,
markdownHref,
markdownResponse,
parsePageParam,
prefersMarkdown,
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
searchContent,
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js'
export {
buildAutoFillMetaHook,
injectAutoFillMeta,
createMetadataGenerator,
createPageMetadata,
buildSitemapEntries,
buildRobots,
AI_ASSISTANT_BOTS,
AI_TRAINING_BOTS,
} from './modules/seo/index.js'
export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export {
createLocaleMiddleware,
DEFAULT_MIDDLEWARE_MATCHER,
} from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export {
CONSENT_CATEGORIES,
DEFAULT_CONSENT,
ACCEPT_ALL_CONSENT,
REJECT_ALL_CONSENT,
CONSENT_COOKIE,
CONSENT_VERSION,
CONSENT_MAX_AGE,
serializeConsent,
parseConsent,
setDefaultConsent,
updateConsent,
getConsentTexts,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'
// Imported straight from the file, NOT from ./modules/email/index.js — that
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.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 type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
export type {
FormsOption,
FormsCollectionOverrides,
FormsFieldsOverride,
FormsOption,
} from './modules/forms/types.js'
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
// Validation rules are pure — exported server-side too, for re-validating a
// submission inside a server action. (useForm/useContactForm are client-only →
// '@intecion/ipal-kit/client'.)
export {
buildValidator,
checked,
custom,
email,
isEmail,
maxLength,
minLength,
pattern,
required,
email,
minLength,
maxLength,
checked,
pattern,
custom,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export { createContentHelpers } from './modules/frontend/index.js'
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
export {
buildCrossLocaleFieldSync,
buildPreventDeleteSystemPage,
buildRevalidateHook,
buildValidateUniqueRole,
setPublishedAtHook,
trackSlugHistoryHook,
} from './modules/hooks/index.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkValue,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export {
getNotificationTexts,
NOTIFICATION_FALLBACK,
resolveFormMessage,
} from './modules/notifications/index.js'
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
getGlobal,
getSiteIntegrations,
getSiteSettings,
SITE_INTEGRATIONS_SLUG,
SITE_SETTINGS_SLUG,
} from './modules/payload/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders } from './modules/security/index.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'
export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'
export { buildSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
export {
buildHreflangAlternates,
buildMetadata,
composeTitle,
readSiteMetaConfig,
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export type {
AutoFillMapping,
RobotsOptions,
RobotsRules,
SitemapEntry,
} from './modules/seo/index.js'
export {
AI_ASSISTANT_BOTS,
AI_TRAINING_BOTS,
buildAutoFillMetaHook,
buildRobots,
buildSitemapEntries,
createMetadataGenerator,
createPageMetadata,
injectAutoFillMeta,
} from './modules/seo/index.js'
export {
createLlmsTxtRoute,
createManifestHandler,
createSitemapRouteHandler,
} from './modules/seo/index.js'
export {
buildIconsMetadata,
buildOrganizationJsonLd,
validateFaviconField,
} from './modules/seo/index.js'
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'
export { buildNoindexField } from './modules/seo/index.js'
export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
export type {
LinkAppearance,
LinkValue,
BuildLinkFieldOptions,
BuildLinksFieldOptions,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
export { buildSpeakableJsonLd } from './modules/seo/index.js'
export { buildSummaryField } from './modules/seo/index.js'
export {
buildBreadcrumbJsonLd,
buildSiteNavigationJsonLd,
buildWebSiteJsonLd,
} from './modules/seo/index.js'
export { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export {
buildFaqJsonLd,
buildLocalBusinessJsonLd,
buildServiceJsonLd,
} from './modules/seo/index.js'
export { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapXml } from './modules/seo/index.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildR2Storage } from './modules/storage/index.js'
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js'
export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js'
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'
export type { A11yState } from './modules/accessibility/index.js'
export type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js'
export type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js'
@@ -0,0 +1,39 @@
'use client'
import { useRowLabel } from '@payloadcms/ui'
export type RowLabelProps = {
/** Shown with the row number when every path is empty, e.g. "Button" → "Button 02". */
fallback?: string
/** Dot paths inside the row, tried in order — the first non-empty text wins. */
fields?: string[]
}
const at = (obj: unknown, path: string): unknown =>
path.split('.').reduce<unknown>((o, k) => (o && typeof o === 'object' ? (o as Record<string, unknown>)[k] : undefined), obj)
const toText = (v: unknown): string => {
if (typeof v === 'string') {return v.trim()}
if (typeof v === 'number') {return String(v)}
// populated relationship / upload → its title, name, filename or alt
if (v && typeof v === 'object') {
for (const k of ['title', 'name', 'label', 'alt', 'filename']) {
const t = (v as Record<string, unknown>)[k]
if (typeof t === 'string' && t.trim()) {return t.trim()}
}
}
return ''
}
/**
* Array row title in the admin panel: shows the row's own content ("Contact us",
* "Fast delivery") instead of "Item 01", so an editor finds the right row
* without expanding every one. Wire it with `rowLabel()`.
*/
export function RowLabel({ fallback = 'Item', fields = ['heading', 'title', 'label', 'link.label', 'name'] }: RowLabelProps) {
const { data, rowNumber } = useRowLabel<Record<string, unknown>>()
for (const f of fields) {
const text = toText(at(data, f))
if (text) {return <span>{text.length > 60 ? `${text.slice(0, 57)}…` : text}</span>}
}
return <span>{`${fallback} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`}</span>
}
+2
View File
@@ -0,0 +1,2 @@
export { rowLabel } from './rowLabel.js'
export type { RowLabelProps } from './RowLabelComponent.js'
+15
View File
@@ -0,0 +1,15 @@
import type { RowLabelProps } from './RowLabelComponent.js'
/**
* Readable array rows in the panel. Spread into an array field's `admin.components`:
*
* { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' },
* admin: { initCollapsed: true, components: rowLabel(['heading'], 'Feature') }, fields: [...] }
*
* Rows then read "Fast delivery", "24/7 support"… instead of "Feature 01, Feature 02".
* After adding it to a project: `pnpm payload generate:importmap`.
*/
export function rowLabel(fields: string | string[], fallback = 'Item') {
const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], fallback }
return { RowLabel: { path: '@intecion/ipal-kit/admin#RowLabel', clientProps } }
}
+6 -6
View File
@@ -79,7 +79,7 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
const secondaryClass = classNames?.secondaryButton ?? defaults.secondaryButton
return (
<div aria-label="Cookie consent" className={rootClass} data-ipal="banner" role="dialog">
<div aria-label={texts.settingsTitle} className={rootClass} data-ipal="banner" role="dialog">
<div className="mx-auto max-w-4xl">
{!showSettings ? (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
@@ -101,13 +101,13 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
</p>
</div>
<div className="flex shrink-0 gap-2">
<button className={secondaryClass} onClick={() => setShowSettings(true)}>
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)}>
{texts.buttons.settings}
</button>
<button className={secondaryClass} onClick={rejectAll}>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll}>
{texts.buttons.reject}
</button>
<button className={primaryClass} onClick={acceptAll}>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll}>
{texts.buttons.acceptAll}
</button>
</div>
@@ -138,10 +138,10 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
))}
</ul>
<div className="flex justify-end gap-2">
<button className={secondaryClass} onClick={() => setShowSettings(false)}>
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)}>
{texts.buttons.back}
</button>
<button className={primaryClass} onClick={() => savePreferences(choices)}>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)}>
{texts.buttons.save}
</button>
</div>
+8 -2
View File
@@ -16,7 +16,7 @@ import { useIsMounted } from './useIsMounted.js'
*/
export function CookieButton({ className }: { className?: string } = {}) {
const isMounted = useIsMounted()
const { decided, reopen } = useConsentContext()
const { decided, reopen, texts } = useConsentContext()
// Render nothing until mounted — prevents hydration mismatch (no project
// ConsentWrapper workaround needed).
@@ -30,7 +30,13 @@ export function CookieButton({ className }: { className?: string } = {}) {
'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'
return (
<button aria-label="Cookie settings" className={cls} data-ipal="cookie-button" onClick={reopen}>
<button
// a11y label per locale: the panel's "settings title" (Cookie Settings global)
aria-label={texts.settingsTitle}
className={cls}
data-ipal="cookie-button"
onClick={reopen}
>
<Cookie
aria-hidden="true"
className="h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]"
+1 -1
View File
@@ -76,7 +76,7 @@ export type SubmitFormResult = { submissionId: number | string; success: true }
*
* Emails aren't sent here. The form-builder sends whatever an editor configured
* under the form's "Emails" tab (form-submissions hook → payload.sendEmail),
* which goes out over panelSmtpAdapter. Storing the submission is enough.
* which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.
*
* server-only: touches the Turnstile secret.
*/
+15 -1
View File
@@ -1,5 +1,7 @@
import type { ArrayField, Field, GroupField } from 'payload'
import { rowLabel } from 'src/modules/admin-ui/rowLabel.js'
export type LinkAppearance = 'link' | 'primary' | 'secondary'
export type BuildLinkFieldOptions = {
@@ -116,6 +118,11 @@ export function buildLinkField({
}
export type BuildLinksFieldOptions = {
/**
* What one row is called in the panel — the add button reads "Add <singular>".
* Default { singular: 'Button', plural: 'Buttons' }; e.g. { singular: 'Link', plural: 'Links' } for a link list.
*/
labels?: { plural: string; singular: string }
/** Max number of buttons. Default 2. */
maxRows?: number
/** Field name. Default 'links'. */
@@ -128,14 +135,21 @@ export type BuildLinksFieldOptions = {
*/
export function buildLinksField({
name = 'links',
labels = { plural: 'Buttons', singular: 'Button' },
maxRows = 2,
...linkOptions
}: BuildLinksFieldOptions = {}): ArrayField {
return {
name,
type: 'array',
admin: { initCollapsed: true },
admin: {
initCollapsed: true,
// Rows read "Contact us" / "Download catalogue", not "Button 01". Needs the importMap entry.
components: rowLabel(['link.label', 'link.url'], labels.singular),
},
fields: [buildLinkField(linkOptions)],
label: labels.plural,
labels,
maxRows,
}
}
+2
View File
@@ -1 +1,3 @@
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
export type { OptimizeUploadOptions } from './optimizeUpload.js'
+180
View File
@@ -0,0 +1,180 @@
import type { CheckboxField, CollectionBeforeOperationHook } from 'payload'
import { readFile } from 'node:fs/promises'
import { APIError } from 'payload'
/**
* Safety net for oversized uploads — NOT an image pipeline. The developer and
* editor are expected to upload prepared files; this only catches the 8 MB
* phone photo or the raw 300 MB video, and asks before touching anything.
*
* - JPG / PNG over the limits → upload is stopped with an explanation; the
* editor ticks "Optimize this upload" and saves again → converted to WebP,
* resized to maxImageWidth, auto-rotated, metadata (EXIF/GPS) removed.
* - Video over maxVideoBytes → stopped with export instructions (never
* transcoded — that needs ffmpeg and minutes of CPU per file).
* - Everything else (GIF, SVG, WebP, AVIF, PDF, animated images) → untouched.
*
* Uses the `sharp` instance passed to buildConfig({ sharp }) — the plugin
* never imports sharp itself.
*/
export type OptimizeUploadOptions = {
/** Name of the consent checkbox (buildOptimizeUploadField). Default 'optimizeOnUpload'. */
consentField?: string
/** Image size limit in bytes. Default 1.5 MB. */
maxImageBytes?: number
/** Image width limit in px — also the target width after optimizing. Default 2560. */
maxImageWidth?: number
/** Video size limit in bytes. Default 20 MB. `false` = no video limit. */
maxVideoBytes?: false | number
/**
* PNG handling: 'lossless' (default — safe for screenshots, logos, text) or
* 'lossy' (much smaller, may soften fine text).
*/
png?: 'lossless' | 'lossy'
/** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */
quality?: number
}
const OPTIMIZABLE = new Set(['image/jpeg', 'image/png'])
const MB = 1024 * 1024
const fmt = (bytes: number) => `${(bytes / MB).toFixed(1)} MB`
/**
* Consent checkbox for the upload collection's sidebar. Unticked by default;
* only read when a file exceeds the limits.
*/
export function buildOptimizeUploadField(name = 'optimizeOnUpload'): CheckboxField {
return {
name,
type: 'checkbox',
admin: {
description:
'Only used when an image is too large: converts it to WebP, resizes it and removes metadata (EXIF/GPS). Prepared files are never changed.',
position: 'sidebar',
},
defaultValue: false,
label: 'Optimize this upload',
}
}
type UploadFile = {
data: Buffer
mimetype: string
name: string
size: number
tempFilePath?: string
}
/**
* beforeOperation hook for an upload collection (e.g. Media):
*
* hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] },
* fields: [..., buildOptimizeUploadField()],
*/
export function buildOptimizeUploadHook(
options: OptimizeUploadOptions = {},
): CollectionBeforeOperationHook {
const {
consentField = 'optimizeOnUpload',
maxImageBytes = 1.5 * MB,
maxImageWidth = 2560,
maxVideoBytes = 20 * MB,
png = 'lossless',
quality = 82,
} = options
return async ({ args, operation, req }) => {
if (operation !== 'create' && operation !== 'update') {return}
const file = req.file as undefined | UploadFile
if (!file) {return}
const data = (args as { data?: Record<string, unknown> }).data
const consent = Boolean(data?.[consentField])
const size = file.size || file.data?.length || 0
// --- Video: limit only, never transcoded ---
if (file.mimetype.startsWith('video/')) {
if (maxVideoBytes !== false && size > maxVideoBytes) {
throw new APIError(
`Video is ${fmt(size)} (limit ${fmt(maxVideoBytes)}). Export it before uploading: ` +
'MP4 (H.264), 720p–1080p, about 2–4 Mbit/s, no audio track for background videos, ' +
'"web optimized" / fast start enabled (e.g. HandBrake preset "Web").',
400,
undefined,
true,
)
}
return
}
if (!OPTIMIZABLE.has(file.mimetype)) {return} // GIF, SVG, WebP, AVIF, PDF… untouched
const sharp = req.payload.config.sharp
const buffer =
file.data && file.data.length > 0
? file.data
: file.tempFilePath
? await readFile(file.tempFilePath)
: undefined
if (!buffer) {return}
let width: number | undefined
let animated = false
if (sharp) {
const meta = await sharp(buffer).metadata()
width = meta.width
animated = (meta.pages ?? 1) > 1
}
if (animated) {return} // APNG — converting would drop the animation
const tooHeavy = size > maxImageBytes
const tooWide = width !== undefined && width > maxImageWidth
if (!tooHeavy && !tooWide) {return}
const problem = [
tooHeavy ? `${fmt(size)} (limit ${fmt(maxImageBytes)})` : null,
tooWide ? `${width} px wide (limit ${maxImageWidth} px)` : null,
]
.filter(Boolean)
.join(', ')
if (!consent) {
throw new APIError(
`Image is ${problem}. Tick "Optimize this upload" in the sidebar and save again to convert it ` +
`to WebP (max ${maxImageWidth} px wide, metadata removed), or upload a smaller file.`,
400,
undefined,
true,
)
}
if (!sharp) {
throw new APIError(
'Image optimization needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.',
500,
undefined,
true,
)
}
const lossless = file.mimetype === 'image/png' && png === 'lossless'
const output = await sharp(buffer)
.rotate() // apply EXIF orientation before metadata is dropped
.resize({ width: maxImageWidth, withoutEnlargement: true })
.webp(lossless ? { lossless: true } : { quality })
.toBuffer()
// Conversion didn't help (rare) and the width was fine → keep the original.
if (output.length >= size && !tooWide) {return}
file.data = output
file.size = output.length
file.mimetype = 'image/webp'
file.name = `${file.name.replace(/\.[^.]+$/, '')}.webp`
delete file.tempFilePath // Payload must read the new buffer, not the temp file
if (data) {data[consentField] = false} // next oversized upload asks again
}
}