Unverified Commit 83f89c4f authored by Bruno Crosier's avatar Bruno Crosier Committed by GitHub

Improve types for `<Image />` and `responseLimit` (#40863)

Currently, a developer building a website using Next.js could write this
code with no type errors:

```tsx
<Image
  width="kangaroo"
  height="100px"
  quality="medium"
  {...rest}
/>
```

This PR adds stricter type checking, which will catch this type of error
earlier.

Similarly, this PR adds stricter types for the `responseLimit`, to
ensure the types align to:
https://nextjs.org/docs/messages/api-routes-response-size-limitCo-authored-by: 's avatarSteven <steven@ceriously.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 7903b04b
...@@ -72,6 +72,8 @@ interface StaticRequire { ...@@ -72,6 +72,8 @@ interface StaticRequire {
type StaticImport = StaticRequire | StaticImageData type StaticImport = StaticRequire | StaticImageData
type SafeNumber = number | `${number}`
function isStaticRequire( function isStaticRequire(
src: StaticRequire | StaticImageData src: StaticRequire | StaticImageData
): src is StaticRequire { ): src is StaticRequire {
...@@ -98,11 +100,11 @@ export type ImageProps = Omit< ...@@ -98,11 +100,11 @@ export type ImageProps = Omit<
> & { > & {
src: string | StaticImport src: string | StaticImport
alt: string alt: string
width?: number | string width?: SafeNumber
height?: number | string height?: SafeNumber
fill?: boolean fill?: boolean
loader?: ImageLoader loader?: ImageLoader
quality?: number | string quality?: SafeNumber
priority?: boolean priority?: boolean
loading?: LoadingValue loading?: LoadingValue
placeholder?: PlaceholderValue placeholder?: PlaceholderValue
......
...@@ -218,6 +218,8 @@ interface StaticRequire { ...@@ -218,6 +218,8 @@ interface StaticRequire {
type StaticImport = StaticRequire | StaticImageData type StaticImport = StaticRequire | StaticImageData
type SafeNumber = number | `${number}`
function isStaticRequire( function isStaticRequire(
src: StaticRequire | StaticImageData src: StaticRequire | StaticImageData
): src is StaticRequire { ): src is StaticRequire {
...@@ -243,11 +245,11 @@ export type ImageProps = Omit< ...@@ -243,11 +245,11 @@ export type ImageProps = Omit<
'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading' 'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading'
> & { > & {
src: string | StaticImport src: string | StaticImport
width?: number | string width?: SafeNumber
height?: number | string height?: SafeNumber
layout?: LayoutValue layout?: LayoutValue
loader?: ImageLoader loader?: ImageLoader
quality?: number | string quality?: SafeNumber
priority?: boolean priority?: boolean
loading?: LoadingValue loading?: LoadingValue
lazyRoot?: React.RefObject<HTMLElement> | null lazyRoot?: React.RefObject<HTMLElement> | null
......
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils' import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils'
import type { PageConfig } from 'next/types' import type { PageConfig, ResponseLimit, SizeLimit } from 'next/types'
import { import {
checkIsManualRevalidate, checkIsManualRevalidate,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
...@@ -140,7 +140,7 @@ function parseJson(str: string): object { ...@@ -140,7 +140,7 @@ function parseJson(str: string): object {
*/ */
export async function parseBody( export async function parseBody(
req: IncomingMessage, req: IncomingMessage,
limit: string | number limit: SizeLimit
): Promise<any> { ): Promise<any> {
let contentType let contentType
try { try {
...@@ -182,7 +182,7 @@ type ApiContext = __ApiPreviewProps & { ...@@ -182,7 +182,7 @@ type ApiContext = __ApiPreviewProps & {
revalidate?: (_req: IncomingMessage, _res: ServerResponse) => Promise<any> revalidate?: (_req: IncomingMessage, _res: ServerResponse) => Promise<any>
} }
function getMaxContentLength(responseLimit?: number | string | boolean) { function getMaxContentLength(responseLimit?: ResponseLimit) {
if (responseLimit && typeof responseLimit !== 'boolean') { if (responseLimit && typeof responseLimit !== 'boolean') {
return bytes.parse(responseLimit) return bytes.parse(responseLimit)
} }
......
import type { ServerResponse, IncomingMessage } from 'http' import type { ServerResponse, IncomingMessage } from 'http'
import type { Writable, Readable } from 'stream' import type { Writable, Readable } from 'stream'
import type { SizeLimit } from 'next/types'
import { NextApiRequestCookies, SYMBOL_CLEARED_COOKIES } from '../api-utils' import { NextApiRequestCookies, SYMBOL_CLEARED_COOKIES } from '../api-utils'
import { parseBody } from '../api-utils/node' import { parseBody } from '../api-utils/node'
...@@ -34,7 +35,7 @@ export class NodeNextRequest extends BaseNextRequest<Readable> { ...@@ -34,7 +35,7 @@ export class NodeNextRequest extends BaseNextRequest<Readable> {
super(_req.method!.toUpperCase(), _req.url!, _req) super(_req.method!.toUpperCase(), _req.url!, _req)
} }
async parseBody(limit: string | number): Promise<any> { async parseBody(limit: SizeLimit): Promise<any> {
return parseBody(this._req, limit) return parseBody(this._req, limit)
} }
} }
......
...@@ -61,6 +61,22 @@ export type Redirect = ...@@ -61,6 +61,22 @@ export type Redirect =
*/ */
export type NextPage<P = {}, IP = P> = NextComponentType<NextPageContext, IP, P> export type NextPage<P = {}, IP = P> = NextComponentType<NextPageContext, IP, P>
export type FileSizeSuffix = `${
| 'k'
| 'K'
| 'm'
| 'M'
| 'g'
| 'G'
| 't'
| 'T'
| 'p'
| 'P'}${'b' | 'B'}`
export type SizeLimit = number | `${number}${FileSizeSuffix}`
export type ResponseLimit = SizeLimit | boolean
/** /**
* `Config` type, use it for export const config * `Config` type, use it for export const config
*/ */
...@@ -72,12 +88,16 @@ export type PageConfig = { ...@@ -72,12 +88,16 @@ export type PageConfig = {
* any string format supported by `bytes`, for example `1000`, `'500kb'` or * any string format supported by `bytes`, for example `1000`, `'500kb'` or
* `'3mb'`. * `'3mb'`.
*/ */
responseLimit?: number | string | boolean responseLimit?: ResponseLimit
/** /**
* The byte limit of the body. This is the number of bytes or any string * The byte limit of the body. This is the number of bytes or any string
* format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`.
*/ */
bodyParser?: { sizeLimit?: number | string } | false bodyParser?:
| {
sizeLimit?: SizeLimit
}
| false
/** /**
* Flag to disable warning "API page resolved * Flag to disable warning "API page resolved
* without sending a response", due to explicitly * without sending a response", due to explicitly
......
...@@ -26,6 +26,24 @@ const Invalid = () => { ...@@ -26,6 +26,24 @@ const Invalid = () => {
height="500" height="500"
placeholder="invalid" placeholder="invalid"
></Image> ></Image>
<Image
id="invalid-width-string-type"
alt="invalid-width-string-type"
src="https://image-optimization-test.vercel.app/test.jpg"
width="500foo"
/>
<Image
id="invalid-height-string-type"
alt="invalid-height-string-type"
src="https://image-optimization-test.vercel.app/test.jpg"
height="500bar"
/>
<Image
id="invalid-quality-string-type"
alt="invalid-quality-string-type"
src="https://image-optimization-test.vercel.app/test.jpg"
quality="500baz"
/>
<p id="stubtext">This is the invalid usage</p> <p id="stubtext">This is the invalid usage</p>
</div> </div>
) )
......
...@@ -43,6 +43,14 @@ const Page = () => { ...@@ -43,6 +43,14 @@ const Page = () => {
width={500} width={500}
height={500} height={500}
/> />
<Image
id="numeric-string-types"
alt="numeric-string-types"
src="https://image-optimization-test.vercel.app/test.jpg"
quality="80"
width="500"
height="500"
/>
<Image <Image
id="data-protocol" id="data-protocol"
src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
......
...@@ -27,6 +27,24 @@ const Invalid = () => { ...@@ -27,6 +27,24 @@ const Invalid = () => {
height="500" height="500"
placeholder="invalid" placeholder="invalid"
/> />
<Image
id="invalid-width-string-type"
alt="invalid-width-string-type"
src="https://image-optimization-test.vercel.app/test.jpg"
width="500foo"
/>
<Image
id="invalid-height-string-type"
alt="invalid-height-string-type"
src="https://image-optimization-test.vercel.app/test.jpg"
height="500bar"
/>
<Image
id="invalid-quality-string-type"
alt="invalid-quality-string-type"
src="https://image-optimization-test.vercel.app/test.jpg"
quality="500baz"
/>
<Image <Image
id="missing-alt" id="missing-alt"
src="https://image-optimization-test.vercel.app/test.jpg" src="https://image-optimization-test.vercel.app/test.jpg"
......
...@@ -28,6 +28,7 @@ const Page = () => { ...@@ -28,6 +28,7 @@ const Page = () => {
id="fill-no-width-and-height" id="fill-no-width-and-height"
src="https://image-optimization-test.vercel.app/test.jpg" src="https://image-optimization-test.vercel.app/test.jpg"
fill fill
alt=""
/> />
<Image <Image
id="quality-num" id="quality-num"
...@@ -35,6 +36,7 @@ const Page = () => { ...@@ -35,6 +36,7 @@ const Page = () => {
quality={80} quality={80}
width={500} width={500}
height={500} height={500}
alt=""
/> />
<Image <Image
id="quality-str" id="quality-str"
...@@ -44,6 +46,14 @@ const Page = () => { ...@@ -44,6 +46,14 @@ const Page = () => {
width={500} width={500}
height={500} height={500}
/> />
<Image
id="numeric-string-types"
alt="numeric-string-types"
src="https://image-optimization-test.vercel.app/test.jpg"
quality="80"
width="500"
height="500"
/>
<Image <Image
id="data-protocol" id="data-protocol"
alt="data-protocol" alt="data-protocol"
......
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