Commit ee7f95c2 authored by RobPruzan's avatar RobPruzan Committed by Jiachi Liu

enable browser debug info in terminal by default

parent f0a6103d
...@@ -314,7 +314,9 @@ export function getDefineEnv({ ...@@ -314,7 +314,9 @@ export function getDefineEnv({
: {}), : {}),
'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify( 'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(
config.experimental.browserDebugInfoInTerminal || false config.experimental?.browserDebugInfoInTerminal ??
config.browserDebugInfoInTerminal ??
true
), ),
// The devtools need to know whether or not to show an option to clear the // The devtools need to know whether or not to show an option to clear the
......
...@@ -8,7 +8,7 @@ export function getTerminalLoggingConfig(): ...@@ -8,7 +8,7 @@ export function getTerminalLoggingConfig():
} { } {
try { try {
return JSON.parse( return JSON.parse(
process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL || 'false' process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL || 'true'
) )
} catch { } catch {
return false return false
......
...@@ -312,6 +312,16 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -312,6 +312,16 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
z.literal(false), z.literal(false),
]) ])
.optional(), .optional(),
browserDebugInfoInTerminal: z
.union([
z.boolean(),
z.object({
depthLimit: z.number().int().positive().optional(),
edgeLimit: z.number().int().positive().optional(),
showSourceLocation: z.boolean().optional(),
}),
])
.optional(),
distDir: z.string().min(1).optional(), distDir: z.string().min(1).optional(),
env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(), env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(),
eslint: z eslint: z
......
...@@ -770,23 +770,25 @@ export interface ExperimentalConfig { ...@@ -770,23 +770,25 @@ export interface ExperimentalConfig {
/** /**
* Enable debug information to be forwarded from browser to dev server stdout/stderr * Enable debug information to be forwarded from browser to dev server stdout/stderr
* @deprecated Use top-level `browserDebugInfoInTerminal` instead
*/ */
browserDebugInfoInTerminal?: browserDebugInfoInTerminal?:
| boolean | boolean
| { | {
/** /**
* Option to limit stringification at a specific nesting depth when logging circular objects. * Limit stringification depth for nested objects/arrays
* @default 5 * @default 5
*/ */
depthLimit?: number depthLimit?: number
/** /**
* Maximum number of properties/elements to stringify when logging objects/arrays with circular references. * Max number of properties or elements to include per object or array
* @default 100 * @default 100
*/ */
edgeLimit?: number edgeLimit?: number
/** /**
* Whether to include source location information in debug output when available * Whether to include source location information in debug output when available
* @default false
*/ */
showSourceLocation?: boolean showSourceLocation?: boolean
} }
...@@ -1042,6 +1044,33 @@ export interface NextConfig extends Record<string, any> { ...@@ -1042,6 +1044,33 @@ export interface NextConfig extends Record<string, any> {
position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
} }
/**
* Enable debug information to be forwarded from browser to dev server stdout/stderr
* @default true
* @see [Browser Debug Info](https://nextjs.org/docs/app/api-reference/config/next-config-js/browserDebugInfoInTerminal)
*/
browserDebugInfoInTerminal?:
| boolean
| {
/**
* Limit stringification depth for nested objects/arrays
* @default 5
*/
depthLimit?: number
/**
* Max number of properties or elements to include per object or array.
* @default 100
*/
edgeLimit?: number
/**
* Whether to include source location information in debug output when available
* @default false
*/
showSourceLocation?: boolean
}
/** /**
* Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development. * Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development.
* *
...@@ -1327,6 +1356,7 @@ export const defaultConfig = Object.freeze({ ...@@ -1327,6 +1356,7 @@ export const defaultConfig = Object.freeze({
devIndicators: { devIndicators: {
position: 'bottom-left', position: 'bottom-left',
}, },
browserDebugInfoInTerminal: true,
onDemandEntries: { onDemandEntries: {
maxInactiveAge: 60 * 1000, maxInactiveAge: 60 * 1000,
pagesBufferLength: 5, pagesBufferLength: 5,
......
...@@ -13,6 +13,19 @@ import { ...@@ -13,6 +13,19 @@ import {
type ConsoleEntry, type ConsoleEntry,
UNDEFINED_MARKER, UNDEFINED_MARKER,
} from '../../../next-devtools/shared/forward-logs-shared' } from '../../../next-devtools/shared/forward-logs-shared'
import type { NextConfigComplete } from '../../config-shared'
export function getDisplayedSourceLocation(
location: string | null | undefined,
config: NextConfigComplete['browserDebugInfoInTerminal']
) {
const shouldShowSourceLocation =
typeof config === 'object' && config.showSourceLocation === true
if (!location || !shouldShowSourceLocation) {
return null
}
return dim(`(${location})`)
}
export function restoreUndefined(x: any): any { export function restoreUndefined(x: any): any {
if (x === UNDEFINED_MARKER) return undefined if (x === UNDEFINED_MARKER) return undefined
...@@ -238,7 +251,8 @@ async function prepareConsoleArgs( ...@@ -238,7 +251,8 @@ async function prepareConsoleArgs(
async function prepareConsoleErrorArgs( async function prepareConsoleErrorArgs(
entry: Extract<ServerLogEntry, { kind: 'any-logged-error' }>, entry: Extract<ServerLogEntry, { kind: 'any-logged-error' }>,
ctx: MappingContext, ctx: MappingContext,
distDir: string distDir: string,
config: NextConfigComplete['browserDebugInfoInTerminal']
) { ) {
const deserialized = await Promise.all( const deserialized = await Promise.all(
entry.args.map(async (arg) => { entry.args.map(async (arg) => {
...@@ -264,10 +278,12 @@ async function prepareConsoleErrorArgs( ...@@ -264,10 +278,12 @@ async function prepareConsoleErrorArgs(
* - the user already knows where the console.error is at because we append the location * - the user already knows where the console.error is at because we append the location
*/ */
const location = getConsoleLocation(mappedStack) const location = getConsoleLocation(mappedStack)
const displayedSourceLocation = getDisplayedSourceLocation(location, config)
if (entry.args.some((a) => a.kind === 'formatted-error-arg')) { if (entry.args.some((a) => a.kind === 'formatted-error-arg')) {
const result = stripFormatSpecifiers(deserialized) const result = stripFormatSpecifiers(deserialized)
if (location) { if (displayedSourceLocation) {
result.push(dim(`(${location})`)) result.push(displayedSourceLocation)
} }
return result return result
} }
...@@ -275,8 +291,8 @@ async function prepareConsoleErrorArgs( ...@@ -275,8 +291,8 @@ async function prepareConsoleErrorArgs(
...processConsoleFormatStrings(deserialized), ...processConsoleFormatStrings(deserialized),
colorError(mappedStack), colorError(mappedStack),
] ]
if (location) { if (displayedSourceLocation) {
result.push(dim(`(${location})`)) result.push(displayedSourceLocation)
} }
return result return result
} }
...@@ -285,7 +301,8 @@ async function handleTable( ...@@ -285,7 +301,8 @@ async function handleTable(
entry: ConsoleEntry<string>, entry: ConsoleEntry<string>,
browserPrefix: string, browserPrefix: string,
ctx: MappingContext, ctx: MappingContext,
distDir: string distDir: string,
config: NextConfigComplete['browserDebugInfoInTerminal']
) { ) {
const deserializedArgs = await Promise.all( const deserializedArgs = await Promise.all(
entry.args.map(async (arg: any) => { entry.args.map(async (arg: any) => {
...@@ -311,8 +328,10 @@ async function handleTable( ...@@ -311,8 +328,10 @@ async function handleTable(
// we can't inline pass browser prefix, but it looks better multiline for table anyways // we can't inline pass browser prefix, but it looks better multiline for table anyways
forwardConsole.log(browserPrefix) forwardConsole.log(browserPrefix)
forwardConsole.table(...deserializedArgs) forwardConsole.table(...deserializedArgs)
if (location) {
forwardConsole.log(dim(`(${location})`)) const displayedSourceLocation = getDisplayedSourceLocation(location, config)
if (displayedSourceLocation) {
forwardConsole.log(displayedSourceLocation)
} }
} }
...@@ -320,7 +339,8 @@ async function handleTrace( ...@@ -320,7 +339,8 @@ async function handleTrace(
entry: ConsoleEntry<string>, entry: ConsoleEntry<string>,
browserPrefix: string, browserPrefix: string,
ctx: MappingContext, ctx: MappingContext,
distDir: string distDir: string,
config: NextConfigComplete['browserDebugInfoInTerminal']
) { ) {
const deserializedArgs = await Promise.all( const deserializedArgs = await Promise.all(
entry.args.map(async (arg: any) => { entry.args.map(async (arg: any) => {
...@@ -349,11 +369,13 @@ async function handleTrace( ...@@ -349,11 +369,13 @@ async function handleTrace(
]) ])
const location = getConsoleLocation(mappedIgnored) const location = getConsoleLocation(mappedIgnored)
const displayedSourceLocation = getDisplayedSourceLocation(location, config)
forwardConsole.log( forwardConsole.log(
browserPrefix, browserPrefix,
...deserializedArgs, ...deserializedArgs,
`\n${mapped.stack}`, `\n${mapped.stack}`,
...(location ? [`\n${dim(`(${location})`)}`] : []) ...(displayedSourceLocation ? [`\n${displayedSourceLocation}`] : [])
) )
} }
...@@ -361,7 +383,8 @@ async function handleDir( ...@@ -361,7 +383,8 @@ async function handleDir(
entry: ConsoleEntry<string>, entry: ConsoleEntry<string>,
browserPrefix: string, browserPrefix: string,
ctx: MappingContext, ctx: MappingContext,
distDir: string distDir: string,
config: NextConfigComplete['browserDebugInfoInTerminal']
) { ) {
const loggableEntry = await prepareConsoleArgs(entry, ctx, distDir) const loggableEntry = await prepareConsoleArgs(entry, ctx, distDir)
const consoleMethod = const consoleMethod =
...@@ -373,7 +396,9 @@ async function handleDir( ...@@ -373,7 +396,9 @@ async function handleDir(
ctx, ctx,
distDir distDir
) )
const location = dim(`(${getConsoleLocation(mapped)})`) const location = getConsoleLocation(mapped)
const displayedSourceLocation = getDisplayedSourceLocation(location, config)
const originalWrite = process.stdout.write.bind(process.stdout) const originalWrite = process.stdout.write.bind(process.stdout)
let captured = '' let captured = ''
process.stdout.write = (chunk) => { process.stdout.write = (chunk) => {
...@@ -386,7 +411,9 @@ async function handleDir( ...@@ -386,7 +411,9 @@ async function handleDir(
process.stdout.write = originalWrite process.stdout.write = originalWrite
} }
const preserved = captured.replace(/\r?\n$/, '') const preserved = captured.replace(/\r?\n$/, '')
originalWrite(`${browserPrefix}${preserved} ${location}\n`) originalWrite(
`${browserPrefix}${preserved}${displayedSourceLocation ? ` ${displayedSourceLocation}` : ''}\n`
)
return return
} }
consoleMethod(browserPrefix, ...loggableEntry) consoleMethod(browserPrefix, ...loggableEntry)
...@@ -397,7 +424,7 @@ async function handleDefaultConsole( ...@@ -397,7 +424,7 @@ async function handleDefaultConsole(
browserPrefix: string, browserPrefix: string,
ctx: MappingContext, ctx: MappingContext,
distDir: string, distDir: string,
config: boolean | { logDepth?: number; showSourceLocation?: boolean } config: NextConfigComplete['browserDebugInfoInTerminal']
) { ) {
const loggableEntry = await prepareConsoleArgs(entry, ctx, distDir) const loggableEntry = await prepareConsoleArgs(entry, ctx, distDir)
const withStackEntry = await withLocation( const withStackEntry = await withLocation(
...@@ -417,7 +444,7 @@ export async function handleLog( ...@@ -417,7 +444,7 @@ export async function handleLog(
entries: ServerLogEntry[], entries: ServerLogEntry[],
ctx: MappingContext, ctx: MappingContext,
distDir: string, distDir: string,
config: boolean | { logDepth?: number; showSourceLocation?: boolean } config: NextConfigComplete['browserDebugInfoInTerminal']
): Promise<void> { ): Promise<void> {
const browserPrefix = cyan('[browser]') const browserPrefix = cyan('[browser]')
...@@ -428,16 +455,16 @@ export async function handleLog( ...@@ -428,16 +455,16 @@ export async function handleLog(
switch (entry.method) { switch (entry.method) {
case 'table': { case 'table': {
// timeout based abort on source mapping result // timeout based abort on source mapping result
await handleTable(entry, browserPrefix, ctx, distDir) await handleTable(entry, browserPrefix, ctx, distDir, config)
break break
} }
// ignore frames // ignore frames
case 'trace': { case 'trace': {
await handleTrace(entry, browserPrefix, ctx, distDir) await handleTrace(entry, browserPrefix, ctx, distDir, config)
break break
} }
case 'dir': { case 'dir': {
await handleDir(entry, browserPrefix, ctx, distDir) await handleDir(entry, browserPrefix, ctx, distDir, config)
break break
} }
case 'dirxml': { case 'dirxml': {
...@@ -476,7 +503,12 @@ export async function handleLog( ...@@ -476,7 +503,12 @@ export async function handleLog(
} }
// any logged errors are anything that are logged as "red" in the browser but aren't only an Error (console.error, Promise.reject(100)) // any logged errors are anything that are logged as "red" in the browser but aren't only an Error (console.error, Promise.reject(100))
case 'any-logged-error': { case 'any-logged-error': {
const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir) const consoleArgs = await prepareConsoleErrorArgs(
entry,
ctx,
distDir,
config
)
forwardConsole.error(browserPrefix, ...consoleArgs) forwardConsole.error(browserPrefix, ...consoleArgs)
break break
} }
...@@ -496,7 +528,12 @@ export async function handleLog( ...@@ -496,7 +528,12 @@ export async function handleLog(
} catch { } catch {
switch (entry.kind) { switch (entry.kind) {
case 'any-logged-error': { case 'any-logged-error': {
const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir) const consoleArgs = await prepareConsoleErrorArgs(
entry,
ctx,
distDir,
config
)
forwardConsole.error(browserPrefix, ...consoleArgs) forwardConsole.error(browserPrefix, ...consoleArgs)
break break
} }
...@@ -531,7 +568,7 @@ export async function receiveBrowserLogsWebpack(opts: { ...@@ -531,7 +568,7 @@ export async function receiveBrowserLogsWebpack(opts: {
edgeServerStats: () => any edgeServerStats: () => any
rootDirectory: string rootDirectory: string
distDir: string distDir: string
config: boolean | { logDepth?: number; showSourceLocation?: boolean } config: NextConfigComplete['browserDebugInfoInTerminal']
}): Promise<void> { }): Promise<void> {
const { const {
entries, entries,
...@@ -569,7 +606,7 @@ export async function receiveBrowserLogsTurbopack(opts: { ...@@ -569,7 +606,7 @@ export async function receiveBrowserLogsTurbopack(opts: {
project: Project project: Project
projectPath: string projectPath: string
distDir: string distDir: string
config: boolean | { logDepth?: number; showSourceLocation?: boolean } config: NextConfigComplete['browserDebugInfoInTerminal']
}): Promise<void> { }): Promise<void> {
const { entries, router, sourceType, project, projectPath, distDir } = opts const { entries, router, sourceType, project, projectPath, distDir } = opts
......
import { getOriginalStackFrames as getOriginalStackFramesWebpack } from '../middleware-webpack' import { getOriginalStackFrames as getOriginalStackFramesWebpack } from '../middleware-webpack'
import { getOriginalStackFrames as getOriginalStackFramesTurbopack } from '../middleware-turbopack' import { getOriginalStackFrames as getOriginalStackFramesTurbopack } from '../middleware-turbopack'
import type { Project } from '../../../build/swc/types' import type { Project } from '../../../build/swc/types'
import { dim } from '../../../lib/picocolors'
import { parseStack, type StackFrame } from '../../lib/parse-stack' import { parseStack, type StackFrame } from '../../lib/parse-stack'
import path from 'path' import path from 'path'
import { LRUCache } from '../../lib/lru-cache' import { LRUCache } from '../../lib/lru-cache'
import { getDisplayedSourceLocation } from './receive-logs'
import type { NextConfigComplete } from '../../config-shared'
type WebpackMappingContext = { type WebpackMappingContext = {
bundler: 'webpack' bundler: 'webpack'
...@@ -261,23 +262,21 @@ export const withLocation = async ( ...@@ -261,23 +262,21 @@ export const withLocation = async (
}, },
ctx: MappingContext, ctx: MappingContext,
distDir: string, distDir: string,
config: boolean | { logDepth?: number; showSourceLocation?: boolean } config: NextConfigComplete['browserDebugInfoInTerminal']
) => { ) => {
if (typeof config === 'object' && config.showSourceLocation === false) {
return original
}
if (!stack) { if (!stack) {
return original return original
} }
const res = await getSourceMappedStackFrames(stack, ctx, distDir) const res = await getSourceMappedStackFrames(stack, ctx, distDir)
const location = getConsoleLocation(res) const location = getConsoleLocation(res)
const displayedSourceLocation = getDisplayedSourceLocation(location, config)
if (!location) { if (!displayedSourceLocation) {
return original return original
} }
return [...original, dim(`(${location})`)] return [...original, displayedSourceLocation]
} }
export const getConsoleLocation = ( export const getConsoleLocation = (
......
...@@ -857,7 +857,11 @@ export async function createHotReloaderTurbopack( ...@@ -857,7 +857,11 @@ export async function createHotReloaderTurbopack(
// TODO // TODO
break break
case 'browser-logs': { case 'browser-logs': {
if (nextConfig.experimental.browserDebugInfoInTerminal) { const browserDebugConfig =
nextConfig.experimental?.browserDebugInfoInTerminal ??
nextConfig.browserDebugInfoInTerminal ??
true
if (browserDebugConfig) {
await receiveBrowserLogsTurbopack({ await receiveBrowserLogsTurbopack({
entries: parsedData.entries, entries: parsedData.entries,
router: parsedData.router, router: parsedData.router,
...@@ -865,7 +869,7 @@ export async function createHotReloaderTurbopack( ...@@ -865,7 +869,7 @@ export async function createHotReloaderTurbopack(
project, project,
projectPath, projectPath,
distDir, distDir,
config: nextConfig.experimental.browserDebugInfoInTerminal, config: browserDebugConfig,
}) })
} }
break break
......
...@@ -560,7 +560,11 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -560,7 +560,11 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
break break
} }
case 'browser-logs': { case 'browser-logs': {
if (this.config.experimental.browserDebugInfoInTerminal) { const browserDebugConfig =
this.config.experimental?.browserDebugInfoInTerminal ??
this.config.browserDebugInfoInTerminal ??
true
if (browserDebugConfig) {
await receiveBrowserLogsWebpack({ await receiveBrowserLogsWebpack({
entries: payload.entries, entries: payload.entries,
router: payload.router, router: payload.router,
...@@ -570,7 +574,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -570,7 +574,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
edgeServerStats: () => this.edgeServerStats, edgeServerStats: () => this.edgeServerStats,
rootDirectory: this.dir, rootDirectory: this.dir,
distDir: this.distDir, distDir: this.distDir,
config: this.config.experimental.browserDebugInfoInTerminal, config: browserDebugConfig,
}) })
} }
break break
......
...@@ -53,13 +53,6 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -53,13 +53,6 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
pages: new FileRef(join(__dirname, 'fixtures/pages')), pages: new FileRef(join(__dirname, 'fixtures/pages')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -162,13 +155,6 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -162,13 +155,6 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
app: new FileRef(join(__dirname, 'fixtures/app')), app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -226,13 +212,6 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -226,13 +212,6 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
app: new FileRef(join(__dirname, 'fixtures/app')), app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -292,13 +271,6 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -292,13 +271,6 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
app: new FileRef(join(__dirname, 'fixtures/app')), app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -341,15 +313,6 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -341,15 +313,6 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
pages: new FileRef(join(__dirname, 'fixtures/pages')), pages: new FileRef(join(__dirname, 'fixtures/pages')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: {
showSourceLocation: false
}
}
}
`,
}, },
}) })
}) })
......
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