Unverified Commit e8a8220d authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Tweak routing tests (#36667)

Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent da8d1984
......@@ -14,8 +14,7 @@ import {
API_ROUTE,
DOT_NEXT_ALIAS,
PAGES_DIR_ALIAS,
ROOT_ALIAS,
ROOT_DIR_ALIAS,
VIEWS_DIR_ALIAS,
} from '../lib/constants'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
......@@ -40,11 +39,7 @@ type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
* special case because it is the only page where we want to preserve the RSC
* server extension.
*/
export function getPageFromPath(
pagePath: string,
pageExtensions: string[],
isRoot?: boolean
) {
export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
const extensions = pagePath.includes('/_app.server.')
? withoutRSCExtensions(pageExtensions)
: pageExtensions
......@@ -53,9 +48,7 @@ export function getPageFromPath(
pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '')
)
if (!isRoot) {
page = page.replace(/\/index$/, '')
}
page = page.replace(/\/index$/, '')
return page === '' ? '/' : page
}
......@@ -63,18 +56,18 @@ export function getPageFromPath(
export function createPagesMapping({
hasServerComponents,
isDev,
isRoot,
isViews,
pageExtensions,
pagePaths,
}: {
hasServerComponents: boolean
isDev: boolean
isRoot?: boolean
isViews?: boolean
pageExtensions: string[]
pagePaths: string[]
}): { [page: string]: string } {
const previousPages: { [key: string]: string } = {}
const pathAlias = isRoot ? ROOT_DIR_ALIAS : PAGES_DIR_ALIAS
const pathAlias = isViews ? VIEWS_DIR_ALIAS : PAGES_DIR_ALIAS
const pages = pagePaths.reduce<{ [key: string]: string }>(
(result, pagePath) => {
// Do not process .d.ts files inside the `pages` folder
......@@ -82,7 +75,7 @@ export function createPagesMapping({
return result
}
const pageKey = getPageFromPath(pagePath, pageExtensions, isRoot)
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.
......@@ -103,11 +96,7 @@ export function createPagesMapping({
previousPages[pageKey] = pagePath
}
if (pageKey === 'root') {
result['root'] = normalizePathSep(join(ROOT_ALIAS, pagePath))
} else {
result[pageKey] = normalizePathSep(join(pathAlias, pagePath))
}
result[pageKey] = normalizePathSep(join(pathAlias, pagePath))
return result
},
{}
......@@ -117,12 +106,7 @@ export function createPagesMapping({
// the correct source file so that HMR can work properly when a file is
// added or removed.
if (isRoot) {
if (isDev) {
pages['root'] = `${ROOT_ALIAS}/root`
} else {
pages['root'] = pages['root'] || 'next/dist/pages/root'
}
if (isViews) {
return pages
}
......@@ -259,8 +243,8 @@ interface CreateEntrypointsParams {
pagesDir: string
previewMode: __ApiPreviewProps
target: 'server' | 'serverless' | 'experimental-serverless-trace'
rootDir?: string
rootPaths?: Record<string, string>
viewsDir?: string
viewPaths?: Record<string, string>
}
export function getEdgeServerEntry(opts: {
......@@ -365,18 +349,18 @@ export function getClientEntry(opts: {
}
export async function createEntrypoints(params: CreateEntrypointsParams) {
const { config, pages, pagesDir, isDev, target, rootDir, rootPaths } = params
const { config, pages, pagesDir, isDev, target, viewsDir, viewPaths } = params
const edgeServer: webpack5.EntryObject = {}
const server: webpack5.EntryObject = {}
const client: webpack5.EntryObject = {}
const getEntryHandler =
(mappings: Record<string, string>, isRoot: boolean) =>
(mappings: Record<string, string>, isViews: boolean) =>
async (page: string) => {
const bundleFile = normalizePagePath(page)
const clientBundlePath = posix.join('pages', bundleFile)
const serverBundlePath = posix.join(
isRoot ? (bundleFile === '/root' ? './' : 'root') : 'pages',
isViews ? 'views' : 'pages',
bundleFile
)
......@@ -387,12 +371,8 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir)
}
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS) && rootDir) {
return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir)
}
if (absolutePagePath.startsWith(ROOT_ALIAS) && rootDir) {
return absolutePagePath.replace(ROOT_ALIAS, join(rootDir, '..'))
if (absolutePagePath.startsWith(VIEWS_DIR_ALIAS) && viewsDir) {
return absolutePagePath.replace(VIEWS_DIR_ALIAS, viewsDir)
}
return require.resolve(absolutePagePath)
......@@ -432,9 +412,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
})
}
if (rootDir && rootPaths) {
const entryHandler = getEntryHandler(rootPaths, true)
await Promise.all(Object.keys(rootPaths).map(entryHandler))
if (viewsDir && viewPaths) {
const entryHandler = getEntryHandler(viewPaths, true)
await Promise.all(Object.keys(viewPaths).map(entryHandler))
}
await Promise.all(Object.keys(pages).map(getEntryHandler(pages, false)))
......
......@@ -114,7 +114,6 @@ import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { findPageFile } from '../server/lib/find-page-file'
export type SsgRoute = {
initialRevalidateSeconds: number | false
......@@ -207,9 +206,9 @@ export default async function build(
setGlobal('telemetry', telemetry)
const publicDir = path.join(dir, 'public')
const { pages: pagesDir, root: rootDir } = findPagesDir(
const { pages: pagesDir, views: viewsDir } = findPagesDir(
dir,
config.experimental.rootDir
config.experimental.viewsDir
)
const hasPublicDir = await fileExists(publicDir)
......@@ -245,7 +244,7 @@ export default async function build(
.traceAsyncFn(() =>
verifyTypeScriptSetup(
dir,
[pagesDir, rootDir].filter(Boolean) as string[],
[pagesDir, viewsDir].filter(Boolean) as string[],
!ignoreTypeScriptErrors,
config,
cacheDir
......@@ -311,24 +310,17 @@ export default async function build(
)
)
let rootPaths: string[] | undefined
let viewPaths: string[] | undefined
if (rootDir) {
rootPaths = await nextBuildSpan
.traceChild('collect-root-paths')
if (viewsDir) {
viewPaths = await nextBuildSpan
.traceChild('collect-view-paths')
.traceAsyncFn(() =>
recursiveReadDir(
rootDir,
viewsDir,
new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`)
)
)
const rootFile = await findPageFile(
path.join(rootDir, '..'),
'root',
config.pageExtensions
)
if (rootFile) rootPaths.push(rootFile)
}
// needed for static exporting since we want to replace with HTML
// files
......@@ -353,17 +345,17 @@ export default async function build(
})
)
let mappedRootPaths: ReturnType<typeof createPagesMapping> | undefined
let mappedViewPaths: ReturnType<typeof createPagesMapping> | undefined
if (rootPaths && rootDir) {
mappedRootPaths = nextBuildSpan
.traceChild('create-root-mapping')
if (viewPaths && viewsDir) {
mappedViewPaths = nextBuildSpan
.traceChild('create-views-mapping')
.traceFn(() =>
createPagesMapping({
pagePaths: rootPaths!,
pagePaths: viewPaths!,
hasServerComponents,
isDev: false,
isRoot: true,
isViews: true,
pageExtensions: config.pageExtensions,
})
)
......@@ -381,8 +373,8 @@ export default async function build(
pagesDir,
previewMode: previewProps,
target,
rootDir,
rootPaths: mappedRootPaths,
viewsDir,
viewPaths: mappedViewPaths,
})
)
......@@ -688,7 +680,7 @@ export default async function build(
rewrites,
runWebpackSpan,
target,
rootDir,
viewsDir,
}
const configs = await runWebpackSpan
......
......@@ -10,8 +10,7 @@ import {
NEXT_PROJECT_ROOT,
NEXT_PROJECT_ROOT_DIST_CLIENT,
PAGES_DIR_ALIAS,
ROOT_ALIAS,
ROOT_DIR_ALIAS,
VIEWS_DIR_ALIAS,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js'
......@@ -315,7 +314,7 @@ export default async function getBaseWebpackConfig(
rewrites,
runWebpackSpan,
target = 'server',
rootDir,
viewsDir,
}: {
buildId: string
config: NextConfigComplete
......@@ -329,7 +328,7 @@ export default async function getBaseWebpackConfig(
rewrites: CustomRoutes['rewrites']
runWebpackSpan: Span
target?: string
rootDir?: string
viewsDir?: string
}
): Promise<webpack.Configuration> {
const isClient = compilerType === 'client'
......@@ -542,7 +541,7 @@ export default async function getBaseWebpackConfig(
)
)
.replace(/\\/g, '/'),
...(config.experimental.rootDir
...(config.experimental.viewsDir
? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]:
`./` +
......@@ -607,16 +606,6 @@ export default async function getBaseWebpackConfig(
}, [] as string[]),
`next/dist/pages/_document.js`,
]
if (config.experimental.rootDir && rootDir) {
customRootAliases[`${ROOT_ALIAS}/root`] = [
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(rootDir, `root.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/root.js',
]
}
}
const resolveConfig = {
......@@ -651,10 +640,9 @@ export default async function getBaseWebpackConfig(
...customRootAliases,
[PAGES_DIR_ALIAS]: pagesDir,
...(rootDir
...(viewsDir
? {
[ROOT_DIR_ALIAS]: rootDir,
[ROOT_ALIAS]: path.join(rootDir, '..'),
[VIEWS_DIR_ALIAS]: viewsDir,
}
: {}),
[DOT_NEXT_ALIAS]: distDir,
......@@ -1190,6 +1178,7 @@ export default async function getBaseWebpackConfig(
'next-middleware-loader',
'next-middleware-ssr-loader',
'next-middleware-wasm-loader',
'next-view-loader',
].reduce((alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules`
alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)
......@@ -1560,7 +1549,7 @@ export default async function getBaseWebpackConfig(
serverless: isLikeServerless,
dev,
isEdgeRuntime: isEdgeServer,
rootEnabled: !!config.experimental.rootDir,
rootEnabled: !!config.experimental.viewsDir,
}),
// MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
// replacement is done before its process.env.* handling
......@@ -1571,7 +1560,7 @@ export default async function getBaseWebpackConfig(
rewrites,
isDevFallback,
exportRuntime: hasConcurrentFeatures,
rootEnabled: !!config.experimental.rootDir,
rootEnabled: !!config.experimental.viewsDir,
}),
new ProfilingPlugin({ runWebpackSpan }),
config.optimizeFonts &&
......
import type webpack from 'webpack5'
const nextViewLoader: webpack.LoaderDefinitionFunction<{
components: string[]
}> = function nextViewLoader() {
const loaderOptions = this.getOptions() || {}
return `
export const components = {
${loaderOptions.components
.map((component) => `'${component}': () => import('${component}')`)
.join(',\n')}
}
`
}
export default nextViewLoader
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import {
PAGES_MANIFEST,
ROOT_PATHS_MANIFEST,
VIEW_PATHS_MANIFEST,
} from '../../../shared/lib/constants'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
......@@ -74,7 +74,7 @@ export default class PagesManifestPlugin implements webpack.Plugin {
}
file = normalizePathSep(file)
if (entrypoint.name.startsWith('root/')) {
if (entrypoint.name.startsWith('views/')) {
rootPaths[pagePath] = file
} else {
pages[pagePath] = file
......@@ -106,7 +106,7 @@ export default class PagesManifestPlugin implements webpack.Plugin {
if (this.rootEnabled) {
assets[
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + ROOT_PATHS_MANIFEST
`${!this.dev && !this.isEdgeRuntime ? '../' : ''}` + VIEW_PATHS_MANIFEST
] = new sources.RawSource(
JSON.stringify(
{
......
......@@ -581,7 +581,7 @@ export default async function exportApp(
outDir,
pagesDataDir,
renderOpts,
rootDir: nextConfig.experimental.rootDir,
viewsDir: nextConfig.experimental.viewsDir,
serverRuntimeConfig,
subFolders,
buildExport: options.buildExport,
......
......@@ -60,7 +60,7 @@ interface ExportPageInput {
parentSpanId: any
httpAgentOptions: NextConfigComplete['httpAgentOptions']
serverComponents?: boolean
rootDir?: boolean
viewsDir?: boolean
}
interface ExportPageResults {
......@@ -85,7 +85,7 @@ interface RenderOpts {
locale?: string
defaultLocale?: string
trailingSlash?: boolean
rootDir?: boolean
viewsDir?: boolean
}
type ComponentModule = ComponentType<{}> & {
......@@ -99,7 +99,7 @@ export default async function exportPage({
pathMap,
distDir,
outDir,
rootDir,
viewsDir,
pagesDataDir,
renderOpts,
buildExport,
......@@ -270,7 +270,7 @@ export default async function exportPage({
page,
serverless,
serverComponents,
rootDir
viewsDir
)
const ampState = {
ampFirst: pageConfig?.amp === true,
......
......@@ -25,8 +25,7 @@ export const MIDDLEWARE_ROUTE = /_middleware$/
// we have to use a private alias
export const PAGES_DIR_ALIAS = 'private-next-pages'
export const DOT_NEXT_ALIAS = 'private-dot-next'
export const ROOT_DIR_ALIAS = 'private-next-root-dir'
export const ROOT_ALIAS = 'private-next-root'
export const VIEWS_DIR_ALIAS = 'private-next-views-dir'
export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`
......
......@@ -10,7 +10,7 @@ export const existsSync = (f: string): boolean => {
}
}
function findDir(dir: string, name: 'pages' | 'root'): string | null {
function findDir(dir: string, name: 'pages' | 'views'): string | null {
// prioritize ./${name} over ./src/${name}
let curDir = path.join(dir, name)
if (existsSync(curDir)) return curDir
......@@ -23,13 +23,13 @@ function findDir(dir: string, name: 'pages' | 'root'): string | null {
export function findPagesDir(
dir: string,
root?: boolean
): { pages: string; root?: string } {
views?: boolean
): { pages: string; views?: string } {
const pagesDir = findDir(dir, 'pages')
let rootDir: undefined | string
let viewsDir: undefined | string
if (root) {
rootDir = findDir(dir, 'root') || undefined
if (views) {
viewsDir = findDir(dir, 'views') || undefined
}
// TODO: allow "root" dir without pages dir
......@@ -41,6 +41,6 @@ export function findPagesDir(
return {
pages: pagesDir,
root: rootDir,
views: viewsDir,
}
}
import React from 'react'
export type RootProps = {
export type LayoutProps = {
headChildren: any
bodyChildren: any
}
export default function Root({ headChildren, bodyChildren }: RootProps) {
export default function ViewsLayout({
headChildren,
bodyChildren,
}: LayoutProps) {
return (
<html>
<head>
......
......@@ -70,7 +70,7 @@ import { createHeaderRoute, createRedirectRoute } from './server-route-utils'
import { PrerenderManifest } from '../build'
import { ImageConfigComplete } from '../shared/lib/image-config'
import { replaceBasePath } from './router-utils'
import { normalizeRootPath } from '../shared/lib/router/utils/root-paths'
import { normalizeViewPath } from '../shared/lib/router/utils/view-paths'
export type FindComponentsResult = {
components: LoadComponentsReturnType
......@@ -142,7 +142,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected publicDir: string
protected hasStaticDir: boolean
protected pagesManifest?: PagesManifest
protected rootPathsManifest?: PagesManifest
protected viewPathsManifest?: PagesManifest
protected buildId: string
protected minimalMode: boolean
protected renderOpts: {
......@@ -182,7 +182,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private responseCache: ResponseCache
protected router: Router
protected dynamicRoutes?: DynamicRoutes
protected rootPathRoutes?: Record<string, string>
protected viewPathRoutes?: Record<string, string>
protected customRoutes: CustomRoutes
protected middlewareManifest?: MiddlewareManifest
protected middleware?: RoutingItem[]
......@@ -193,7 +193,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean
protected abstract getPagesManifest(): PagesManifest | undefined
protected abstract getRootPathsManifest(): PagesManifest | undefined
protected abstract getViewPathsManifest(): PagesManifest | undefined
protected abstract getBuildId(): string
protected abstract generatePublicRoutes(): Route[]
protected abstract generateImageRoutes(): Route[]
......@@ -356,7 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
})
this.pagesManifest = this.getPagesManifest()
this.rootPathsManifest = this.getRootPathsManifest()
this.viewPathsManifest = this.getViewPathsManifest()
this.middlewareManifest = this.getMiddlewareManifest()
this.customRoutes = this.getCustomRoutes()
......@@ -876,7 +876,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const { useFileSystemPublicRoutes } = this.nextConfig
if (useFileSystemPublicRoutes) {
this.rootPathRoutes = this.getRootPathRoutes()
this.viewPathRoutes = this.getViewPathRoutes()
this.dynamicRoutes = this.getDynamicRoutes()
if (!this.minimalMode) {
this.middleware = this.getMiddleware()
......@@ -898,30 +898,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
}
protected isRoutableRootPath(pathname: string): boolean {
if (this.rootPathRoutes) {
const paths = Object.keys(this.rootPathRoutes)
/**
* a root path is only routable if
* 1. has root/hello.js and no root/hello/ folder
* 2. has root/hello.js and a root/hello/index.js
*/
const hasFolderIndex = this.rootPathRoutes[`${pathname}/index`]
const hasFolder = paths.some((path) => {
return path.startsWith(`${pathname}/`)
})
if (hasFolder && hasFolderIndex) {
return true
}
if (!hasFolder && this.rootPathRoutes[pathname]) {
return true
}
}
return false
}
protected async hasPage(pathname: string): Promise<boolean> {
let found = false
try {
......@@ -995,7 +971,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return getSortedRoutes(
[
...Object.keys(this.rootPathRoutes || {}),
...Object.keys(this.viewPathRoutes || {}),
...Object.keys(this.pagesManifest!),
].map(
(page) =>
......@@ -1013,31 +989,33 @@ export default abstract class Server<ServerOptions extends Options = Options> {
.filter((item): item is RoutingItem => Boolean(item))
}
protected getRootPathRoutes(): Record<string, string> {
const rootPathRoutes: Record<string, string> = {}
protected getViewPathRoutes(): Record<string, string> {
const viewPathRoutes: Record<string, string> = {}
Object.keys(this.rootPathsManifest || {}).forEach((entry) => {
rootPathRoutes[normalizeRootPath(entry)] = entry
Object.keys(this.viewPathsManifest || {}).forEach((entry) => {
viewPathRoutes[normalizeViewPath(entry)] = entry
})
return rootPathRoutes
return viewPathRoutes
}
protected getRootPathLayouts(pathname: string): string[] {
protected getViewPathLayouts(pathname: string): string[] {
const layoutPaths: string[] = []
if (this.rootPathRoutes) {
const paths = Object.values(this.rootPathRoutes)
if (this.viewPathRoutes) {
const paths = Object.values(this.viewPathRoutes)
const parts = pathname.split('/').filter(Boolean)
for (let i = 1; i < parts.length; i++) {
const parentPath = `/${parts.slice(0, i).join('/')}`
const layoutPath = `/${parts.slice(0, i).join('/')}/layout`
if (paths.includes(parentPath)) {
layoutPaths.push(parentPath)
if (paths.includes(layoutPath)) {
layoutPaths.push(layoutPath)
}
}
// TODO: when should we bail on adding the root.js wrapper
layoutPaths.unshift('/_root')
if (this.viewPathRoutes['/layout']) {
layoutPaths.unshift('/layout')
}
}
return layoutPaths
}
......@@ -1755,38 +1733,31 @@ export default abstract class Server<ServerOptions extends Options = Options> {
delete query._nextBubbleNoFallback
// map the route to the actual bundle name e.g.
// `/dashboard/rootonly/hello` -> `/dashboard+rootonly/hello`
const getOriginalRootPath = (rootPath: string) => {
if (this.nextConfig.experimental.rootDir) {
const originalRootPath =
this.rootPathRoutes?.[`${pathname}/index`] ||
this.rootPathRoutes?.[pathname]
const getOriginalViewPath = (viewPath: string) => {
if (this.nextConfig.experimental.viewsDir) {
const originalViewPath =
this.viewPathRoutes?.[`${viewPath}/index`] ||
this.viewPathRoutes?.[`${viewPath}`]
if (!originalRootPath) {
if (!originalViewPath) {
return null
}
const isRoutable = this.isRoutableRootPath(rootPath)
// 404 when layout is hit and this isn't a routable path
// e.g. root/hello.js with root/hello/another.js but
// no root/hello/index.js
if (!isRoutable) {
return ''
}
return originalRootPath
return originalViewPath
}
return null
}
const gatherRootLayouts = async (
rootPath: string,
const gatherViewLayouts = async (
viewPath: string,
result: FindComponentsResult
): Promise<void> => {
const layoutPaths = this.getRootPathLayouts(rootPath)
result.components.rootLayouts = await Promise.all(
const layoutPaths = this.getViewPathLayouts(viewPath)
result.components.viewLayouts = await Promise.all(
layoutPaths.map(async (path) => {
const layoutRes = await this.findPageComponents(path)
return {
isRoot: path === '/_root',
isRootLayout: path === '/layout',
Component: layoutRes?.components.Component!,
getStaticProps: layoutRes?.components.getStaticProps,
getServerSideProps: layoutRes?.components.getServerSideProps,
......@@ -1799,16 +1770,16 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Ensure a request to the URL /accounts/[id] will be treated as a dynamic
// route correctly and not loaded immediately without parsing params.
if (!isDynamicRoute(pathname)) {
const rootPath = getOriginalRootPath(pathname)
const viewPath = getOriginalViewPath(pathname)
if (typeof rootPath === 'string') {
page = rootPath
if (typeof viewPath === 'string') {
page = viewPath
}
const result = await this.findPageComponents(page, query)
if (result) {
try {
if (result.components.isRootPath) {
await gatherRootLayouts(page, result)
if (result.components.isViewPath) {
await gatherViewLayouts(page, result)
}
return await this.renderToResponseWithComponents(ctx, result)
} catch (err) {
......@@ -1828,21 +1799,21 @@ export default abstract class Server<ServerOptions extends Options = Options> {
continue
}
page = dynamicRoute.page
const rootPath = getOriginalRootPath(page)
const viewPath = getOriginalViewPath(page)
if (typeof rootPath === 'string') {
page = rootPath
if (typeof viewPath === 'string') {
page = viewPath
}
const dynamicRouteResult = await this.findPageComponents(
dynamicRoute.page,
page,
query,
params
)
if (dynamicRouteResult) {
try {
if (dynamicRouteResult.components.isRootPath) {
await gatherRootLayouts(page, dynamicRouteResult)
if (dynamicRouteResult.components.isViewPath) {
await gatherViewLayouts(page, dynamicRouteResult)
}
return await this.renderToResponseWithComponents(
{
......
......@@ -96,7 +96,7 @@ export interface ExperimentalConfig {
scrollRestoration?: boolean
externalDir?: boolean
conformance?: boolean
rootDir?: boolean
viewsDir?: boolean
amp?: {
optimizer?: any
validator?: string
......@@ -494,7 +494,7 @@ export const defaultConfig: NextConfig = {
swcFileReading: true,
craCompat: false,
esmExternals: true,
rootDir: false,
viewsDir: false,
// default to 50MB limit
isrMemoryCacheSize: 50 * 1024 * 1024,
serverComponents: false,
......
......@@ -168,7 +168,7 @@ export default class HotReloader {
private fallbackWatcher: any
private hotReloaderSpan: Span
private pagesMapping: { [key: string]: string } = {}
private rootDir?: string
private viewsDir?: string
constructor(
dir: string,
......@@ -179,7 +179,7 @@ export default class HotReloader {
buildId,
previewProps,
rewrites,
rootDir,
viewsDir,
}: {
config: NextConfigComplete
pagesDir: string
......@@ -187,14 +187,14 @@ export default class HotReloader {
buildId: string
previewProps: __ApiPreviewProps
rewrites: CustomRoutes['rewrites']
rootDir?: string
viewsDir?: string
}
) {
this.buildId = buildId
this.dir = dir
this.middlewares = []
this.pagesDir = pagesDir
this.rootDir = rootDir
this.viewsDir = viewsDir
this.distDir = distDir
this.clientStats = null
this.serverStats = null
......@@ -427,7 +427,7 @@ export default class HotReloader {
pagesDir: this.pagesDir,
rewrites: this.rewrites,
runWebpackSpan: this.hotReloaderSpan,
rootDir: this.rootDir,
viewsDir: this.viewsDir,
}
return webpackConfigSpan
......@@ -839,7 +839,7 @@ export default class HotReloader {
multiCompiler,
watcher: this.watcher,
pagesDir: this.pagesDir,
rootDir: this.rootDir,
viewsDir: this.viewsDir,
nextConfig: this.config,
...(this.config.onDemandEntries as {
maxInactiveAge: number
......
......@@ -66,7 +66,7 @@ import { isCustomErrorPage, isReservedPage } from '../../build/utils'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { getPageRuntime, invalidatePageRuntimeCache } from '../../build/entries'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizeRootPath } from '../../shared/lib/router/utils/root-paths'
import { normalizeViewPath } from '../../shared/lib/router/utils/view-paths'
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent
......@@ -98,7 +98,7 @@ export default class DevServer extends Server {
protected sortedRoutes?: string[]
private addedUpgradeListener = false
private pagesDir: string
private rootDir?: string
private viewsDir?: string
protected staticPathsWorker?: { [key: string]: any } & {
loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths
......@@ -179,12 +179,12 @@ export default class DevServer extends Server {
this.isCustomServer = !options.isNextDevCommand
// TODO: hot-reload root/pages dirs?
const { pages: pagesDir, root: rootDir } = findPagesDir(
const { pages: pagesDir, views: viewsDir } = findPagesDir(
this.dir,
this.nextConfig.experimental.rootDir
this.nextConfig.experimental.viewsDir
)
this.pagesDir = pagesDir
this.rootDir = rootDir
this.viewsDir = viewsDir
}
protected getBuildId(): string {
......@@ -267,8 +267,8 @@ export default class DevServer extends Server {
let wp = (this.webpackWatcher = new Watchpack())
const toWatch = [this.pagesDir!]
if (this.rootDir) {
toWatch.push(this.rootDir)
if (this.viewsDir) {
toWatch.push(this.viewsDir)
}
wp.watch([], toWatch, 0)
......@@ -276,7 +276,7 @@ export default class DevServer extends Server {
const routedMiddleware = []
const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries()
const rootPaths: Record<string, string> = {}
const viewPaths: Record<string, string> = {}
const ssrMiddleware = new Set<string>()
for (const [fileName, { accuracy, safeTime }] of knownFiles) {
......@@ -284,17 +284,17 @@ export default class DevServer extends Server {
continue
}
let pageName: string = ''
let isRootPath = false
let isViewPath = false
if (
this.rootDir &&
this.viewsDir &&
normalizePathSep(fileName).startsWith(
normalizePathSep(this.rootDir)
normalizePathSep(this.viewsDir)
)
) {
isRootPath = true
isViewPath = true
pageName = absolutePathToPage(
this.rootDir,
this.viewsDir,
fileName,
this.nextConfig.pageExtensions,
false
......@@ -307,11 +307,11 @@ export default class DevServer extends Server {
)
}
if (isRootPath) {
if (isViewPath) {
// TODO: should only routes ending in /index.js be route-able?
const originalPageName = pageName
pageName = normalizeRootPath(pageName)
rootPaths[pageName] = originalPageName
pageName = normalizeViewPath(pageName)
viewPaths[pageName] = originalPageName
if (routedPages.includes(pageName)) {
continue
......@@ -348,7 +348,7 @@ export default class DevServer extends Server {
routedPages.push(pageName)
}
this.rootPathRoutes = rootPaths
this.viewPathRoutes = viewPaths
this.middleware = getSortedRoutes(routedMiddleware).map((page) => ({
match: getRouteMatcher(
getMiddlewareRegex(page, !ssrMiddleware.has(page))
......@@ -410,7 +410,7 @@ export default class DevServer extends Server {
setGlobal('phase', PHASE_DEVELOPMENT_SERVER)
await verifyTypeScriptSetup(
this.dir,
[this.pagesDir!, this.rootDir].filter(Boolean) as string[],
[this.pagesDir!, this.viewsDir].filter(Boolean) as string[],
false,
this.nextConfig
)
......@@ -437,7 +437,7 @@ export default class DevServer extends Server {
previewProps: this.getPreviewProps(),
buildId: this.buildId,
rewrites,
rootDir: this.rootDir,
viewsDir: this.viewsDir,
})
await super.prepare()
await this.addExportPathMapRoutes()
......@@ -495,10 +495,10 @@ export default class DevServer extends Server {
return false
}
// check rootDir first if enabled
if (this.rootDir) {
// check viewsDir first if enabled
if (this.viewsDir) {
const pageFile = await findPageFile(
this.rootDir,
this.viewsDir,
normalizedPath,
this.nextConfig.pageExtensions
)
......@@ -786,7 +786,7 @@ export default class DevServer extends Server {
return undefined
}
protected getRootPathsManifest(): undefined {
protected getViewPathsManifest(): undefined {
return undefined
}
......
......@@ -54,7 +54,7 @@ export function onDemandEntryHandler({
nextConfig,
pagesBufferLength,
pagesDir,
rootDir,
viewsDir,
watcher,
}: {
maxInactiveAge: number
......@@ -62,7 +62,7 @@ export function onDemandEntryHandler({
nextConfig: NextConfigComplete
pagesBufferLength: number
pagesDir: string
rootDir?: string
viewsDir?: string
watcher: any
}) {
const invalidator = new Invalidator(watcher)
......@@ -101,7 +101,7 @@ export function onDemandEntryHandler({
return invalidator.doneBuilding()
}
const [clientStats, serverStats, edgeServerStats] = multiStats.stats
const root = !!rootDir
const root = !!viewsDir
const pagePaths = [
...getPagePathsFromEntrypoints(
'client',
......@@ -182,7 +182,7 @@ export function onDemandEntryHandler({
pagesDir,
page,
nextConfig.pageExtensions,
rootDir
viewsDir
)
let entryAdded = false
......@@ -340,23 +340,18 @@ async function findPagePathData(
pagesDir: string,
page: string,
extensions: string[],
rootDir?: string
viewsDir?: string
) {
const normalizedPagePath = tryToNormalizePagePath(page)
let pagePath: string | null = null
let isRoot = false
const isRootFile = rootDir && normalizedPagePath === '/_root'
// check rootDir first
if (rootDir) {
pagePath = await findPageFile(
join(rootDir, isRootFile ? '..' : ''),
isRootFile ? 'root' : normalizedPagePath,
extensions
)
let isView = false
// check viewsDir first
if (viewsDir) {
pagePath = await findPageFile(viewsDir, normalizedPagePath, extensions)
if (pagePath) {
isRoot = true
isView = true
}
}
......@@ -366,19 +361,11 @@ async function findPagePathData(
if (pagePath !== null) {
const pageUrl = ensureLeadingSlash(
removePagePathTail(normalizePathSep(pagePath), extensions, !isRoot)
removePagePathTail(normalizePathSep(pagePath), extensions, !isView)
)
const bundleFile = normalizePagePath(pageUrl)
let bundlePath
let absolutePagePath
if (isRootFile) {
bundlePath = 'root'
absolutePagePath = join(rootDir!, '..', pagePath)
} else {
bundlePath = posix.join(isRoot ? 'root' : 'pages', bundleFile)
absolutePagePath = join(isRoot ? rootDir! : pagesDir, pagePath)
}
const bundlePath = posix.join(isView ? 'views' : 'pages', bundleFile)
const absolutePagePath = join(isView ? viewsDir! : pagesDir, pagePath)
return {
absolutePagePath,
......
......@@ -3,7 +3,7 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
// matches pages/:page*.js
const SERVER_ROUTE_NAME_REGEX = /^pages[/\\](.*)$/
// matches root/:path*.js
const ROOT_ROUTE_NAME_REGEX = /^root[/\\](.*)$/
const ROOT_ROUTE_NAME_REGEX = /^views[/\\](.*)$/
// matches static/pages/:page*.js
const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/
......
......@@ -20,12 +20,7 @@ export async function findPageFile(
normalizedPagePath: string,
pageExtensions: string[]
): Promise<string | null> {
const isRootPaths = pagesDir.replace(/\\/g, '/').endsWith('/root')
const pagePaths = getPagePaths(
normalizedPagePath,
pageExtensions,
isRootPaths
)
const pagePaths = getPagePaths(normalizedPagePath, pageExtensions)
const [existingPath, ...others] = (
await Promise.all(
pagePaths.map(async (path) =>
......
......@@ -40,9 +40,9 @@ export type LoadComponentsReturnType = {
ComponentMod: any
AppMod: any
AppServerMod: any
isRootPath?: boolean
rootLayouts?: Array<{
isRoot?: boolean
isViewPath?: boolean
viewLayouts?: Array<{
isRootLayout?: boolean
Component: NextComponentType
getStaticProps?: GetStaticProps
getServerSideProps?: GetServerSideProps
......@@ -134,7 +134,7 @@ export async function loadComponents(
const { getServerSideProps, getStaticProps, getStaticPaths } = ComponentMod
let isRootPath = false
let isViewPath = false
if (rootEnabled) {
const pagePath = getPagePath(
......@@ -145,7 +145,7 @@ export async function loadComponents(
undefined,
rootEnabled
)
isRootPath = !!pagePath?.match(/server[/\\]root[/\\]/)
isViewPath = !!pagePath?.match(/server[/\\]views[/\\]/)
}
return {
......@@ -162,6 +162,6 @@ export async function loadComponents(
getStaticProps,
getStaticPaths,
serverComponentManifest,
isRootPath,
isViewPath,
}
}
......@@ -31,7 +31,7 @@ import {
ROUTES_MANIFEST,
MIDDLEWARE_FLIGHT_MANIFEST,
CLIENT_PUBLIC_FILES_PATH,
ROOT_PATHS_MANIFEST,
VIEW_PATHS_MANIFEST,
} from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { format as formatUrl, UrlWithParsedQuery } from 'url'
......@@ -46,7 +46,7 @@ import { getExtension, serveStatic } from './serve-static'
import { ParsedUrlQuery } from 'querystring'
import { apiResolver } from './api-utils/node'
import { RenderOpts, renderToHTML } from './render'
import { renderToHTML as rootRenderToHTML } from './root-render'
import { renderToHTML as viewRenderToHTML } from './view-render'
import { ParsedUrl, parseUrl } from '../shared/lib/router/utils/parse-url'
import * as Log from '../build/output/log'
......@@ -159,13 +159,13 @@ export default class NextNodeServer extends BaseServer {
return require(join(this.serverDistDir, PAGES_MANIFEST))
}
protected getRootPathsManifest(): PagesManifest | undefined {
if (this.nextConfig.experimental.rootDir) {
const rootPathsManifestPath = join(
protected getViewPathsManifest(): PagesManifest | undefined {
if (this.nextConfig.experimental.viewsDir) {
const viewPathsManifestPath = join(
this.serverDistDir,
ROOT_PATHS_MANIFEST
VIEW_PATHS_MANIFEST
)
return require(rootPathsManifestPath)
return require(viewPathsManifestPath)
}
}
......@@ -584,8 +584,8 @@ export default class NextNodeServer extends BaseServer {
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.serverComponentManifest = this.serverComponentManifest
if (renderOpts.isRootPath) {
return rootRenderToHTML(
if (renderOpts.isViewPath) {
return viewRenderToHTML(
req.originalRequest,
res.originalResponse,
pathname,
......@@ -642,7 +642,7 @@ export default class NextNodeServer extends BaseServer {
this._isLikeServerless,
this.renderOpts.dev,
locales,
this.nextConfig.experimental.rootDir
this.nextConfig.experimental.viewsDir
)
}
......@@ -673,7 +673,7 @@ export default class NextNodeServer extends BaseServer {
pagePath!,
!this.renderOpts.dev && this._isLikeServerless,
this.renderOpts.serverComponents,
this.nextConfig.experimental.rootDir
this.nextConfig.experimental.viewsDir
)
if (
......
......@@ -6,7 +6,7 @@ import {
PAGES_MANIFEST,
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
ROOT_PATHS_MANIFEST,
VIEW_PATHS_MANIFEST,
} from '../shared/lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
......@@ -39,7 +39,7 @@ export function getPagePath(
if (page === '/_root') {
return join(serverBuildPath, 'root.js')
}
rootPathsManifest = require(join(serverBuildPath, ROOT_PATHS_MANIFEST))
rootPathsManifest = require(join(serverBuildPath, VIEW_PATHS_MANIFEST))
}
const pagesManifest = require(join(
serverBuildPath,
......
......@@ -21,6 +21,7 @@ import { FlushEffectsContext } from '../shared/lib/flush-effects'
import ReactDOMServer from 'react-dom/server.browser'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { tryGetPreviewData } from './api-utils/node'
import DefaultRootLayout from '../lib/views-layout'
export type RenderOptsPartial = {
err?: Error | null
......@@ -215,7 +216,7 @@ export async function renderToHTML(
const hasConcurrentFeatures = !!runtime
const pageIsDynamic = isDynamicRoute(pathname)
const layouts = renderOpts.rootLayouts || []
const layouts = renderOpts.viewLayouts || []
layouts.push({
Component: renderOpts.Component,
......@@ -242,7 +243,7 @@ export async function renderToHTML(
const dataCacheKey = i.toString()
const layout = layouts[i]
if (layout.isRoot) {
if (layout.isRootLayout) {
RootLayout = layout.Component
continue
}
......@@ -330,7 +331,8 @@ export async function renderToHTML(
if (!RootLayout) {
// TODO: fallback to our own root layout?
throw new Error('invariant RootLayout not loaded')
// throw new Error('invariant RootLayout not loaded')
RootLayout = DefaultRootLayout
}
const headChildren = buildManifest.rootMainFiles.map((src) => (
......
......@@ -103,7 +103,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
[this.serverOptions.webServerConfig.page]: '',
}
}
protected getRootPathsManifest() {
protected getViewPathsManifest() {
return {
[this.serverOptions.webServerConfig.page]: '',
}
......
......@@ -4,7 +4,7 @@ export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PHASE_TEST = 'phase-test'
export const PAGES_MANIFEST = 'pages-manifest.json'
export const ROOT_PATHS_MANIFEST = 'root-paths-manifest.json'
export const VIEW_PATHS_MANIFEST = 'view-paths-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json'
export const EXPORT_MARKER = 'export-marker.json'
export const EXPORT_DETAIL = 'export-detail.json'
......
......@@ -10,23 +10,9 @@ import { join } from '../isomorphic/path'
* @param normalizedPagePath Normalized page path (it will denormalize).
* @param extensions Allowed extensions.
*/
export function getPagePaths(
normalizedPagePath: string,
extensions: string[],
isRoot?: boolean
) {
export function getPagePaths(normalizedPagePath: string, extensions: string[]) {
const page = denormalizePagePath(normalizedPagePath)
if (isRoot) {
return flatten(
extensions.map((extension) => {
return normalizedPagePath.endsWith('/index')
? [`${page}.${extension}`, join(page, `index.${extension}`)]
: [`${page}.${extension}`]
})
)
}
return flatten(
extensions.map((extension) => {
return !normalizedPagePath.endsWith('/index')
......
// strip `@propName` from pathname and normalize `+` to `/`
export function normalizeRootPath(pathname: string) {
let normalized = ''
pathname.split('/').forEach((segment) => {
segment.split('+').forEach((subSegment) => {
const value = subSegment.split('@').shift()
if (value) {
normalized += `/${value}`
}
})
})
return normalized
}
// remove (name) from pathname as it's not considered for routing
export function normalizeViewPath(pathname: string) {
let normalized = ''
const segments = pathname.split('/')
segments.forEach((segment, index) => {
if (!segment) return
if (segment.startsWith('(') && segment.endsWith(')')) {
return
}
if (segment === 'page' && index === segments.length - 1) {
return
}
normalized += `/${segment}`
})
return normalized
}
......@@ -1887,21 +1887,9 @@ export async function pages_document(task, opts) {
.target('dist/pages')
}
export async function pages_root(task, opts) {
await task
.source('pages/root.tsx')
.swc('server', { dev: opts.dev, keepImportAssertions: true })
}
export async function pages(task, opts) {
await task.parallel(
[
'pages_app',
'pages_app_server',
'pages_error',
'pages_document',
'pages_root',
],
['pages_app', 'pages_app_server', 'pages_error', 'pages_document'],
opts
)
}
......
export async function getServerSideProps({ params }) {
if (params.slug === 'nonexistent') {
return {
notFound: true,
}
}
return {
props: {
isUser: params.slug === 'tim',
isBoth: params.slug === 'both',
},
}
}
export default function UserOrTeam({ isUser, isBoth, user, team }) {
return (
<>
{isUser && !isBoth ? user : team}
{isBoth ? (
<>
{user}
{team}
</>
) : null}
</>
)
}
export default function TeamHomePage(props) {
return (
<>
<p>hello from team homepage</p>
</>
)
}
export default function TeamMembersPage(props) {
return (
<>
<p>hello from team/members</p>
</>
)
}
export default function UserHomePage(props) {
return (
<>
<p>hello from user homepage</p>
</>
)
}
export default function UserTeamsPage(props) {
return (
<>
<p>hello from user/teams</p>
</>
)
}
module.exports = {
experimental: {
rootDir: true,
viewsDir: true,
runtime: 'nodejs',
reactRoot: true,
serverComponents: true,
......
......@@ -5,7 +5,11 @@ import path from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
describe('root dir', () => {
describe('views dir', () => {
if (process.env.NEXT_TEST_REACT_VERSION === '^17') {
it('should skip for react v17', () => {})
return
}
let next: NextInstance
beforeAll(async () => {
......@@ -13,18 +17,11 @@ describe('root dir', () => {
files: {
public: new FileRef(path.join(__dirname, 'app/public')),
pages: new FileRef(path.join(__dirname, 'app/pages')),
root: new FileRef(path.join(__dirname, 'app/root')),
'root.server.js': new FileRef(
path.join(__dirname, 'app/root.server.js')
),
views: new FileRef(path.join(__dirname, 'app/views')),
'next.config.js': new FileRef(
path.join(__dirname, 'app/next.config.js')
),
},
dependencies: {
react: '18.0.0-rc.2',
'react-dom': '18.0.0-rc.2',
},
})
})
afterAll(() => next.destroy())
......@@ -60,7 +57,7 @@ describe('root dir', () => {
// TODO: why is this routable but /should-not-serve-server.server.js
it('should not include parent when not in parent directory with route in directory', async () => {
const html = await renderViaHTTP(next.url, '/dashboard/rootonly/hello')
const html = await renderViaHTTP(next.url, '/dashboard/hello')
const $ = cheerio.load(html)
// Should be nested in /root.js
......@@ -131,51 +128,6 @@ describe('root dir', () => {
expect(html).toContain('hello from root/partial-match-[id]. ID is: 123')
})
// TODO: Implement
describe.skip('parallel routes', () => {
describe('conditional routes', () => {
it('should serve user page', async () => {
const html = await renderViaHTTP(next.url, '/conditional/tim')
expect(html).toContain('hello from user homepage')
})
it('should serve user teams page', async () => {
const html = await renderViaHTTP(next.url, '/conditional/tim/teams')
expect(html).toContain('hello from user/teams')
})
it('should not serve teams page to user', async () => {
const html = await renderViaHTTP(next.url, '/conditional/tim/members')
expect(html).not.toContain('hello from team/members')
})
it('should serve team page', async () => {
const html = await renderViaHTTP(next.url, '/conditional/vercel')
expect(html).toContain('hello from team homepage')
})
it('should serve team members page', async () => {
const html = await renderViaHTTP(
next.url,
'/conditional/vercel/members'
)
expect(html).toContain('hello from team/members')
})
it('should provide both matches if both paths match', async () => {
const html = await renderViaHTTP(next.url, '/conditional/both')
expect(html).toContain('hello from team homepage')
expect(html).toContain('hello from user homepage')
})
it('should 404 based on getServerSideProps', async () => {
const res = await fetchViaHTTP(next.url, '/conditional/nonexistent')
expect(res.status).toBe(404)
expect(await res.text()).toContain('This page could not be found')
})
})
})
describe('server components', () => {
// TODO: why is this not servable but /dashboard+rootonly/hello.server.js
// should be? Seems like they both either should be servable or not
......
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