Unverified Commit c7d3f9d4 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Drop legacy RSC handling in client for pages (#40472)

Remove the unused RSC handling for pages in both server router and client side in favor of using RSC in app dir
parent f92a4cee
...@@ -93,7 +93,6 @@ export function getDefineEnv({ ...@@ -93,7 +93,6 @@ export function getDefineEnv({
isNodeServer, isNodeServer,
isEdgeServer, isEdgeServer,
middlewareMatchers, middlewareMatchers,
hasServerComponents,
}: { }: {
dev?: boolean dev?: boolean
distDir: string distDir: string
...@@ -104,7 +103,6 @@ export function getDefineEnv({ ...@@ -104,7 +103,6 @@ export function getDefineEnv({
isEdgeServer?: boolean isEdgeServer?: boolean
middlewareMatchers?: MiddlewareMatcher[] middlewareMatchers?: MiddlewareMatcher[]
config: NextConfigComplete config: NextConfigComplete
hasServerComponents?: boolean
}) { }) {
return { return {
// internal field to identify the plugin config // internal field to identify the plugin config
...@@ -178,7 +176,6 @@ export function getDefineEnv({ ...@@ -178,7 +176,6 @@ export function getDefineEnv({
), ),
'process.env.__NEXT_STRICT_MODE': JSON.stringify(config.reactStrictMode), 'process.env.__NEXT_STRICT_MODE': JSON.stringify(config.reactStrictMode),
'process.env.__NEXT_REACT_ROOT': JSON.stringify(hasReactRoot), 'process.env.__NEXT_REACT_ROOT': JSON.stringify(hasReactRoot),
'process.env.__NEXT_RSC': JSON.stringify(hasServerComponents),
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify( 'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
config.optimizeFonts && !dev config.optimizeFonts && !dev
), ),
...@@ -540,15 +537,23 @@ export default async function getBaseWebpackConfig( ...@@ -540,15 +537,23 @@ export default async function getBaseWebpackConfig(
rewrites.afterFiles.length > 0 || rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0 rewrites.fallback.length > 0
if (isClient && !hasReactRoot) { // Only error in first one compiler (client) once
if (config.experimental.runtime) { if (isClient) {
throw new Error( if (!hasReactRoot) {
'`experimental.runtime` requires React 18 to be installed.' if (config.experimental.runtime) {
) throw new Error(
'`experimental.runtime` requires React 18 to be installed.'
)
}
if (config.experimental.serverComponents) {
throw new Error(
'`experimental.serverComponents` requires React 18 to be installed.'
)
}
} }
if (config.experimental.serverComponents) { if (!config.experimental.appDir && config.experimental.serverComponents) {
throw new Error( throw new Error(
'`experimental.serverComponents` requires React 18 to be installed.' '`experimental.serverComponents` requires experimental.appDir to be enabled.'
) )
} }
} }
...@@ -1680,7 +1685,6 @@ export default async function getBaseWebpackConfig( ...@@ -1680,7 +1685,6 @@ export default async function getBaseWebpackConfig(
isNodeServer, isNodeServer,
isEdgeServer, isEdgeServer,
middlewareMatchers, middlewareMatchers,
hasServerComponents,
}) })
), ),
isClient && isClient &&
......
...@@ -289,149 +289,6 @@ export async function initialize(opts: { webpackHMR?: any } = {}): Promise<{ ...@@ -289,149 +289,6 @@ export async function initialize(opts: { webpackHMR?: any } = {}): Promise<{
return { assetPrefix: prefix } return { assetPrefix: prefix }
} }
let RSCComponent: (props: any) => JSX.Element
if (process.env.__NEXT_RSC) {
const getCacheKey = () => {
const { pathname, search } = location
return pathname + search
}
const {
createFromFetch,
createFromReadableStream,
} = require('next/dist/compiled/react-server-dom-webpack')
const encoder = new TextEncoder()
let initialServerDataBuffer: string[] | undefined = undefined
let initialServerDataWriter: ReadableStreamDefaultController | undefined =
undefined
let initialServerDataLoaded = false
let initialServerDataFlushed = false
function nextServerDataCallback(seg: [number, string, string]) {
if (seg[0] === 0) {
initialServerDataBuffer = []
} else {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[2]))
} else {
initialServerDataBuffer.push(seg[2])
}
}
}
// There might be race conditions between `nextServerDataRegisterWriter` and
// `DOMContentLoaded`. The former will be called when React starts to hydrate
// the root, the latter will be called when the DOM is fully loaded.
// For streaming, the former is called first due to partial hydration.
// For non-streaming, the latter can be called first.
// Hence, we use two variables `initialServerDataLoaded` and
// `initialServerDataFlushed` to make sure the writer will be closed and
// `initialServerDataBuffer` will be cleared in the right time.
function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) {
if (initialServerDataBuffer) {
initialServerDataBuffer.forEach((val) => {
ctr.enqueue(encoder.encode(val))
})
if (initialServerDataLoaded && !initialServerDataFlushed) {
ctr.close()
initialServerDataFlushed = true
initialServerDataBuffer = undefined
}
}
initialServerDataWriter = ctr
}
// When `DOMContentLoaded`, we can close all pending writers to finish hydration.
const DOMContentLoaded = function () {
if (initialServerDataWriter && !initialServerDataFlushed) {
initialServerDataWriter.close()
initialServerDataFlushed = true
initialServerDataBuffer = undefined
}
initialServerDataLoaded = true
}
// It's possible that the DOM is already loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false)
} else {
DOMContentLoaded()
}
const nextServerDataLoadingGlobal = ((self as any).__next_s =
(self as any).__next_s || [])
nextServerDataLoadingGlobal.forEach(nextServerDataCallback)
nextServerDataLoadingGlobal.push = nextServerDataCallback
function createResponseCache() {
return new Map<string, any>()
}
const rscCache = createResponseCache()
function fetchFlight(href: string, props?: any) {
const url = new URL(href, location.origin)
const searchParams = url.searchParams
searchParams.append('__flight__', '1')
if (props) {
searchParams.append('__props__', JSON.stringify(props))
}
return fetch(url.toString())
}
function useServerResponse(cacheKey: string, serialized?: string) {
let response = rscCache.get(cacheKey)
if (response) return response
if (initialServerDataBuffer) {
const readable = new ReadableStream({
start(controller) {
nextServerDataRegisterWriter(controller)
},
})
response = createFromReadableStream(readable)
} else {
if (serialized) {
const readable = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(serialized))
controller.close()
},
})
response = createFromReadableStream(readable)
} else {
response = createFromFetch(fetchFlight(getCacheKey()))
}
}
rscCache.set(cacheKey, response)
return response
}
const ServerRoot = ({
cacheKey,
serialized,
}: {
cacheKey: string
serialized?: string
}) => {
React.useEffect(() => {
rscCache.delete(cacheKey)
})
const response = useServerResponse(cacheKey, serialized)
return response.readRoot()
}
RSCComponent = (props: any) => {
const cacheKey = getCacheKey()
const { __flight__ } = props
return <ServerRoot cacheKey={cacheKey} serialized={__flight__} />
}
}
function renderApp(App: AppComponent, appProps: AppProps) { function renderApp(App: AppComponent, appProps: AppProps) {
return <App {...appProps} /> return <App {...appProps} />
} }
...@@ -691,18 +548,15 @@ function Root({ ...@@ -691,18 +548,15 @@ function Root({
} }
function doRender(input: RenderRouteInfo): Promise<any> { function doRender(input: RenderRouteInfo): Promise<any> {
let { App, Component, props, err, __N_RSC }: RenderRouteInfo = input let { App, Component, props, err }: RenderRouteInfo = input
let styleSheets: StyleSheetTuple[] | undefined = let styleSheets: StyleSheetTuple[] | undefined =
'initial' in input ? undefined : input.styleSheets 'initial' in input ? undefined : input.styleSheets
Component = Component || lastAppProps.Component Component = Component || lastAppProps.Component
props = props || lastAppProps.props props = props || lastAppProps.props
const isRSC =
process.env.__NEXT_RSC && 'initial' in input ? !!initialData.rsc : !!__N_RSC
const appProps: AppProps = { const appProps: AppProps = {
...props, ...props,
Component: isRSC ? RSCComponent : Component, Component,
err, err,
router, router,
} }
...@@ -1026,7 +880,6 @@ export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) { ...@@ -1026,7 +880,6 @@ export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) {
defaultLocale, defaultLocale,
domainLocales: initialData.domainLocales, domainLocales: initialData.domainLocales,
isPreview: initialData.isPreview, isPreview: initialData.isPreview,
isRsc: initialData.rsc,
}) })
initialMatchesMiddleware = await router._initialMatchesMiddlewarePromise initialMatchesMiddleware = await router._initialMatchesMiddlewarePromise
......
...@@ -526,7 +526,6 @@ export default class DevServer extends Server { ...@@ -526,7 +526,6 @@ export default class DevServer extends Server {
hasReactRoot: this.hotReloader?.hasReactRoot, hasReactRoot: this.hotReloader?.hasReactRoot,
isNodeServer, isNodeServer,
isEdgeServer, isEdgeServer,
hasServerComponents: this.hotReloader?.hasServerComponents,
}) })
Object.keys(plugin.definitions).forEach((key) => { Object.keys(plugin.definitions).forEach((key) => {
......
...@@ -375,7 +375,6 @@ export async function renderToHTML( ...@@ -375,7 +375,6 @@ export async function renderToHTML(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
getServerSideProps, getServerSideProps,
serverComponentManifest,
isDataReq, isDataReq,
params, params,
previewProps, previewProps,
...@@ -384,18 +383,11 @@ export async function renderToHTML( ...@@ -384,18 +383,11 @@ export async function renderToHTML(
supportsDynamicHTML, supportsDynamicHTML,
images, images,
runtime: globalRuntime, runtime: globalRuntime,
ComponentMod,
App, App,
} = renderOpts } = renderOpts
let Document = renderOpts.Document let Document = renderOpts.Document
// We don't need to opt-into the flight inlining logic if the page isn't a RSC.
const isServerComponent =
!!process.env.__NEXT_REACT_ROOT &&
!!serverComponentManifest &&
!!ComponentMod.__next_rsc__?.server
// Component will be wrapped by ServerComponentWrapper for RSC // Component will be wrapped by ServerComponentWrapper for RSC
let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) = let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) =
renderOpts.Component renderOpts.Component
...@@ -412,12 +404,6 @@ export async function renderToHTML( ...@@ -412,12 +404,6 @@ export async function renderToHTML(
// next internal queries should be stripped out // next internal queries should be stripped out
stripInternalQueries(query) stripInternalQueries(query)
if (isServerComponent) {
throw new Error(
'Server Components are not supported from the pages/ directory.'
)
}
const callMiddleware = async (method: string, args: any[], props = false) => { const callMiddleware = async (method: string, args: any[], props = false) => {
let results: any = props ? {} : [] let results: any = props ? {} : []
...@@ -1417,7 +1403,6 @@ export async function renderToHTML( ...@@ -1417,7 +1403,6 @@ export async function renderToHTML(
err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps
gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps
rsc: isServerComponent ? true : undefined, // whether the page is a server components page
customServer, // whether the user is using a custom server customServer, // whether the user is using a custom server
gip: hasPageGetInitialProps ? true : undefined, // whether the page has getInitialProps gip: hasPageGetInitialProps ? true : undefined, // whether the page has getInitialProps
appGip: !defaultAppGetInitialProps ? true : undefined, // whether the _app has getInitialProps appGip: !defaultAppGetInitialProps ? true : undefined, // whether the _app has getInitialProps
......
...@@ -86,7 +86,6 @@ export const TEMPORARY_REDIRECT_STATUS = 307 ...@@ -86,7 +86,6 @@ export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308 export const PERMANENT_REDIRECT_STATUS = 308
export const STATIC_PROPS_ID = '__N_SSG' export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP' export const SERVER_PROPS_ID = '__N_SSP'
export const FLIGHT_PROPS_ID = '__N_RSC'
export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/' export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/'
export const OPTIMIZED_FONT_PROVIDERS = [ export const OPTIMIZED_FONT_PROVIDERS = [
{ url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' }, { url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' },
......
...@@ -564,7 +564,6 @@ export type CompletePrivateRouteInfo = { ...@@ -564,7 +564,6 @@ export type CompletePrivateRouteInfo = {
styleSheets: StyleSheetTuple[] styleSheets: StyleSheetTuple[]
__N_SSG?: boolean __N_SSG?: boolean
__N_SSP?: boolean __N_SSP?: boolean
__N_RSC?: boolean
props?: Record<string, any> props?: Record<string, any>
err?: Error err?: Error
error?: any error?: any
...@@ -881,7 +880,6 @@ export default class Router implements BaseRouter { ...@@ -881,7 +880,6 @@ export default class Router implements BaseRouter {
defaultLocale, defaultLocale,
domainLocales, domainLocales,
isPreview, isPreview,
isRsc,
}: { }: {
subscription: Subscription subscription: Subscription
initialProps: any initialProps: any
...@@ -896,7 +894,6 @@ export default class Router implements BaseRouter { ...@@ -896,7 +894,6 @@ export default class Router implements BaseRouter {
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: DomainLocale[]
isPreview?: boolean isPreview?: boolean
isRsc?: boolean
} }
) { ) {
// represents the current component key // represents the current component key
...@@ -915,7 +912,6 @@ export default class Router implements BaseRouter { ...@@ -915,7 +912,6 @@ export default class Router implements BaseRouter {
err, err,
__N_SSG: initialProps && initialProps.__N_SSG, __N_SSG: initialProps && initialProps.__N_SSG,
__N_SSP: initialProps && initialProps.__N_SSP, __N_SSP: initialProps && initialProps.__N_SSP,
__N_RSC: !!isRsc,
} }
} }
...@@ -1993,7 +1989,6 @@ export default class Router implements BaseRouter { ...@@ -1993,7 +1989,6 @@ export default class Router implements BaseRouter {
styleSheets: res.styleSheets, styleSheets: res.styleSheets,
__N_SSG: res.mod.__N_SSG, __N_SSG: res.mod.__N_SSG,
__N_SSP: res.mod.__N_SSP, __N_SSP: res.mod.__N_SSP,
__N_RSC: !!res.mod.__next_rsc__,
}) })
)) ))
...@@ -2006,20 +2001,10 @@ export default class Router implements BaseRouter { ...@@ -2006,20 +2001,10 @@ export default class Router implements BaseRouter {
} }
} }
/** const shouldFetchData = routeInfo.__N_SSG || routeInfo.__N_SSP
* For server components, non-SSR pages will have statically optimized
* flight data in a production build. So only development and SSR pages
* will always have the real-time generated and streamed flight data.
*/
const useStreamedFlightData =
routeInfo.__N_RSC &&
(process.env.NODE_ENV !== 'production' || routeInfo.__N_SSP)
const shouldFetchData =
routeInfo.__N_SSG || routeInfo.__N_SSP || routeInfo.__N_RSC
const { props, cacheKey } = await this._getData(async () => { const { props, cacheKey } = await this._getData(async () => {
if (shouldFetchData && !useStreamedFlightData) { if (shouldFetchData) {
const { json, cacheKey: _cacheKey } = data?.json const { json, cacheKey: _cacheKey } = data?.json
? data ? data
: await fetchNextData({ : await fetchNextData({
...@@ -2083,31 +2068,7 @@ export default class Router implements BaseRouter { ...@@ -2083,31 +2068,7 @@ export default class Router implements BaseRouter {
).catch(() => {}) ).catch(() => {})
} }
let flightInfo props.pageProps = Object.assign({}, props.pageProps)
if (routeInfo.__N_RSC) {
flightInfo = {
__flight__: useStreamedFlightData
? (
await this._getData(() =>
this._getFlightData(
formatWithValidation({
query: { ...query, __flight__: '1' },
pathname: isDynamicRoute(route)
? interpolateAs(
pathname,
parseRelativeUrl(resolvedAs).pathname,
query
).result
: pathname,
})
)
)
).data
: props.__flight__,
}
}
props.pageProps = Object.assign({}, props.pageProps, flightInfo)
routeInfo.props = props routeInfo.props = props
routeInfo.route = route routeInfo.route = route
routeInfo.query = query routeInfo.query = query
......
...@@ -109,7 +109,6 @@ export type NEXT_DATA = { ...@@ -109,7 +109,6 @@ export type NEXT_DATA = {
scriptLoader?: any[] scriptLoader?: any[]
isPreview?: boolean isPreview?: boolean
notFoundSrcPage?: string notFoundSrcPage?: string
rsc?: boolean
} }
/** /**
...@@ -177,7 +176,6 @@ export type AppPropsType< ...@@ -177,7 +176,6 @@ export type AppPropsType<
router: R router: R
__N_SSG?: boolean __N_SSG?: boolean
__N_SSP?: boolean __N_SSP?: boolean
__N_RSC?: boolean
} }
export type DocumentContext = NextPageContext & { export type DocumentContext = NextPageContext & {
......
...@@ -48,7 +48,6 @@ function isSafeExport(key: string): boolean { ...@@ -48,7 +48,6 @@ function isSafeExport(key: string): boolean {
key === '__esModule' || key === '__esModule' ||
key === '__N_SSG' || key === '__N_SSG' ||
key === '__N_SSP' || key === '__N_SSP' ||
key === '__N_RSC' ||
// TODO: remove this key from page config instead of allow listing it // TODO: remove this key from page config instead of allow listing it
key === 'config' key === 'config'
) )
......
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