Unverified Commit 3ac76585 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor entries.ts (#48460)

Couple of small changes, I'm preparing the file for a larger refactor
around the new entries resolving.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 9f676389
......@@ -40,7 +40,6 @@ import {
isMiddlewareFile,
isMiddlewareFilename,
isInstrumentationHookFile,
NestedMiddlewareError,
} from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
......@@ -67,6 +66,32 @@ export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
return page === '' ? '/' : page
}
function getPageFilePath({
absolutePagePath,
pagesDir,
appDir,
rootDir,
}: {
absolutePagePath: string
pagesDir: string | undefined
appDir: string | undefined
rootDir: string
}) {
if (absolutePagePath.startsWith(PAGES_DIR_ALIAS) && pagesDir) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir)
}
if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) {
return absolutePagePath.replace(APP_DIR_ALIAS, appDir)
}
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) {
return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir)
}
return require.resolve(absolutePagePath)
}
export function createPagesMapping({
isDev,
pageExtensions,
......@@ -328,7 +353,14 @@ export async function runDependingOnPageType<T>(params: {
return
}
export async function createEntrypoints(params: CreateEntrypointsParams) {
export async function createEntrypoints(
params: CreateEntrypointsParams
): Promise<{
client: webpack.EntryObject
server: webpack.EntryObject
edgeServer: webpack.EntryObject
middlewareMatchers: undefined
}> {
const {
config,
pages,
......@@ -343,7 +375,6 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const edgeServer: webpack.EntryObject = {}
const server: webpack.EntryObject = {}
const client: webpack.EntryObject = {}
const nestedMiddleware: string[] = []
let middlewareMatchers: MiddlewareMatcher[] | undefined = undefined
let appPathsPerRoute: Record<string, string[]> = {}
......@@ -367,8 +398,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}
const getEntryHandler =
(mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') =>
async (page: string) => {
(
mappings: Record<string, string>,
pagesType: 'app' | 'pages' | 'root'
): ((page: string) => void) =>
async (page) => {
const bundleFile = normalizePagePath(page)
const clientBundlePath = posix.join(pagesType, bundleFile)
const serverBundlePath =
......@@ -380,33 +414,12 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const absolutePagePath = mappings[page]
// Handle paths that have aliases
const pageFilePath = (() => {
if (absolutePagePath.startsWith(PAGES_DIR_ALIAS) && pagesDir) {
return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir)
}
if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) {
return absolutePagePath.replace(APP_DIR_ALIAS, appDir)
}
if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) {
return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir)
}
return require.resolve(absolutePagePath)
})()
/**
* When we find a middleware file that is not in the ROOT_DIR we fail.
* There is no need to check on `dev` as this should only happen when
* building for production.
*/
if (
!absolutePagePath.startsWith(ROOT_DIR_ALIAS) &&
/[\\\\/]_middleware$/.test(page)
) {
nestedMiddleware.push(page)
}
const pageFilePath = getPageFilePath({
absolutePagePath,
pagesDir,
appDir,
rootDir,
})
const isInsideAppDir =
!!appDir &&
......@@ -505,24 +518,24 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
})
}
if (appDir && appPaths) {
const promises: Promise<void[]>[] = []
if (appPaths) {
const entryHandler = getEntryHandler(appPaths, 'app')
await Promise.all(Object.keys(appPaths).map(entryHandler))
promises.push(Promise.all(Object.keys(appPaths).map(entryHandler)))
}
if (rootPaths) {
await Promise.all(
Object.keys(rootPaths).map(getEntryHandler(rootPaths, 'root'))
promises.push(
Promise.all(
Object.keys(rootPaths).map(getEntryHandler(rootPaths, 'root'))
)
)
}
await Promise.all(Object.keys(pages).map(getEntryHandler(pages, 'pages')))
promises.push(
Promise.all(Object.keys(pages).map(getEntryHandler(pages, 'pages')))
)
if (nestedMiddleware.length > 0) {
throw new NestedMiddlewareError(
nestedMiddleware,
rootDir,
(appDir || pagesDir)!
)
}
await Promise.all(promises)
return {
client,
......@@ -551,69 +564,76 @@ export function finalizeEntrypoint({
: value
const isApi = name.startsWith('pages/api/')
if (compilerType === COMPILER_NAMES.server) {
return {
publicPath: isApi ? '' : undefined,
runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
layer: isApi
? WEBPACK_LAYERS.api
: isServerComponent
? WEBPACK_LAYERS.server
: undefined,
...entry,
}
}
if (compilerType === COMPILER_NAMES.edgeServer) {
return {
layer:
isMiddlewareFilename(name) || isApi
? WEBPACK_LAYERS.middleware
switch (compilerType) {
case COMPILER_NAMES.server: {
return {
publicPath: isApi ? '' : undefined,
runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
layer: isApi
? WEBPACK_LAYERS.api
: isServerComponent
? WEBPACK_LAYERS.server
: undefined,
library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' },
runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
...entry,
...entry,
}
}
}
const isAppLayer =
hasAppDir &&
(name === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP ||
name === APP_CLIENT_INTERNALS ||
name.startsWith('app/'))
if (
// Client special cases
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) {
if (isAppLayer) {
case COMPILER_NAMES.edgeServer: {
return {
dependOn: CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
layer: WEBPACK_LAYERS.appClient,
layer:
isMiddlewareFilename(name) || isApi
? WEBPACK_LAYERS.middleware
: undefined,
library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' },
runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
...entry,
}
}
case COMPILER_NAMES.client: {
const isAppLayer =
hasAppDir &&
(name === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP ||
name === APP_CLIENT_INTERNALS ||
name.startsWith('app/'))
return {
dependOn:
name.startsWith('pages/') && name !== 'pages/_app'
? 'pages/_app'
: CLIENT_STATIC_FILES_RUNTIME_MAIN,
...entry,
}
}
if (
// Client special cases
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH
) {
if (isAppLayer) {
return {
dependOn: CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
layer: WEBPACK_LAYERS.appClient,
...entry,
}
}
if (isAppLayer) {
return {
layer: WEBPACK_LAYERS.appClient,
...entry,
return {
dependOn:
name.startsWith('pages/') && name !== 'pages/_app'
? 'pages/_app'
: CLIENT_STATIC_FILES_RUNTIME_MAIN,
...entry,
}
}
if (isAppLayer) {
return {
layer: WEBPACK_LAYERS.appClient,
...entry,
}
}
return entry
}
default: {
// Should never happen.
throw new Error('Invalid compiler type')
}
}
return entry
}
import { NextResponse } from 'next/server'
export default function middleware() {
return NextResponse.next()
}
export default function About() {
return (
<div>
<h1 className="title">About Page</h1>
</div>
)
}
export default function Page() {
return <div>ok</div>
}
/* eslint-env jest */
import { join } from 'path'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const context = {
appDir: join(__dirname, '../'),
logs: { output: '', stdout: '', stderr: '' },
}
describe('Middleware importing Node.js modules', () => {
afterEach(() => {
if (context.app) {
killApp(context.app)
}
})
describe('dev mode', () => {
// restart the app for every test since the latest error is not shown sometimes
// See https://github.com/vercel/next.js/issues/36575
beforeEach(async () => {
context.logs = { stdout: '', stderr: '' }
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
context.logs.stdout += msg
},
onStderr(msg) {
context.logs.stderr += msg
},
})
})
it('warns about nested middleware being not allowed', async () => {
const res = await fetchViaHTTP(context.appPort, '/about')
expect(res.status).toBe(200)
context.logs.stderr.includes('Nested Middleware is not allowed, found:')
context.logs.stderr.includes('pages/about/_middleware')
context.logs.stderr.includes('pages/api/_middleware')
})
})
describe('production mode', () => {
it('fails when there is a not allowed middleware', async () => {
const buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
expect(buildResult.stderr).toContain(
'Nested Middleware is not allowed, found:'
)
expect(buildResult.stderr).toContain('pages/about/_middleware')
expect(buildResult.stderr).toContain('pages/api/_middleware')
})
})
})
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