Skip to content

Commit

Permalink
Refactor entries.ts (#48460)
Browse files Browse the repository at this point in the history
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 #

-->
  • Loading branch information
timneutkens committed Apr 17, 2023
1 parent 9f67638 commit 3ac7658
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 180 deletions.
216 changes: 118 additions & 98 deletions packages/next/src/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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[]> = {}
Expand All @@ -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 =
Expand All @@ -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 &&
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
}
5 changes: 0 additions & 5 deletions test/integration/middleware-nested-error/middleware.js

This file was deleted.

This file was deleted.

7 changes: 0 additions & 7 deletions test/integration/middleware-nested-error/pages/about/index.js

This file was deleted.

This file was deleted.

3 changes: 0 additions & 3 deletions test/integration/middleware-nested-error/pages/index.js

This file was deleted.

65 changes: 0 additions & 65 deletions test/integration/middleware-nested-error/test/index.test.js

This file was deleted.

0 comments on commit 3ac7658

Please sign in to comment.