Unverified Commit 5f95b6b0 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Improved route resolution in next-app-loader (#40109)

This PR implements the logic to make next-app-loader able to match multiple routes.

The app loader is refactored to construct the tree recursively instead of within a loop, as there could be multiple branches. Similarly, when entering a new layout level or branch, we resolve both the slot name (defaults to `"children"`) and the segment.

In order to make that work, the loader has to know all matched app paths. This is passed in as the `appPaths` loader option, which is gathered when creating the entrypoint.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] 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 avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 5c2faad3
...@@ -51,7 +51,7 @@ jobs: ...@@ -51,7 +51,7 @@ jobs:
run: sudo ethtool -K eth0 tx off rx off run: sudo ethtool -K eth0 tx off rx off
- name: Check non-docs only change - name: Check non-docs only change
run: echo ::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope') run: echo "::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope')"
id: docs-change id: docs-change
- run: echo ${{steps.docs-change.outputs.DOCS_CHANGE}} - run: echo ${{steps.docs-change.outputs.DOCS_CHANGE}}
...@@ -124,7 +124,7 @@ jobs: ...@@ -124,7 +124,7 @@ jobs:
path: ./* path: ./*
key: ${{ github.sha }}-${{ github.run_number }} key: ${{ github.sha }}-${{ github.run_number }}
- run: echo ::set-output name=SWC_CHANGE::$(node scripts/run-for-change.js --type next-swc --exec echo 'yup') - run: echo "::set-output name=SWC_CHANGE::$(node scripts/run-for-change.js --type next-swc --exec echo 'yup')"
id: swc-change id: swc-change
- run: echo ${{ steps.swc-change.outputs.SWC_CHANGE }} - run: echo ${{ steps.swc-change.outputs.SWC_CHANGE }}
...@@ -1102,7 +1102,7 @@ jobs: ...@@ -1102,7 +1102,7 @@ jobs:
with: with:
fetch-depth: 25 fetch-depth: 25
- run: echo ::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope') - run: echo "::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope')"
id: docs-change id: docs-change
- name: Setup node - name: Setup node
...@@ -1191,7 +1191,7 @@ jobs: ...@@ -1191,7 +1191,7 @@ jobs:
with: with:
fetch-depth: 25 fetch-depth: 25
- run: echo ::set-output name=SWC_CHANGE::$(node scripts/run-for-change.js --type next-swc --exec echo 'yup') - run: echo "::set-output name=SWC_CHANGE::$(node scripts/run-for-change.js --type next-swc --exec echo 'yup')"
id: swc-change id: swc-change
- run: echo ${{ steps.swc-change.outputs.SWC_CHANGE }} - run: echo ${{ steps.swc-change.outputs.SWC_CHANGE }}
......
...@@ -24,7 +24,7 @@ jobs: ...@@ -24,7 +24,7 @@ jobs:
fetch-depth: 25 fetch-depth: 25
- name: Check non-docs only change - name: Check non-docs only change
run: echo ::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope') run: echo "::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope')"
id: docs-change id: docs-change
- name: Setup node - name: Setup node
...@@ -118,7 +118,7 @@ jobs: ...@@ -118,7 +118,7 @@ jobs:
fetch-depth: 25 fetch-depth: 25
- name: Check non-docs only change - name: Check non-docs only change
run: echo ::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope') run: echo "::set-output name=DOCS_CHANGE::$(node scripts/run-for-change.js --not --type docs --exec echo 'nope')"
id: docs-change id: docs-change
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3
......
...@@ -46,6 +46,7 @@ import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' ...@@ -46,6 +46,7 @@ import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { serverComponentRegex } from './webpack/loaders/utils' import { serverComponentRegex } from './webpack/loaders/utils'
import { ServerRuntime } from '../types' import { ServerRuntime } from '../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader' import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
...@@ -223,6 +224,7 @@ export function getAppEntry(opts: { ...@@ -223,6 +224,7 @@ export function getAppEntry(opts: {
name: string name: string
pagePath: string pagePath: string
appDir: string appDir: string
appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
}) { }) {
return { return {
...@@ -353,6 +355,22 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -353,6 +355,22 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const nestedMiddleware: string[] = [] const nestedMiddleware: string[] = []
let middlewareMatchers: MiddlewareMatcher[] | undefined = undefined let middlewareMatchers: MiddlewareMatcher[] | undefined = undefined
let appPathsPerRoute: Record<string, string[]> = {}
if (appDir && appPaths) {
for (const pathname in appPaths) {
const normalizedPath = normalizeAppPath(pathname) || '/'
if (!appPathsPerRoute[normalizedPath]) {
appPathsPerRoute[normalizedPath] = []
}
appPathsPerRoute[normalizedPath].push(pathname)
}
// Make sure to sort parallel routes to make the result deterministic.
appPathsPerRoute = Object.fromEntries(
Object.entries(appPathsPerRoute).map(([k, v]) => [k, v.sort()])
)
}
const getEntryHandler = const getEntryHandler =
(mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') => (mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') =>
async (page: string) => { async (page: string) => {
...@@ -431,10 +449,13 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -431,10 +449,13 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}, },
onServer: () => { onServer: () => {
if (pagesType === 'app' && appDir) { if (pagesType === 'app' && appDir) {
const matchedAppPaths =
appPathsPerRoute[normalizeAppPath(page) || '/']
server[serverBundlePath] = getAppEntry({ server[serverBundlePath] = getAppEntry({
name: serverBundlePath, name: serverBundlePath,
pagePath: mappings[page], pagePath: mappings[page],
appDir, appDir,
appPaths: matchedAppPaths,
pageExtensions, pageExtensions,
}) })
} else if (isTargetLikeServerless(target)) { } else if (isTargetLikeServerless(target)) {
...@@ -450,15 +471,18 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -450,15 +471,18 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
} }
}, },
onEdgeServer: () => { onEdgeServer: () => {
const appDirLoader = let appDirLoader: string = ''
pagesType === 'app' if (pagesType === 'app') {
? getAppEntry({ const matchedAppPaths =
name: serverBundlePath, appPathsPerRoute[normalizeAppPath(page) || '/']
pagePath: mappings[page], appDirLoader = getAppEntry({
appDir: appDir!, name: serverBundlePath,
pageExtensions, pagePath: mappings[page],
}).import appDir: appDir!,
: '' appPaths: matchedAppPaths,
pageExtensions,
}).import
}
edgeServer[serverBundlePath] = getEdgeServerEntry({ edgeServer[serverBundlePath] = getEdgeServerEntry({
...params, ...params,
......
...@@ -550,7 +550,9 @@ export default async function build( ...@@ -550,7 +550,9 @@ export default async function build(
const pageKeys = { const pageKeys = {
pages: Object.keys(mappedPages), pages: Object.keys(mappedPages),
app: mappedAppPages app: mappedAppPages
? Object.keys(mappedAppPages).map((key) => normalizeAppPath(key)) ? Object.keys(mappedAppPages).map(
(key) => normalizeAppPath(key) || '/'
)
: undefined, : undefined,
} }
......
...@@ -5,86 +5,104 @@ import { getModuleBuildInfo } from './get-module-build-info' ...@@ -5,86 +5,104 @@ import { getModuleBuildInfo } from './get-module-build-info'
async function createTreeCodeFromPath({ async function createTreeCodeFromPath({
pagePath, pagePath,
resolve, resolve,
removeExt, resolveParallelSegments,
}: { }: {
pagePath: string pagePath: string
resolve: (pathname: string) => Promise<string | undefined> resolve: (pathname: string) => Promise<string | undefined>
removeExt: (pathToRemoveExtensions: string) => string resolveParallelSegments: (
pathname: string
) => [key: string, segment: string][]
}) { }) {
let tree: undefined | string
const splittedPath = pagePath.split(/[\\/]/) const splittedPath = pagePath.split(/[\\/]/)
const appDirPrefix = splittedPath[0] const appDirPrefix = splittedPath[0]
const segments = ['', ...splittedPath.slice(1)] async function createSubtreePropsFromSegmentPath(
segments: string[]
// segment.length - 1 because arrays start at 0 and we're decrementing ): Promise<string> {
for (let i = segments.length - 1; i >= 0; i--) { const segmentPath = segments.join('/')
const segment = removeExt(segments[i])
const segmentPath = segments.slice(0, i + 1).join('/')
// First item in the list is the page which can't have layouts by itself
if (i === segments.length - 1) {
const resolvedPagePath = await resolve(pagePath)
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
tree = `['', {}, {filePath: ${JSON.stringify(
resolvedPagePath
)}, page: () => require(${JSON.stringify(resolvedPagePath)})}]`
continue
}
// For segmentPath === '' avoid double `/`
const layoutPath = `${appDirPrefix}${segmentPath}/layout`
// For segmentPath === '' avoid double `/`
const loadingPath = `${appDirPrefix}${segmentPath}/loading`
const resolvedLayoutPath = await resolve(layoutPath)
const resolvedLoadingPath = await resolve(loadingPath)
// Existing tree are the children of the current segment // Existing tree are the children of the current segment
const children = tree const props: Record<string, string> = {}
// We need to resolve all parallel routes in this level.
const parallelSegments: [key: string, segment: string][] = []
if (segments.length === 0) {
parallelSegments.push(['children', ''])
} else {
parallelSegments.push(...resolveParallelSegments(segmentPath))
}
tree = `['${segment}', { for (const [parallelKey, parallelSegment] of parallelSegments) {
${ const parallelSegmentPath = segmentPath + '/' + parallelSegment
// When there are no children the current index is the page component
children ? `children: ${children},` : '' if (parallelSegment === 'page') {
const matchedPagePath = `${appDirPrefix}${parallelSegmentPath}`
const resolvedPagePath = await resolve(matchedPagePath)
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[parallelKey] = `['', {}, {filePath: ${JSON.stringify(
resolvedPagePath
)}, page: () => require(${JSON.stringify(resolvedPagePath)})}]`
continue
} }
}, {
filePath: ${JSON.stringify(resolvedLayoutPath)}, const subtree = await createSubtreePropsFromSegmentPath([
${ ...segments,
resolvedLayoutPath parallelSegment,
? `layout: () => require(${JSON.stringify(resolvedLayoutPath)}),` ])
: ''
} // For segmentPath === '' avoid double `/`
${ const layoutPath = `${appDirPrefix}${parallelSegmentPath}/layout`
resolvedLoadingPath // For segmentPath === '' avoid double `/`
? `loading: () => require(${JSON.stringify(resolvedLoadingPath)}),` const loadingPath = `${appDirPrefix}${parallelSegmentPath}/loading`
: ''
} const resolvedLayoutPath = await resolve(layoutPath)
}]` const resolvedLoadingPath = await resolve(loadingPath)
props[parallelKey] = `[
'${parallelSegment}',
${subtree},
{
filePath: ${JSON.stringify(resolvedLayoutPath)},
${
resolvedLayoutPath
? `layout: () => require(${JSON.stringify(resolvedLayoutPath)}),`
: ''
}
${
resolvedLoadingPath
? `loading: () => require(${JSON.stringify(
resolvedLoadingPath
)}),`
: ''
}
}
]`
}
return `{
${Object.entries(props)
.map(([key, value]) => `${key}: ${value}`)
.join(',\n')}
}`
} }
return `const tree = ${tree};` const tree = await createSubtreePropsFromSegmentPath([])
return `const tree = ${tree}.children;`
} }
function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) { function createAbsolutePath(appDir: string, pathToTurnAbsolute: string) {
return pathToTurnAbsolute.replace(/^private-next-app-dir/, appDir) return pathToTurnAbsolute.replace(/^private-next-app-dir/, appDir)
} }
function removeExtensions(
extensions: string[],
pathToRemoveExtensions: string
) {
const regex = new RegExp(`(${extensions.join('|')})$`.replace(/\./g, '\\.'))
return pathToRemoveExtensions.replace(regex, '')
}
const nextAppLoader: webpack.LoaderDefinitionFunction<{ const nextAppLoader: webpack.LoaderDefinitionFunction<{
name: string name: string
pagePath: string pagePath: string
appDir: string appDir: string
appPaths: string[] | null
pageExtensions: string[] pageExtensions: string[]
}> = async function nextAppLoader() { }> = async function nextAppLoader() {
const { name, appDir, pagePath, pageExtensions } = this.getOptions() || {} const { name, appDir, appPaths, pagePath, pageExtensions } =
this.getOptions() || {}
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
buildInfo.route = { buildInfo.route = {
...@@ -99,6 +117,24 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -99,6 +117,24 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
} }
const resolve = this.getResolve(resolveOptions) const resolve = this.getResolve(resolveOptions)
const normalizedAppPaths =
typeof appPaths === 'string' ? [appPaths] : appPaths || []
const resolveParallelSegments = (pathname: string) => {
const matched: Record<string, string> = {}
for (const path of normalizedAppPaths) {
if (path.startsWith(pathname + '/')) {
const restPath = path.slice(pathname.length + 1)
const matchedSegment = restPath.split('/')[0]
const matchedKey = matchedSegment.startsWith('@')
? matchedSegment.slice(1)
: 'children'
matched[matchedKey] = matchedSegment
}
}
return Object.entries(matched)
}
const resolver = async (pathname: string) => { const resolver = async (pathname: string) => {
try { try {
const resolved = await resolve(this.rootContext, pathname) const resolved = await resolve(this.rootContext, pathname)
...@@ -120,7 +156,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -120,7 +156,7 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
const treeCode = await createTreeCodeFromPath({ const treeCode = await createTreeCodeFromPath({
pagePath, pagePath,
resolve: resolver, resolve: resolver,
removeExt: (p) => removeExtensions(extensions, p), resolveParallelSegments,
}) })
const result = ` const result = `
......
...@@ -225,7 +225,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -225,7 +225,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private responseCache: ResponseCacheBase private responseCache: ResponseCacheBase
protected router: Router protected router: Router
protected dynamicRoutes?: DynamicRoutes protected dynamicRoutes?: DynamicRoutes
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 protected serverCSSManifest?: any
...@@ -239,12 +239,13 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -239,12 +239,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getBuildId(): string protected abstract getBuildId(): string
protected abstract getFilesystemPaths(): Set<string> protected abstract getFilesystemPaths(): Set<string>
protected abstract findPageComponents( protected abstract findPageComponents(params: {
pathname: string, pathname: string
query: NextParsedUrlQuery, query: NextParsedUrlQuery
params: Params, params: Params
isAppPath: boolean isAppPath: boolean
): Promise<FindComponentsResult | null> appPaths?: string[] | null
}): Promise<FindComponentsResult | null>
protected abstract getFontManifest(): FontManifest | undefined protected abstract getFontManifest(): FontManifest | undefined
protected abstract getPrerenderManifest(): PrerenderManifest protected abstract getPrerenderManifest(): PrerenderManifest
protected abstract getServerComponentManifest(): any protected abstract getServerComponentManifest(): any
...@@ -758,11 +759,15 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -758,11 +759,15 @@ export default abstract class Server<ServerOptions extends Options = Options> {
.filter((item): item is RoutingItem => Boolean(item)) .filter((item): item is RoutingItem => Boolean(item))
} }
protected getAppPathRoutes(): Record<string, string> { protected getAppPathRoutes(): Record<string, string[]> {
const appPathRoutes: Record<string, string> = {} const appPathRoutes: Record<string, string[]> = {}
Object.keys(this.appPathsManifest || {}).forEach((entry) => { Object.keys(this.appPathsManifest || {}).forEach((entry) => {
appPathRoutes[normalizeAppPath(entry) || '/'] = entry const normalizedPath = normalizeAppPath(entry) || '/'
if (!appPathRoutes[normalizedPath]) {
appPathRoutes[normalizedPath] = []
}
appPathRoutes[normalizedPath].push(entry)
}) })
return appPathRoutes return appPathRoutes
} }
...@@ -1504,7 +1509,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1504,7 +1509,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
// map the route to the actual bundle name // map the route to the actual bundle name
protected getOriginalAppPath(route: string) { protected getOriginalAppPaths(route: string) {
if (this.nextConfig.experimental.appDir) { if (this.nextConfig.experimental.appDir) {
const originalAppPath = this.appPathRoutes?.[route] const originalAppPath = this.appPathRoutes?.[route]
...@@ -1523,18 +1528,22 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1523,18 +1528,22 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) { ) {
const { query, pathname } = ctx const { query, pathname } = ctx
const appPaths = this.getOriginalAppPaths(pathname)
let page = pathname let page = pathname
const appPath = this.getOriginalAppPath(pathname) if (Array.isArray(appPaths)) {
if (typeof appPath === 'string') { // When it's an array, we need to pass all parallel routes to the loader.
page = appPath page = appPaths[0]
} }
const result = await this.findPageComponents( const result = await this.findPageComponents({
page, pathname: page,
query, query,
ctx.renderOpts.params || {}, params: ctx.renderOpts.params || {},
typeof appPath === 'string' isAppPath: Array.isArray(appPaths),
) appPaths,
})
if (result) { if (result) {
try { try {
return await this.renderToResponseWithComponents(ctx, result) return await this.renderToResponseWithComponents(ctx, result)
...@@ -1737,7 +1746,12 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1737,7 +1746,12 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// use static 404 page if available and is 404 response // use static 404 page if available and is 404 response
if (is404 && (await this.hasPage('/404'))) { if (is404 && (await this.hasPage('/404'))) {
result = await this.findPageComponents('/404', query, {}, false) result = await this.findPageComponents({
pathname: '/404',
query,
params: {},
isAppPath: false,
})
using404Page = result !== null using404Page = result !== null
} }
let statusPage = `/${res.statusCode}` let statusPage = `/${res.statusCode}`
...@@ -1750,12 +1764,22 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1750,12 +1764,22 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// skip ensuring /500 in dev mode as it isn't used and the // skip ensuring /500 in dev mode as it isn't used and the
// dev overlay is used instead // dev overlay is used instead
if (statusPage !== '/500' || !this.renderOpts.dev) { if (statusPage !== '/500' || !this.renderOpts.dev) {
result = await this.findPageComponents(statusPage, query, {}, false) result = await this.findPageComponents({
pathname: statusPage,
query,
params: {},
isAppPath: false,
})
} }
} }
if (!result) { if (!result) {
result = await this.findPageComponents('/_error', query, {}, false) result = await this.findPageComponents({
pathname: '/_error',
query,
params: {},
isAppPath: false,
})
statusPage = '/_error' statusPage = '/_error'
} }
......
...@@ -272,7 +272,7 @@ export default class HotReloader { ...@@ -272,7 +272,7 @@ export default class HotReloader {
if (page === '/_error' || BLOCKED_PAGES.indexOf(page) === -1) { if (page === '/_error' || BLOCKED_PAGES.indexOf(page) === -1) {
try { try {
await this.ensurePage(page, true) await this.ensurePage({ page, clientOnly: true })
} catch (error) { } catch (error) {
await renderScriptError(pageBundleRes, getProperError(error)) await renderScriptError(pageBundleRes, getProperError(error))
return { finished: true } return { finished: true }
...@@ -616,6 +616,7 @@ export default class HotReloader { ...@@ -616,6 +616,7 @@ export default class HotReloader {
isApp && this.appDir isApp && this.appDir
? getAppEntry({ ? getAppEntry({
name: bundlePath, name: bundlePath,
appPaths: entryData.appPaths,
pagePath: posix.join( pagePath: posix.join(
APP_DIR_ALIAS, APP_DIR_ALIAS,
relative( relative(
...@@ -693,6 +694,7 @@ export default class HotReloader { ...@@ -693,6 +694,7 @@ export default class HotReloader {
this.appDir && bundlePath.startsWith('app/') this.appDir && bundlePath.startsWith('app/')
? getAppEntry({ ? getAppEntry({
name: bundlePath, name: bundlePath,
appPaths: entryData.appPaths,
pagePath: posix.join( pagePath: posix.join(
APP_DIR_ALIAS, APP_DIR_ALIAS,
relative( relative(
...@@ -1072,7 +1074,15 @@ export default class HotReloader { ...@@ -1072,7 +1074,15 @@ export default class HotReloader {
) )
} }
public async ensurePage(page: string, clientOnly: boolean): Promise<void> { public async ensurePage({
page,
clientOnly,
appPaths,
}: {
page: string
clientOnly: boolean
appPaths?: string[] | null
}): Promise<void> {
// Make sure we don't re-build or dispose prebuilt pages // Make sure we don't re-build or dispose prebuilt pages
if (page !== '/_error' && BLOCKED_PAGES.indexOf(page) !== -1) { if (page !== '/_error' && BLOCKED_PAGES.indexOf(page) !== -1) {
return return
...@@ -1083,6 +1093,10 @@ export default class HotReloader { ...@@ -1083,6 +1093,10 @@ export default class HotReloader {
if (error) { if (error) {
return Promise.reject(error) return Promise.reject(error)
} }
return this.onDemandEntries?.ensurePage(page, clientOnly) as any return this.onDemandEntries?.ensurePage({
page,
clientOnly,
appPaths,
}) as any
} }
} }
...@@ -311,7 +311,7 @@ export default class DevServer extends Server { ...@@ -311,7 +311,7 @@ export default class DevServer extends Server {
let middlewareMatchers: MiddlewareMatcher[] | undefined let middlewareMatchers: MiddlewareMatcher[] | undefined
const routedPages: string[] = [] const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const appPaths: Record<string, string> = {} const appPaths: Record<string, string[]> = {}
const edgeRoutesSet = new Set<string>() const edgeRoutesSet = new Set<string>()
let envChange = false let envChange = false
...@@ -396,7 +396,10 @@ export default class DevServer extends Server { ...@@ -396,7 +396,10 @@ export default class DevServer extends Server {
const originalPageName = pageName const originalPageName = pageName
pageName = normalizeAppPath(pageName) || '/' pageName = normalizeAppPath(pageName) || '/'
appPaths[pageName] = originalPageName if (!appPaths[pageName]) {
appPaths[pageName] = []
}
appPaths[pageName].push(originalPageName)
if (routedPages.includes(pageName)) { if (routedPages.includes(pageName)) {
continue continue
...@@ -542,13 +545,15 @@ export default class DevServer extends Server { ...@@ -542,13 +545,15 @@ export default class DevServer extends Server {
nestedMiddleware = [] nestedMiddleware = []
} }
this.appPathRoutes = appPaths // Make sure to sort parallel routes to make the result deterministic.
this.appPathRoutes = Object.fromEntries(
Object.entries(appPaths).map(([k, v]) => [k, v.sort()])
)
const edgeRoutes = Array.from(edgeRoutesSet) const edgeRoutes = Array.from(edgeRoutesSet)
this.edgeFunctions = getSortedRoutes(edgeRoutes).map((page) => { this.edgeFunctions = getSortedRoutes(edgeRoutes).map((page) => {
const appPath = this.getOriginalAppPath(page) const matchedAppPaths = this.getOriginalAppPaths(page)
if (Array.isArray(matchedAppPaths)) {
if (typeof appPath === 'string') { page = matchedAppPaths[0]
page = appPath
} }
const edgeRegex = getRouteRegex(page) const edgeRegex = getRouteRegex(page)
return { return {
...@@ -902,6 +907,7 @@ export default class DevServer extends Server { ...@@ -902,6 +907,7 @@ export default class DevServer extends Server {
query: ParsedUrlQuery query: ParsedUrlQuery
params: Params | undefined params: Params | undefined
page: string page: string
appPaths: string[] | null
isAppPath: boolean isAppPath: boolean
}) { }) {
try { try {
...@@ -1118,11 +1124,20 @@ export default class DevServer extends Server { ...@@ -1118,11 +1124,20 @@ export default class DevServer extends Server {
} }
protected async ensureMiddleware() { protected async ensureMiddleware() {
return this.hotReloader!.ensurePage(this.actualMiddlewareFile!, false) return this.hotReloader!.ensurePage({
page: this.actualMiddlewareFile!,
clientOnly: false,
})
} }
protected async ensureEdgeFunction(pathname: string) { protected async ensureEdgeFunction({
return this.hotReloader!.ensurePage(pathname, false) page,
appPaths,
}: {
page: string
appPaths: string[] | null
}) {
return this.hotReloader!.ensurePage({ page, appPaths, clientOnly: false })
} }
generateRoutes() { generateRoutes() {
...@@ -1288,15 +1303,22 @@ export default class DevServer extends Server { ...@@ -1288,15 +1303,22 @@ export default class DevServer extends Server {
} }
protected async ensureApiPage(pathname: string): Promise<void> { protected async ensureApiPage(pathname: string): Promise<void> {
return this.hotReloader!.ensurePage(pathname, false) return this.hotReloader!.ensurePage({ page: pathname, clientOnly: false })
} }
protected async findPageComponents( protected async findPageComponents({
pathname: string, pathname,
query: ParsedUrlQuery, query,
params: Params, params,
isAppPath,
appPaths,
}: {
pathname: string
query: ParsedUrlQuery
params: Params
isAppPath: boolean isAppPath: boolean
): Promise<FindComponentsResult | null> { appPaths?: string[] | null
}): Promise<FindComponentsResult | null> {
await this.devReady await this.devReady
const compilationErr = await this.getCompilationError(pathname) const compilationErr = await this.getCompilationError(pathname)
if (compilationErr) { if (compilationErr) {
...@@ -1304,7 +1326,11 @@ export default class DevServer extends Server { ...@@ -1304,7 +1326,11 @@ export default class DevServer extends Server {
throw new WrappedBuildError(compilationErr) throw new WrappedBuildError(compilationErr)
} }
try { try {
await this.hotReloader!.ensurePage(pathname, false) await this.hotReloader!.ensurePage({
page: pathname,
appPaths,
clientOnly: false,
})
const serverComponents = this.nextConfig.experimental.serverComponents const serverComponents = this.nextConfig.experimental.serverComponents
...@@ -1315,7 +1341,7 @@ export default class DevServer extends Server { ...@@ -1315,7 +1341,7 @@ export default class DevServer extends Server {
this.serverCSSManifest = super.getServerCSSManifest() this.serverCSSManifest = super.getServerCSSManifest()
} }
return super.findPageComponents(pathname, query, params, isAppPath) return super.findPageComponents({ pathname, query, params, isAppPath })
} catch (err) { } catch (err) {
if ((err as any).code !== 'ENOENT') { if ((err as any).code !== 'ENOENT') {
throw err throw err
...@@ -1328,7 +1354,7 @@ export default class DevServer extends Server { ...@@ -1328,7 +1354,7 @@ export default class DevServer extends Server {
await this.hotReloader!.buildFallbackError() await this.hotReloader!.buildFallbackError()
// Build the error page to ensure the fallback is built too. // Build the error page to ensure the fallback is built too.
// TODO: See if this can be moved into hotReloader or removed. // TODO: See if this can be moved into hotReloader or removed.
await this.hotReloader!.ensurePage('/_error', false) await this.hotReloader!.ensurePage({ page: '/_error', clientOnly: false })
return await loadDefaultErrorComponents(this.distDir) return await loadDefaultErrorComponents(this.distDir)
} }
......
...@@ -41,7 +41,9 @@ function treePathToEntrypoint( ...@@ -41,7 +41,9 @@ function treePathToEntrypoint(
// TODO-APP: modify this path to cover parallelRouteKey convention // TODO-APP: modify this path to cover parallelRouteKey convention
const path = const path =
(parentPath ? parentPath + '/' : '') + (parentPath ? parentPath + '/' : '') +
(parallelRouteKey !== 'children' ? parallelRouteKey + '/' : '') + (parallelRouteKey !== 'children' && !segment.startsWith('@')
? parallelRouteKey + '/'
: '') +
(segment === '' ? 'page' : segment) (segment === '' ? 'page' : segment)
// Last segment // Last segment
...@@ -143,6 +145,11 @@ interface Entry extends EntryType { ...@@ -143,6 +145,11 @@ interface Entry extends EntryType {
* `/Users/Rick/project/pages/about/index.js` * `/Users/Rick/project/pages/about/index.js`
*/ */
absolutePagePath: string absolutePagePath: string
/**
* All parallel pages that match the same entry, for example:
* ['/parallel/@bar/nested/@a/page', '/parallel/@bar/nested/@b/page', '/parallel/@foo/nested/@a/page', '/parallel/@foo/nested/@b/page']
*/
appPaths: string[] | null
} }
interface ChildEntry extends EntryType { interface ChildEntry extends EntryType {
...@@ -499,6 +506,7 @@ export function onDemandEntryHandler({ ...@@ -499,6 +506,7 @@ export function onDemandEntryHandler({
toSend = { success: true } toSend = { success: true }
} }
} }
return toSend return toSend
} }
...@@ -545,7 +553,15 @@ export function onDemandEntryHandler({ ...@@ -545,7 +553,15 @@ export function onDemandEntryHandler({
} }
return { return {
async ensurePage(page: string, clientOnly: boolean): Promise<void> { async ensurePage({
page,
clientOnly,
appPaths = null,
}: {
page: string
clientOnly: boolean
appPaths?: string[] | null
}): Promise<void> {
const stalledTime = 60 const stalledTime = 60
const stalledEnsureTimeout = setTimeout(() => { const stalledEnsureTimeout = setTimeout(() => {
debug( debug(
...@@ -597,6 +613,7 @@ export function onDemandEntryHandler({ ...@@ -597,6 +613,7 @@ export function onDemandEntryHandler({
entries[entryKey] = { entries[entryKey] = {
type: EntryTypes.ENTRY, type: EntryTypes.ENTRY,
appPaths,
absolutePagePath: pagePathData.absolutePagePath, absolutePagePath: pagePathData.absolutePagePath,
request: pagePathData.absolutePagePath, request: pagePathData.absolutePagePath,
bundlePath: pagePathData.bundlePath, bundlePath: pagePathData.bundlePath,
......
...@@ -759,6 +759,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -759,6 +759,7 @@ export default class NextNodeServer extends BaseServer {
query, query,
params, params,
page, page,
appPaths: null,
isAppPath: false, isAppPath: false,
}) })
...@@ -889,40 +890,47 @@ export default class NextNodeServer extends BaseServer { ...@@ -889,40 +890,47 @@ export default class NextNodeServer extends BaseServer {
ctx: RequestContext, ctx: RequestContext,
bubbleNoFallback: boolean bubbleNoFallback: boolean
) { ) {
const appPath = this.getOriginalAppPath(ctx.pathname) || undefined
let page = ctx.pathname
const isAppPath = typeof appPath === 'string'
if (isAppPath) {
page = appPath
}
const edgeFunctions = this.getEdgeFunctions() || [] const edgeFunctions = this.getEdgeFunctions() || []
if (edgeFunctions.length) {
const appPaths = this.getOriginalAppPaths(ctx.pathname)
const isAppPath = Array.isArray(appPaths)
let page = ctx.pathname
if (isAppPath) {
// When it's an array, we need to pass all parallel routes to the loader.
page = appPaths[0]
}
for (const item of edgeFunctions) { for (const item of edgeFunctions) {
if (item.page === page) { if (item.page === page) {
await this.runEdgeFunction({ await this.runEdgeFunction({
req: ctx.req, req: ctx.req,
res: ctx.res, res: ctx.res,
query: ctx.query, query: ctx.query,
params: ctx.renderOpts.params, params: ctx.renderOpts.params,
page: ctx.pathname, page,
appPath, appPaths,
isAppPath: isAppPath, isAppPath,
}) })
return null return null
}
} }
} }
return super.renderPageComponent(ctx, bubbleNoFallback) return super.renderPageComponent(ctx, bubbleNoFallback)
} }
protected async findPageComponents( protected async findPageComponents({
pathname: string, pathname,
query: NextParsedUrlQuery, query,
params: Params, params,
isAppPath,
}: {
pathname: string
query: NextParsedUrlQuery
params: Params | null
isAppPath: boolean isAppPath: boolean
): Promise<FindComponentsResult | null> { }): Promise<FindComponentsResult | null> {
let paths = [ let paths = [
// try serving a static AMP version first // try serving a static AMP version first
query.amp query.amp
...@@ -1668,7 +1676,10 @@ export default class NextNodeServer extends BaseServer { ...@@ -1668,7 +1676,10 @@ export default class NextNodeServer extends BaseServer {
* so that we can run it. * so that we can run it.
*/ */
protected async ensureMiddleware() {} protected async ensureMiddleware() {}
protected async ensureEdgeFunction(_pathname: string) {} protected async ensureEdgeFunction(_params: {
page: string
appPaths: string[] | null
}) {}
/** /**
* This method gets all middleware matchers and execute them when the request * This method gets all middleware matchers and execute them when the request
...@@ -2016,17 +2027,16 @@ export default class NextNodeServer extends BaseServer { ...@@ -2016,17 +2027,16 @@ export default class NextNodeServer extends BaseServer {
query: ParsedUrlQuery query: ParsedUrlQuery
params: Params | undefined params: Params | undefined
page: string page: string
appPaths: string[] | null
isAppPath: boolean isAppPath: boolean
appPath?: string
onWarning?: (warning: Error) => void onWarning?: (warning: Error) => void
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined
// If it's edge app route, use appPath to find the edge SSR page const page = params.page
const page = params.isAppPath ? params.appPath! : params.page await this.ensureEdgeFunction({ page, appPaths: params.appPaths })
await this.ensureEdgeFunction(page)
middlewareInfo = this.getEdgeFunctionInfo({ middlewareInfo = this.getEdgeFunctionInfo({
page: page, page,
middleware: false, middleware: false,
}) })
......
...@@ -404,12 +404,17 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -404,12 +404,17 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
// @TODO // @TODO
return true return true
} }
protected async findPageComponents(
pathname: string, protected async findPageComponents({
query: NextParsedUrlQuery, pathname,
params: Params | null, query,
_isAppPath: boolean params,
) { }: {
pathname: string
query: NextParsedUrlQuery
params: Params | null
isAppPath: boolean
}) {
const result = await this.serverOptions.webServerConfig.loadComponent( const result = await this.serverOptions.webServerConfig.loadComponent(
pathname pathname
) )
......
...@@ -10,6 +10,10 @@ export function normalizeAppPath(pathname: string) { ...@@ -10,6 +10,10 @@ export function normalizeAppPath(pathname: string) {
return acc return acc
} }
if (segment.startsWith('@')) {
return acc
}
if (segment === 'page' && index === segments.length - 1) { if (segment === 'page' && index === segments.length - 1) {
return acc return acc
} }
......
export default function Page() {
return <div>parallel/(new)/@baz/nested/page</div>
}
export default function Layout({ baz }) {
return (
<div>
parallel/(new)/layout:
<div className="parallel" title="@baz">
{baz}
</div>
</div>
)
}
export default function Page() {
return <div>parallel/@bar/nested/@a/page</div>
}
export default function Page() {
return <div>parallel/@bar/nested/@b/page</div>
}
export default function Parallel({ a, b, children }) {
return (
<div>
parallel/@bar/nested/layout
<div className="parallel" title="@a">
{a}
</div>
<div className="parallel" title="@b">
{b}
</div>
<div className="parallel" title="children">
{children}
</div>
</div>
)
}
export default function Page() {
return <div>Bar</div>
}
export default function Page() {
return <div>parallel/@foo/nested/@a/page</div>
}
export default function Page() {
return <div>parallel/@foo/nested/@b/page</div>
}
export default function Parallel({ a, b, children }) {
return (
<div>
parallel/@foo/nested/layout
<div className="parallel" title="@a">
{a}
</div>
<div className="parallel" title="@b">
{b}
</div>
<div className="parallel" title="children">
{children}
</div>
</div>
)
}
export default function Page() {
return <div>Foo</div>
}
import './style.css'
export default function Parallel({ foo, bar, children }) {
return (
<div>
parallel/layout:
<div className="parallel" title="@foo">
{foo}
</div>
<div className="parallel" title="@bar">
{bar}
</div>
<div className="parallel" title="children">
{children}
</div>
</div>
)
}
export default function Page() {
return <div>parallel/nested/page</div>
}
div {
font-size: 16px;
}
.parallel {
border: 1px solid;
margin: 10px;
}
.parallel::before {
content: attr(title);
background: black;
color: white;
padding: 1px;
}
...@@ -273,6 +273,25 @@ describe('app dir', () => { ...@@ -273,6 +273,25 @@ describe('app dir', () => {
} }
}) })
it('should match parallel routes', async () => {
const html = await renderViaHTTP(next.url, '/parallel/nested')
expect(html).toContain('parallel/layout')
expect(html).toContain('parallel/@foo/nested/layout')
expect(html).toContain('parallel/@foo/nested/@a/page')
expect(html).toContain('parallel/@foo/nested/@b/page')
expect(html).toContain('parallel/@bar/nested/layout')
expect(html).toContain('parallel/@bar/nested/@a/page')
expect(html).toContain('parallel/@bar/nested/@b/page')
expect(html).toContain('parallel/nested/page')
})
it('should match parallel routes in route groups', async () => {
const html = await renderViaHTTP(next.url, '/parallel/nested-2')
expect(html).toContain('parallel/layout')
expect(html).toContain('parallel/(new)/layout')
expect(html).toContain('parallel/(new)/@baz/nested/page')
})
describe('<Link />', () => { describe('<Link />', () => {
// TODO-APP: fix development test // TODO-APP: fix development test
it.skip('should hard push', async () => { it.skip('should hard push', async () => {
......
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