Unverified Commit bc05ce92 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Move Pages `render` out of server (#51678)

This removes calls for rendering files in `pages/` via the server code and relies instead relies on the bundled `routeModule` to perform the rendering.

Future cases that try to call the legacy render will hit a new: 

```
Invariant: render should have used routeModule
```

Error. These cases should be reported.
parent 0a4b6ef8
...@@ -53,7 +53,7 @@ import { isAppRouteRoute } from '../lib/is-app-route-route' ...@@ -53,7 +53,7 @@ import { isAppRouteRoute } from '../lib/is-app-route-route'
import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route' import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader'
import { isInternalPathname } from '../lib/is-internal-pathname' import { isInternalComponent } from '../lib/is-internal-component'
import { isStaticMetadataRouteFile } from '../lib/metadata/is-metadata-route' import { isStaticMetadataRouteFile } from '../lib/metadata/is-metadata-route'
export async function getStaticInfoIncludingLayouts({ export async function getStaticInfoIncludingLayouts({
...@@ -596,16 +596,15 @@ export async function createEntrypoints( ...@@ -596,16 +596,15 @@ export async function createEntrypoints(
} else if ( } else if (
!isAPIRoute(page) && !isAPIRoute(page) &&
!isMiddlewareFile(page) && !isMiddlewareFile(page) &&
!isInternalPathname(absolutePagePath) !isInternalComponent(absolutePagePath)
) { ) {
server[serverBundlePath] = [ server[serverBundlePath] = [
getRouteLoaderEntry({ getRouteLoaderEntry({
page, page,
pages,
absolutePagePath, absolutePagePath,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from( middlewareConfig: staticInfo.middleware ?? {},
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}), }),
] ]
} else { } else {
......
...@@ -6,6 +6,16 @@ import { PagesRouteModuleOptions } from '../../../../server/future/route-modules ...@@ -6,6 +6,16 @@ import { PagesRouteModuleOptions } from '../../../../server/future/route-modules
import { RouteKind } from '../../../../server/future/route-kind' import { RouteKind } from '../../../../server/future/route-kind'
import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'
import { MiddlewareConfig } from '../../../analysis/get-page-static-info' import { MiddlewareConfig } from '../../../analysis/get-page-static-info'
import { decodeFromBase64, encodeToBase64 } from '../utils'
import { isInstrumentationHookFile } from '../../../worker'
type RouteLoaderOptionsInput = {
page: string
pages: { [page: string]: string }
preferredRegion: string | string[] | undefined
absolutePagePath: string
middlewareConfig: MiddlewareConfig
}
/** /**
* The options for the route loader. * The options for the route loader.
...@@ -25,17 +35,29 @@ type RouteLoaderOptions = { ...@@ -25,17 +35,29 @@ type RouteLoaderOptions = {
* The absolute path to the userland page file. * The absolute path to the userland page file.
*/ */
absolutePagePath: string absolutePagePath: string
absoluteAppPath: string
middlewareConfig: string absoluteDocumentPath: string
middlewareConfigBase64: string
} }
/** /**
* Returns the loader entry for a given page. * Returns the loader entry for a given page.
* *
* @param query the options to create the loader entry * @param options the options to create the loader entry
* @returns the encoded loader entry * @returns the encoded loader entry
*/ */
export function getRouteLoaderEntry(query: RouteLoaderOptions): string { export function getRouteLoaderEntry(options: RouteLoaderOptionsInput): string {
const query: RouteLoaderOptions = {
page: options.page,
preferredRegion: options.preferredRegion,
absolutePagePath: options.absolutePagePath,
// These are the path references to the internal components that may be
// overridden by userland components.
absoluteAppPath: options.pages['/_app'],
absoluteDocumentPath: options.pages['/_document'],
middlewareConfigBase64: encodeToBase64(options.middlewareConfig),
}
return `next-route-loader?${stringify(query)}!` return `next-route-loader?${stringify(query)}!`
} }
...@@ -49,7 +71,9 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -49,7 +71,9 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
page, page,
preferredRegion, preferredRegion,
absolutePagePath, absolutePagePath,
middlewareConfig: middlewareConfigBase64, absoluteAppPath,
absoluteDocumentPath,
middlewareConfigBase64,
} = this.getOptions() } = this.getOptions()
// Ensure we only run this loader for as a module. // Ensure we only run this loader for as a module.
...@@ -57,8 +81,8 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -57,8 +81,8 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
throw new Error('Invariant: expected this to reference a module') throw new Error('Invariant: expected this to reference a module')
} }
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: MiddlewareConfig = decodeFromBase64(
Buffer.from(middlewareConfigBase64, 'base64').toString() middlewareConfigBase64
) )
// Attach build info to the module. // Attach build info to the module.
...@@ -70,7 +94,7 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -70,7 +94,7 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
middlewareConfig, middlewareConfig,
} }
const options: Omit<PagesRouteModuleOptions, 'userland'> = { const options: Omit<PagesRouteModuleOptions, 'userland' | 'components'> = {
definition: { definition: {
kind: RouteKind.PAGES, kind: RouteKind.PAGES,
page: normalizePagePath(page), page: normalizePagePath(page),
...@@ -86,6 +110,10 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -86,6 +110,10 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
import RouteModule from "next/dist/server/future/route-modules/pages/module" import RouteModule from "next/dist/server/future/route-modules/pages/module"
import { hoist } from "next/dist/build/webpack/loaders/next-route-loader/helpers" import { hoist } from "next/dist/build/webpack/loaders/next-route-loader/helpers"
// Import the app and document modules.
import * as moduleDocument from ${JSON.stringify(absoluteDocumentPath)}
import * as moduleApp from ${JSON.stringify(absoluteAppPath)}
// Import the userland code. // Import the userland code.
import * as userland from ${JSON.stringify(absolutePagePath)} import * as userland from ${JSON.stringify(absolutePagePath)}
...@@ -98,6 +126,14 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -98,6 +126,14 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
export const getServerSideProps = hoist(userland, "getServerSideProps") export const getServerSideProps = hoist(userland, "getServerSideProps")
export const config = hoist(userland, "config") export const config = hoist(userland, "config")
export const reportWebVitals = hoist(userland, "reportWebVitals") export const reportWebVitals = hoist(userland, "reportWebVitals")
${
// When we're building the instrumentation page (only when the
// instrumentation file conflicts with a page also labeled
// /instrumentation) hoist the `register` method.
isInstrumentationHookFile(page)
? 'export const register = hoist(userland, "register")'
: ''
}
// Re-export legacy methods. // Re-export legacy methods.
export const unstable_getStaticProps = hoist(userland, "unstable_getStaticProps") export const unstable_getStaticProps = hoist(userland, "unstable_getStaticProps")
...@@ -108,7 +144,14 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> = ...@@ -108,7 +144,14 @@ const loader: webpack.LoaderDefinitionFunction<RouteLoaderOptions> =
// Create and export the route module that will be consumed. // Create and export the route module that will be consumed.
const options = ${JSON.stringify(options)} const options = ${JSON.stringify(options)}
const routeModule = new RouteModule({ ...options, userland }) const routeModule = new RouteModule({
...options,
components: {
App: moduleApp.default,
Document: moduleDocument.default,
},
userland,
})
export { routeModule } export { routeModule }
` `
......
...@@ -50,3 +50,11 @@ export function generateActionId(filePath: string, exportName: string) { ...@@ -50,3 +50,11 @@ export function generateActionId(filePath: string, exportName: string) {
.update(filePath + ':' + exportName) .update(filePath + ':' + exportName)
.digest('hex') .digest('hex')
} }
export function encodeToBase64<T extends {}>(obj: T): string {
return Buffer.from(JSON.stringify(obj)).toString('base64')
}
export function decodeFromBase64<T extends {}>(str: string): T {
return JSON.parse(Buffer.from(str, 'base64').toString('utf8'))
}
export function isInternalComponent(pathname: string): boolean {
switch (pathname) {
case 'next/dist/pages/_app':
case 'next/dist/pages/_document':
return true
default:
return false
}
}
export function isInternalPathname(pathname: string): boolean {
return pathname.startsWith('next/dist/pages/')
}
...@@ -30,6 +30,7 @@ import type { NextFontManifest } from '../build/webpack/plugins/next-font-manife ...@@ -30,6 +30,7 @@ import type { NextFontManifest } from '../build/webpack/plugins/next-font-manife
import type { PagesRouteModule } from './future/route-modules/pages/module' import type { PagesRouteModule } from './future/route-modules/pages/module'
import type { NodeNextRequest, NodeNextResponse } from './base-http/node' import type { NodeNextRequest, NodeNextResponse } from './base-http/node'
import type { AppRouteRouteMatch } from './future/route-matches/app-route-route-match' import type { AppRouteRouteMatch } from './future/route-matches/app-route-route-match'
import type { RouteDefinition } from './future/route-definitions/route-definition'
import { format as formatUrl, parse as parseUrl } from 'url' import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/redirect-status' import { getRedirectStatus } from '../lib/redirect-status'
...@@ -109,7 +110,11 @@ import { ...@@ -109,7 +110,11 @@ import {
toNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders,
} from './web/utils' } from './web/utils'
import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants' import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants'
import { isRouteMatch } from './future/route-matches/route-match' import {
isRouteMatch,
parsedUrlQueryToParams,
type RouteMatch,
} from './future/route-matches/route-match'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -1675,7 +1680,18 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1675,7 +1680,18 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let result: RenderResult let result: RenderResult
// Get the match for the page if it exists. // Get the match for the page if it exists.
const match = getRequestMeta(req, '_nextMatch') const match: RouteMatch<RouteDefinition<RouteKind>> | undefined =
getRequestMeta(req, '_nextMatch') ??
// If the match can't be found, rely on the loaded route module. This
// should only be required during development when we add FS routes.
(this.renderOpts.dev && components.ComponentMod?.routeModule
? {
definition: components.ComponentMod.routeModule.definition,
params: opts.params
? parsedUrlQueryToParams(opts.params)
: undefined,
}
: undefined)
if ( if (
match && match &&
...@@ -2578,6 +2594,13 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2578,6 +2594,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const fallbackComponents = await this.getFallbackErrorComponents() const fallbackComponents = await this.getFallbackErrorComponents()
if (fallbackComponents) { if (fallbackComponents) {
// There was an error, so use it's definition from the route module
// to add the match to the request.
addRequestMeta(ctx.req, '_nextMatch', {
definition: fallbackComponents.ComponentMod.routeModule.definition,
params: undefined,
})
return this.renderToResponseWithComponents( return this.renderToResponseWithComponents(
{ {
...ctx, ...ctx,
......
...@@ -47,7 +47,6 @@ import getRouteFromEntrypoint from '../get-route-from-entrypoint' ...@@ -47,7 +47,6 @@ import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { fileExists } from '../../lib/file-exists' import { fileExists } from '../../lib/file-exists'
import { import {
difference, difference,
isInstrumentationHookFile,
isMiddlewareFile, isMiddlewareFile,
isMiddlewareFilename, isMiddlewareFilename,
} from '../../build/utils' } from '../../build/utils'
...@@ -62,7 +61,7 @@ import { RouteMatch } from '../future/route-matches/route-match' ...@@ -62,7 +61,7 @@ import { RouteMatch } from '../future/route-matches/route-match'
import { parseVersionInfo, VersionInfo } from './parse-version-info' import { parseVersionInfo, VersionInfo } from './parse-version-info'
import { isAPIRoute } from '../../lib/is-api-route' import { isAPIRoute } from '../../lib/is-api-route'
import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader'
import { isInternalPathname } from '../../lib/is-internal-pathname' import { isInternalComponent } from '../../lib/is-internal-component'
function diff(a: Set<any>, b: Set<any>) { function diff(a: Set<any>, b: Set<any>) {
return new Set([...a].filter((v) => !b.has(v))) return new Set([...a].filter((v) => !b.has(v)))
...@@ -899,16 +898,14 @@ export default class HotReloader { ...@@ -899,16 +898,14 @@ export default class HotReloader {
} else if ( } else if (
!isAPIRoute(page) && !isAPIRoute(page) &&
!isMiddlewareFile(page) && !isMiddlewareFile(page) &&
!isInternalPathname(relativeRequest) && !isInternalComponent(relativeRequest)
!isInstrumentationHookFile(page)
) { ) {
value = getRouteLoaderEntry({ value = getRouteLoaderEntry({
page, page,
pages: this.pagesMapping,
absolutePagePath: relativeRequest, absolutePagePath: relativeRequest,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: Buffer.from( middlewareConfig: staticInfo.middleware ?? {},
JSON.stringify(staticInfo.middleware || {})
).toString('base64'),
}) })
} else { } else {
value = relativeRequest value = relativeRequest
......
import type { ParsedUrlQuery } from 'querystring'
import type { RouteDefinition } from '../route-definitions/route-definition' import type { RouteDefinition } from '../route-definitions/route-definition'
/** /**
...@@ -31,3 +32,22 @@ export function isRouteMatch<M extends RouteMatch>( ...@@ -31,3 +32,22 @@ export function isRouteMatch<M extends RouteMatch>(
): match is M { ): match is M {
return match.definition.kind === kind return match.definition.kind === kind
} }
/**
* Converts the query into params.
*
* @param query the query to convert to params
* @returns the params
*/
export function parsedUrlQueryToParams(
query: ParsedUrlQuery
): Record<string, string | string[]> {
const params: Record<string, string | string[]> = {}
for (const [key, value] of Object.entries(query)) {
if (typeof value === 'undefined') continue
params[key] = value
}
return params
}
import Document from '../../../../../pages/_document'
import App from '../../../../../pages/_app'
import { RouteKind } from '../../../route-kind'
import * as moduleError from '../../../../../pages/_error'
import PagesRouteModule from '../module'
export const routeModule = new PagesRouteModule({
// TODO: add descriptor for internal error page
definition: {
kind: RouteKind.PAGES,
page: '/_error',
pathname: '/_error',
filename: '',
bundlePath: '',
},
components: {
App,
Document,
},
userland: moduleError,
})
...@@ -10,13 +10,14 @@ import type { PagesRouteDefinition } from '../../route-definitions/pages-route-d ...@@ -10,13 +10,14 @@ import type { PagesRouteDefinition } from '../../route-definitions/pages-route-d
import type { NextParsedUrlQuery } from '../../../request-meta' import type { NextParsedUrlQuery } from '../../../request-meta'
import type { RenderOpts } from '../../../render' import type { RenderOpts } from '../../../render'
import type RenderResult from '../../../render-result' import type RenderResult from '../../../render-result'
import type { AppType, DocumentType } from '../../../../shared/lib/utils'
import { import {
RouteModule, RouteModule,
type RouteModuleHandleContext, type RouteModuleHandleContext,
type RouteModuleOptions, type RouteModuleOptions,
} from '../route-module' } from '../route-module'
import { renderToHTML } from '../../../render' import { renderToHTMLImpl } from '../../../render'
/** /**
* The userland module for a page. This is the module that is exported from the * The userland module for a page. This is the module that is exported from the
...@@ -50,6 +51,30 @@ export type PagesUserlandModule = { ...@@ -50,6 +51,30 @@ export type PagesUserlandModule = {
readonly getServerSideProps?: GetServerSideProps readonly getServerSideProps?: GetServerSideProps
} }
/**
* The components that are used to render a page. These aren't tied to the
* specific page being rendered, but rather are the components that are used to
* render all pages.
*/
type PagesComponents = {
/**
* The `App` component. This could be exported by a user's custom `_app` page
* file, or it could be the default `App` component.
*/
readonly App: AppType
/**
* The `Document` component. This could be exported by a user's custom
* `_document` page file, or it could be the default `Document` component.
*/
readonly Document: DocumentType
}
export interface PagesRouteModuleOptions
extends RouteModuleOptions<PagesRouteDefinition, PagesUserlandModule> {
readonly components: PagesComponents
}
/** /**
* AppRouteRouteHandlerContext is the context that is passed to the route * AppRouteRouteHandlerContext is the context that is passed to the route
* handler for app routes. * handler for app routes.
...@@ -70,18 +95,21 @@ export interface PagesRouteHandlerContext extends RouteModuleHandleContext { ...@@ -70,18 +95,21 @@ export interface PagesRouteHandlerContext extends RouteModuleHandleContext {
* use for rendering. * use for rendering.
*/ */
// TODO: (wyattjoh) break this out into smaller parts, it currently includes the userland components // TODO: (wyattjoh) break this out into smaller parts, it currently includes the userland components
renderOpts: RenderOpts renderOpts: Omit<RenderOpts, 'Document' | 'App'>
} }
export type PagesRouteModuleOptions = RouteModuleOptions<
PagesRouteDefinition,
PagesUserlandModule
>
export class PagesRouteModule extends RouteModule< export class PagesRouteModule extends RouteModule<
PagesRouteDefinition, PagesRouteDefinition,
PagesUserlandModule PagesUserlandModule
> { > {
private readonly components: PagesComponents
constructor(options: PagesRouteModuleOptions) {
super(options)
this.components = options.components
}
public handle(): Promise<Response> { public handle(): Promise<Response> {
throw new Error('Method not implemented.') throw new Error('Method not implemented.')
} }
...@@ -91,12 +119,16 @@ export class PagesRouteModule extends RouteModule< ...@@ -91,12 +119,16 @@ export class PagesRouteModule extends RouteModule<
res: ServerResponse, res: ServerResponse,
context: PagesRouteHandlerContext context: PagesRouteHandlerContext
): Promise<RenderResult> { ): Promise<RenderResult> {
return renderToHTML( return renderToHTMLImpl(
req, req,
res, res,
context.page, context.page,
context.query, context.query,
context.renderOpts context.renderOpts,
{
App: this.components.App,
Document: this.components.Document,
}
) )
} }
} }
......
...@@ -48,12 +48,18 @@ export type LoadComponentsReturnType = { ...@@ -48,12 +48,18 @@ export type LoadComponentsReturnType = {
pathname: string pathname: string
} }
async function loadDefaultErrorComponentsImpl(distDir: string) { async function loadDefaultErrorComponentsImpl(
distDir: string
): Promise<LoadComponentsReturnType> {
const Document = interopDefault(require('next/dist/pages/_document')) const Document = interopDefault(require('next/dist/pages/_document'))
const AppMod = require('next/dist/pages/_app') const AppMod = require('next/dist/pages/_app')
const App = interopDefault(AppMod) const App = interopDefault(AppMod)
const ComponentMod = require('next/dist/pages/_error')
const Component = interopDefault(ComponentMod) // Load the compiled route module for this builtin error.
// TODO: (wyattjoh) replace this with just exporting the route module when the transition is complete
const ComponentMod =
require('./future/route-modules/pages/builtin/_error') as typeof import('./future/route-modules/pages/builtin/_error')
const Component = ComponentMod.routeModule.userland.default
return { return {
App, App,
......
...@@ -28,6 +28,7 @@ import { ...@@ -28,6 +28,7 @@ import {
} from '../shared/lib/router/utils/route-matcher' } from '../shared/lib/router/utils/route-matcher'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher' import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { RouteMatch } from './future/route-matches/route-match' import type { RouteMatch } from './future/route-matches/route-match'
import type { RenderOpts } from './render'
import fs from 'fs' import fs from 'fs'
import { join, relative, resolve, sep, isAbsolute } from 'path' import { join, relative, resolve, sep, isAbsolute } from 'path'
...@@ -59,7 +60,6 @@ import { sendRenderResult } from './send-payload' ...@@ -59,7 +60,6 @@ import { sendRenderResult } from './send-payload'
import { getExtension, serveStatic } from './serve-static' import { getExtension, serveStatic } from './serve-static'
import { ParsedUrlQuery } from 'querystring' import { ParsedUrlQuery } from 'querystring'
import { apiResolver } from './api-utils/node' import { apiResolver } from './api-utils/node'
import { RenderOpts, renderToHTML } from './render'
import { ParsedUrl, parseUrl } from '../shared/lib/router/utils/parse-url' import { ParsedUrl, parseUrl } from '../shared/lib/router/utils/parse-url'
import { parse as nodeParseUrl } from 'url' import { parse as nodeParseUrl } from 'url'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
...@@ -984,13 +984,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -984,13 +984,7 @@ export default class NextNodeServer extends BaseServer {
) )
} }
return renderToHTML( throw new Error('Invariant: render should have used routeModule')
req.originalRequest,
res.originalResponse,
pathname,
query,
renderOpts
)
} }
private streamResponseChunk(res: ServerResponse, chunk: any) { private streamResponseChunk(res: ServerResponse, chunk: any) {
......
...@@ -182,7 +182,17 @@ class FontOptimizerMiddleware implements PostProcessMiddleware { ...@@ -182,7 +182,17 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
async function postProcessHTML( async function postProcessHTML(
pathname: string, pathname: string,
content: string, content: string,
renderOpts: RenderOpts, renderOpts: Pick<
RenderOpts,
| 'ampOptimizerConfig'
| 'ampValidator'
| 'ampSkipValidation'
| 'optimizeFonts'
| 'fontManifest'
| 'optimizeCss'
| 'distDir'
| 'assetPrefix'
>,
{ inAmpMode, hybridAmp }: { inAmpMode: boolean; hybridAmp: boolean } { inAmpMode, hybridAmp }: { inAmpMode: boolean; hybridAmp: boolean }
) { ) {
const postProcessors: Array<PostProcessorFunction> = [ const postProcessors: Array<PostProcessorFunction> = [
......
...@@ -272,6 +272,11 @@ export type RenderOptsPartial = { ...@@ -272,6 +272,11 @@ export type RenderOptsPartial = {
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
export type RenderOptsExtra = {
App: AppType
Document: DocumentType
}
const invalidKeysMsg = ( const invalidKeysMsg = (
methodName: 'getServerSideProps' | 'getStaticProps', methodName: 'getServerSideProps' | 'getStaticProps',
invalidKeys: string[] invalidKeys: string[]
...@@ -399,12 +404,13 @@ function serializeError( ...@@ -399,12 +404,13 @@ function serializeError(
} }
} }
export async function renderToHTML( export async function renderToHTMLImpl(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: Omit<RenderOpts, keyof RenderOptsExtra>,
extra: RenderOptsExtra
): Promise<RenderResult> { ): Promise<RenderResult> {
const renderResultMeta: RenderResultMetadata = {} const renderResultMeta: RenderResultMetadata = {}
...@@ -442,12 +448,12 @@ export async function renderToHTML( ...@@ -442,12 +448,12 @@ export async function renderToHTML(
basePath, basePath,
images, images,
runtime: globalRuntime, runtime: globalRuntime,
App,
} = renderOpts } = renderOpts
const { App } = extra
const assetQueryString = renderResultMeta.assetQueryString const assetQueryString = renderResultMeta.assetQueryString
let Document = renderOpts.Document let Document = extra.Document
// 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) =
...@@ -1540,4 +1546,12 @@ export async function renderToHTML( ...@@ -1540,4 +1546,12 @@ export async function renderToHTML(
return new RenderResult(optimizedHtml, renderResultMeta) return new RenderResult(optimizedHtml, renderResultMeta)
} }
export type RenderToHTMLResult = typeof renderToHTML export async function renderToHTML(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts
): Promise<RenderResult> {
return renderToHTMLImpl(req, res, pathname, query, renderOpts, renderOpts)
}
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