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