Unverified Commit b5aa571c authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor client entry plugin to separate methods. (#39162)

WIP.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarShu Ding <3676859+shuding@users.noreply.github.com>
parent 0c7217ba
...@@ -15,12 +15,16 @@ import { ...@@ -15,12 +15,16 @@ import {
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
APP_DIR_ALIAS, APP_DIR_ALIAS,
SERVER_RUNTIME, SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants' } from '../lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CompilerNameValues,
COMPILER_NAMES,
EDGE_RUNTIME_WEBPACK, EDGE_RUNTIME_WEBPACK,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
...@@ -203,7 +207,7 @@ export function getEdgeServerEntry(opts: { ...@@ -203,7 +207,7 @@ export function getEdgeServerEntry(opts: {
return { return {
import: `next-edge-ssr-loader?${stringify(loaderParams)}!`, import: `next-edge-ssr-loader?${stringify(loaderParams)}!`,
layer: opts.isServerComponent ? 'sc_server' : undefined, layer: opts.isServerComponent ? WEBPACK_LAYERS.server : undefined,
} }
} }
...@@ -215,7 +219,7 @@ export function getAppEntry(opts: { ...@@ -215,7 +219,7 @@ export function getAppEntry(opts: {
}) { }) {
return { return {
import: `next-app-loader?${stringify(opts)}!`, import: `next-app-loader?${stringify(opts)}!`,
layer: 'sc_server', layer: WEBPACK_LAYERS.server,
} }
} }
...@@ -359,7 +363,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -359,7 +363,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
} }
} }
runDependingOnPageType({ await runDependingOnPageType({
page, page,
pageRuntime: staticInfo.runtime, pageRuntime: staticInfo.runtime,
onClient: () => { onClient: () => {
...@@ -393,7 +397,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -393,7 +397,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
server[serverBundlePath] = isServerComponent server[serverBundlePath] = isServerComponent
? { ? {
import: mappings[page], import: mappings[page],
layer: 'sc_server', layer: WEBPACK_LAYERS.server,
} }
: [mappings[page]] : [mappings[page]]
} }
...@@ -435,33 +439,46 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -435,33 +439,46 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
} }
} }
export function runDependingOnPageType<T>(params: { export async function runDependingOnPageType<T>(params: {
onClient: () => T onClient: () => T
onEdgeServer: () => T onEdgeServer: () => T
onServer: () => T onServer: () => T
page: string page: string
pageRuntime: ServerRuntime pageRuntime: ServerRuntime
}) { }): Promise<void> {
if (isMiddlewareFile(params.page)) { if (isMiddlewareFile(params.page)) {
return { edgeServer: params.onEdgeServer() } await params.onEdgeServer()
} else if (params.page.match(API_ROUTE)) { return
return params.pageRuntime === SERVER_RUNTIME.edge }
? { edgeServer: params.onEdgeServer() } if (params.page.match(API_ROUTE)) {
: { server: params.onServer() } if (params.pageRuntime === SERVER_RUNTIME.edge) {
} else if (params.page === '/_document') { await params.onEdgeServer()
return { server: params.onServer() } return
} else if ( }
await params.onServer()
return
}
if (params.page === '/_document') {
await params.onServer()
return
}
if (
params.page === '/_app' || params.page === '/_app' ||
params.page === '/_error' || params.page === '/_error' ||
params.page === '/404' || params.page === '/404' ||
params.page === '/500' params.page === '/500'
) { ) {
return { client: params.onClient(), server: params.onServer() } await Promise.all([params.onClient(), params.onServer()])
} else { return
return params.pageRuntime === SERVER_RUNTIME.edge
? { client: params.onClient(), edgeServer: params.onEdgeServer() }
: { client: params.onClient(), server: params.onServer() }
} }
if (params.pageRuntime === SERVER_RUNTIME.edge) {
await Promise.all([params.onClient(), params.onEdgeServer()])
return
}
await Promise.all([params.onClient(), params.onServer()])
return
} }
export function finalizeEntrypoint({ export function finalizeEntrypoint({
...@@ -471,7 +488,7 @@ export function finalizeEntrypoint({ ...@@ -471,7 +488,7 @@ export function finalizeEntrypoint({
isServerComponent, isServerComponent,
appDir, appDir,
}: { }: {
compilerType?: 'client' | 'server' | 'edge-server' compilerType?: CompilerNameValues
name: string name: string
value: ObjectValue<webpack5.EntryObject> value: ObjectValue<webpack5.EntryObject>
isServerComponent?: boolean isServerComponent?: boolean
...@@ -483,18 +500,25 @@ export function finalizeEntrypoint({ ...@@ -483,18 +500,25 @@ export function finalizeEntrypoint({
: value : value
const isApi = name.startsWith('pages/api/') const isApi = name.startsWith('pages/api/')
if (compilerType === 'server') { if (compilerType === COMPILER_NAMES.server) {
return { return {
publicPath: isApi ? '' : undefined, publicPath: isApi ? '' : undefined,
runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime', runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
layer: isApi ? 'api' : isServerComponent ? 'sc_server' : undefined, layer: isApi
? WEBPACK_LAYERS.api
: isServerComponent
? WEBPACK_LAYERS.server
: undefined,
...entry, ...entry,
} }
} }
if (compilerType === 'edge-server') { if (compilerType === COMPILER_NAMES.edgeServer) {
return { return {
layer: isMiddlewareFilename(name) || isApi ? 'middleware' : undefined, layer:
isMiddlewareFilename(name) || isApi
? WEBPACK_LAYERS.middleware
: undefined,
library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' }, library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' },
runtime: EDGE_RUNTIME_WEBPACK, runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false, asyncChunks: false,
...@@ -504,7 +528,7 @@ export function finalizeEntrypoint({ ...@@ -504,7 +528,7 @@ export function finalizeEntrypoint({
if ( if (
// Client special cases // Client special cases
name !== 'polyfills' && name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP && name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
......
...@@ -55,6 +55,7 @@ import { ...@@ -55,6 +55,7 @@ import {
MIDDLEWARE_MANIFEST, MIDDLEWARE_MANIFEST,
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
APP_PATH_ROUTES_MANIFEST, APP_PATH_ROUTES_MANIFEST,
COMPILER_NAMES,
APP_BUILD_MANIFEST, APP_BUILD_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils' import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
...@@ -749,17 +750,17 @@ export default async function build( ...@@ -749,17 +750,17 @@ export default async function build(
Promise.all([ Promise.all([
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
...commonWebpackOptions, ...commonWebpackOptions,
compilerType: 'client', compilerType: COMPILER_NAMES.client,
entrypoints: entrypoints.client, entrypoints: entrypoints.client,
}), }),
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
...commonWebpackOptions, ...commonWebpackOptions,
compilerType: 'server', compilerType: COMPILER_NAMES.server,
entrypoints: entrypoints.server, entrypoints: entrypoints.server,
}), }),
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
...commonWebpackOptions, ...commonWebpackOptions,
compilerType: 'edge-server', compilerType: COMPILER_NAMES.edgeServer,
entrypoints: entrypoints.edgeServer, entrypoints: entrypoints.edgeServer,
}), }),
]) ])
......
...@@ -5,6 +5,7 @@ import createStore from 'next/dist/compiled/unistore' ...@@ -5,6 +5,7 @@ import createStore from 'next/dist/compiled/unistore'
import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages'
import { OutputState, store as consoleStore } from './store' import { OutputState, store as consoleStore } from './store'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack' import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { CompilerNameValues, COMPILER_NAMES } from '../../shared/lib/constants'
export function startedDevelopmentServer(appUrl: string, bindAddr: string) { export function startedDevelopmentServer(appUrl: string, bindAddr: string) {
consoleStore.setState({ appUrl, bindAddr }) consoleStore.setState({ appUrl, bindAddr })
...@@ -238,7 +239,7 @@ export function watchCompilers( ...@@ -238,7 +239,7 @@ export function watchCompilers(
}) })
function tapCompiler( function tapCompiler(
key: 'client' | 'server' | 'edgeServer', key: CompilerNameValues,
compiler: webpack5.Compiler, compiler: webpack5.Compiler,
onEvent: (status: WebpackStatus) => void onEvent: (status: WebpackStatus) => void
) { ) {
...@@ -268,7 +269,7 @@ export function watchCompilers( ...@@ -268,7 +269,7 @@ export function watchCompilers(
}) })
} }
tapCompiler('client', client, (status) => { tapCompiler(COMPILER_NAMES.client, client, (status) => {
if ( if (
!status.loading && !status.loading &&
!buildStore.getState().server.loading && !buildStore.getState().server.loading &&
...@@ -284,7 +285,7 @@ export function watchCompilers( ...@@ -284,7 +285,7 @@ export function watchCompilers(
}) })
} }
}) })
tapCompiler('server', server, (status) => { tapCompiler(COMPILER_NAMES.server, server, (status) => {
if ( if (
!status.loading && !status.loading &&
!buildStore.getState().client.loading && !buildStore.getState().client.loading &&
...@@ -300,7 +301,7 @@ export function watchCompilers( ...@@ -300,7 +301,7 @@ export function watchCompilers(
}) })
} }
}) })
tapCompiler('edgeServer', edgeServer, (status) => { tapCompiler(COMPILER_NAMES.edgeServer, edgeServer, (status) => {
if ( if (
!status.loading && !status.loading &&
!buildStore.getState().client.loading && !buildStore.getState().client.loading &&
......
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
ROOT_DIR_ALIAS, ROOT_DIR_ALIAS,
APP_DIR_ALIAS, APP_DIR_ALIAS,
SERVER_RUNTIME, SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js' import { CustomRoutes } from '../lib/load-custom-routes.js'
...@@ -28,6 +29,8 @@ import { ...@@ -28,6 +29,8 @@ import {
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
SERVER_DIRECTORY, SERVER_DIRECTORY,
MODERN_BROWSERSLIST_TARGET, MODERN_BROWSERSLIST_TARGET,
COMPILER_NAMES,
CompilerNameValues,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils' import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
...@@ -334,13 +337,13 @@ export default async function getBaseWebpackConfig( ...@@ -334,13 +337,13 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling = false, reactProductionProfiling = false,
rewrites, rewrites,
runWebpackSpan, runWebpackSpan,
target = 'server', target = COMPILER_NAMES.server,
appDir, appDir,
middlewareRegex, middlewareRegex,
}: { }: {
buildId: string buildId: string
config: NextConfigComplete config: NextConfigComplete
compilerType: 'client' | 'server' | 'edge-server' compilerType: CompilerNameValues
dev?: boolean dev?: boolean
entrypoints: webpack5.EntryObject entrypoints: webpack5.EntryObject
hasReactRoot: boolean hasReactRoot: boolean
...@@ -354,9 +357,9 @@ export default async function getBaseWebpackConfig( ...@@ -354,9 +357,9 @@ export default async function getBaseWebpackConfig(
middlewareRegex?: string middlewareRegex?: string
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
const isClient = compilerType === 'client' const isClient = compilerType === COMPILER_NAMES.client
const isEdgeServer = compilerType === 'edge-server' const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer
const isNodeServer = compilerType === 'server' const isNodeServer = compilerType === COMPILER_NAMES.server
const { useTypeScript, jsConfig, resolvedBaseUrl } = await loadJsConfig( const { useTypeScript, jsConfig, resolvedBaseUrl } = await loadJsConfig(
dir, dir,
config config
...@@ -650,9 +653,9 @@ export default async function getBaseWebpackConfig( ...@@ -650,9 +653,9 @@ export default async function getBaseWebpackConfig(
const reactDomDir = dirname(require.resolve('react-dom/package.json')) const reactDomDir = dirname(require.resolve('react-dom/package.json'))
const mainFieldsPerCompiler: Record<typeof compilerType, string[]> = { const mainFieldsPerCompiler: Record<typeof compilerType, string[]> = {
server: ['main', 'module'], [COMPILER_NAMES.server]: ['main', 'module'],
client: ['browser', 'module', 'main'], [COMPILER_NAMES.client]: ['browser', 'module', 'main'],
'edge-server': ['browser', 'module', 'main'], [COMPILER_NAMES.edgeServer]: ['browser', 'module', 'main'],
} }
const resolveConfig = { const resolveConfig = {
...@@ -1310,14 +1313,14 @@ export default async function getBaseWebpackConfig( ...@@ -1310,14 +1313,14 @@ export default async function getBaseWebpackConfig(
// RSC server compilation loaders // RSC server compilation loaders
{ {
...serverComponentCodeCondition, ...serverComponentCodeCondition,
issuerLayer: 'sc_server', issuerLayer: WEBPACK_LAYERS.server,
use: { use: {
loader: 'next-flight-server-loader', loader: 'next-flight-server-loader',
}, },
}, },
{ {
test: clientComponentRegex, test: clientComponentRegex,
issuerLayer: 'sc_server', issuerLayer: WEBPACK_LAYERS.server,
use: { use: {
loader: 'next-flight-client-loader', loader: 'next-flight-client-loader',
}, },
...@@ -1325,7 +1328,7 @@ export default async function getBaseWebpackConfig( ...@@ -1325,7 +1328,7 @@ export default async function getBaseWebpackConfig(
// _app should be treated as a client component as well as all its dependencies. // _app should be treated as a client component as well as all its dependencies.
{ {
test: new RegExp(`_app\\.(${rawPageExtensions.join('|')})$`), test: new RegExp(`_app\\.(${rawPageExtensions.join('|')})$`),
layer: 'sc_client', layer: WEBPACK_LAYERS.client,
}, },
] ]
: [] : []
...@@ -1336,13 +1339,13 @@ export default async function getBaseWebpackConfig( ...@@ -1336,13 +1339,13 @@ export default async function getBaseWebpackConfig(
// same layer. // same layer.
{ {
test: rscSharedRegex, test: rscSharedRegex,
layer: 'rsc_shared_deps', layer: WEBPACK_LAYERS.rscShared,
}, },
] ]
: []), : []),
{ {
test: /\.(js|cjs|mjs)$/, test: /\.(js|cjs|mjs)$/,
issuerLayer: 'api', issuerLayer: WEBPACK_LAYERS.api,
parser: { parser: {
// Switch back to normal URL handling // Switch back to normal URL handling
url: true, url: true,
...@@ -1352,7 +1355,7 @@ export default async function getBaseWebpackConfig( ...@@ -1352,7 +1355,7 @@ export default async function getBaseWebpackConfig(
oneOf: [ oneOf: [
{ {
...codeCondition, ...codeCondition,
issuerLayer: 'api', issuerLayer: WEBPACK_LAYERS.api,
parser: { parser: {
// Switch back to normal URL handling // Switch back to normal URL handling
url: true, url: true,
...@@ -1361,7 +1364,7 @@ export default async function getBaseWebpackConfig( ...@@ -1361,7 +1364,7 @@ export default async function getBaseWebpackConfig(
}, },
{ {
...codeCondition, ...codeCondition,
issuerLayer: 'middleware', issuerLayer: WEBPACK_LAYERS.middleware,
use: getBabelOrSwcLoader(), use: getBabelOrSwcLoader(),
}, },
{ {
...@@ -1399,7 +1402,7 @@ export default async function getBaseWebpackConfig( ...@@ -1399,7 +1402,7 @@ export default async function getBaseWebpackConfig(
{ {
oneOf: [ oneOf: [
{ {
issuerLayer: 'middleware', issuerLayer: WEBPACK_LAYERS.middleware,
resolve: { resolve: {
fallback: { fallback: {
process: require.resolve('./polyfills/process'), process: require.resolve('./polyfills/process'),
...@@ -1499,7 +1502,7 @@ export default async function getBaseWebpackConfig( ...@@ -1499,7 +1502,7 @@ export default async function getBaseWebpackConfig(
[`process.env.${key}`]: JSON.stringify(config.env[key]), [`process.env.${key}`]: JSON.stringify(config.env[key]),
} }
}, {}), }, {}),
...(compilerType !== 'edge-server' ...(compilerType !== COMPILER_NAMES.edgeServer
? {} ? {}
: { : {
EdgeRuntime: JSON.stringify( EdgeRuntime: JSON.stringify(
...@@ -1785,10 +1788,10 @@ export default async function getBaseWebpackConfig( ...@@ -1785,10 +1788,10 @@ export default async function getBaseWebpackConfig(
dependency: 'url', dependency: 'url',
loader: 'next-middleware-asset-loader', loader: 'next-middleware-asset-loader',
type: 'javascript/auto', type: 'javascript/auto',
layer: 'edge-asset', layer: WEBPACK_LAYERS.edgeAsset,
}) })
webpack5Config.module?.rules?.unshift({ webpack5Config.module?.rules?.unshift({
issuerLayer: 'edge-asset', issuerLayer: WEBPACK_LAYERS.edgeAsset,
type: 'asset/source', type: 'asset/source',
}) })
} }
......
import curry from 'next/dist/compiled/lodash.curry' import curry from 'next/dist/compiled/lodash.curry'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import { COMPILER_NAMES } from '../../../../shared/lib/constants'
import { ConfigurationContext } from '../utils' import { ConfigurationContext } from '../utils'
export const base = curry(function base( export const base = curry(function base(
...@@ -9,9 +10,9 @@ export const base = curry(function base( ...@@ -9,9 +10,9 @@ export const base = curry(function base(
config.mode = ctx.isDevelopment ? 'development' : 'production' config.mode = ctx.isDevelopment ? 'development' : 'production'
config.name = ctx.isServer config.name = ctx.isServer
? ctx.isEdgeRuntime ? ctx.isEdgeRuntime
? 'edge-server' ? COMPILER_NAMES.edgeServer
: 'server' : COMPILER_NAMES.server
: 'client' : COMPILER_NAMES.client
// @ts-ignore TODO webpack 5 typings // @ts-ignore TODO webpack 5 typings
config.target = !ctx.targetWeb config.target = !ctx.targetWeb
......
import { SERVER_RUNTIME } from '../../../lib/constants' export type ClientComponentImports = string[]
export type CssImports = Record<string, string[]>
export type NextFlightClientEntryLoaderOptions = {
modules: ClientComponentImports
/** This is transmitted as a string to `getOptions` */
server: boolean | 'true' | 'false'
}
export default async function transformSource(this: any): Promise<string> { export default async function transformSource(this: any): Promise<string> {
let { modules, runtime, ssr, server } = this.getOptions() let { modules, server }: NextFlightClientEntryLoaderOptions =
this.getOptions()
const isServer = server === 'true'
if (!Array.isArray(modules)) { if (!Array.isArray(modules)) {
modules = modules ? [modules] : [] modules = modules ? [modules] : []
} }
...@@ -9,25 +19,17 @@ export default async function transformSource(this: any): Promise<string> { ...@@ -9,25 +19,17 @@ export default async function transformSource(this: any): Promise<string> {
const requests = modules as string[] const requests = modules as string[]
const code = const code =
requests requests
.filter((request) => (server ? !request.endsWith('.css') : true)) // Filter out css files on the server
.filter((request) => (isServer ? !request.endsWith('.css') : true))
.map((request) => `import(/* webpackMode: "eager" */ '${request}')`) .map((request) => `import(/* webpackMode: "eager" */ '${request}')`)
.join(';\n') + .join(';\n') +
` `
export const __next_rsc_css__ = ${JSON.stringify(
requests.filter((request) => request.endsWith('.css'))
)};
export const __next_rsc__ = { export const __next_rsc__ = {
server: false, server: false,
__webpack_require__ __webpack_require__
}; };
export default function RSC() {}; export default function RSC() {};
` + `
// Currently for the Edge runtime, we treat all RSC pages as SSR pages.
(runtime === SERVER_RUNTIME.edge
? 'export const __N_SSP = true;'
: ssr
? `export const __N_SSP = true;`
: `export const __N_SSG = true;`)
return code return code
} }
...@@ -24,9 +24,13 @@ interface Options { ...@@ -24,9 +24,13 @@ interface Options {
pageExtensions: string[] pageExtensions: string[]
} }
type ModuleId = string | number /**
* Webpack module id
*/
// TODO-APP ensure `null` is included as it is used.
type ModuleId = string | number /*| null*/
type ManifestChunks = Array<`${string}:${string}` | string> export type ManifestChunks = Array<`${string}:${string}` | string>
interface ManifestNode { interface ManifestNode {
[moduleExport: string]: { [moduleExport: string]: {
...@@ -45,7 +49,7 @@ interface ManifestNode { ...@@ -45,7 +49,7 @@ interface ManifestNode {
} }
} }
type FlightManifest = { export type FlightManifest = {
__ssr_module_mapping__: { __ssr_module_mapping__: {
[moduleId: string]: ManifestNode [moduleId: string]: ManifestNode
} }
...@@ -53,6 +57,10 @@ type FlightManifest = { ...@@ -53,6 +57,10 @@ type FlightManifest = {
[modulePath: string]: ManifestNode [modulePath: string]: ManifestNode
} }
export type FlightCSSManifest = {
[modulePath: string]: string[]
}
const PLUGIN_NAME = 'FlightManifestPlugin' const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin { export class FlightManifestPlugin {
...@@ -139,7 +147,6 @@ export class FlightManifestPlugin { ...@@ -139,7 +147,6 @@ export class FlightManifestPlugin {
const moduleExports = manifest[resource] || {} const moduleExports = manifest[resource] || {}
const moduleIdMapping = manifest.__ssr_module_mapping__ const moduleIdMapping = manifest.__ssr_module_mapping__
moduleIdMapping[id] = moduleIdMapping[id] || {}
// Note that this isn't that reliable as webpack is still possible to assign // Note that this isn't that reliable as webpack is still possible to assign
// additional queries to make sure there's no conflict even using the `named` // additional queries to make sure there's no conflict even using the `named`
...@@ -161,6 +168,7 @@ export class FlightManifestPlugin { ...@@ -161,6 +168,7 @@ export class FlightManifestPlugin {
chunks, chunks,
}, },
} }
moduleIdMapping[id] = moduleIdMapping[id] || {}
moduleIdMapping[id]['default'] = { moduleIdMapping[id]['default'] = {
id: ssrNamedModuleId, id: ssrNamedModuleId,
name: 'default', name: 'default',
...@@ -269,6 +277,8 @@ export class FlightManifestPlugin { ...@@ -269,6 +277,8 @@ export class FlightManifestPlugin {
chunks: requiredChunks.concat([...cssChunks]), chunks: requiredChunks.concat([...cssChunks]),
} }
} }
moduleIdMapping[id] = moduleIdMapping[id] || {}
if (!moduleIdMapping[id][name]) { if (!moduleIdMapping[id][name]) {
moduleIdMapping[id][name] = { moduleIdMapping[id][name] = {
...moduleExports[name], ...moduleExports[name],
......
...@@ -626,6 +626,7 @@ function getEntryFiles(entryFiles: string[], meta: EntryMetadata) { ...@@ -626,6 +626,7 @@ function getEntryFiles(entryFiles: string[], meta: EntryMetadata) {
.map( .map(
(file) => (file) =>
'server/' + 'server/' +
// TODO-APP: seems this should be removed.
file.replace('.js', NEXT_CLIENT_SSR_ENTRY_SUFFIX + '.js') file.replace('.js', NEXT_CLIENT_SSR_ENTRY_SUFFIX + '.js')
) )
) )
......
...@@ -89,13 +89,11 @@ let initialParallelRoutes: CacheNode['parallelRoutes'] = ...@@ -89,13 +89,11 @@ let initialParallelRoutes: CacheNode['parallelRoutes'] =
export default function AppRouter({ export default function AppRouter({
initialTree, initialTree,
initialCanonicalUrl, initialCanonicalUrl,
initialStylesheets,
children, children,
hotReloader, hotReloader,
}: { }: {
initialTree: FlightRouterState initialTree: FlightRouterState
initialCanonicalUrl: string initialCanonicalUrl: string
initialStylesheets: string[]
children: React.ReactNode children: React.ReactNode
hotReloader?: React.ReactNode hotReloader?: React.ReactNode
}) { }) {
...@@ -293,6 +291,7 @@ export default function AppRouter({ ...@@ -293,6 +291,7 @@ export default function AppRouter({
window.removeEventListener('popstate', onPopState) window.removeEventListener('popstate', onPopState)
} }
}, [onPopState]) }, [onPopState])
return ( return (
<PathnameContext.Provider value={pathname}> <PathnameContext.Provider value={pathname}>
<SearchParamsContext.Provider value={searchParams}> <SearchParamsContext.Provider value={searchParams}>
...@@ -311,7 +310,6 @@ export default function AppRouter({ ...@@ -311,7 +310,6 @@ export default function AppRouter({
// Root node always has `url` // Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router // Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl, url: canonicalUrl,
stylesheets: initialStylesheets,
}} }}
> >
<ErrorOverlay> <ErrorOverlay>
......
...@@ -360,11 +360,6 @@ export default function OuterLayoutRouter({ ...@@ -360,11 +360,6 @@ export default function OuterLayoutRouter({
return ( return (
<> <>
{/* {stylesheets
? stylesheets.map((href) => (
<link rel="stylesheet" href={`/_next/${href}`} key={href} />
))
: null} */}
{preservedSegments.map((preservedSegment) => { {preservedSegments.map((preservedSegment) => {
return ( return (
// Loading boundary is render for each segment to ensure they have their own loading state. // Loading boundary is render for each segment to ensure they have their own loading state.
......
...@@ -75,3 +75,12 @@ export const SERVER_RUNTIME: Record<string, ServerRuntime> = { ...@@ -75,3 +75,12 @@ export const SERVER_RUNTIME: Record<string, ServerRuntime> = {
edge: 'experimental-edge', edge: 'experimental-edge',
nodejs: 'nodejs', nodejs: 'nodejs',
} }
export const WEBPACK_LAYERS = {
server: 'sc_server',
client: 'sc_client',
api: 'api',
rscShared: 'rsc_shared_deps',
middleware: 'middleware',
edgeAsset: 'edge-asset',
}
...@@ -22,6 +22,10 @@ import { htmlEscapeJsonString } from './htmlescape' ...@@ -22,6 +22,10 @@ import { htmlEscapeJsonString } from './htmlescape'
import { shouldUseReactRoot, stripInternalQueries } from './utils' import { shouldUseReactRoot, stripInternalQueries } from './utils'
import { NextApiRequestCookies } from './api-utils' import { NextApiRequestCookies } from './api-utils'
import { matchSegment } from '../client/components/match-segments' import { matchSegment } from '../client/components/match-segments'
import {
FlightCSSManifest,
FlightManifest,
} from '../build/webpack/plugins/flight-manifest-plugin'
import { FlushEffectsContext } from '../client/components/hooks-client' import { FlushEffectsContext } from '../client/components/hooks-client'
// this needs to be required lazily so that `next-server` can set // this needs to be required lazily so that `next-server` can set
...@@ -34,6 +38,7 @@ export type RenderOptsPartial = { ...@@ -34,6 +38,7 @@ export type RenderOptsPartial = {
err?: Error | null err?: Error | null
dev?: boolean dev?: boolean
serverComponentManifest?: any serverComponentManifest?: any
serverCSSManifest?: any
supportsDynamicHTML?: boolean supportsDynamicHTML?: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
...@@ -369,26 +374,32 @@ function getSegmentParam(segment: string): { ...@@ -369,26 +374,32 @@ function getSegmentParam(segment: string): {
} }
/** /**
* Get inline <link> tags based on __next_rsc_css__ manifest. Only used when rendering to HTML. * Get inline <link> tags based on server CSS manifest. Only used when rendering to HTML.
*/ */
function getCssInlinedLinkTags( function getCssInlinedLinkTags(
ComponentMod: any, serverComponentManifest: FlightManifest,
serverComponentManifest: any serverCSSManifest: FlightCSSManifest
) { ) {
const importedServerCSSFiles: string[] = const chunks: { [file: string]: string[] } = {}
ComponentMod.__client__?.__next_rsc_css__ || []
// APP-TODO: Remove this once we have CSS injections at each level.
return Array.from( const allChunks = new Set<string>()
new Set(
importedServerCSSFiles for (const layoutOrPage in serverCSSManifest) {
.map((css) => const uniqueChunks = new Set<string>()
css.endsWith('.css') for (const css of serverCSSManifest[layoutOrPage]) {
? serverComponentManifest[css].default.chunks for (const chunk of serverComponentManifest[css].default.chunks) {
: [] if (!uniqueChunks.has(chunk)) {
) uniqueChunks.add(chunk)
.flat() chunks[layoutOrPage] = chunks[layoutOrPage] || []
) chunks[layoutOrPage].push(chunk)
) }
allChunks.add(chunk)
}
}
}
return [chunks, [...allChunks]] as [{ [file: string]: string[] }, string[]]
} }
export async function renderToHTMLOrFlight( export async function renderToHTMLOrFlight(
...@@ -412,6 +423,7 @@ export async function renderToHTMLOrFlight( ...@@ -412,6 +423,7 @@ export async function renderToHTMLOrFlight(
const { const {
buildManifest, buildManifest,
serverComponentManifest, serverComponentManifest,
serverCSSManifest,
supportsDynamicHTML, supportsDynamicHTML,
ComponentMod, ComponentMod,
} = renderOpts } = renderOpts
...@@ -583,12 +595,16 @@ export async function renderToHTMLOrFlight( ...@@ -583,12 +595,16 @@ export async function renderToHTMLOrFlight(
parentParams, parentParams,
firstItem, firstItem,
rootLayoutIncluded, rootLayoutIncluded,
}: { serverStylesheets,
}: // parentSegmentPath,
{
createSegmentPath: CreateSegmentPath createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree loaderTree: LoaderTree
parentParams: { [key: string]: any } parentParams: { [key: string]: any }
rootLayoutIncluded?: boolean rootLayoutIncluded?: boolean
firstItem?: boolean firstItem?: boolean
serverStylesheets: { [file: string]: string[] }
// parentSegmentPath: string
}): Promise<{ Component: React.ComponentType }> => { }): Promise<{ Component: React.ComponentType }> => {
const Loading = loading ? await interopDefault(loading()) : undefined const Loading = loading ? await interopDefault(loading()) : undefined
const isLayout = typeof layout !== 'undefined' const isLayout = typeof layout !== 'undefined'
...@@ -608,6 +624,10 @@ export async function renderToHTMLOrFlight( ...@@ -608,6 +624,10 @@ export async function renderToHTMLOrFlight(
const rootLayoutIncludedAtThisLevelOrAbove = const rootLayoutIncludedAtThisLevelOrAbove =
rootLayoutIncluded || rootLayoutAtThisLevel rootLayoutIncluded || rootLayoutAtThisLevel
// const cssSegmentPath =
// !parentSegmentPath && !segment ? '' : parentSegmentPath + '/' + segment
// const stylesheets = serverStylesheets[cssSegmentPath]
/** /**
* Check if the current layout/page is a client component * Check if the current layout/page is a client component
*/ */
...@@ -668,6 +688,8 @@ export async function renderToHTMLOrFlight( ...@@ -668,6 +688,8 @@ export async function renderToHTMLOrFlight(
loaderTree: parallelRoutes[parallelRouteKey], loaderTree: parallelRoutes[parallelRouteKey],
parentParams: currentParams, parentParams: currentParams,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
serverStylesheets,
// parentSegmentPath: cssSegmentPath,
}) })
const childSegment = parallelRoutes[parallelRouteKey][0] const childSegment = parallelRoutes[parallelRouteKey][0]
...@@ -807,6 +829,12 @@ export async function renderToHTMLOrFlight( ...@@ -807,6 +829,12 @@ export async function renderToHTMLOrFlight(
} }
return ( return (
<>
{/* {stylesheets
? stylesheets.map((href) => (
<link rel="stylesheet" href={`/_next/${href}`} key={href} />
))
: null} */}
<Component <Component
{...props} {...props}
{...parallelRouteComponents} {...parallelRouteComponents}
...@@ -817,6 +845,7 @@ export async function renderToHTMLOrFlight( ...@@ -817,6 +845,7 @@ export async function renderToHTMLOrFlight(
// Query is only provided to page // Query is only provided to page
{...(isPage ? { searchParams: query } : {})} {...(isPage ? { searchParams: query } : {})}
/> />
</>
) )
}, },
} }
...@@ -881,6 +910,8 @@ export async function renderToHTMLOrFlight( ...@@ -881,6 +910,8 @@ export async function renderToHTMLOrFlight(
loaderTree: loaderTreeToFilter, loaderTree: loaderTreeToFilter,
parentParams: currentParams, parentParams: currentParams,
firstItem: true, firstItem: true,
serverStylesheets: serverCSSManifest,
// parentSegmentPath: '',
} }
) )
).Component ).Component
...@@ -928,12 +959,20 @@ export async function renderToHTMLOrFlight( ...@@ -928,12 +959,20 @@ export async function renderToHTMLOrFlight(
// Below this line is handling for rendering to HTML. // Below this line is handling for rendering to HTML.
// Get all the server imported styles.
const [mappedServerCSSManifest, initialStylesheets] = getCssInlinedLinkTags(
serverComponentManifest,
serverCSSManifest
)
// Create full component tree from root to leaf. // Create full component tree from root to leaf.
const { Component: ComponentTree } = await createComponentTree({ const { Component: ComponentTree } = await createComponentTree({
createSegmentPath: (child) => child, createSegmentPath: (child) => child,
loaderTree: loaderTree, loaderTree: loaderTree,
parentParams: {}, parentParams: {},
firstItem: true, firstItem: true,
serverStylesheets: mappedServerCSSManifest,
// parentSegmentPath: '',
}) })
// AppRouter is provided by next-app-loader // AppRouter is provided by next-app-loader
...@@ -947,10 +986,6 @@ export async function renderToHTMLOrFlight( ...@@ -947,10 +986,6 @@ export async function renderToHTMLOrFlight(
// TODO-APP: validate req.url as it gets passed to render. // TODO-APP: validate req.url as it gets passed to render.
const initialCanonicalUrl = req.url! const initialCanonicalUrl = req.url!
const initialStylesheets: string[] = getCssInlinedLinkTags(
ComponentMod,
serverComponentManifest
)
/** /**
* A new React Component that renders the provided React Component * A new React Component that renders the provided React Component
...@@ -969,7 +1004,6 @@ export async function renderToHTMLOrFlight( ...@@ -969,7 +1004,6 @@ export async function renderToHTMLOrFlight(
} }
initialCanonicalUrl={initialCanonicalUrl} initialCanonicalUrl={initialCanonicalUrl}
initialTree={initialTree} initialTree={initialTree}
initialStylesheets={initialStylesheets}
> >
<ComponentTree /> <ComponentTree />
</AppRouter> </AppRouter>
......
...@@ -30,7 +30,6 @@ import { format as formatUrl, parse as parseUrl } from 'url' ...@@ -30,7 +30,6 @@ import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/redirect-status' import { getRedirectStatus } from '../lib/redirect-status'
import { import {
NEXT_BUILTIN_DOCUMENT, NEXT_BUILTIN_DOCUMENT,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
SERVER_DIRECTORY, SERVER_DIRECTORY,
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
...@@ -211,6 +210,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -211,6 +210,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected appPathRoutes?: Record<string, string> protected appPathRoutes?: Record<string, string>
protected customRoutes: CustomRoutes protected customRoutes: CustomRoutes
protected serverComponentManifest?: any protected serverComponentManifest?: any
protected serverCSSManifest?: any
public readonly hostname?: string public readonly hostname?: string
public readonly port?: number public readonly port?: number
...@@ -245,6 +245,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -245,6 +245,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getRoutesManifest(): CustomRoutes protected abstract getRoutesManifest(): CustomRoutes
protected abstract getPrerenderManifest(): PrerenderManifest protected abstract getPrerenderManifest(): PrerenderManifest
protected abstract getServerComponentManifest(): any protected abstract getServerComponentManifest(): any
protected abstract getServerCSSManifest(): any
protected abstract attachRequestMeta( protected abstract attachRequestMeta(
req: BaseNextRequest, req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
...@@ -331,6 +332,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -331,6 +332,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.serverComponentManifest = serverComponents this.serverComponentManifest = serverComponents
? this.getServerComponentManifest() ? this.getServerComponentManifest()
: undefined : undefined
this.serverCSSManifest = serverComponents
? this.getServerCSSManifest()
: undefined
this.renderOpts = { this.renderOpts = {
poweredByHeader: this.nextConfig.poweredByHeader, poweredByHeader: this.nextConfig.poweredByHeader,
...@@ -1046,9 +1050,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1046,9 +1050,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const appPathRoutes: Record<string, string> = {} const appPathRoutes: Record<string, string> = {}
Object.keys(this.appPathsManifest || {}).forEach((entry) => { Object.keys(this.appPathsManifest || {}).forEach((entry) => {
if (entry.endsWith(NEXT_CLIENT_SSR_ENTRY_SUFFIX)) {
return
}
appPathRoutes[normalizeAppPath(entry) || '/'] = entry appPathRoutes[normalizeAppPath(entry) || '/'] = entry
}) })
return appPathRoutes return appPathRoutes
......
This diff is collapsed.
...@@ -30,6 +30,7 @@ import { ...@@ -30,6 +30,7 @@ import {
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
DEV_CLIENT_PAGES_MANIFEST, DEV_CLIENT_PAGES_MANIFEST,
DEV_MIDDLEWARE_MANIFEST, DEV_MIDDLEWARE_MANIFEST,
COMPILER_NAMES,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import Server, { WrappedBuildError } from '../next-server' import Server, { WrappedBuildError } from '../next-server'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
...@@ -376,7 +377,7 @@ export default class DevServer extends Server { ...@@ -376,7 +377,7 @@ export default class DevServer extends Server {
continue continue
} }
runDependingOnPageType({ await runDependingOnPageType({
page: pageName, page: pageName,
pageRuntime: staticInfo.runtime, pageRuntime: staticInfo.runtime,
onClient: () => {}, onClient: () => {},
...@@ -836,7 +837,7 @@ export default class DevServer extends Server { ...@@ -836,7 +837,7 @@ export default class DevServer extends Server {
const src = getErrorSource(err as Error) const src = getErrorSource(err as Error)
const compilation = ( const compilation = (
src === 'edge-server' src === COMPILER_NAMES.edgeServer
? this.hotReloader?.edgeServerStats?.compilation ? this.hotReloader?.edgeServerStats?.compilation
: this.hotReloader?.serverStats?.compilation : this.hotReloader?.serverStats?.compilation
)! )!
...@@ -865,7 +866,7 @@ export default class DevServer extends Server { ...@@ -865,7 +866,7 @@ export default class DevServer extends Server {
Log[type === 'warning' ? 'warn' : 'error']( Log[type === 'warning' ? 'warn' : 'error'](
`${file} (${lineNumber}:${column}) @ ${methodName}` `${file} (${lineNumber}:${column}) @ ${methodName}`
) )
if (src === 'edge-server') { if (src === COMPILER_NAMES.edgeServer) {
err = err.message err = err.message
} }
if (type === 'warning') { if (type === 'warning') {
...@@ -939,6 +940,10 @@ export default class DevServer extends Server { ...@@ -939,6 +940,10 @@ export default class DevServer extends Server {
return undefined return undefined
} }
protected getServerCSSManifest() {
return undefined
}
protected async hasMiddleware(): Promise<boolean> { protected async hasMiddleware(): Promise<boolean> {
return this.hasPage(this.actualMiddlewareFile!) return this.hasPage(this.actualMiddlewareFile!)
} }
...@@ -1123,7 +1128,7 @@ export default class DevServer extends Server { ...@@ -1123,7 +1128,7 @@ export default class DevServer extends Server {
} }
} }
protected async ensureApiPage(pathname: string) { protected async ensureApiPage(pathname: string): Promise<void> {
return this.hotReloader!.ensurePage(pathname) return this.hotReloader!.ensurePage(pathname)
} }
...@@ -1148,6 +1153,7 @@ export default class DevServer extends Server { ...@@ -1148,6 +1153,7 @@ export default class DevServer extends Server {
// manifest. // manifest.
if (serverComponents) { if (serverComponents) {
this.serverComponentManifest = super.getServerComponentManifest() this.serverComponentManifest = super.getServerComponentManifest()
this.serverCSSManifest = super.getServerCSSManifest()
} }
return super.findPageComponents(pathname, query, params, isAppDir) return super.findPageComponents(pathname, query, params, isAppDir)
......
...@@ -13,13 +13,11 @@ import { ...@@ -13,13 +13,11 @@ import {
BUILD_MANIFEST, BUILD_MANIFEST,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
FLIGHT_MANIFEST, FLIGHT_MANIFEST,
NEXT_CLIENT_SSR_ENTRY_SUFFIX,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { join } from 'path' import { join } from 'path'
import { requirePage, getPagePath } from './require' import { requirePage, getPagePath } from './require'
import { BuildManifest } from './get-page-files' import { BuildManifest } from './get-page-files'
import { interopDefault } from '../lib/interop-default' import { interopDefault } from '../lib/interop-default'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
export type ManifestItem = { export type ManifestItem = {
id: number | string id: number | string
...@@ -122,22 +120,6 @@ export async function loadComponents( ...@@ -122,22 +120,6 @@ export async function loadComponents(
: null, : null,
]) ])
if (hasServerComponents) {
try {
// Make sure to also load the client entry in cache.
const __client__ = await requirePage(
normalizePagePath(pathname) + NEXT_CLIENT_SSR_ENTRY_SUFFIX,
distDir,
serverless,
appDirEnabled
)
ComponentMod.__client__ = __client__
} catch (_) {
// This page might not be a server component page, so there is no
// client entry to load.
}
}
const Component = interopDefault(ComponentMod) const Component = interopDefault(ComponentMod)
const Document = interopDefault(DocumentMod) const Document = interopDefault(DocumentMod)
const App = interopDefault(AppMod) const App = interopDefault(AppMod)
......
...@@ -38,6 +38,7 @@ import { ...@@ -38,6 +38,7 @@ import {
FLIGHT_MANIFEST, FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
APP_PATHS_MANIFEST, APP_PATHS_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync' import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { format as formatUrl, UrlWithParsedQuery } from 'url' import { format as formatUrl, UrlWithParsedQuery } from 'url'
...@@ -642,6 +643,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -642,6 +643,7 @@ export default class NextNodeServer extends BaseServer {
// object here but only updating its `serverComponentManifest` field. // object here but only updating its `serverComponentManifest` field.
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952 // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.serverComponentManifest = this.serverComponentManifest renderOpts.serverComponentManifest = this.serverComponentManifest
renderOpts.serverCSSManifest = this.serverCSSManifest
if ( if (
this.nextConfig.experimental.appDir && this.nextConfig.experimental.appDir &&
...@@ -787,6 +789,15 @@ export default class NextNodeServer extends BaseServer { ...@@ -787,6 +789,15 @@ export default class NextNodeServer extends BaseServer {
return require(join(this.distDir, 'server', FLIGHT_MANIFEST + '.json')) return require(join(this.distDir, 'server', FLIGHT_MANIFEST + '.json'))
} }
protected getServerCSSManifest() {
if (!this.nextConfig.experimental.serverComponents) return undefined
return require(join(
this.distDir,
'server',
FLIGHT_SERVER_CSS_MANIFEST + '.json'
))
}
protected getCacheFilesystem(): CacheFs { protected getCacheFilesystem(): CacheFs {
return { return {
readFile: (f) => fs.promises.readFile(f, 'utf8'), readFile: (f) => fs.promises.readFile(f, 'utf8'),
......
...@@ -136,6 +136,18 @@ export function createFlushEffectStream( ...@@ -136,6 +136,18 @@ export function createFlushEffectStream(
}) })
} }
export function renderToInitialStream({
ReactDOMServer,
element,
streamOptions,
}: {
ReactDOMServer: any
element: React.ReactElement
streamOptions?: any
}): Promise<ReactReadableStream> {
return ReactDOMServer.renderToReadableStream(element, streamOptions)
}
export function createHeadInjectionTransformStream( export function createHeadInjectionTransformStream(
inject: () => string inject: () => string
): TransformStream<Uint8Array, Uint8Array> { ): TransformStream<Uint8Array, Uint8Array> {
...@@ -156,18 +168,6 @@ export function createHeadInjectionTransformStream( ...@@ -156,18 +168,6 @@ export function createHeadInjectionTransformStream(
}) })
} }
export function renderToInitialStream({
ReactDOMServer,
element,
streamOptions,
}: {
ReactDOMServer: any
element: React.ReactElement
streamOptions?: any
}): Promise<ReactReadableStream> {
return ReactDOMServer.renderToReadableStream(element, streamOptions)
}
export async function continueFromInitialStream( export async function continueFromInitialStream(
renderStream: ReactReadableStream, renderStream: ReactReadableStream,
{ {
......
...@@ -40,6 +40,7 @@ import { ...@@ -40,6 +40,7 @@ import {
UNSTABLE_REVALIDATE_RENAME_ERROR, UNSTABLE_REVALIDATE_RENAME_ERROR,
} from '../lib/constants' } from '../lib/constants'
import { import {
COMPILER_NAMES,
NEXT_BUILTIN_DOCUMENT, NEXT_BUILTIN_DOCUMENT,
SERVER_PROPS_ID, SERVER_PROPS_ID,
STATIC_PROPS_ID, STATIC_PROPS_ID,
...@@ -229,6 +230,7 @@ export type RenderOptsPartial = { ...@@ -229,6 +230,7 @@ export type RenderOptsPartial = {
resolvedUrl?: string resolvedUrl?: string
resolvedAsPath?: string resolvedAsPath?: string
serverComponentManifest?: any serverComponentManifest?: any
serverCSSManifest?: any
distDir?: string distDir?: string
locale?: string locale?: string
locales?: string[] locales?: string[]
...@@ -1491,7 +1493,8 @@ export async function renderToHTML( ...@@ -1491,7 +1493,8 @@ export async function renderToHTML(
} }
function errorToJSON(err: Error) { function errorToJSON(err: Error) {
let source: 'server' | 'edge-server' = 'server' let source: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer =
'server'
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
source = source =
...@@ -1511,7 +1514,10 @@ function errorToJSON(err: Error) { ...@@ -1511,7 +1514,10 @@ function errorToJSON(err: Error) {
function serializeError( function serializeError(
dev: boolean | undefined, dev: boolean | undefined,
err: Error err: Error
): Error & { statusCode?: number; source?: 'edge-server' | 'server' } { ): Error & {
statusCode?: number
source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer
} {
if (dev) { if (dev) {
return errorToJSON(err) return errorToJSON(err)
} }
......
...@@ -127,6 +127,10 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -127,6 +127,10 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
// @TODO: Need to return `extendRenderOpts.serverComponentManifest` here. // @TODO: Need to return `extendRenderOpts.serverComponentManifest` here.
return undefined return undefined
} }
protected getServerCSSManifest() {
// TODO-APP: Support web server.
return undefined
}
protected async renderHTML( protected async renderHTML(
req: WebNextRequest, req: WebNextRequest,
_res: WebNextResponse, _res: WebNextResponse,
......
...@@ -3,7 +3,10 @@ import { ...@@ -3,7 +3,10 @@ import {
decorateServerError, decorateServerError,
getServerError, getServerError,
} from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware' } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { EDGE_UNSUPPORTED_NODE_APIS } from '../../../shared/lib/constants' import {
COMPILER_NAMES,
EDGE_UNSUPPORTED_NODE_APIS,
} from '../../../shared/lib/constants'
import { EdgeRuntime } from 'next/dist/compiled/edge-runtime' import { EdgeRuntime } from 'next/dist/compiled/edge-runtime'
import { readFileSync, promises as fs } from 'fs' import { readFileSync, promises as fs } from 'fs'
import { validateURL } from '../utils' import { validateURL } from '../utils'
...@@ -126,7 +129,7 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -126,7 +129,7 @@ async function createModuleContext(options: ModuleContextOptions) {
new Error( new Error(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime` `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
), ),
'edge-server' COMPILER_NAMES.edgeServer
) )
warning.name = 'DynamicCodeEvaluationWarning' warning.name = 'DynamicCodeEvaluationWarning'
Error.captureStackTrace(warning, __next_eval__) Error.captureStackTrace(warning, __next_eval__)
...@@ -143,7 +146,7 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -143,7 +146,7 @@ async function createModuleContext(options: ModuleContextOptions) {
const warning = getServerError( const warning = getServerError(
new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime. new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`), Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server' COMPILER_NAMES.edgeServer
) )
warning.name = 'DynamicWasmCodeGenerationWarning' warning.name = 'DynamicWasmCodeGenerationWarning'
Error.captureStackTrace(warning, __next_webassembly_compile__) Error.captureStackTrace(warning, __next_webassembly_compile__)
...@@ -170,7 +173,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation ...@@ -170,7 +173,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
const warning = getServerError( const warning = getServerError(
new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime. new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`), Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server' COMPILER_NAMES.edgeServer
) )
warning.name = 'DynamicWasmCodeGenerationWarning' warning.name = 'DynamicWasmCodeGenerationWarning'
Error.captureStackTrace(warning, __next_webassembly_instantiate__) Error.captureStackTrace(warning, __next_webassembly_instantiate__)
...@@ -334,7 +337,7 @@ function throwUnsupportedAPIError(name: string) { ...@@ -334,7 +337,7 @@ function throwUnsupportedAPIError(name: string) {
const error = const error =
new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime. new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
decorateServerError(error, 'edge-server') decorateServerError(error, COMPILER_NAMES.edgeServer)
throw error throw error
} }
...@@ -342,7 +345,7 @@ function getDecorateUnhandledError(runtime: EdgeRuntime) { ...@@ -342,7 +345,7 @@ function getDecorateUnhandledError(runtime: EdgeRuntime) {
const EdgeRuntimeError = runtime.evaluate(`Error`) const EdgeRuntimeError = runtime.evaluate(`Error`)
return (error: any) => { return (error: any) => {
if (error instanceof EdgeRuntimeError) { if (error instanceof EdgeRuntimeError) {
decorateServerError(error, 'edge-server') decorateServerError(error, COMPILER_NAMES.edgeServer)
} }
} }
} }
...@@ -75,10 +75,12 @@ function withTaggedErrors(fn: RunnerFn): RunnerFn { ...@@ -75,10 +75,12 @@ function withTaggedErrors(fn: RunnerFn): RunnerFn {
.then((result) => ({ .then((result) => ({
...result, ...result,
waitUntil: result?.waitUntil?.catch((error) => { waitUntil: result?.waitUntil?.catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.
throw getServerError(error, 'edge-server') throw getServerError(error, 'edge-server')
}), }),
})) }))
.catch((error) => { .catch((error) => {
// TODO: used COMPILER_NAMES.edgeServer instead
throw getServerError(error, 'edge-server') throw getServerError(error, 'edge-server')
}) })
} }
...@@ -62,7 +62,6 @@ export const LayoutRouterContext = React.createContext<{ ...@@ -62,7 +62,6 @@ export const LayoutRouterContext = React.createContext<{
childNodes: CacheNode['parallelRoutes'] childNodes: CacheNode['parallelRoutes']
tree: FlightRouterState tree: FlightRouterState
url: string url: string
stylesheets?: string[]
}>(null as any) }>(null as any)
export const GlobalLayoutRouterContext = React.createContext<{ export const GlobalLayoutRouterContext = React.createContext<{
tree: FlightRouterState tree: FlightRouterState
......
type ValueOf<T> = Required<T>[keyof T]
export const COMPILER_NAMES = {
client: 'client',
server: 'server',
edgeServer: 'edge-server',
} as const
export type CompilerNameValues = ValueOf<typeof COMPILER_NAMES>
export const COMPILER_INDEXES: {
[compilerKey in CompilerNameValues]: number
} = {
[COMPILER_NAMES.client]: 0,
[COMPILER_NAMES.server]: 1,
[COMPILER_NAMES.edgeServer]: 2,
} as const
export const PHASE_EXPORT = 'phase-export' export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build' export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server' export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
...@@ -40,6 +58,8 @@ export const NEXT_CLIENT_SSR_ENTRY_SUFFIX = '.__sc_client__' ...@@ -40,6 +58,8 @@ export const NEXT_CLIENT_SSR_ENTRY_SUFFIX = '.__sc_client__'
// server/flight-manifest.js // server/flight-manifest.js
export const FLIGHT_MANIFEST = 'flight-manifest' export const FLIGHT_MANIFEST = 'flight-manifest'
// server/flight-server-css-manifest.json
export const FLIGHT_SERVER_CSS_MANIFEST = 'flight-server-css-manifest'
// server/middleware-build-manifest.js // server/middleware-build-manifest.js
export const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest' export const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest'
// server/middleware-react-loadable-manifest.js // server/middleware-react-loadable-manifest.js
...@@ -56,7 +76,10 @@ export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp` ...@@ -56,7 +76,10 @@ export const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`
// static/runtime/webpack.js // static/runtime/webpack.js
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack` export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`
// static/runtime/polyfills.js // static/runtime/polyfills.js
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(`polyfills`) export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills'
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS
)
export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack' export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'
export const TEMPORARY_REDIRECT_STATUS = 307 export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308 export const PERMANENT_REDIRECT_STATUS = 308
......
...@@ -6,6 +6,7 @@ import type { IncomingMessage, ServerResponse } from 'http' ...@@ -6,6 +6,7 @@ import type { IncomingMessage, ServerResponse } from 'http'
import type { NextRouter } from './router/router' import type { NextRouter } from './router/router'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { PreviewData } from 'next/types' import type { PreviewData } from 'next/types'
import { COMPILER_NAMES } from './constants'
export type NextComponentType< export type NextComponentType<
C extends BaseContext = NextPageContext, C extends BaseContext = NextPageContext,
...@@ -92,7 +93,10 @@ export type NEXT_DATA = { ...@@ -92,7 +93,10 @@ export type NEXT_DATA = {
autoExport?: boolean autoExport?: boolean
isFallback?: boolean isFallback?: boolean
dynamicIds?: (string | number)[] dynamicIds?: (string | number)[]
err?: Error & { statusCode?: number; source?: 'server' | 'edge-server' } err?: Error & {
statusCode?: number
source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer
}
gsp?: boolean gsp?: boolean
gssp?: boolean gssp?: boolean
customServer?: boolean customServer?: boolean
......
import './style2.css'
export default function ServerLayout({ children }) {
return <>{children}</>
}
import './style.css'
export default function Page() {
return <h1>Page</h1>
}
import './style.module.css'
import './style.css' import './style.css'
import './css-page/style.css'
import styles from './style.module.css' import styles from './style.module.css'
export default function ServerLayout({ children }) { export default function ServerLayout({ children }) {
......
import '../styles/global.css' import '../styles/global.css'
import './style.css'
export async function getServerSideProps() { export async function getServerSideProps() {
return { return {
......
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