Skip to content

Commit

Permalink
fix: updated typescript types for React API's (#70410)
Browse files Browse the repository at this point in the history
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


This adds and updates some Typescript types for the React libraries used
by Next.js. As a result some of the code was modified to match.
  • Loading branch information
wyattjoh authored Sep 25, 2024
1 parent 3d6ecf3 commit e2ae5e9
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 39 deletions.
32 changes: 23 additions & 9 deletions packages/next/src/server/app-render/action-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,8 @@ export async function handleAction({
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
)
let bound = []

let boundActionArguments: unknown[] = []

const { actionAsyncStorage } = ComponentMod

Expand Down Expand Up @@ -620,14 +621,18 @@ export async function handleAction({
// TODO-APP: Add streaming support
const formData = await req.request.formData()
if (isFetchAction) {
bound = await decodeReply(formData, serverModuleMap)
boundActionArguments = await decodeReply(formData, serverModuleMap)
} else {
const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') {
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
const actionReturnedState = await action()
formState = decodeFormState(actionReturnedState, formData)
formState = decodeFormState(
actionReturnedState,
formData,
serverModuleMap
)
}

// Skip the fetch path
Expand Down Expand Up @@ -659,9 +664,12 @@ export async function handleAction({

if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
bound = await decodeReply(formData, serverModuleMap)
boundActionArguments = await decodeReply(formData, serverModuleMap)
} else {
bound = await decodeReply(actionData, serverModuleMap)
boundActionArguments = await decodeReply(
actionData,
serverModuleMap
)
}
}
} else if (
Expand Down Expand Up @@ -723,7 +731,10 @@ export async function handleAction({

body.pipe(busboy)

bound = await decodeReplyFromBusboy(busboy, serverModuleMap)
boundActionArguments = await decodeReplyFromBusboy(
busboy,
serverModuleMap
)
} else {
// React doesn't yet publish a busboy version of decodeAction
// so we polyfill the parsing of FormData.
Expand Down Expand Up @@ -779,9 +790,12 @@ export async function handleAction({

if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
bound = await decodeReply(formData, serverModuleMap)
boundActionArguments = await decodeReply(formData, serverModuleMap)
} else {
bound = await decodeReply(actionData, serverModuleMap)
boundActionArguments = await decodeReply(
actionData,
serverModuleMap
)
}
}
} else {
Expand Down Expand Up @@ -819,7 +833,7 @@ export async function handleAction({
actionId!
]

const returnVal = await actionHandler.apply(null, bound)
const returnVal = await actionHandler.apply(null, boundActionArguments)

// For form actions, we need to continue rendering the page.
if (isFetchAction) {
Expand Down
32 changes: 11 additions & 21 deletions packages/next/src/server/app-render/app-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { IncomingHttpHeaders } from 'http'

import React, { type ErrorInfo, type JSX } from 'react'
import React, { type JSX } from 'react'

import RenderResult, {
type AppPageRenderResultMetadata,
Expand Down Expand Up @@ -506,7 +506,6 @@ async function generateDynamicFlightRenderResult(
ctx.clientReferenceManifest.clientModules,
{
onError,
nonce: ctx.nonce,
}
)

Expand Down Expand Up @@ -1388,7 +1387,6 @@ async function renderToStream(
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
nonce: ctx.nonce,
}
)
)
Expand Down Expand Up @@ -1596,7 +1594,6 @@ async function renderToStream(
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
nonce: ctx.nonce,
}
)

Expand Down Expand Up @@ -1837,7 +1834,7 @@ async function prerenderToStream(
ctx,
res.statusCode === 404
)
function voidOnError() {}

;(
prerenderAsyncStorage.run(
// The store to scope
Expand All @@ -1848,9 +1845,8 @@ async function prerenderToStream(
firstAttemptRSCPayload,
clientReferenceManifest.clientModules,
{
nonce: ctx.nonce,
// This render will be thrown away so we don't need to track errors or postpones
onError: voidOnError,
onError: undefined,
onPostpone: undefined,
// we don't care to track postpones during the prospective render because we need
// to always do a final render anyway
Expand Down Expand Up @@ -1882,13 +1878,13 @@ async function prerenderToStream(
}

let reactServerIsDynamic = false
function onError(err: unknown, errorInfo: ErrorInfo) {
function onError(err: unknown) {
if (err === abortReason || isPrerenderInterruptedError(err)) {
reactServerIsDynamic = true
return
}

return serverComponentsErrorHandler(err, errorInfo)
return serverComponentsErrorHandler(err)
}

function onPostpone(reason: string) {
Expand Down Expand Up @@ -1917,7 +1913,6 @@ async function prerenderToStream(
finalAttemptRSCPayload,
clientReferenceManifest.clientModules,
{
nonce: ctx.nonce,
onError,
onPostpone,
signal: flightController.signal,
Expand Down Expand Up @@ -1946,13 +1941,13 @@ async function prerenderToStream(
dynamicTracking,
}
let SSRIsDynamic = false
function SSROnError(err: unknown, errorInfo: unknown) {
function SSROnError(err: unknown) {
if (err === abortReason || isPrerenderInterruptedError(err)) {
SSRIsDynamic = true
return
}

return htmlRendererErrorHandler(err, errorInfo)
return htmlRendererErrorHandler(err)
}

function SSROnPostpone(reason: string) {
Expand Down Expand Up @@ -2117,13 +2112,13 @@ async function prerenderToStream(
let flightController = new AbortController()

let reactServerIsDynamic = false
function onError(err: unknown, errorInfo: ErrorInfo) {
function onError(err: unknown) {
if (err === abortReason || isPrerenderInterruptedError(err)) {
reactServerIsDynamic = true
return
}

return serverComponentsErrorHandler(err, errorInfo)
return serverComponentsErrorHandler(err)
}

dynamicTracking = createDynamicTrackingState(
Expand Down Expand Up @@ -2157,7 +2152,6 @@ async function prerenderToStream(
firstAttemptRSCPayload,
clientReferenceManifest.clientModules,
{
nonce: ctx.nonce,
onError,
signal: flightController.signal,
}
Expand Down Expand Up @@ -2224,7 +2218,6 @@ async function prerenderToStream(
finalAttemptRSCPayload,
clientReferenceManifest.clientModules,
{
nonce: ctx.nonce,
onError,
signal: flightController.signal,
}
Expand Down Expand Up @@ -2262,13 +2255,13 @@ async function prerenderToStream(
dynamicTracking,
}
let SSRIsDynamic = false
function SSROnError(err: unknown, errorInfo: unknown) {
function SSROnError(err: unknown) {
if (err === abortReason || isPrerenderInterruptedError(err)) {
SSRIsDynamic = true
return
}

return htmlRendererErrorHandler(err, errorInfo)
return htmlRendererErrorHandler(err)
}
function SSROnPostpone(_: string) {
// We don't really support postponing when PPR is off but since experimental react
Expand Down Expand Up @@ -2372,7 +2365,6 @@ async function prerenderToStream(
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
nonce: ctx.nonce,
}
)
))
Expand Down Expand Up @@ -2543,7 +2535,6 @@ async function prerenderToStream(
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
nonce: ctx.nonce,
}
)
))
Expand Down Expand Up @@ -2686,7 +2677,6 @@ async function prerenderToStream(
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
nonce: ctx.nonce,
}
)

Expand Down
11 changes: 8 additions & 3 deletions packages/next/src/server/app-render/create-error-handler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,26 @@ declare global {
var __next_log_error__: undefined | ((err: unknown) => void)
}

type ErrorHandler = (err: unknown, errorInfo: unknown) => string | undefined
type ErrorHandler = (err: unknown, errorInfo?: unknown) => string | undefined

export type DigestedError = Error & { digest: string }

export function createFlightReactServerErrorHandler(
dev: boolean,
onReactServerRenderError: (err: any) => void
): ErrorHandler {
return (err: any, errorInfo: any) => {
return (err: any, errorInfo?: unknown) => {
// If the error already has a digest, respect the original digest,
// so it won't get re-generated into another new error.
if (!err.digest) {
// TODO-APP: look at using webcrypto instead. Requires a promise to be awaited.
err.digest = stringHash(
err.message + (errorInfo?.stack || err.stack || '')
err.message +
(typeof errorInfo === 'object' &&
errorInfo !== null &&
'stack' in errorInfo
? errorInfo.stack
: err.stack || '')
).toString()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export function renderToInitialFizzStream({
}: {
ReactDOMServer: typeof import('react-dom/server.edge')
element: React.ReactElement
streamOptions?: any
streamOptions?: Parameters<typeof ReactDOMServer.renderToReadableStream>[1]
}): Promise<ReactReadableStream> {
return getTracer().trace(AppRenderSpan.renderToReadableStream, async () =>
ReactDOMServer.renderToReadableStream(element, streamOptions)
Expand Down
71 changes: 69 additions & 2 deletions packages/next/types/$$compiled.internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,76 @@ declare module 'next/dist/compiled/react-dom/server.edge'
declare module 'next/dist/compiled/browserslist'

declare module 'react-server-dom-webpack/client'
declare module 'react-server-dom-webpack/server.edge'
declare module 'react-server-dom-webpack/server.edge' {
export function renderToReadableStream(
model: any,
webpackMap: {
readonly [id: string]: {
readonly id: string | number
readonly chunks: readonly string[]
readonly name: string
readonly async?: boolean
}
},
options?: {
filterStackFrame?: (url: string, functionName: string) => boolean
onError?: (error: unknown) => void
onPostpone?: (reason: string) => void
signal?: AbortSignal
}
): ReadableStream<Uint8Array>

type ServerManifest = {}

export function decodeReply<T>(
body: string | FormData,
webpackMap: ServerManifest,
options?: {
temporaryReferences?: unknown
}
): Promise<T>
export function decodeAction<T>(
body: FormData,
serverManifest: ServerManifest
): Promise<() => T> | null
export function decodeFormState<S>(
actionResult: S,
body: FormData,
serverManifest: ServerManifest
): Promise<unknown | null>

export function registerServerReference<T>(
reference: T,
id: string,
exportName: string | null
): unknown

export function createClientModuleProxy(moduleId: string): unknown
}
declare module 'react-server-dom-webpack/server.node'
declare module 'react-server-dom-webpack/static.edge'
declare module 'react-server-dom-webpack/static.edge' {
export function prerender(
children: any,
webpackMap: {
readonly [id: string]: {
readonly id: string | number
readonly chunks: readonly string[]
readonly name: string
readonly async?: boolean
}
},
options?: {
environmentName?: string | (() => string)
filterStackFrame?: (url: string, functionName: string) => boolean
identifierPrefix?: string
signal?: AbortSignal
onError?: (error: unknown) => void
onPostpone?: (reason: string) => void
}
): Promise<{
prelude: ReadableStream<Uint8Array>
}>
}
declare module 'react-server-dom-webpack/client.edge'

declare module 'VAR_MODULE_GLOBAL_ERROR'
Expand Down
6 changes: 3 additions & 3 deletions packages/next/types/react-dom.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ declare module 'react-dom/server.edge' {
export type ResumeOptions = {
nonce?: string
signal?: AbortSignal
onError?: (error: unknown, errorInfo: unknown) => string | undefined
onError?: (error: unknown) => string | undefined
onPostpone?: (reason: string) => void
unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor
}
Expand All @@ -42,7 +42,7 @@ declare module 'react-dom/server.edge' {
bootstrapModules?: Array<string | BootstrapScriptDescriptor>
progressiveChunkSize?: number
signal?: AbortSignal
onError?: (error: unknown, errorInfo: unknown) => string | undefined
onError?: (error: unknown) => string | undefined
onPostpone?: (reason: string) => void
unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor
importMap?: {
Expand Down Expand Up @@ -94,7 +94,7 @@ declare module 'react-dom/static.edge' {
bootstrapModules?: Array<string | BootstrapScriptDescriptor>
progressiveChunkSize?: number
signal?: AbortSignal
onError?: (error: unknown, errorInfo: unknown) => string | undefined
onError?: (error: unknown) => string | undefined
onPostpone?: (reason: string) => void
unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor
importMap?: {
Expand Down

0 comments on commit e2ae5e9

Please sign in to comment.