Unverified Commit 295f9da3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Client directive (#40415)

## Feature
Change server components convention from using `.server.js` / `.client.js` file extension to determine it's a server or client component to using `'client'` js literal as a directive for determine client components boundary.
React RFC: https://github.com/reactjs/rfcs/pull/189
New behavior doesn't consume `.server.js` as server components any more, if you're enabling `serverComponents` flag, every `page.js` in app dir will become server components by default. If you adding a `'client'` directive to the page, then that page will become a client component. This rule also applies to the normal js components, client components will require a `'client'` directive to indicate its identity, instead of having a `.client.js` extension.
- [x] 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`
- [x] 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`
Co-authored-by: 's avatarShu Ding <3676859+shuding@users.noreply.github.com>
parent f0ed328b
......@@ -13,6 +13,7 @@ import { SERVER_RUNTIME } from '../../lib/constants'
import { ServerRuntime } from 'next/types'
import { checkCustomRoutes } from '../../lib/load-custom-routes'
import { matcher } from 'next/dist/compiled/micromatch'
import { RSC_MODULE_TYPES } from '../../shared/lib/constants'
export interface MiddlewareConfig {
matchers: MiddlewareMatcher[]
......@@ -29,9 +30,18 @@ export interface PageStaticInfo {
runtime?: ServerRuntime
ssg?: boolean
ssr?: boolean
rsc?: RSCModuleType
middleware?: Partial<MiddlewareConfig>
}
const CLIENT_MODULE_LABEL = `/* __next_internal_client_entry_do_not_use__ */`
export type RSCModuleType = 'server' | 'client'
export function getRSCModuleType(source: string): RSCModuleType {
return source.includes(CLIENT_MODULE_LABEL)
? RSC_MODULE_TYPES.client
: RSC_MODULE_TYPES.server
}
/**
* Receives a parsed AST from SWC and checks if it belongs to a module that
* requires a runtime to be specified. Those are:
......@@ -252,6 +262,7 @@ export async function getPageStaticInfo(params: {
) {
const swcAST = await parseModule(pageFilePath, fileContent)
const { ssg, ssr } = checkExports(swcAST)
const rsc = getRSCModuleType(fileContent)
// default / failsafe value for config
let config: any = {}
......@@ -303,10 +314,16 @@ export async function getPageStaticInfo(params: {
return {
ssr,
ssg,
rsc,
...(middlewareConfig && { middleware: middlewareConfig }),
...(runtime && { runtime }),
}
}
return { ssr: false, ssg: false, runtime: nextConfig.experimental?.runtime }
return {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
runtime: nextConfig.experimental?.runtime,
}
}
......@@ -21,6 +21,7 @@ import {
SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants'
import { RSC_MODULE_TYPES } from '../shared/lib/constants'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
......@@ -37,14 +38,12 @@ import { warn } from './output/log'
import {
isMiddlewareFile,
isMiddlewareFilename,
isServerComponentPage,
NestedMiddlewareError,
MiddlewareInServerlessTargetError,
} from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { serverComponentRegex } from './webpack/loaders/utils'
import { ServerRuntime } from '../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
......@@ -66,14 +65,12 @@ export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
}
export function createPagesMapping({
hasServerComponents,
isDev,
pageExtensions,
pagePaths,
pagesType,
pagesDir,
}: {
hasServerComponents: boolean
isDev: boolean
pageExtensions: string[]
pagePaths: string[]
......@@ -90,13 +87,6 @@ export function createPagesMapping({
const pageKey = getPageFromPath(pagePath, pageExtensions)
// Assume that if there's a Client Component, that there is
// a matching Server Component that will map to the page.
// so we will not process it
if (hasServerComponents && /\.client$/.test(pageKey)) {
return result
}
if (pageKey in result) {
warn(
`Duplicate page detected. ${chalk.cyan(
......@@ -208,10 +198,7 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath,
buildId: opts.buildId,
dev: opts.isDev,
isServerComponent: isServerComponentPage(
opts.config,
opts.absolutePagePath
),
isServerComponent: opts.isServerComponent,
page: opts.page,
stringifiedConfig: JSON.stringify(opts.config),
pagesType: opts.pagesType,
......@@ -418,8 +405,10 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
nestedMiddleware.push(page)
}
const isServerComponent = serverComponentRegex.test(absolutePagePath)
const isInsideAppDir = appDir && absolutePagePath.startsWith(appDir)
const isInsideAppDir =
!!appDir &&
(absolutePagePath.startsWith(APP_DIR_ALIAS) ||
absolutePagePath.startsWith(appDir))
const staticInfo = await getPageStaticInfo({
nextConfig: config,
......@@ -428,6 +417,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
page,
})
const isServerComponent =
isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client
if (isMiddlewareFile(page)) {
middlewareMatchers = staticInfo.middleware?.matchers ?? [
{ regexp: '.*' },
......
......@@ -58,6 +58,7 @@ import {
COMPILER_NAMES,
APP_BUILD_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
RSC_MODULE_TYPES,
} from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
import { __ApiPreviewProps } from '../server/api-utils'
......@@ -96,7 +97,6 @@ import {
printTreeView,
copyTracedFiles,
isReservedPage,
isServerComponentPage,
} from './utils'
import getBaseWebpackConfig from './webpack-config'
import { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
......@@ -489,7 +489,6 @@ export default async function build(
.traceChild('create-pages-mapping')
.traceFn(() =>
createPagesMapping({
hasServerComponents,
isDev: false,
pageExtensions: config.pageExtensions,
pagesType: 'pages',
......@@ -506,7 +505,6 @@ export default async function build(
.traceFn(() =>
createPagesMapping({
pagePaths: appPaths!,
hasServerComponents,
isDev: false,
pagesType: 'app',
pageExtensions: config.pageExtensions,
......@@ -518,7 +516,6 @@ export default async function build(
let mappedRootPaths: { [page: string]: string } = {}
if (rootPaths.length > 0) {
mappedRootPaths = createPagesMapping({
hasServerComponents,
isDev: false,
pageExtensions: config.pageExtensions,
pagePaths: rootPaths,
......@@ -1267,21 +1264,17 @@ export default async function build(
)
: appPaths?.find((p) => p.startsWith(actualPage + '/page.'))
const pageRuntime =
const staticInfo =
pagesDir && pageType === 'pages' && pagePath
? (
await getPageStaticInfo({
pageFilePath: join(pagesDir, pagePath),
nextConfig: config,
})
).runtime
: undefined
if (hasServerComponents && pagePath) {
if (isServerComponentPage(config, pagePath)) {
isServerComponent = true
}
}
? await getPageStaticInfo({
pageFilePath: join(pagesDir, pagePath),
nextConfig: config,
})
: {}
const pageRuntime = staticInfo.runtime
isServerComponent =
pageType === 'app' &&
staticInfo.rsc !== RSC_MODULE_TYPES.client
if (
// Only calculate page static information if the page is not an
......
......@@ -1327,33 +1327,6 @@ export function detectConflictingPaths(
}
}
/**
* With RSC we automatically add .server and .client to page extensions. This
* function allows to remove them for cases where we just need to strip out
* the actual extension keeping the .server and .client.
*/
export function withoutRSCExtensions(pageExtensions: string[]): string[] {
return pageExtensions.filter(
(ext) => !ext.startsWith('client.') && !ext.startsWith('server.')
)
}
export function isServerComponentPage(
nextConfig: NextConfigComplete,
filePath: string
): boolean {
if (!nextConfig.experimental.serverComponents) {
return false
}
const rawPageExtensions = withoutRSCExtensions(
nextConfig.pageExtensions || []
)
return rawPageExtensions.some((ext) => {
return filePath.endsWith(`.server.${ext}`)
})
}
export async function copyTracedFiles(
dir: string,
distDir: string,
......
......@@ -56,7 +56,6 @@ import type {
} from './webpack/plugins/telemetry-plugin'
import type { Span } from '../trace'
import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import { withoutRSCExtensions } from './utils'
import browserslist from 'next/dist/compiled/browserslist'
import loadJsConfig from './load-jsconfig'
import { loadBindings } from './swc'
......@@ -687,13 +686,7 @@ export default async function getBaseWebpackConfig(
babel: getBabelOrSwcLoader(),
}
const rawPageExtensions = hasServerComponents
? withoutRSCExtensions(config.pageExtensions)
: config.pageExtensions
const serverComponentsRegex = new RegExp(
`\\.server\\.(${rawPageExtensions.join('|')})$`
)
const pageExtensions = config.pageExtensions
const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/]shared[\\/]lib/,
......@@ -801,7 +794,7 @@ export default async function getBaseWebpackConfig(
if (dev) {
customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [
...(pagesDir
? rawPageExtensions.reduce((prev, ext) => {
? pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.${ext}`))
return prev
}, [] as string[])
......@@ -810,7 +803,7 @@ export default async function getBaseWebpackConfig(
]
customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [
...(pagesDir
? rawPageExtensions.reduce((prev, ext) => {
? pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_error.${ext}`))
return prev
}, [] as string[])
......@@ -819,7 +812,7 @@ export default async function getBaseWebpackConfig(
]
customDocumentAliases[`${PAGES_DIR_ALIAS}/_document`] = [
...(pagesDir
? rawPageExtensions.reduce((prev, ext) => {
? pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_document.${ext}`))
return prev
}, [] as string[])
......@@ -874,7 +867,7 @@ export default async function getBaseWebpackConfig(
...getReactProfilingInProduction(),
[RSC_MOD_REF_PROXY_ALIAS]:
'next/dist/build/webpack/loaders/next-flight-client-loader/module-proxy',
'next/dist/build/webpack/loaders/next-flight-loader/module-proxy',
...(isClient || isEdgeServer
? {
......@@ -1151,11 +1144,6 @@ export default async function getBaseWebpackConfig(
},
}
const serverComponentCodeCondition = {
test: serverComponentsRegex,
include: [dir, /next[\\/]dist[\\/]pages/],
}
const rscSharedRegex =
/(node_modules\/react\/|\/shared\/lib\/(head-manager-context|router-context|flush-effects)\.js|node_modules\/styled-jsx\/)/
......@@ -1451,8 +1439,7 @@ export default async function getBaseWebpackConfig(
'next-image-loader',
'next-serverless-loader',
'next-style-loader',
'next-flight-client-loader',
'next-flight-server-loader',
'next-flight-loader',
'next-flight-client-entry-loader',
'noop-loader',
'next-middleware-loader',
......@@ -1492,24 +1479,17 @@ export default async function getBaseWebpackConfig(
? [
// RSC server compilation loaders
{
...serverComponentCodeCondition,
test: codeCondition.test,
include: [
dir,
// To let the internal client components passing through flight loader
/next[\\/]dist[\\/]client[\\/]/,
],
issuerLayer: WEBPACK_LAYERS.server,
use: {
loader: 'next-flight-server-loader',
loader: 'next-flight-loader',
},
},
// {
// test: clientComponentRegex,
// issuerLayer: WEBPACK_LAYERS.server,
// use: {
// loader: 'next-flight-client-loader',
// },
// },
// _app should be treated as a client component as well as all its dependencies.
{
test: new RegExp(`_app\\.(${rawPageExtensions.join('|')})$`),
layer: WEBPACK_LAYERS.client,
},
]
: []
: []),
......@@ -1841,11 +1821,10 @@ export default async function getBaseWebpackConfig(
isClient &&
new AppBuildManifestPlugin({ dev }),
hasServerComponents &&
!!config.experimental.appDir &&
(isClient
? new FlightManifestPlugin({
dev,
appDir: !!config.experimental.appDir,
pageExtensions: rawPageExtensions,
})
: new FlightClientEntryPlugin({
dev,
......@@ -1995,7 +1974,7 @@ export default async function getBaseWebpackConfig(
const configVars = JSON.stringify({
crossOrigin: config.crossOrigin,
pageExtensions: rawPageExtensions,
pageExtensions: pageExtensions,
trailingSlash: config.trailingSlash,
buildActivity: config.devIndicators.buildActivity,
buildActivityPosition: config.devIndicators.buildActivityPosition,
......
......@@ -501,7 +501,7 @@ export const css = curry(async function css(
// If it's inside the app dir, but not importing from a layout file,
// throw an error.
and: [ctx.rootDirectory],
not: [/layout(\.client|\.server)?\.(js|mjs|jsx|ts|tsx)$/],
not: [/layout\.(js|mjs|jsx|ts|tsx)$/],
}
: undefined,
use: {
......
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import type {
MiddlewareMatcher,
RSCModuleType,
} from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack'
/**
......@@ -17,9 +20,15 @@ export function getModuleBuildInfo(webpackModule: webpack.Module) {
route?: RouteMeta
importLocByPath?: Map<string, any>
rootDir?: string
rsc?: RSCMeta
}
}
export interface RSCMeta {
type?: RSCModuleType
requests?: string[] // client requests in flight client entry
}
export interface RouteMeta {
page: string
absolutePagePath: string
......
......@@ -3,7 +3,6 @@ import { stringifyRequest } from '../stringify-request'
export type ClientPagesLoaderOptions = {
absolutePagePath: string
page: string
isServerComponent?: boolean
}
// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
......@@ -13,14 +12,12 @@ function nextClientPagesLoader(this: any) {
)
return pagesLoaderSpan.traceFn(() => {
const { absolutePagePath, page, isServerComponent } =
const { absolutePagePath, page } =
this.getOptions() as ClientPagesLoaderOptions
pagesLoaderSpan.setAttribute('absolutePagePath', absolutePagePath)
const stringifiedPageRequest = isServerComponent
? JSON.stringify(absolutePagePath + '!')
: stringifyRequest(this, absolutePagePath)
const stringifiedPageRequest = stringifyRequest(this, absolutePagePath)
const stringifiedPage = JSON.stringify(page)
return `
......
......@@ -118,7 +118,7 @@ export default async function edgeSSRLoader(this: any) {
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
})
export const ComponentMod = pageMod
export default function(opts) {
......
import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
import { getModuleBuildInfo } from './get-module-build-info'
export type ClientComponentImports = string[]
export type CssImports = Record<string, string[]>
......@@ -37,5 +40,11 @@ export default async function transformSource(this: any): Promise<string> {
export default function RSC() {};
`
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.rsc = {
type: RSC_MODULE_TYPES.client,
requests,
}
return code
}
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path'
import { checkExports } from '../../../analysis/get-page-static-info'
import { parse } from '../../../swc'
function containsPath(parent: string, child: string) {
const relation = path.relative(parent, child)
return !!relation && !relation.startsWith('..') && !path.isAbsolute(relation)
}
export default async function transformSource(
this: any,
source: string,
map: any
) {
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const callback = this.async()
const appDir = path.join(this.rootContext, 'app')
const isUnderAppDir = containsPath(appDir, this.resourcePath)
const filename = path.basename(this.resourcePath)
const isPageOrLayoutFile = /^(page|layout)\.client\.\w+$/.test(filename)
const createError = (name: string) =>
new Error(
`${name} is not supported in client components.\nFrom: ${this.resourcePath}`
)
if (isUnderAppDir && isPageOrLayoutFile) {
const swcAST = await parse(source, {
filename: this.resourcePath,
isModule: 'unknown',
})
const { ssg, ssr } = checkExports(swcAST)
if (ssg) {
this.emitError(createError('getStaticProps'))
}
if (ssr) {
this.emitError(createError('getServerSideProps'))
}
}
const output = `
const { createProxy } = require("private-next-rsc-mod-ref-proxy")\n
module.exports = createProxy(${JSON.stringify(this.resourcePath)})
`
// Pass empty sourcemap
callback(null, output, map)
return
}
import path from 'path'
import { RSC_MODULE_TYPES } from '../../../../shared/lib/constants'
import {
checkExports,
getRSCModuleType,
} from '../../../analysis/get-page-static-info'
import { parse } from '../../../swc'
import { getModuleBuildInfo } from '../get-module-build-info'
function transformServer(source: string, isESModule: boolean) {
return (
source +
(isESModule ? `export const __next_rsc__` : `exports.__next_rsc__`) +
` = { __webpack_require__, server: true }\n`
)
}
function containsPath(parent: string, child: string) {
const relation = path.relative(parent, child)
return !!relation && !relation.startsWith('..') && !path.isAbsolute(relation)
}
const isPageOrLayoutFile = (filePath: string) => {
const filename = path.basename(filePath)
return /[\\/]?(page|layout)\.(js|ts)x?$/.test(filename)
}
export default async function transformSource(
this: any,
source: string,
sourceMap: any
) {
// Avoid buffer to be consumed
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const { resourcePath } = this
const callback = this.async()
const buildInfo = getModuleBuildInfo(this._module)
const swcAST = await parse(source, {
filename: resourcePath,
isModule: 'unknown',
})
const rscType = getRSCModuleType(source)
const isModule = swcAST.type === 'Module'
const createError = (name: string) =>
new Error(
`${name} is not supported in client components.\nFrom: ${this.resourcePath}`
)
const appDir = path.join(this.rootContext, 'app')
const isUnderAppDir = containsPath(appDir, this.resourcePath)
const isResourcePageOrLayoutFile = isPageOrLayoutFile(this.resourcePath)
// If client entry has any gSSP/gSP data fetching methods, error
function errorForInvalidDataFetching(onError: (error: any) => void) {
if (isUnderAppDir && isResourcePageOrLayoutFile) {
const { ssg, ssr } = checkExports(swcAST)
if (ssg) {
onError(createError('getStaticProps'))
}
if (ssr) {
onError(createError('getServerSideProps'))
}
}
}
// Assign the RSC meta information to buildInfo.
// Exclude next internal files which are not marked as client files
buildInfo.rsc = { type: rscType }
if (buildInfo.rsc?.type === RSC_MODULE_TYPES.client) {
errorForInvalidDataFetching(this.emitError)
return callback(null, source, sourceMap)
}
const code = transformServer(source, isModule)
return callback(null, code, sourceMap)
}
import { parse } from '../../swc'
export default async function transformSource(
this: any,
source: string
): Promise<string> {
const { resourcePath } = this
const ast = await parse(source, {
filename: resourcePath,
isModule: 'unknown',
})
const isModule = ast.type === 'Module'
return (
source +
(isModule
? `
export const __next_rsc__ = {
__webpack_require__,
server: true
}
`
: `
exports.__next_rsc__ = {
__webpack_require__,
server: true
}
`)
)
}
import { getPageStaticInfo } from '../../analysis/get-page-static-info'
import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
export const defaultJsFileExtensions = ['js', 'mjs', 'jsx', 'ts', 'tsx']
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif']
const nextClientComponents = [
'dist/client/link',
'dist/client/image',
......@@ -11,46 +9,26 @@ const nextClientComponents = [
'dist/shared/lib/dynamic',
]
export function buildExports(moduleExports: any, isESM: boolean) {
let ret = ''
Object.keys(moduleExports).forEach((key) => {
const exportExpression = isESM
? `export ${key === 'default' ? key : `const ${key} =`} ${
moduleExports[key]
}`
: `exports.${key} = ${moduleExports[key]}`
ret += exportExpression + '\n'
})
return ret
}
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif']
const imageRegex = new RegExp(`\\.(${imageExtensions.join('|')})$`)
// Special cases for Next.js APIs that are considered as client components:
// - .client.[ext]
// - next built-in client components
// - .[imageExt]
export const clientComponentRegex = new RegExp(
'(' +
`\\.client(\\.(${defaultJsFileExtensions.join('|')}))?|` +
`next[\\\\/](${nextClientComponents.join('|')})(\\.js)?|` +
`\\.(${imageExtensions.join('|')})` +
')$'
const NEXT_API_CLIENT_RSC_REGEX = new RegExp(
`next[\\\\/](${nextClientComponents.join('|')})(\\.js)?`
)
export const serverComponentRegex = new RegExp(
`\\.server(\\.(${defaultJsFileExtensions.join('|')}))?$`
)
// Cover resource paths like `next/dist/client/*`
export function isNextBuiltInClientComponent(resource: string) {
return NEXT_API_CLIENT_RSC_REGEX.test(resource)
}
export async function loadEdgeFunctionConfigFromFile(
absolutePagePath: string,
resolve: (context: string, request: string) => Promise<string>
) {
const pageFilePath = await resolve('/', absolutePagePath)
export function isClientComponentModule(mod: {
resource: string
buildInfo: any
}) {
const hasClientDirective = mod.buildInfo.rsc?.type === RSC_MODULE_TYPES.client
return (
await getPageStaticInfo({
nextConfig: {},
pageFilePath,
isDev: false,
})
).middleware
isNextBuiltInClientComponent(mod.resource) ||
hasClientDirective ||
imageRegex.test(mod.resource)
)
}
import { stringify } from 'querystring'
import path from 'path'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { clientComponentRegex } from '../loaders/utils'
import {
getInvalidator,
entries,
......@@ -18,6 +17,7 @@ import {
FLIGHT_SERVER_CSS_MANIFEST,
} from '../../../shared/lib/constants'
import { FlightCSSManifest } from './flight-manifest-plugin'
import { isClientComponentModule } from '../loaders/utils'
interface Options {
dev: boolean
......@@ -131,10 +131,7 @@ export class FlightClientEntryPlugin {
: layoutOrPageRequest
// Replace file suffix as `.js` will be added.
const bundlePath = relativeRequest.replace(
/(\.server|\.client)?\.(js|ts)x?$/,
''
)
const bundlePath = relativeRequest.replace(/\.(js|ts)x?$/, '')
promises.push(
this.injectClientEntryAndSSRModules({
......@@ -240,7 +237,7 @@ export class FlightClientEntryPlugin {
visitedBySegment[layoutOrPageRequest].add(modRequest)
const isCSS = regexCSS.test(modRequest)
const isClientComponent = clientComponentRegex.test(modRequest)
const isClientComponent = isClientComponentModule(mod)
if (isCSS) {
serverCSSImports[layoutOrPageRequest] =
......
......@@ -7,8 +7,8 @@
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { FLIGHT_MANIFEST } from '../../../shared/lib/constants'
import { clientComponentRegex } from '../loaders/utils'
import { relative } from 'path'
import { isClientComponentModule } from '../loaders/utils'
// This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on.
......@@ -19,8 +19,6 @@ import { relative } from 'path'
interface Options {
dev: boolean
appDir: boolean
pageExtensions: string[]
}
/**
......@@ -64,13 +62,9 @@ const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin {
dev: Options['dev'] = false
pageExtensions: Options['pageExtensions']
appDir: Options['appDir'] = false
constructor(options: Options) {
this.dev = options.dev
this.appDir = options.appDir
this.pageExtensions = options.pageExtensions
}
apply(compiler: webpack.Compiler) {
......@@ -109,9 +103,36 @@ export class FlightManifestPlugin {
const manifest: FlightManifest = {
__ssr_module_mapping__: {},
}
const appDir = this.appDir
const dev = this.dev
const clientRequestsSet = new Set()
// Collect client requests
function collectClientRequest(mod: webpack.NormalModule) {
if (mod.resource === '' && mod.buildInfo.rsc) {
const { requests = [] } = mod.buildInfo.rsc
requests.forEach((r: string) => {
clientRequestsSet.add(require.resolve(r))
})
}
}
compilation.chunkGroups.forEach((chunkGroup) => {
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
chunk
// TODO: Update type so that it doesn't have to be cast.
) as Iterable<webpack.NormalModule>
for (const mod of chunkModules) {
collectClientRequest(mod)
const anyModule = mod as any
if (anyModule.modules) {
for (const subMod of anyModule.modules) collectClientRequest(subMod)
}
}
})
})
compilation.chunkGroups.forEach((chunkGroup) => {
const cssResourcesInChunkGroup = new Set<string>()
let entryFilepath: string = ''
......@@ -122,8 +143,9 @@ export class FlightManifestPlugin {
mod: webpack.NormalModule
) {
const isCSSModule =
mod.resource?.endsWith('.css') ||
mod.type === 'css/mini-extract' ||
(mod.loaders &&
(!!mod.loaders &&
(dev
? mod.loaders.some((item) =>
item.loader.includes('next-style-loader/index.js')
......@@ -138,7 +160,9 @@ export class FlightManifestPlugin {
mod._identifier.slice(mod._identifier.lastIndexOf('!') + 1)
: mod.resource
if (!resource) return
if (!resource) {
return
}
const moduleExports = manifest[resource] || {}
const moduleIdMapping = manifest.__ssr_module_mapping__
......@@ -173,14 +197,13 @@ export class FlightManifestPlugin {
return
}
// TODO: Hook into deps instead of the target module.
// That way we know by the type of dep whether to include.
// It also resolves conflicts when the same module is in multiple chunks.
if (!clientComponentRegex.test(resource)) {
// Only apply following logic to client module requests from client entry,
// or if the module is marked as client module.
if (!clientRequestsSet.has(resource) && !isClientComponentModule(mod)) {
return
}
if (/\/(page|layout)\.client\.(ts|js)x?$/.test(resource)) {
if (/[\\/](page|layout)\.(ts|js)x?$/.test(resource)) {
entryFilepath = resource
}
......@@ -207,6 +230,17 @@ export class FlightManifestPlugin {
]),
]
function getAppPathRequiredChunks() {
return chunkGroup.chunks.map((requiredChunk: webpack.Chunk) => {
return (
requiredChunk.id +
':' +
(requiredChunk.name || requiredChunk.id) +
(dev ? '' : '-' + requiredChunk.hash)
)
})
}
const moduleExportedKeys = ['', '*']
.concat(
[...exportsInfo.exports]
......@@ -217,29 +251,10 @@ export class FlightManifestPlugin {
.filter((name) => name !== null)
moduleExportedKeys.forEach((name) => {
let requiredChunks: ManifestChunks = []
if (!moduleExports[name]) {
const isRelatedChunk = (c: webpack.Chunk) => {
// If current chunk is a page, it should require the related page chunk;
// If current chunk is a component, it should filter out the related page chunk;
return (
chunk.name?.startsWith('pages/') ||
!c.name?.startsWith('pages/')
)
}
if (appDir) {
requiredChunks = chunkGroup.chunks
.filter(isRelatedChunk)
.map((requiredChunk: webpack.Chunk) => {
return (
requiredChunk.id +
':' +
(requiredChunk.name || requiredChunk.id) +
(dev ? '' : '-' + requiredChunk.hash)
)
})
}
// If the chunk is from `app/` chunkGroup, use it first.
// This make sure not to load the overlapped chunk from `pages/` chunkGroup
if (!moduleExports[name] || chunkGroup.name?.startsWith('app/')) {
const requiredChunks = getAppPathRequiredChunks()
moduleExports[name] = {
id,
......@@ -249,11 +264,9 @@ export class FlightManifestPlugin {
}
moduleIdMapping[id] = moduleIdMapping[id] || {}
if (!moduleIdMapping[id][name]) {
moduleIdMapping[id][name] = {
...moduleExports[name],
id: ssrNamedModuleId,
}
moduleIdMapping[id][name] = {
...moduleExports[name],
id: ssrNamedModuleId,
}
})
......
......@@ -25,7 +25,7 @@ import {
FlightCSSManifest,
FlightManifest,
} from '../build/webpack/plugins/flight-manifest-plugin'
import { FlushEffectsContext } from '../client/components/hooks-client'
import { FlushEffectsContext } from '../shared/lib/flush-effects'
import { stripInternalQueries } from './internal-utils'
import type { ComponentsType } from '../build/webpack/loaders/next-app-loader'
......
......@@ -20,7 +20,11 @@ import * as Log from '../../build/output/log'
import getBaseWebpackConfig from '../../build/webpack-config'
import { APP_DIR_ALIAS } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete'
import { BLOCKED_PAGES, COMPILER_NAMES } from '../../shared/lib/constants'
import {
BLOCKED_PAGES,
COMPILER_NAMES,
RSC_MODULE_TYPES,
} from '../../shared/lib/constants'
import { __ApiPreviewProps } from '../api-utils'
import { getPathMatch } from '../../shared/lib/router/utils/path-match'
import { findPageFile } from '../lib/find-page-file'
......@@ -35,18 +39,13 @@ import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { fileExists } from '../../lib/file-exists'
import {
difference,
withoutRSCExtensions,
isMiddlewareFilename,
} from '../../build/utils'
import { difference, isMiddlewareFilename } from '../../build/utils'
import { DecodeError } from '../../shared/lib/utils'
import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws'
import { promises as fs } from 'fs'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { serverComponentRegex } from '../../build/webpack/loaders/utils'
import { UnwrapPromise } from '../../lib/coalesced-function'
function diff(a: Set<any>, b: Set<any>) {
......@@ -404,9 +403,7 @@ export default class HotReloader {
private async getWebpackConfig(span: Span) {
const webpackConfigSpan = span.traceChild('get-webpack-config')
const rawPageExtensions = this.hasServerComponents
? withoutRSCExtensions(this.config.pageExtensions)
: this.config.pageExtensions
const pageExtensions = this.config.pageExtensions
return webpackConfigSpan.traceAsyncFn(async () => {
const pagePaths = !this.pagesDir
......@@ -415,11 +412,11 @@ export default class HotReloader {
.traceChild('get-page-paths')
.traceAsyncFn(() =>
Promise.all([
findPageFile(this.pagesDir!, '/_app', rawPageExtensions, false),
findPageFile(this.pagesDir!, '/_app', pageExtensions, false),
findPageFile(
this.pagesDir!,
'/_document',
rawPageExtensions,
pageExtensions,
false
),
])
......@@ -429,7 +426,6 @@ export default class HotReloader {
.traceChild('create-pages-mapping')
.traceFn(() =>
createPagesMapping({
hasServerComponents: this.hasServerComponents,
isDev: true,
pageExtensions: this.config.pageExtensions,
pagesType: 'pages',
......@@ -444,6 +440,7 @@ export default class HotReloader {
.traceChild('create-entrypoints')
.traceAsyncFn(() =>
createEntrypoints({
appDir: this.appDir,
buildId: this.buildId,
config: this.config,
envFiles: [],
......@@ -511,6 +508,7 @@ export default class HotReloader {
isDevFallback: true,
entrypoints: (
await createEntrypoints({
appDir: this.appDir,
buildId: this.buildId,
config: this.config,
envFiles: [],
......@@ -598,10 +596,7 @@ export default class HotReloader {
}
}
const isServerComponent = isEntry
? serverComponentRegex.test(entryData.absolutePagePath)
: false
const isAppPath = !!this.appDir && bundlePath.startsWith('app/')
const staticInfo = isEntry
? await getPageStaticInfo({
pageFilePath: entryData.absolutePagePath,
......@@ -609,6 +604,8 @@ export default class HotReloader {
isDev: true,
})
: {}
const isServerComponent =
isAppPath && staticInfo.rsc !== RSC_MODULE_TYPES.client
await runDependingOnPageType({
page,
......@@ -616,9 +613,8 @@ export default class HotReloader {
onEdgeServer: () => {
// TODO-APP: verify if child entry should support.
if (!isEdgeServerCompilation || !isEntry) return
const isApp = this.appDir && bundlePath.startsWith('app/')
const appDirLoader =
isApp && this.appDir
isAppPath && this.appDir
? getAppEntry({
name: bundlePath,
appPaths: entryData.appPaths,
......@@ -649,7 +645,7 @@ export default class HotReloader {
pages: this.pagesMapping,
isServerComponent,
appDirLoader,
pagesType: isApp ? 'app' : undefined,
pagesType: isAppPath ? 'app' : undefined,
}),
appDir: this.config.experimental.appDir,
})
......
......@@ -12,7 +12,6 @@ import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-sl
import { removePagePathTail } from '../../shared/lib/page-path/remove-page-path-tail'
import { reportTrigger } from '../../build/output'
import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { serverComponentRegex } from '../../build/webpack/loaders/utils'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { isMiddlewareFile, isMiddlewareFilename } from '../../build/utils'
import { PageNotFoundError } from '../../shared/lib/utils'
......@@ -21,6 +20,7 @@ import {
CompilerNameValues,
COMPILER_INDEXES,
COMPILER_NAMES,
RSC_MODULE_TYPES,
} from '../../shared/lib/constants'
const debug = origDebug('next:on-demand-entry-handler')
......@@ -578,11 +578,8 @@ export function onDemandEntryHandler({
appDir
)
const isServerComponent = serverComponentRegex.test(
pagePathData.absolutePagePath
)
const isInsideAppDir =
appDir && pagePathData.absolutePagePath.startsWith(appDir)
!!appDir && pagePathData.absolutePagePath.startsWith(appDir)
const addEntry = (
compilerType: CompilerNameValues
......@@ -636,6 +633,8 @@ export function onDemandEntryHandler({
})
const added = new Map<CompilerNameValues, ReturnType<typeof addEntry>>()
const isServerComponent =
isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client
await runDependingOnPageType({
page: pagePathData.page,
......
......@@ -96,6 +96,11 @@ export const DEFAULT_SANS_SERIF_FONT = 'Arial'
export const STATIC_STATUS_PAGES = ['/500']
export const TRACE_OUTPUT_VERSION = 1
export const RSC_MODULE_TYPES = {
client: 'client',
server: 'server',
} as const
// comparing
// https://nextjs.org/docs/api-reference/edge-runtime
// with
......
......@@ -114,7 +114,7 @@ module.exports = function (task) {
// Make sure the output content keeps the `"client"` directive.
// TODO: Remove this once SWC fixes the issue.
if (source.startsWith("'client'")) {
if (/^['"]client['"]/.test(source)) {
output.code = '"client";\n' + output.code
}
......
......@@ -2,7 +2,7 @@
import dynamic from 'next/dist/client/components/shared/dynamic'
const Dynamic = dynamic(() => import('../text-dynamic.client'))
const Dynamic = dynamic(() => import('../text-dynamic-client'))
export function NextDynamicClientComponent() {
return <Dynamic />
......
import dynamic from 'next/dist/client/components/shared/dynamic'
const Dynamic = dynamic(() => import('../text-dynamic.server'))
const Dynamic = dynamic(() => import('../text-dynamic-server'))
export function NextDynamicServerComponent() {
return <Dynamic />
......
......@@ -2,7 +2,7 @@
import { useState, lazy } from 'react'
const Lazy = lazy(() => import('../text-lazy.client.js'))
const Lazy = lazy(() => import('../text-lazy-client.js'))
export function LazyClientComponent() {
let [state] = useState('client')
......
import { LazyClientComponent } from './dynamic-imports/react-lazy.client'
import { NextDynamicServerComponent } from './dynamic-imports/dynamic.server'
import { NextDynamicClientComponent } from './dynamic-imports/dynamic.client'
import { LazyClientComponent } from './dynamic-imports/react-lazy-client'
import { NextDynamicServerComponent } from './dynamic-imports/dynamic-server'
import { NextDynamicClientComponent } from './dynamic-imports/dynamic-client'
export default function DashboardIndexPage() {
return (
......
import ClientComp from './client-comp.client'
import ClientComp from './client-comp-client'
export default function DashboardPage(props) {
return (
<>
......
This diff is collapsed.
This diff is collapsed.
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