Added more agent skills
This commit is contained in:
@@ -1 +1,3 @@
|
||||
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'
|
||||
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
|
||||
export type { OptimizeUploadOptions } from './optimizeUpload.js'
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user