Unverified Commit d4c838a7 authored by Steven's avatar Steven Committed by GitHub

chore: remove unused code from image optimizer (#98060)

This PR removes some unused code from the image optimizer.

- Remove redundant MIME validation
- Remove unreachable fallback error

These used to be necessary until PR
https://github.com/vercel/next.js/pull/82118 removed the fallback.

Before 82118:

```js
upstreamType = detectContentType(upstreamBuffer) || imageUpstream.contentType?.toLowerCase().trim()
```

After 82118:

```js
upstreamType = detectContentType(upstreamBuffer)
```

Now there is never a case where upstreamType is invalid since its
already been validated, there is no more fallback.
parent 086294e2
...@@ -47,10 +47,6 @@ const CACHE_VERSION = 4 ...@@ -47,10 +47,6 @@ const CACHE_VERSION = 4
const BLUR_IMG_SIZE = 8 // should match `next-image-loader` const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
const BLUR_QUALITY = 70 // should match `next-image-loader` const BLUR_QUALITY = 70 // should match `next-image-loader`
function isValidMime(contentType: string) {
return Boolean(getExtension(contentType))
}
async function initCacheEntries( async function initCacheEntries(
cacheDir: string cacheDir: string
): Promise<Array<{ key: string; size: number; expireAt: number }>> { ): Promise<Array<{ key: string; size: number; expireAt: number }>> {
...@@ -769,7 +765,6 @@ export async function imageOptimizer( ...@@ -769,7 +765,6 @@ export async function imageOptimizer(
) )
return imageOptimizerTransform(imageUpstream, paramsResult, nextConfig, { return imageOptimizerTransform(imageUpstream, paramsResult, nextConfig, {
isValidMime,
previousOutput: previouslyCachedImage previousOutput: previouslyCachedImage
? { ? {
buffer: previouslyCachedImage.buffer, buffer: previouslyCachedImage.buffer,
......
...@@ -62,7 +62,6 @@ export interface ImageOptimizerTransformLogger { ...@@ -62,7 +62,6 @@ export interface ImageOptimizerTransformLogger {
} }
export interface ImageOptimizerTransformOptions { export interface ImageOptimizerTransformOptions {
isValidMime: (contentType: string) => boolean
previousOutput?: { previousOutput?: {
buffer: Buffer buffer: Buffer
maxAge?: number maxAge?: number
...@@ -195,7 +194,7 @@ export async function imageOptimizerTransform( ...@@ -195,7 +194,7 @@ export async function imageOptimizerTransform(
imageUpstream: ImageUpstream, imageUpstream: ImageUpstream,
paramsResult: ImageOptimizerTransformParams, paramsResult: ImageOptimizerTransformParams,
nextConfig: ImageOptimizerTransformConfig, nextConfig: ImageOptimizerTransformConfig,
opts: ImageOptimizerTransformOptions opts: ImageOptimizerTransformOptions = {}
): Promise<ImageOptimizerResult> { ): Promise<ImageOptimizerResult> {
const { href, quality, width, mimeType } = paramsResult const { href, quality, width, mimeType } = paramsResult
const { buffer: upstreamBuffer, etag: upstreamEtag } = imageUpstream const { buffer: upstreamBuffer, etag: upstreamEtag } = imageUpstream
...@@ -256,14 +255,11 @@ export async function imageOptimizerTransform( ...@@ -256,14 +255,11 @@ export async function imageOptimizerTransform(
if (mimeType) { if (mimeType) {
contentType = mimeType contentType = mimeType
} else if ( } else if (upstreamType === WEBP || upstreamType === AVIF) {
opts.isValidMime(upstreamType) && // Downlevel WebP and AVIF when the client does not advertise support.
upstreamType !== WEBP &&
upstreamType !== AVIF
) {
contentType = upstreamType
} else {
contentType = JPEG contentType = JPEG
} else {
contentType = upstreamType
} }
if (opts.previousOutput) { if (opts.previousOutput) {
...@@ -301,21 +297,14 @@ export async function imageOptimizerTransform( ...@@ -301,21 +297,14 @@ export async function imageOptimizerTransform(
upstreamEtag, upstreamEtag,
} }
} catch (error) { } catch (error) {
if (upstreamType) { // If we fail to optimize, fallback to the original image
// If we fail to optimize, fallback to the original image return {
return { buffer: upstreamBuffer,
buffer: upstreamBuffer, contentType: upstreamType,
contentType: upstreamType, maxAge: nextConfig.images.minimumCacheTTL,
maxAge: nextConfig.images.minimumCacheTTL, etag: upstreamEtag,
etag: upstreamEtag, upstreamEtag,
upstreamEtag, error,
error,
}
} else {
throw new ImageError(
400,
'Unable to optimize image and unable to fallback to upstream image'
)
} }
} }
} }
/* eslint-env jest */ /* eslint-env jest */
import { readFile } from 'fs-extra' import { readFile } from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { import { imageOptimizerTransform } from 'next/dist/server/image-optimizer/transform'
imageOptimizerTransform,
type ImageOptimizerTransformOptions,
} from 'next/dist/server/image-optimizer/transform'
import type { import type {
CachedRouteKind, CachedRouteKind,
IncrementalResponseCacheEntry, IncrementalResponseCacheEntry,
...@@ -13,8 +10,6 @@ import type { ...@@ -13,8 +10,6 @@ import type {
const getImage = (filename: string) => const getImage = (filename: string) =>
readFile(join(__dirname, 'images', filename)) readFile(join(__dirname, 'images', filename))
const isValidMime = (contentType: string) => contentType === 'image/png'
const config = { const config = {
images: { images: {
dangerouslyAllowSVG: true, dangerouslyAllowSVG: true,
...@@ -29,11 +24,7 @@ const config = { ...@@ -29,11 +24,7 @@ const config = {
}, },
} }
async function transform( async function transform(filename: string, mimeType = 'image/webp') {
filename: string,
mimeType = 'image/webp',
options?: ImageOptimizerTransformOptions
) {
const buffer = await getImage(filename) const buffer = await getImage(filename)
return imageOptimizerTransform( return imageOptimizerTransform(
{ {
...@@ -43,8 +34,7 @@ async function transform( ...@@ -43,8 +34,7 @@ async function transform(
etag: 'source-etag', etag: 'source-etag',
}, },
{ href: `/${filename}`, width: 64, quality: 75, mimeType }, { href: `/${filename}`, width: 64, quality: 75, mimeType },
config, config
{ isValidMime, ...options }
) )
} }
...@@ -110,6 +100,11 @@ describe('imageOptimizerTransform', () => { ...@@ -110,6 +100,11 @@ describe('imageOptimizerTransform', () => {
expect(result.contentType).toBe('image/webp') expect(result.contentType).toBe('image/webp')
}) })
it('downlevels an avif source when no output format is requested', async () => {
const result = await transform('test.avif', '')
expect(result.contentType).toBe('image/jpeg')
})
it('generates blur placeholders in development', async () => { it('generates blur placeholders in development', async () => {
const result = await transformInDevelopment('test.png') const result = await transformInDevelopment('test.png')
expect(result.contentType).toBe('image/svg+xml') expect(result.contentType).toBe('image/svg+xml')
...@@ -167,8 +162,7 @@ describe('imageOptimizerTransform', () => { ...@@ -167,8 +162,7 @@ describe('imageOptimizerTransform', () => {
{ {
...config, ...config,
images: { ...config.images, dangerouslyAllowSVG: false }, images: { ...config.images, dangerouslyAllowSVG: false },
}, }
{ isValidMime }
) )
).rejects.toMatchObject({ statusCode: 400 }) ).rejects.toMatchObject({ statusCode: 400 })
}) })
...@@ -183,8 +177,7 @@ describe('imageOptimizerTransform', () => { ...@@ -183,8 +177,7 @@ describe('imageOptimizerTransform', () => {
etag: 'source-etag', etag: 'source-etag',
}, },
{ href: '/bad', width: 64, quality: 75, mimeType: 'image/webp' }, { href: '/bad', width: 64, quality: 75, mimeType: 'image/webp' },
config, config
{ isValidMime }
) )
).rejects.toMatchObject({ statusCode: 400 }) ).rejects.toMatchObject({ statusCode: 400 })
}) })
......
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