Unverified Commit 4de5b64c authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Wait for shell resolve with gIP is customized in react 18 (#36792)

When getInitialProps is customized with react 18, since gIP requires to return `html` as doc property which could be used by  user-land customization, we do blocking-rendering there and passdown the `html` to document

Fixes #36675
Closes #36419
parent e05a95a8
import { nonNullable } from '../lib/non-nullable' import { nonNullable } from '../lib/non-nullable'
export type ReactReadableStream = ReadableStream<Uint8Array> & {
allReady?: Promise<void> | undefined
}
export function readableStreamTee<T = any>( export function readableStreamTee<T = any>(
readable: ReadableStream<T> readable: ReadableStream<T>
): [ReadableStream<T>, ReadableStream<T>] { ): [ReadableStream<T>, ReadableStream<T>] {
...@@ -138,29 +142,24 @@ export function renderToInitialStream({ ...@@ -138,29 +142,24 @@ export function renderToInitialStream({
}: { }: {
ReactDOMServer: any ReactDOMServer: any
element: React.ReactElement element: React.ReactElement
}): Promise< }): Promise<ReactReadableStream> {
ReadableStream<Uint8Array> & {
allReady?: Promise<void>
}
> {
return ReactDOMServer.renderToReadableStream(element) return ReactDOMServer.renderToReadableStream(element)
} }
export async function continueFromInitialStream({ export async function continueFromInitialStream(
suffix, renderStream: ReactReadableStream,
dataStream, {
generateStaticHTML, suffix,
flushEffectHandler, dataStream,
renderStream, generateStaticHTML,
}: { flushEffectHandler,
suffix?: string }: {
dataStream?: ReadableStream<Uint8Array> suffix?: string
generateStaticHTML: boolean dataStream?: ReadableStream<Uint8Array>
flushEffectHandler?: () => string generateStaticHTML: boolean
renderStream: ReadableStream<Uint8Array> & { flushEffectHandler?: () => string
allReady?: Promise<void>
} }
}): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
const closeTag = '</body></html>' const closeTag = '</body></html>'
const suffixUnclosed = suffix ? suffix.split(closeTag)[0] : null const suffixUnclosed = suffix ? suffix.split(closeTag)[0] : null
...@@ -198,12 +197,11 @@ export async function renderToStream({ ...@@ -198,12 +197,11 @@ export async function renderToStream({
flushEffectHandler?: () => string flushEffectHandler?: () => string
}): Promise<ReadableStream<Uint8Array>> { }): Promise<ReadableStream<Uint8Array>> {
const renderStream = await renderToInitialStream({ ReactDOMServer, element }) const renderStream = await renderToInitialStream({ ReactDOMServer, element })
return continueFromInitialStream({ return continueFromInitialStream(renderStream, {
suffix, suffix,
dataStream, dataStream,
generateStaticHTML, generateStaticHTML,
flushEffectHandler, flushEffectHandler,
renderStream,
}) })
} }
......
...@@ -20,6 +20,7 @@ import type { FontManifest } from './font-utils' ...@@ -20,6 +20,7 @@ import type { FontManifest } from './font-utils'
import type { LoadComponentsReturnType, ManifestItem } from './load-components' import type { LoadComponentsReturnType, ManifestItem } from './load-components'
import type { GetServerSideProps, GetStaticProps, PreviewData } from '../types' import type { GetServerSideProps, GetStaticProps, PreviewData } from '../types'
import type { UnwrapPromise } from '../lib/coalesced-function' import type { UnwrapPromise } from '../lib/coalesced-function'
import type { ReactReadableStream } from './node-web-streams-helper'
import React from 'react' import React from 'react'
import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack' import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack'
...@@ -1340,11 +1341,11 @@ export async function renderToHTML( ...@@ -1340,11 +1341,11 @@ export async function renderToHTML(
} }
} }
async function documentInitialProps( async function loadDocumentInitialProps(
renderShell?: ( renderShell?: (
_App: AppType, _App: AppType,
_Component: NextComponentType _Component: NextComponentType
) => Promise<void> ) => Promise<ReactReadableStream>
) { ) {
const renderPage: RenderPage = ( const renderPage: RenderPage = (
options: ComponentsEnhancer = {} options: ComponentsEnhancer = {}
...@@ -1373,11 +1374,13 @@ export async function renderToHTML( ...@@ -1373,11 +1374,13 @@ export async function renderToHTML(
enhanceComponents(options, App, Component) enhanceComponents(options, App, Component)
if (renderShell) { if (renderShell) {
return renderShell(EnhancedApp, EnhancedComponent).then(() => { return renderShell(EnhancedApp, EnhancedComponent).then(
// When using concurrent features, we don't have or need the full async (stream) => {
// html so it's fine to return nothing here. const forwardStream = readableStreamTee(stream)[1]
return { html: '', head } const html = await streamToString(forwardStream)
}) return { html, head }
}
)
} }
const html = ReactDOMServer.renderToString( const html = ReactDOMServer.renderToString(
...@@ -1438,9 +1441,9 @@ export async function renderToHTML( ...@@ -1438,9 +1441,9 @@ export async function renderToHTML(
if (!process.env.__NEXT_REACT_ROOT) { if (!process.env.__NEXT_REACT_ROOT) {
// Enabling react legacy rendering mode: __NEXT_REACT_ROOT = false // Enabling react legacy rendering mode: __NEXT_REACT_ROOT = false
if (Document.getInitialProps) { if (Document.getInitialProps) {
const documentInitialPropsRes = await documentInitialProps() const documentInitialProps = await loadDocumentInitialProps()
if (documentInitialPropsRes === null) return null if (documentInitialProps === null) return null
const { docProps, documentCtx } = documentInitialPropsRes const { docProps, documentCtx } = documentInitialProps
return { return {
bodyResult: (suffix: string) => bodyResult: (suffix: string) =>
...@@ -1473,80 +1476,75 @@ export async function renderToHTML( ...@@ -1473,80 +1476,75 @@ export async function renderToHTML(
} }
} else { } else {
// Enabling react concurrent rendering mode: __NEXT_REACT_ROOT = true // Enabling react concurrent rendering mode: __NEXT_REACT_ROOT = true
let renderStream: ReadableStream<Uint8Array> & {
allReady?: Promise<void> | undefined
}
const renderShell = async ( const renderShell = async (
EnhancedApp: AppType, EnhancedApp: AppType,
EnhancedComponent: NextComponentType EnhancedComponent: NextComponentType
) => { ) => {
const content = renderContent(EnhancedApp, EnhancedComponent) const content = renderContent(EnhancedApp, EnhancedComponent)
renderStream = await renderToInitialStream({ return await renderToInitialStream({
ReactDOMServer, ReactDOMServer,
element: content, element: content,
}) })
} }
const bodyResult = async (suffix: string) => { const createBodyResult =
// this must be called inside bodyResult so appWrappers is (initialStream: ReactReadableStream) => (suffix: string) => {
// up to date when `wrapApp` is called // this must be called inside bodyResult so appWrappers is
// up to date when `wrapApp` is called
const flushEffectHandler = (): string => { const flushEffectHandler = (): string => {
const allFlushEffects = [ const allFlushEffects = [
styledJsxFlushEffect, styledJsxFlushEffect,
...(flushEffects || []), ...(flushEffects || []),
] ]
const flushed = ReactDOMServer.renderToString( const flushed = ReactDOMServer.renderToString(
<> <>
{allFlushEffects.map((flushEffect, i) => ( {allFlushEffects.map((flushEffect, i) => (
<React.Fragment key={i}>{flushEffect()}</React.Fragment> <React.Fragment key={i}>{flushEffect()}</React.Fragment>
))} ))}
</> </>
) )
return flushed return flushed
} }
// Handle static data for server components. // Handle static data for server components.
async function generateStaticFlightDataIfNeeded() { async function generateStaticFlightDataIfNeeded() {
if (serverComponentsPageDataTransformStream) { if (serverComponentsPageDataTransformStream) {
// If it's a server component with the Node.js runtime, we also // If it's a server component with the Node.js runtime, we also
// statically generate the page data. // statically generate the page data.
let data = '' let data = ''
const readable = serverComponentsPageDataTransformStream.readable const readable = serverComponentsPageDataTransformStream.readable
const reader = readable.getReader() const reader = readable.getReader()
const textDecoder = new TextDecoder() const textDecoder = new TextDecoder()
while (true) { while (true) {
const { done, value } = await reader.read() const { done, value } = await reader.read()
if (done) { if (done) {
break break
}
data += decodeText(value, textDecoder)
} }
data += decodeText(value, textDecoder)
}
;(renderOpts as any).pageData = { ;(renderOpts as any).pageData = {
...(renderOpts as any).pageData, ...(renderOpts as any).pageData,
__flight__: data, __flight__: data,
}
return data
} }
return data
} }
}
// @TODO: A potential improvement would be to reuse the inlined // @TODO: A potential improvement would be to reuse the inlined
// data stream, or pass a callback inside as this doesn't need to // data stream, or pass a callback inside as this doesn't need to
// be streamed. // be streamed.
// Do not use `await` here. // Do not use `await` here.
generateStaticFlightDataIfNeeded() generateStaticFlightDataIfNeeded()
return await continueFromInitialStream({ return continueFromInitialStream(initialStream, {
renderStream, suffix,
suffix, dataStream: serverComponentsInlinedTransformStream?.readable,
dataStream: serverComponentsInlinedTransformStream?.readable, generateStaticHTML,
generateStaticHTML, flushEffectHandler,
flushEffectHandler, })
}) }
}
const hasDocumentGetInitialProps = !( const hasDocumentGetInitialProps = !(
isServerComponent || isServerComponent ||
...@@ -1554,16 +1552,21 @@ export async function renderToHTML( ...@@ -1554,16 +1552,21 @@ export async function renderToHTML(
!Document.getInitialProps !Document.getInitialProps
) )
let bodyResult: (s: string) => Promise<ReadableStream<Uint8Array>>
// If it has getInitialProps, we will render the shell in `renderPage`. // If it has getInitialProps, we will render the shell in `renderPage`.
// Otherwise we do it right now. // Otherwise we do it right now.
let documentInitialPropsRes: let documentInitialPropsRes:
| {} | {}
| Awaited<ReturnType<typeof documentInitialProps>> | Awaited<ReturnType<typeof loadDocumentInitialProps>>
if (hasDocumentGetInitialProps) { if (hasDocumentGetInitialProps) {
documentInitialPropsRes = await documentInitialProps(renderShell) documentInitialPropsRes = await loadDocumentInitialProps(renderShell)
if (documentInitialPropsRes === null) return null if (documentInitialPropsRes === null) return null
const { docProps } = documentInitialPropsRes as any
bodyResult = createBodyResult(streamFromArray([docProps.html]))
} else { } else {
await renderShell(App, Component) const stream = await renderShell(App, Component)
bodyResult = createBodyResult(stream)
documentInitialPropsRes = {} documentInitialPropsRes = {}
} }
......
...@@ -506,8 +506,7 @@ export async function renderToHTML( ...@@ -506,8 +506,7 @@ export async function renderToHTML(
// Do not use `await` here. // Do not use `await` here.
// generateStaticFlightDataIfNeeded() // generateStaticFlightDataIfNeeded()
return await continueFromInitialStream({ return await continueFromInitialStream(renderStream, {
renderStream,
suffix: '', suffix: '',
dataStream: serverComponentsInlinedTransformStream?.readable, dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures, generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures,
......
const path = require('path')
module.exports = require(path.join(__dirname, '../../lib/with-react-17.js'))({})
...@@ -12,19 +12,14 @@ import { ...@@ -12,19 +12,14 @@ import {
} from 'next-test-utils' } from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const nodeArgs = ['-r', join(appDir, '../../lib/react-17-require-hook.js')]
let appPort let appPort
let app let app
describe('AMP Fragment Styles', () => { describe('AMP Fragment Styles', () => {
beforeAll(async () => { beforeAll(async () => {
await nextBuild(appDir, [], { await nextBuild(appDir, [])
nodeArgs,
})
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort, { app = await nextStart(appDir, appPort)
nodeArgs,
})
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
......
...@@ -42,6 +42,7 @@ export default class MyDocument extends Document { ...@@ -42,6 +42,7 @@ export default class MyDocument extends Document {
return { return {
...result, ...result,
cssInJsCount: (result.html.match(/css-in-js-class/g) || []).length,
customProperty: 'Hello Document', customProperty: 'Hello Document',
withCSP: ctx.query.withCSP, withCSP: ctx.query.withCSP,
} }
...@@ -74,6 +75,7 @@ export default class MyDocument extends Document { ...@@ -74,6 +75,7 @@ export default class MyDocument extends Document {
<p id="document-hmr">Hello Document HMR</p> <p id="document-hmr">Hello Document HMR</p>
<Main /> <Main />
<NextScript nonce="test-nonce" /> <NextScript nonce="test-nonce" />
<div id="css-in-cjs-count">{this.props.cssInJsCount}</div>
</body> </body>
</Html> </Html>
) )
......
...@@ -2,8 +2,10 @@ import Link from 'next/link' ...@@ -2,8 +2,10 @@ import Link from 'next/link'
export default () => ( export default () => (
<div> <div>
<div className="page-index">index</div> <div className="page-index">index</div>
<span className="css-in-js-class" />
<Link href="/about"> <Link href="/about">
<a id="about-link">about</a> <a id="about-link">about</a>
</Link> </Link>
<span className="css-in-js-class" />
</div> </div>
) )
...@@ -22,6 +22,14 @@ export default function ({ app }, suiteName, render, fetch) { ...@@ -22,6 +22,14 @@ export default function ({ app }, suiteName, render, fetch) {
expect($('body').hasClass('custom_class')).toBe(true) expect($('body').hasClass('custom_class')).toBe(true)
}) })
it('Document.getInitialProps returns html prop representing app shell', async () => {
// Extract css-in-js-class from the rendered HTML, which is returned by Document.getInitialProps
const $index = await get$('/')
const $about = await get$('/about')
expect($index('#css-in-cjs-count').text()).toBe('2')
expect($about('#css-in-cjs-count').text()).toBe('0')
})
test('It injects custom head tags', async () => { test('It injects custom head tags', async () => {
const $ = await get$('/') const $ = await get$('/')
expect($('head').text()).toMatch('body { margin: 0 }') expect($('head').text()).toMatch('body { margin: 0 }')
......
const path = require('path')
module.exports = require(path.join(__dirname, '../../../lib/with-react-17.js'))(
{}
)
...@@ -12,7 +12,6 @@ import { ...@@ -12,7 +12,6 @@ import {
} from 'next-test-utils' } from 'next-test-utils'
const appDir = join(__dirname, '../app') const appDir = join(__dirname, '../app')
const nodeArgs = ['-r', join(appDir, '../../../lib/react-17-require-hook.js')]
let appPort let appPort
let app let app
...@@ -49,13 +48,9 @@ function runTests() { ...@@ -49,13 +48,9 @@ function runTests() {
describe('styled-jsx using in node_modules', () => { describe('styled-jsx using in node_modules', () => {
describe('Production', () => { describe('Production', () => {
beforeAll(async () => { beforeAll(async () => {
await nextBuild(appDir, undefined, { await nextBuild(appDir)
nodeArgs,
})
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort, { app = await nextStart(appDir, appPort)
nodeArgs,
})
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
...@@ -65,9 +60,7 @@ describe('styled-jsx using in node_modules', () => { ...@@ -65,9 +60,7 @@ describe('styled-jsx using in node_modules', () => {
describe('Development', () => { describe('Development', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort, { app = await launchApp(appDir, appPort)
nodeArgs,
})
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
......
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