Unverified Commit 4593aec0 authored by Josh Story's avatar Josh Story Committed by GitHub

Prepare image options without mutating configuration (#99394)

## Summary

Image helpers and components sort arrays from their configuration, which
fails when that configuration comes from a frozen deployment manifest.
Prepare owned image options once and reuse them across rendering and
`getImageProps`. This supports immutable Next.js configuration in Vercel
adapter deployments.

Modern and legacy Image components share a `useImageConfig` hook that
preserves existing configuration selection and SSR `localPatterns`
validation. `getImageProps` prepares its fixed options once at module
initialization without context.

## Verification

Existing local-pattern, query-string validation, and custom-loader
production fixtures pass with Webpack and Turbopack. Development checks
cover local patterns, legacy remote-image rejection, and the
static-export diagnostic with both bundlers.

<!-- NEXT_JS_LLM -->
parent d7a18cc1
......@@ -4,7 +4,6 @@ import React, {
useRef,
useEffect,
useContext,
useMemo,
useState,
forwardRef,
use,
......@@ -20,21 +19,14 @@ import type {
OnLoadingComplete,
PlaceholderValue,
} from '../shared/lib/get-img-props'
import type {
ImageConfigComplete,
ImageLoaderProps,
} from '../shared/lib/image-config'
import { imageConfigDefault } from '../shared/lib/image-config'
import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime'
import type { ImageLoaderProps } from '../shared/lib/image-config'
import { RouterContext } from '../shared/lib/router-context.shared-runtime'
import { useImageConfig } from './use-image-config'
// This is replaced by webpack alias
import defaultLoader from 'next/dist/shared/lib/image-loader'
import { useMergedRef } from './use-merged-ref'
// This is replaced by webpack define plugin
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
if (typeof window === 'undefined') {
;(globalThis as any).__NEXT_IMAGE_IMPORTED = true
}
......@@ -380,28 +372,7 @@ export const Image = forwardRef<HTMLImageElement | null, ImageProps>(
// We're in the app directory if there is no pages router.
const isAppRouter = !pagesRouter
const configContext = useContext(ImageConfigContext)
const config = useMemo(() => {
const c = configEnv || configContext || imageConfigDefault
const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b)
const deviceSizes = c.deviceSizes.sort((a, b) => a - b)
const qualities = c.qualities?.sort((a, b) => a - b)
return {
...c,
allSizes,
deviceSizes,
qualities,
// During the SSR, configEnv (__NEXT_IMAGE_OPTS) does not include
// security sensitive configs like `localPatterns`, which is needed
// during the server render to ensure it's validated. Therefore use
// configContext, which holds the config from the server for validation.
localPatterns:
typeof window === 'undefined'
? configContext?.localPatterns
: c.localPatterns,
}
}, [configContext])
const config = useImageConfig()
const { onLoad, onLoadingComplete } = props
const onLoadRef = useRef(onLoad)
......
......@@ -4,23 +4,18 @@ import React, {
useRef,
useEffect,
useCallback,
useContext,
useMemo,
useState,
type JSX,
} from 'react'
import * as ReactDOM from 'react-dom'
import Head from '../../shared/lib/head'
import {
imageConfigDefault,
VALID_LOADERS,
} from '../../shared/lib/image-config'
import { VALID_LOADERS } from '../../shared/lib/image-config'
import type {
ImageConfigComplete,
PreparedImageConfig,
LoaderValue,
} from '../../shared/lib/image-config'
import { useIntersection } from '../use-intersection'
import { ImageConfigContext } from '../../shared/lib/image-config-context.shared-runtime'
import { useImageConfig } from '../use-image-config'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import { normalizePathTrailingSlash } from '../normalize-trailing-slash'
import { findClosestQuality } from '../../shared/lib/find-closest-quality'
......@@ -31,7 +26,6 @@ function normalizeSrc(src: string): string {
}
const supportsFloat = typeof ReactDOM.preload === 'function'
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const loadedImageURLs = new Set<string>()
const allImgs = new Map<
string,
......@@ -47,7 +41,7 @@ if (typeof window === 'undefined') {
const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = (typeof VALID_LOADING_VALUES)[number]
type ImageConfig = ImageConfigComplete & { allSizes: number[] }
type ImageConfig = PreparedImageConfig
export type ImageLoader = (resolverProps: ImageLoaderProps) => string
export type ImageLoaderProps = {
......@@ -223,7 +217,13 @@ function defaultLoader({
// We use dynamic require because this should only error in development
const { hasRemoteMatch } =
require('../../shared/lib/match-remote-pattern') as typeof import('../../shared/lib/match-remote-pattern')
if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) {
if (
!hasRemoteMatch(
config.domains ?? [],
config.remotePatterns ?? [],
parsedSrc
)
) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
......@@ -701,26 +701,7 @@ export default function Image({
blurDataURL,
...all
}: ImageProps) {
const configContext = useContext(ImageConfigContext)
const config: ImageConfig = useMemo(() => {
const c = configEnv || configContext || imageConfigDefault
const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b)
const deviceSizes = c.deviceSizes.sort((a, b) => a - b)
const qualities = c.qualities?.sort((a, b) => a - b)
return {
...c,
allSizes,
deviceSizes,
qualities, // During the SSR, configEnv (__NEXT_IMAGE_OPTS) does not include
// security sensitive configs like `localPatterns`, which is needed
// during the server render to ensure it's validated. Therefore use
// configContext, which holds the config from the server for validation.
localPatterns:
typeof window === 'undefined'
? configContext?.localPatterns
: c.localPatterns,
}
}, [configContext])
const config: ImageConfig = useImageConfig()
let rest: Partial<ImageProps> = all
let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic'
......
'use client'
import { useContext } from 'react'
import {
prepareImageConfig,
type ImageConfigForRendering,
} from '../shared/lib/image-config'
import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime'
// This is replaced by the bundler define plugin.
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as
| ImageConfigForRendering
| undefined
export function useImageConfig() {
const configContext = useContext(ImageConfigContext)
return prepareImageConfig(configEnv, configContext)
}
import { getAssetToken, getDeploymentId } from './deployment-id'
import { getImageBlurSvg } from './image-blur-svg'
import { imageConfigDefault } from './image-config'
import type {
ImageConfigComplete,
ImageLoaderProps,
ImageLoaderPropsWithConfig,
PreparedImageConfig,
} from './image-config'
import type { CSSProperties, JSX } from 'react'
......@@ -95,10 +94,7 @@ const INVALID_BACKGROUND_SIZE_VALUES = [
undefined,
]
type LoadingValue = (typeof VALID_LOADING_VALUES)[number]
type ImageConfig = ImageConfigComplete & {
allSizes: number[]
output?: 'standalone' | 'export'
}
type ImageConfig = PreparedImageConfig
export type ImageLoader = (p: ImageLoaderProps) => string
......@@ -313,7 +309,7 @@ export function getImgProps(
}: ImageProps,
_state: {
defaultLoader: ImageLoaderWithConfig
imgConf: ImageConfigComplete
imgConf: ImageConfig
showAltText?: boolean
blurComplete?: boolean
}
......@@ -326,17 +322,7 @@ export function getImgProps(
fill: boolean
}
} {
const { imgConf, showAltText, blurComplete, defaultLoader } = _state
let config: ImageConfig
let c = imgConf || imageConfigDefault
if ('allSizes' in c) {
config = c as ImageConfig
} else {
const allSizes = [...c.deviceSizes, ...c.imageSizes].sort((a, b) => a - b)
const deviceSizes = c.deviceSizes.sort((a, b) => a - b)
const qualities = c.qualities?.sort((a, b) => a - b)
config = { ...c, allSizes, deviceSizes, qualities }
}
const { imgConf: config, showAltText, blurComplete, defaultLoader } = _state
if (typeof defaultLoader === 'undefined') {
throw new Error(
......
......@@ -146,6 +146,94 @@ export type ImageConfigComplete = {
export type ImageConfig = Partial<ImageConfigComplete>
type RequiredImageConfigForRendering = Pick<
ImageConfigComplete,
| 'deviceSizes'
| 'imageSizes'
| 'loader'
| 'path'
| 'dangerouslyAllowSVG'
| 'unoptimized'
>
export type ImageConfigForRendering = RequiredImageConfigForRendering &
Partial<
Pick<
ImageConfigComplete,
'qualities' | 'domains' | 'remotePatterns' | 'localPatterns'
>
> & {
output?: 'standalone' | 'export'
}
export type PreparedImageConfig = RequiredImageConfigForRendering & {
allSizes: number[]
qualities: ImageConfigComplete['qualities']
domains: ImageConfigComplete['domains'] | undefined
remotePatterns: ImageConfigComplete['remotePatterns'] | undefined
localPatterns: ImageConfigComplete['localPatterns']
output: 'standalone' | 'export' | undefined
}
const missingImageConfig = {}
const preparedImageConfigs = new WeakMap<
object,
WeakMap<object, PreparedImageConfig>
>()
/**
* Prepare owned, sorted image options once for each env/context pair.
* Changed options require new objects because results are cached by identity.
*/
export function prepareImageConfig(
envConfig?: ImageConfigForRendering,
contextConfig?: ImageConfigComplete
): PreparedImageConfig {
const envKey = envConfig ?? missingImageConfig
const contextKey = contextConfig ?? missingImageConfig
let preparedByContext = preparedImageConfigs.get(envKey)
if (preparedByContext) {
const cached = preparedByContext.get(contextKey)
if (cached) {
return cached
}
}
const source: ImageConfigForRendering =
envConfig || contextConfig || imageConfigDefault
const deviceSizes = [...source.deviceSizes].sort((a, b) => a - b)
const imageSizes = [...source.imageSizes]
const prepared: PreparedImageConfig = {
deviceSizes,
imageSizes,
allSizes: [...deviceSizes, ...imageSizes].sort((a, b) => a - b),
qualities:
source.qualities === undefined
? undefined
: [...source.qualities].sort((a, b) => a - b),
path: source.path,
loader: source.loader,
dangerouslyAllowSVG: source.dangerouslyAllowSVG,
unoptimized: source.unoptimized,
domains: source.domains,
remotePatterns: source.remotePatterns,
// The inlined browser options supply their own patterns. During SSR the
// context supplies security-sensitive patterns omitted from the inline data.
localPatterns:
typeof window === 'undefined' && contextConfig !== undefined
? contextConfig.localPatterns
: source.localPatterns,
output: source.output,
}
if (!preparedByContext) {
preparedByContext = new WeakMap()
preparedImageConfigs.set(envKey, preparedByContext)
}
preparedByContext.set(contextKey, prepared)
return prepared
}
export const imageConfigDefault: ImageConfigComplete = {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
imageSizes: [32, 48, 64, 96, 128, 256, 384],
......
import type { ImageConfigComplete } from './image-config'
import {
prepareImageConfig,
type ImageConfigForRendering,
} from './image-config'
import type { ImageProps } from './get-img-props'
import { getImgProps } from './get-img-props'
......@@ -9,6 +12,11 @@ import { getImgProps } from './get-img-props'
import * as defaultLoaderModule from 'next/dist/shared/lib/image-loader'
const defaultLoader = Reflect.get(defaultLoaderModule, 'default')
// The bundler replaces this with fixed options. Public getImageProps has no
// context, so prepare those options once when the module is loaded.
const imageConfig = prepareImageConfig(
process.env.__NEXT_IMAGE_OPTS as any as ImageConfigForRendering | undefined
)
/**
* For more advanced use cases, you can call `getImageProps()`
......@@ -20,8 +28,7 @@ const defaultLoader = Reflect.get(defaultLoaderModule, 'default')
export function getImageProps(imgProps: ImageProps) {
const { props } = getImgProps(imgProps, {
defaultLoader,
// This is replaced by webpack define plugin
imgConf: process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete,
imgConf: imageConfig,
})
// Normally we don't care about undefined props because we pass to JSX,
// but this exported function could be used by the end user for anything
......
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