Unverified Commit a0c68c5d authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix issue with outputFileTracingExcludes and pages/api edge runtime (#59157)

## What?

Ensures `Object.entries` is not called on the `Map`. Seems this only
fails in a very particular case but potentially this fixes other issues
than the one I added in the tests too.

## How?

`Object.entries()` results in an empty array when called on a `Map`.
Created a shared type declaration for the value and removed the
`Object.entries`. Benefit of this is that we can skip the loop as well.


<!-- 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

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating 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 5d091ed9
......@@ -14,7 +14,11 @@ import {
import path from 'path'
import fs from 'fs/promises'
import type { PageInfo } from './utils'
import {
deserializePageInfos,
type PageInfos,
type SerializedPageInfos,
} from './utils'
import { loadBindings } from './swc'
import { nonNullable } from '../lib/non-nullable'
import * as ciEnvironment from '../telemetry/ci-info'
......@@ -79,7 +83,8 @@ export async function collectBuildTraces({
staticPages: string[]
hasSsrAmpPages: boolean
outputFileTracingRoot: string
pageInfos: [string, PageInfo][]
// pageInfos is serialized when this function runs in a worker.
pageInfos: PageInfos | SerializedPageInfos
nextBuildSpan?: Span
config: NextConfigComplete
buildTraceContext?: BuildTraceContext
......@@ -623,6 +628,9 @@ export async function collectBuildTraces({
}
const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}
const infos =
pageInfos instanceof Map ? pageInfos : deserializePageInfos(pageInfos)
await Promise.all(
[
...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),
......@@ -642,7 +650,7 @@ export async function collectBuildTraces({
}
// edge routes have no trace files
const [, pageInfo] = pageInfos.find((item) => item[0] === route) || []
const pageInfo = infos.get(route)
if (pageInfo?.runtime === 'edge') {
return
}
......
......@@ -114,8 +114,9 @@ import {
copyTracedFiles,
isReservedPage,
isAppBuiltinNotFoundPage,
serializePageInfos,
} from './utils'
import type { PageInfo, AppConfig } from './utils'
import type { PageInfo, PageInfos, AppConfig } from './utils'
import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import isError from '../lib/is-error'
......@@ -361,8 +362,8 @@ export default async function build(
turboNextBuildRoot = null,
buildMode: 'default' | 'experimental-compile' | 'experimental-generate'
): Promise<void> {
const isCompile = buildMode === 'experimental-compile'
const isGenerate = buildMode === 'experimental-generate'
const isCompileMode = buildMode === 'experimental-compile'
const isGenerateMode = buildMode === 'experimental-generate'
try {
const nextBuildSpan = trace('next-build', undefined, {
......@@ -407,7 +408,7 @@ export default async function build(
let buildId: string = ''
if (isGenerate) {
if (isGenerateMode) {
buildId = await fs.readFile(path.join(distDir, 'BUILD_ID'), 'utf8')
} else {
buildId = await nextBuildSpan
......@@ -497,7 +498,8 @@ export default async function build(
// For app directory, we run type checking after build. That's because
// we dynamically generate types for each layout and page in the app
// directory.
if (!appDir && !isCompile) await startTypeChecking(typeCheckingOptions)
if (!appDir && !isCompileMode)
await startTypeChecking(typeCheckingOptions)
if (appDir && 'exportPathMap' in config) {
Log.error(
......@@ -529,7 +531,7 @@ export default async function build(
expFeatureInfo,
})
if (!isGenerate) {
if (!isGenerateMode) {
buildSpinner = createSpinner('Creating an optimized production build')
}
......@@ -909,7 +911,7 @@ export default async function build(
)
}
if (config.cleanDistDir && !isGenerate) {
if (config.cleanDistDir && !isGenerateMode) {
await recursiveDelete(distDir, /^cache/)
}
......@@ -974,7 +976,7 @@ export default async function build(
? path.relative(distDir, incrementalCacheHandlerPath)
: undefined,
isExperimentalCompile: isCompile,
isExperimentalCompile: isCompileMode,
},
},
appDir: dir,
......@@ -1111,8 +1113,8 @@ export default async function build(
)
}
if (!isGenerate) {
if (isCompile && useBuildWorker) {
if (!isGenerateMode) {
if (isCompileMode && useBuildWorker) {
let durationInSeconds = 0
await webpackBuild(useBuildWorker, ['server']).then((res) => {
......@@ -1131,7 +1133,8 @@ export default async function build(
dir,
config,
distDir,
pageInfos: [],
// Serialize Map as this is sent to the worker.
pageInfos: serializePageInfos(new Map()),
staticPages: [],
hasSsrAmpPages: false,
buildTraceContext,
......@@ -1177,7 +1180,7 @@ export default async function build(
}
// For app directory, we run type checking after build.
if (appDir && !(isCompile || isGenerate)) {
if (appDir && !(isCompileMode || isGenerateMode)) {
await startTypeChecking(typeCheckingOptions)
}
......@@ -1205,7 +1208,7 @@ export default async function build(
const appNormalizedPaths = new Map<string, string>()
const appDynamicParamPaths = new Set<string>()
const appDefaultConfigs = new Map<string, AppConfig>()
const pageInfos = new Map<string, PageInfo>()
const pageInfos: PageInfos = new Map<string, PageInfo>()
const pagesManifest = JSON.parse(
await fs.readFile(pagesManifestPath, 'utf8')
) as PagesManifest
......@@ -1388,7 +1391,7 @@ export default async function build(
hasSsrAmpPages,
hasNonStaticErrorPage,
} = await staticCheckSpan.traceAsyncFn(async () => {
if (isCompile) {
if (isCompileMode) {
return {
customAppGetInitialProps: false,
namedExports: [],
......@@ -1590,7 +1593,7 @@ export default async function build(
? 'edge'
: staticInfo?.runtime
if (!isCompile) {
if (!isCompileMode) {
isServerComponent =
pageType === 'app' &&
staticInfo?.rsc !== RSC_MODULE_TYPES.client
......@@ -1940,12 +1943,12 @@ export default async function build(
)
}
if (!isGenerate && config.outputFileTracing && !buildTracesPromise) {
if (!isGenerateMode && config.outputFileTracing && !buildTracesPromise) {
buildTracesPromise = collectBuildTraces({
dir,
config,
distDir,
pageInfos: Object.entries(pageInfos),
pageInfos,
staticPages: [...staticPages],
nextBuildSpan,
hasSsrAmpPages,
......@@ -2086,7 +2089,7 @@ export default async function build(
// - getStaticProps paths
// - experimental app is enabled
if (
!isCompile &&
!isCompileMode &&
(combinedPages.length > 0 ||
useStaticPages404 ||
useDefaultStatic500 ||
......
......@@ -343,6 +343,18 @@ export interface PageInfo {
isDynamicAppRoute?: boolean
}
export type PageInfos = Map<string, PageInfo>
export type SerializedPageInfos = [string, PageInfo][]
export function serializePageInfos(input: PageInfos): SerializedPageInfos {
return Array.from(input.entries())
}
export function deserializePageInfos(input: SerializedPageInfos): PageInfos {
return new Map(input)
}
export async function printTreeView(
lists: {
pages: ReadonlyArray<string>
......
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'Edge runtime pages-api route',
{
files: __dirname,
},
({ next }) => {
it('should work edge runtime', async () => {
const res = await next.fetch('/api/edge')
const text = await res.text()
expect(text).toContain('All Good')
})
it('should work with node runtime', async () => {
const res = await next.fetch('/api/node')
const text = await res.text()
expect(text).toContain('All Good')
})
}
)
/** @type {import('next').NextConfig} */
const config = {
experimental: {
outputFileTracingExcludes: {
'*': ['anyvaluewillcauseit'],
},
},
}
module.exports = config
export const config = {
runtime: 'edge',
}
export default (_req) => new Response('All Good')
export default (_req, res) => res.send('All Good')
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