Unverified Commit 1a7ccf48 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Re-enable AVIF image optimization (#97931)

Reverts #97875 and bumps `sharp` from `^0.35.3` to `^0.35.4`,
re-enabling AVIF image optimization.


`minimumReleaseAge` interplay (verified with pnpm 10.33.0 and 11.22.0 in
a standalone repo with a `file:` dependency declaring sharp as an
optional dependency):

- sharp 0.35.4 was published on 2026-08-26 and is younger than this
repo's 48h `minimumReleaseAge`.
- pnpm aborts the whole install with
`ERR_PNPM_NO_MATURE_MATCHING_VERSION` when no in-range release satisfies
the age gate. This applies to `optionalDependencies` (no warn-and-skip)
and through `file:` dependencies alike.
- The gate also covers the `@img/sharp-*` binary packages sharp 0.35.4
depends on, so excluding only `sharp@0.35.4` is not enough.
- `pnpm-workspace.yaml` therefore exempts `sharp@0.35.4` and
`@img/sharp-*` (pnpm does not allow version qualifiers on name patterns
in this setting). Both entries can be dropped once 0.35.4 is older than
48 hours.
- Downstream users who configure their own `minimumReleaseAge` will hit
the same hard install failure when installing a release with this bump
until 0.35.4 ages out, unless they add the same excludes. Keeping
`^0.35.3` is not a safer alternative: age-gated installs would then
silently resolve the vulnerable 0.35.3.

Part of https://linear.app/vercel/issue/VOC-34654/

---------
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 0c7f81e6
...@@ -130,7 +130,7 @@ ...@@ -130,7 +130,7 @@
} }
}, },
"optionalDependencies": { "optionalDependencies": {
"sharp": "^0.35.3" "sharp": "^0.35.4"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "7.26.10", "@babel/core": "7.26.10",
......
...@@ -1822,8 +1822,6 @@ export default async function getBaseWebpackConfig( ...@@ -1822,8 +1822,6 @@ export default async function getBaseWebpackConfig(
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
outputHashSalt: config.outputHashSalt, outputHashSalt: config.outputHashSalt,
imgOptDangerouslyAllowAVIF:
config.experimental.imgOptDangerouslyAllowAVIF,
}, },
}, },
] ]
......
...@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer' ...@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer'
const BLUR_IMG_SIZE = 8 const BLUR_IMG_SIZE = 8
const BLUR_QUALITY = 70 const BLUR_QUALITY = 70
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match other usages const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match other usages
export async function getBlurImage( export async function getBlurImage(
content: Buffer, content: Buffer,
...@@ -13,7 +13,6 @@ export async function getBlurImage( ...@@ -13,7 +13,6 @@ export async function getBlurImage(
basePath, basePath,
outputPath, outputPath,
isDev, isDev,
imgOptDangerouslyAllowAVIF = false,
tracing = () => ({ tracing = () => ({
traceFn: traceFn:
(fn) => (fn) =>
...@@ -28,7 +27,6 @@ export async function getBlurImage( ...@@ -28,7 +27,6 @@ export async function getBlurImage(
basePath: string basePath: string
outputPath: string outputPath: string
isDev: boolean isDev: boolean
imgOptDangerouslyAllowAVIF?: boolean
tracing: (name?: string) => { tracing: (name?: string) => {
traceFn(fn: Function): any traceFn(fn: Function): any
traceAsyncFn(fn: Function): any traceAsyncFn(fn: Function): any
...@@ -39,11 +37,7 @@ export async function getBlurImage( ...@@ -39,11 +37,7 @@ export async function getBlurImage(
let blurWidth: number = 0 let blurWidth: number = 0
let blurHeight: number = 0 let blurHeight: number = 0
const isValidBlurExtension = if (VALID_BLUR_EXT.includes(extension) && !isAnimated(content)) {
VALID_BLUR_EXT.includes(extension) ||
(extension === 'avif' && imgOptDangerouslyAllowAVIF)
if (isValidBlurExtension && !isAnimated(content)) {
// Shrink the image's largest dimension // Shrink the image's largest dimension
if (imageSize.width >= imageSize.height) { if (imageSize.width >= imageSize.height) {
blurWidth = BLUR_IMG_SIZE blurWidth = BLUR_IMG_SIZE
...@@ -78,7 +72,6 @@ export async function getBlurImage( ...@@ -78,7 +72,6 @@ export async function getBlurImage(
height: blurHeight, height: blurHeight,
contentType: `image/${extension}`, contentType: `image/${extension}`,
quality: BLUR_QUALITY, quality: BLUR_QUALITY,
dangerouslyAllowAVIF: imgOptDangerouslyAllowAVIF,
}) })
) )
const blurDataURLSpan = tracing('image-base64-tostring') const blurDataURLSpan = tracing('image-base64-tostring')
......
...@@ -11,21 +11,14 @@ interface Options { ...@@ -11,21 +11,14 @@ interface Options {
assetPrefix: string assetPrefix: string
basePath: string basePath: string
outputHashSalt: string outputHashSalt: string
imgOptDangerouslyAllowAVIF: boolean
} }
function nextImageLoader(this: any, content: Buffer) { function nextImageLoader(this: any, content: Buffer) {
const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader') const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader')
return imageLoaderSpan.traceAsyncFn(async () => { return imageLoaderSpan.traceAsyncFn(async () => {
const options: Options = this.getOptions() const options: Options = this.getOptions()
const { const { compilerType, isDev, assetPrefix, basePath, outputHashSalt } =
compilerType, options
isDev,
assetPrefix,
basePath,
outputHashSalt,
imgOptDangerouslyAllowAVIF,
} = options
const context = this.rootContext const context = this.rootContext
// Prepend the hash salt to the content for filename hash computation, so // Prepend the hash salt to the content for filename hash computation, so
...@@ -65,7 +58,6 @@ function nextImageLoader(this: any, content: Buffer) { ...@@ -65,7 +58,6 @@ function nextImageLoader(this: any, content: Buffer) {
basePath, basePath,
outputPath, outputPath,
isDev, isDev,
imgOptDangerouslyAllowAVIF,
tracing: imageLoaderSpan.traceChild.bind(imageLoaderSpan), tracing: imageLoaderSpan.traceChild.bind(imageLoaderSpan),
}) })
......
...@@ -748,7 +748,6 @@ export default function Image({ ...@@ -748,7 +748,6 @@ export default function Image({
} }
let staticSrc = '' let staticSrc = ''
let isStaticAvif = false
if (isStaticImport(src)) { if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src const staticImageData = isStaticRequire(src) ? src.default : src
...@@ -761,7 +760,6 @@ export default function Image({ ...@@ -761,7 +760,6 @@ export default function Image({
} }
blurDataURL = blurDataURL || staticImageData.blurDataURL blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!layout || layout !== 'fill') { if (!layout || layout !== 'fill') {
height = height || staticImageData.height height = height || staticImageData.height
width = width || staticImageData.width width = width || staticImageData.width
...@@ -776,12 +774,6 @@ export default function Image({ ...@@ -776,12 +774,6 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
warnOnce( warnOnce(
`Image with src "${src}" is using next/legacy/image which is deprecated and will be removed in a future version of Next.js.` `Image with src "${src}" is using next/legacy/image which is deprecated and will be removed in a future version of Next.js.`
) )
...@@ -916,7 +908,7 @@ export default function Image({ ...@@ -916,7 +908,7 @@ export default function Image({
) )
} }
if (!blurDataURL) { if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
...@@ -266,7 +266,6 @@ export const experimentalSchema = { ...@@ -266,7 +266,6 @@ export const experimentalSchema = {
forceSwcTransforms: z.boolean().optional(), forceSwcTransforms: z.boolean().optional(),
fullySpecified: z.boolean().optional(), fullySpecified: z.boolean().optional(),
gzipSize: z.boolean().optional(), gzipSize: z.boolean().optional(),
imgOptDangerouslyAllowAVIF: z.boolean().optional(),
imgOptConcurrency: z.number().int().optional().nullable(), imgOptConcurrency: z.number().int().optional().nullable(),
imgOptOperationCache: z.boolean().optional().nullable(), imgOptOperationCache: z.boolean().optional().nullable(),
imgOptTimeoutInSeconds: z.number().int().optional(), imgOptTimeoutInSeconds: z.number().int().optional(),
......
...@@ -597,11 +597,6 @@ export interface ExperimentalConfig { ...@@ -597,11 +597,6 @@ export interface ExperimentalConfig {
extensionAlias?: Record<string, any> extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
/**
* Re-enables AVIF input optimization and automatic blur generation.
* This may expose applications to security risks in native image decoders.
*/
imgOptDangerouslyAllowAVIF?: boolean
imgOptConcurrency?: number | null imgOptConcurrency?: number | null
imgOptOperationCache?: boolean | null imgOptOperationCache?: boolean | null
imgOptTimeoutInSeconds?: number imgOptTimeoutInSeconds?: number
...@@ -2286,7 +2281,6 @@ export const defaultConfig = Object.freeze({ ...@@ -2286,7 +2281,6 @@ export const defaultConfig = Object.freeze({
(os.cpus() || { length: 1 }).length) - 1 (os.cpus() || { length: 1 }).length) - 1
), ),
memoryBasedWorkersCount: false, memoryBasedWorkersCount: false,
imgOptDangerouslyAllowAVIF: false,
imgOptConcurrency: null, imgOptConcurrency: null,
imgOptOperationCache: null, imgOptOperationCache: null,
imgOptTimeoutInSeconds: 7, imgOptTimeoutInSeconds: 7,
...@@ -2447,7 +2441,6 @@ export interface NextConfigRuntime { ...@@ -2447,7 +2441,6 @@ export interface NextConfigRuntime {
| 'preloadEntriesOnStart' | 'preloadEntriesOnStart'
| 'hideLogsAfterAbort' | 'hideLogsAfterAbort'
| 'removeUncaughtErrorAndRejectionListeners' | 'removeUncaughtErrorAndRejectionListeners'
| 'imgOptDangerouslyAllowAVIF'
| 'imgOptConcurrency' | 'imgOptConcurrency'
| 'imgOptOperationCache' | 'imgOptOperationCache'
| 'imgOptMaxInputPixels' | 'imgOptMaxInputPixels'
...@@ -2516,7 +2509,6 @@ export function getNextConfigRuntime( ...@@ -2516,7 +2509,6 @@ export function getNextConfigRuntime(
hideLogsAfterAbort: ex.hideLogsAfterAbort, hideLogsAfterAbort: ex.hideLogsAfterAbort,
removeUncaughtErrorAndRejectionListeners: removeUncaughtErrorAndRejectionListeners:
ex.removeUncaughtErrorAndRejectionListeners, ex.removeUncaughtErrorAndRejectionListeners,
imgOptDangerouslyAllowAVIF: ex.imgOptDangerouslyAllowAVIF,
imgOptConcurrency: ex.imgOptConcurrency, imgOptConcurrency: ex.imgOptConcurrency,
imgOptOperationCache: ex.imgOptOperationCache, imgOptOperationCache: ex.imgOptOperationCache,
imgOptMaxInputPixels: ex.imgOptMaxInputPixels, imgOptMaxInputPixels: ex.imgOptMaxInputPixels,
......
...@@ -85,8 +85,7 @@ async function initCacheEntries( ...@@ -85,8 +85,7 @@ async function initCacheEntries(
export function getSharp( export function getSharp(
concurrency: number | null | undefined, concurrency: number | null | undefined,
operationCache: boolean | null | undefined, operationCache: boolean | null | undefined
dangerouslyAllowAVIF = false
) { ) {
if (_sharp) { if (_sharp) {
return _sharp return _sharp
...@@ -96,6 +95,7 @@ export function getSharp( ...@@ -96,6 +95,7 @@ export function getSharp(
_sharp.block({ operation: ['VipsForeignLoad'] }) _sharp.block({ operation: ['VipsForeignLoad'] })
_sharp.unblock({ _sharp.unblock({
operation: [ operation: [
'VipsForeignLoadHeif', // avif
'VipsForeignLoadJpeg', 'VipsForeignLoadJpeg',
'VipsForeignLoadNsgif', 'VipsForeignLoadNsgif',
'VipsForeignLoadPng', 'VipsForeignLoadPng',
...@@ -104,9 +104,6 @@ export function getSharp( ...@@ -104,9 +104,6 @@ export function getSharp(
'VipsForeignLoadWebp', 'VipsForeignLoadWebp',
], ],
}) })
if (dangerouslyAllowAVIF) {
_sharp.unblock({ operation: ['VipsForeignLoadHeif'] })
}
if (typeof operationCache === 'boolean') { if (typeof operationCache === 'boolean') {
_sharp.cache(operationCache) _sharp.cache(operationCache)
} }
...@@ -810,7 +807,6 @@ export async function optimizeImage({ ...@@ -810,7 +807,6 @@ export async function optimizeImage({
limitInputPixels, limitInputPixels,
sequentialRead, sequentialRead,
timeoutInSeconds, timeoutInSeconds,
dangerouslyAllowAVIF,
}: { }: {
buffer: Buffer buffer: Buffer
contentType: string contentType: string
...@@ -822,9 +818,8 @@ export async function optimizeImage({ ...@@ -822,9 +818,8 @@ export async function optimizeImage({
limitInputPixels?: number limitInputPixels?: number
sequentialRead?: boolean | null sequentialRead?: boolean | null
timeoutInSeconds?: number timeoutInSeconds?: number
dangerouslyAllowAVIF?: boolean
}): Promise<Buffer> { }): Promise<Buffer> {
const sharp = getSharp(concurrency, operationCache, dangerouslyAllowAVIF) const sharp = getSharp(concurrency, operationCache)
const transformer = sharp(buffer, { const transformer = sharp(buffer, {
limitInputPixels, limitInputPixels,
sequentialRead: sequentialRead ?? undefined, sequentialRead: sequentialRead ?? undefined,
...@@ -1061,7 +1056,6 @@ export async function imageOptimizer( ...@@ -1061,7 +1056,6 @@ export async function imageOptimizer(
experimental: Pick< experimental: Pick<
NextConfigComplete['experimental'], NextConfigComplete['experimental'],
| 'imgOptConcurrency' | 'imgOptConcurrency'
| 'imgOptDangerouslyAllowAVIF'
| 'imgOptOperationCache' | 'imgOptOperationCache'
| 'imgOptMaxInputPixels' | 'imgOptMaxInputPixels'
| 'imgOptSequentialRead' | 'imgOptSequentialRead'
...@@ -1137,11 +1131,7 @@ export async function imageOptimizer( ...@@ -1137,11 +1131,7 @@ export async function imageOptimizer(
upstreamEtag, upstreamEtag,
} }
} }
if ( if (BYPASS_TYPES.includes(upstreamType)) {
BYPASS_TYPES.includes(upstreamType) ||
(upstreamType === AVIF &&
!nextConfig.experimental.imgOptDangerouslyAllowAVIF)
) {
return { return {
buffer: upstreamBuffer, buffer: upstreamBuffer,
contentType: upstreamType, contentType: upstreamType,
...@@ -1185,7 +1175,6 @@ export async function imageOptimizer( ...@@ -1185,7 +1175,6 @@ export async function imageOptimizer(
quality, quality,
width, width,
concurrency: nextConfig.experimental.imgOptConcurrency, concurrency: nextConfig.experimental.imgOptConcurrency,
dangerouslyAllowAVIF: nextConfig.experimental.imgOptDangerouslyAllowAVIF,
operationCache: nextConfig.experimental.imgOptOperationCache, operationCache: nextConfig.experimental.imgOptOperationCache,
limitInputPixels: nextConfig.experimental.imgOptMaxInputPixels, limitInputPixels: nextConfig.experimental.imgOptMaxInputPixels,
sequentialRead: nextConfig.experimental.imgOptSequentialRead, sequentialRead: nextConfig.experimental.imgOptSequentialRead,
......
...@@ -398,7 +398,6 @@ export function getImgProps( ...@@ -398,7 +398,6 @@ export function getImgProps(
let heightInt = getInt(height) let heightInt = getInt(height)
let blurWidth: number | undefined let blurWidth: number | undefined
let blurHeight: number | undefined let blurHeight: number | undefined
let isStaticAvif = false
if (isStaticImport(src)) { if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src const staticImageData = isStaticRequire(src) ? src.default : src
...@@ -421,7 +420,6 @@ export function getImgProps( ...@@ -421,7 +420,6 @@ export function getImgProps(
blurHeight = staticImageData.blurHeight blurHeight = staticImageData.blurHeight
blurDataURL = blurDataURL || staticImageData.blurDataURL blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!fill) { if (!fill) {
if (!widthInt && !heightInt) { if (!widthInt && !heightInt) {
...@@ -438,12 +436,6 @@ export function getImgProps( ...@@ -438,12 +436,6 @@ export function getImgProps(
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
let isLazy = let isLazy =
!priority && !priority &&
!preload && !preload &&
...@@ -594,7 +586,7 @@ export function getImgProps( ...@@ -594,7 +586,7 @@ export function getImgProps(
) )
} }
if (placeholder === 'blur' && !blurDataURL) { if (placeholder === 'blur' && !blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
This diff is collapsed.
...@@ -36,6 +36,35 @@ ignoredBuiltDependencies: ...@@ -36,6 +36,35 @@ ignoredBuiltDependencies:
blockExoticSubdeps: true blockExoticSubdeps: true
minimumReleaseAge: 2880 # 48 hrs minimumReleaseAge: 2880 # 48 hrs
minimumReleaseAgeExclude: minimumReleaseAgeExclude:
# sharp 0.35.4 and its @img/* binaries fix a security vulnerability, so they
# are exempt from the 48h release age gate.
# These exemptions should be removed on 2026-08-28
- '@img/sharp-darwin-arm64@0.35.4'
- '@img/sharp-darwin-x64@0.35.4'
- '@img/sharp-freebsd-wasm32@0.35.4'
- '@img/sharp-libvips-darwin-arm64@1.3.3'
- '@img/sharp-libvips-darwin-x64@1.3.3'
- '@img/sharp-libvips-linux-arm64@1.3.3'
- '@img/sharp-libvips-linux-arm@1.3.3'
- '@img/sharp-libvips-linux-ppc64@1.3.3'
- '@img/sharp-libvips-linux-riscv64@1.3.3'
- '@img/sharp-libvips-linux-s390x@1.3.3'
- '@img/sharp-libvips-linux-x64@1.3.3'
- '@img/sharp-libvips-linuxmusl-arm64@1.3.3'
- '@img/sharp-libvips-linuxmusl-x64@1.3.3'
- '@img/sharp-linux-arm64@0.35.4'
- '@img/sharp-linux-arm@0.35.4'
- '@img/sharp-linux-ppc64@0.35.4'
- '@img/sharp-linux-riscv64@0.35.4'
- '@img/sharp-linux-s390x@0.35.4'
- '@img/sharp-linux-x64@0.35.4'
- '@img/sharp-linuxmusl-arm64@0.35.4'
- '@img/sharp-linuxmusl-x64@0.35.4'
- '@img/sharp-wasm32@0.35.4'
- '@img/sharp-webcontainers-wasm32@0.35.4'
- '@img/sharp-win32-arm64@0.35.4'
- '@img/sharp-win32-ia32@0.35.4'
- '@img/sharp-win32-x64@0.35.4'
- '@mswjs/interceptors@0.42.0' - '@mswjs/interceptors@0.42.0'
- '@next/*' - '@next/*'
- '@turbo/*' - '@turbo/*'
...@@ -51,4 +80,5 @@ minimumReleaseAgeExclude: ...@@ -51,4 +80,5 @@ minimumReleaseAgeExclude:
- react-is - react-is
- react-server-dom-* - react-server-dom-*
- scheduler - scheduler
- sharp@0.35.4
- turbo - turbo
...@@ -445,26 +445,6 @@ describe('Image Optimizer', () => { ...@@ -445,26 +445,6 @@ describe('Image Optimizer', () => {
}) })
} }
) )
describe('experimental.imgOptDangerouslyAllowAVIF in next.config.js', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'app'),
nextConfig: {
experimental: { imgOptDangerouslyAllowAVIF: true },
},
skipDeployment: true,
})
if (skipped) return
it('should optimize avif input when enabled', async () => {
const query = { w: 256, q: 75, url: '/test.avif' }
const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/webp')
await expectWidth(res, 256)
})
})
;(isNextStart ? describe : describe.skip)( ;(isNextStart ? describe : describe.skip)(
'External rewrite support with for serving static content in images', 'External rewrite support with for serving static content in images',
() => { () => {
......
import fs from 'fs-extra'
import { join } from 'path'
import { optimizeImage } from 'next/dist/server/image-optimizer'
import { setupTests } from './util' import { setupTests } from './util'
describe('with latest sharp', () => { describe('with latest sharp', () => {
it('should block avif decoding below the optimizer bypass', async () => {
const buffer = await fs.readFile(join(__dirname, 'app/public/test.avif'))
await expect(
optimizeImage({
buffer,
contentType: 'image/webp',
quality: 75,
width: 100,
})
).rejects.toThrow()
})
setupTests({}) setupTests({})
}) })
...@@ -122,15 +122,6 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) { ...@@ -122,15 +122,6 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) {
expect(isAnimated(buffer)).toBe(expectAnimated) expect(isAnimated(buffer)).toBe(expectAnimated)
} }
async function expectUnoptimizedImage(res, filename: string) {
const buffer = Buffer.from(await res.arrayBuffer())
const source = await fs.readFile(join(__dirname, 'app/public', filename))
expect(buffer).toEqual(source)
expect(res.headers.get('Content-Length')).toBe(
Buffer.byteLength(source).toString()
)
}
export const cleanImagesDir = async (imagesDir) => { export const cleanImagesDir = async (imagesDir) => {
console.warn('Cleaning', imagesDir) console.warn('Cleaning', imagesDir)
await fs.remove(imagesDir) await fs.remove(imagesDir)
...@@ -614,23 +605,23 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -614,23 +605,23 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should bypass avif input for old Safari', async () => { it('should downlevel avif format to jpeg for old Safari', async () => {
const accept = const accept =
'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5' 'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5'
const query = { w: ctx.w, q: ctx.q, url: '/test.avif' } const query = { w: ctx.w, q: ctx.q, url: '/test.avif' }
const opts = { headers: { accept } } const opts = { headers: { accept } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts) const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('image/avif') expect(res.headers.get('Content-Type')).toContain('image/jpeg')
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate` `public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
) )
expect(res.headers.get('Vary')).toBe('Accept') expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.jpeg"`
) )
await expectUnoptimizedImage(res, 'test.avif') await expectWidth(res, ctx.w)
}) })
it('should fail when url is missing', async () => { it('should fail when url is missing', async () => {
...@@ -941,21 +932,21 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -941,21 +932,21 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should bypass optimization for avif input', async () => { it('should resize avif', async () => {
const query = { url: '/test.avif', w: ctx.w, q: ctx.q } const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts) const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/avif') expect(res.headers.get('Content-Type')).toBe('image/webp')
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate` `public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
) )
expect(res.headers.get('Vary')).toBe('Accept') expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.webp"`
) )
await expectUnoptimizedImage(res, 'test.avif') await expectWidth(res, ctx.w)
}) })
it('should resize relative url and old Chrome accept header as webp', async () => { it('should resize relative url and old Chrome accept header as webp', async () => {
...@@ -999,7 +990,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -999,7 +990,7 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should bypass avif input when avif output is enabled', async () => { it('should resize avif and maintain format', async () => {
const query = { url: '/test.avif', w: ctx.w, q: ctx.q } const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/avif' } } const opts = { headers: { accept: 'image/avif' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts) const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
...@@ -1013,7 +1004,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -1013,7 +1004,7 @@ export function runTests(ctx: RunTestsCtx) {
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.avif"`
) )
await expectUnoptimizedImage(res, 'test.avif') await expectWidth(res, ctx.w)
}) })
it('should compress avif smaller than webp at q=100', async () => { it('should compress avif smaller than webp at q=100', async () => {
......
...@@ -90,36 +90,6 @@ describe('getImageProps()', () => { ...@@ -90,36 +90,6 @@ describe('getImageProps()', () => {
expect(props.srcSet).toBeString() expect(props.srcSet).toBeString()
}) })
it('should disable an automatic blur placeholder for a static avif', () => {
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
})
expect(props.style).toStrictEqual({ color: 'transparent' })
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
})
expect(props.style?.backgroundImage).toContain(blurDataURL)
})
it('should handle preload', async () => { it('should handle preload', async () => {
const { props } = getImageProps({ const { props } = getImageProps({
alt: 'a nice desc', alt: 'a nice desc',
......
...@@ -103,40 +103,6 @@ describe('Image Legacy Rendering', () => { ...@@ -103,40 +103,6 @@ describe('Image Legacy Rendering', () => {
expect($3('noscript').length).toBe(1) expect($3('noscript').length).toBe(1)
}) })
it('should disable an automatic blur placeholder for a static avif', () => {
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(0)
expect($.html()).not.toContain('background-image')
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(1)
expect($.html()).toContain(blurDataURL)
})
it('should render the correct sizes passed when a noscript element is rendered', async () => { it('should render the correct sizes passed when a noscript element is rendered', async () => {
const element = React.createElement(Image, { const element = React.createElement(Image, {
src: '/test.png', src: '/test.png',
......
...@@ -35,42 +35,4 @@ describe('getBlurImage', () => { ...@@ -35,42 +35,4 @@ describe('getBlurImage', () => {
expect(result).toBeObject() expect(result).toBeObject()
expect(result.dataURL).toBeUndefined() expect(result.dataURL).toBeUndefined()
}) })
it('should not generate a blur placeholder for avif', async () => {
const buffer = await getImage('../image-optimizer/images/test.avif')
const result = await getBlurImage(
buffer,
'avif',
{ width: 400, height: 400 },
{
...context,
outputPath: '/_next/static/media/test.avif',
}
)
expect(result).toBeObject()
expect(result).toStrictEqual({
dataURL: undefined,
width: 0,
height: 0,
})
})
it('should generate a blur placeholder for avif when enabled', async () => {
jest.resetModules()
const { getBlurImage: getBlurImageWithAVIF } = await import(
'next/dist/build/webpack/loaders/next-image-loader/blur'
)
const buffer = await getImage('../image-optimizer/images/test.avif')
const result = await getBlurImageWithAVIF(
buffer,
'avif',
{ width: 400, height: 400 },
{
...context,
imgOptDangerouslyAllowAVIF: true,
}
)
expect(result).toBeObject()
expect(result.dataURL).toStartWith('data:image/avif;base64,')
expect(result.width).toBe(8)
expect(result.height).toBe(8)
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment