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