Unverified Commit be19d30b authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Replace the group frames with button for ignored frames (#72964)

parent f121fbe2
export function shouldIgnorePath(modulePath: string): boolean {
return (
modulePath.includes('node_modules') ||
// Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
modulePath.includes('next/dist')
)
}
...@@ -6,6 +6,7 @@ const styles = css` ...@@ -6,6 +6,7 @@ const styles = css`
border-radius: var(--size-gap-half); border-radius: var(--size-gap-half);
background-color: var(--color-ansi-bg); background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg); color: var(--color-ansi-fg);
margin-bottom: var(--size-gap-double);
} }
[data-nextjs-codeframe]::selection, [data-nextjs-codeframe]::selection,
[data-nextjs-codeframe] *::selection { [data-nextjs-codeframe] *::selection {
......
...@@ -42,6 +42,7 @@ export const CallStackFrame: React.FC<{ ...@@ -42,6 +42,7 @@ export const CallStackFrame: React.FC<{
</h3> </h3>
<div <div
data-has-source={hasSource ? 'true' : undefined} data-has-source={hasSource ? 'true' : undefined}
data-no-source={hasSource ? undefined : 'true'}
tabIndex={hasSource ? 10 : undefined} tabIndex={hasSource ? 10 : undefined}
role={hasSource ? 'link' : undefined} role={hasSource ? 'link' : undefined}
onClick={open} onClick={open}
......
...@@ -2,69 +2,78 @@ import * as React from 'react' ...@@ -2,69 +2,78 @@ import * as React from 'react'
import { CodeFrame } from '../../components/CodeFrame' import { CodeFrame } from '../../components/CodeFrame'
import type { ReadyRuntimeError } from '../../helpers/get-error-by-type' import type { ReadyRuntimeError } from '../../helpers/get-error-by-type'
import { noop as css } from '../../helpers/noop-template' import { noop as css } from '../../helpers/noop-template'
import { groupStackFramesByFramework } from '../../helpers/group-stack-frames-by-framework' import { CallStackFrame } from './CallStackFrame'
import { GroupedStackFrames } from './GroupedStackFrames'
export type RuntimeErrorProps = { error: ReadyRuntimeError } export type RuntimeErrorProps = { error: ReadyRuntimeError }
export function RuntimeError({ error }: RuntimeErrorProps) { export function RuntimeError({ error }: RuntimeErrorProps) {
const { frames } = error const [isIgnoredExpanded, setIsIgnoredExpanded] = React.useState(false)
const { firstFrame, allLeadingFrames, allCallStackFrames } = const {
React.useMemo(() => { firstFrame,
const firstFirstPartyFrameIndex = frames.findIndex( allLeadingFrames,
(entry) => trailingCallStackFrames,
!entry.ignored && displayedFramesCount,
Boolean(entry.originalCodeFrame) && } = React.useMemo(() => {
Boolean(entry.originalStackFrame) const filteredFrames = error.frames.filter((frame) =>
) isIgnoredExpanded ? true : !frame.ignored
)
return {
firstFrame: frames[firstFirstPartyFrameIndex] ?? null, const firstFirstPartyFrameIndex = filteredFrames.findIndex(
allLeadingFrames: (entry) =>
firstFirstPartyFrameIndex < 0 !entry.ignored &&
? [] Boolean(entry.originalCodeFrame) &&
: frames.slice(0, firstFirstPartyFrameIndex), Boolean(entry.originalStackFrame)
allCallStackFrames: frames.slice(firstFirstPartyFrameIndex + 1), )
}
}, [frames]) return {
displayedFramesCount: filteredFrames.length,
const { leadingFramesGroupedByFramework, stackFramesGroupedByFramework } = firstFrame: filteredFrames[firstFirstPartyFrameIndex] ?? null,
React.useMemo(() => { allLeadingFrames:
const leadingFrames = allLeadingFrames.filter((f) => !f.ignored) firstFirstPartyFrameIndex < 0
? []
return { : filteredFrames.slice(0, firstFirstPartyFrameIndex),
stackFramesGroupedByFramework: trailingCallStackFrames: filteredFrames.slice(
groupStackFramesByFramework(allCallStackFrames), firstFirstPartyFrameIndex + 1
),
leadingFramesGroupedByFramework: }
groupStackFramesByFramework(leadingFrames), }, [error.frames, isIgnoredExpanded])
}
}, [allCallStackFrames, allLeadingFrames])
return ( return (
<React.Fragment> <React.Fragment>
{firstFrame ? ( {firstFrame ? (
<React.Fragment> <>
<h2>Source</h2> <h2>Source</h2>
<GroupedStackFrames {allLeadingFrames.map((frame, frameIndex) => (
groupedStackFrames={leadingFramesGroupedByFramework} <CallStackFrame
/> key={`call-stack-leading-${frameIndex}`}
frame={frame}
/>
))}
<CodeFrame <CodeFrame
stackFrame={firstFrame.originalStackFrame!} stackFrame={firstFrame.originalStackFrame!}
codeFrame={firstFrame.originalCodeFrame!} codeFrame={firstFrame.originalCodeFrame!}
/> />
</React.Fragment> </>
) : undefined} ) : undefined}
{stackFramesGroupedByFramework.length ? ( {trailingCallStackFrames.map((frame, frameIndex) => (
<React.Fragment> <CallStackFrame
<h2>Call Stack</h2> key={`call-stack-leading-${frameIndex}`}
frame={frame}
<GroupedStackFrames />
groupedStackFrames={stackFramesGroupedByFramework} ))}
/> {
</React.Fragment> // if the default displayed ignored frames count is equal equal to the total frames count, hide the button
) : undefined} displayedFramesCount === error.frames.length &&
!isIgnoredExpanded ? null : (
<button
data-expand-ignore-button={isIgnoredExpanded}
onClick={() => setIsIgnoredExpanded(!isIgnoredExpanded)}
>
{`${isIgnoredExpanded ? 'Hide' : 'Show'} ignored frames`}
</button>
)
}
</React.Fragment> </React.Fragment>
) )
} }
...@@ -75,6 +84,19 @@ export const styles = css` ...@@ -75,6 +84,19 @@ export const styles = css`
margin-bottom: var(--size-gap-double); margin-bottom: var(--size-gap-double);
} }
[data-expand-ignore-button]:focus:not(:focus-visible),
[data-expand-ignore-button] {
background: none;
border: none;
color: var(--color-font);
cursor: pointer;
font-size: var(--size-font);
margin: var(--size-gap) 0;
padding: 0;
text-decoration: underline;
outline: none;
}
[data-nextjs-data-runtime-error-copy-button], [data-nextjs-data-runtime-error-copy-button],
[data-nextjs-data-runtime-error-copy-button]:focus:not(:focus-visible) { [data-nextjs-data-runtime-error-copy-button]:focus:not(:focus-visible) {
position: relative; position: relative;
...@@ -108,13 +130,13 @@ export const styles = css` ...@@ -108,13 +130,13 @@ export const styles = css`
[data-nextjs-call-stack-frame] > h3, [data-nextjs-call-stack-frame] > h3,
[data-nextjs-component-stack-frame] > h3 { [data-nextjs-component-stack-frame] > h3 {
margin-top: 0; margin-top: 0;
margin-bottom: var(--size-gap); margin-bottom: 0;
font-family: var(--font-stack-monospace); font-family: var(--font-stack-monospace);
font-size: var(--size-font); font-size: var(--size-font);
color: #666;
} }
[data-nextjs-call-stack-frame] > h3[data-nextjs-frame-expanded='false'] { [data-nextjs-call-stack-frame] > h3[data-nextjs-frame-expanded='false'] {
color: #666; color: #666;
display: inline-block;
} }
[data-nextjs-call-stack-frame] > div, [data-nextjs-call-stack-frame] > div,
[data-nextjs-component-stack-frame] > div { [data-nextjs-component-stack-frame] > div {
......
...@@ -19,6 +19,14 @@ import type { Project, TurbopackStackFrame } from '../../../../build/swc/types' ...@@ -19,6 +19,14 @@ import type { Project, TurbopackStackFrame } from '../../../../build/swc/types'
import { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file' import { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file'
import { findSourceMap } from 'node:module' import { findSourceMap } from 'node:module'
function shouldIgnorePath(modulePath: string): boolean {
return (
modulePath.includes('node_modules') ||
// Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo
modulePath.includes('next/dist')
)
}
type IgnorableStackFrame = StackFrame & { ignored: boolean } type IgnorableStackFrame = StackFrame & { ignored: boolean }
const currentSourcesByFile: Map<string, Promise<string | null>> = new Map() const currentSourcesByFile: Map<string, Promise<string | null>> = new Map()
...@@ -33,16 +41,12 @@ export async function batchedTraceSource( ...@@ -33,16 +41,12 @@ export async function batchedTraceSource(
if (!sourceFrame) return if (!sourceFrame) return
let source = null let source = null
let ignored = true
// Don't look up source for node_modules or internals. These can often be large bundled files. // Don't look up source for node_modules or internals. These can often be large bundled files.
if ( const ignored =
sourceFrame.file && shouldIgnorePath(sourceFrame.file) ||
!( // isInternal means resource starts with turbopack://[turbopack]
sourceFrame.file.includes('node_modules') || !!sourceFrame.isInternal
// isInternal means resource starts with turbopack://[turbopack] if (sourceFrame.file && !ignored) {
sourceFrame.isInternal
)
) {
let sourcePromise = currentSourcesByFile.get(sourceFrame.file) let sourcePromise = currentSourcesByFile.get(sourceFrame.file)
if (!sourcePromise) { if (!sourcePromise) {
sourcePromise = project.getSourceForAsset(sourceFrame.file) sourcePromise = project.getSourceForAsset(sourceFrame.file)
...@@ -53,7 +57,6 @@ export async function batchedTraceSource( ...@@ -53,7 +57,6 @@ export async function batchedTraceSource(
currentSourcesByFile.delete(sourceFrame.file!) currentSourcesByFile.delete(sourceFrame.file!)
}, 100) }, 100)
} }
ignored = false
source = await sourcePromise source = await sourcePromise
} }
......
...@@ -14,7 +14,6 @@ import { ...@@ -14,7 +14,6 @@ import {
noContent, noContent,
type OriginalStackFrameResponse, type OriginalStackFrameResponse,
} from './shared' } from './shared'
import { NEXT_PROJECT_ROOT } from '../../../../build/next-dir-paths'
export { getServerError } from '../internal/helpers/node-stack-frames' export { getServerError } from '../internal/helpers/node-stack-frames'
export { parseStack } from '../internal/helpers/parse-stack' export { parseStack } from '../internal/helpers/parse-stack'
export { getSourceMapFromFile } export { getSourceMapFromFile }
...@@ -313,7 +312,6 @@ async function getSource( ...@@ -313,7 +312,6 @@ async function getSource(
const modulePath = moduleId.replace(/^(\(.*\)\/?)/, '') const modulePath = moduleId.replace(/^(\(.*\)\/?)/, '')
for (const compilation of getCompilations()) { for (const compilation of getCompilations()) {
// TODO: `ignoreList`
const sourceMap = await getSourceMapFromCompilation(moduleId, compilation) const sourceMap = await getSourceMapFromCompilation(moduleId, compilation)
const ignoreList = [] const ignoreList = []
const moduleFilenames = sourceMap?.sources ?? [] const moduleFilenames = sourceMap?.sources ?? []
...@@ -364,18 +362,8 @@ export function getOverlayMiddleware(options: { ...@@ -364,18 +362,8 @@ export function getOverlayMiddleware(options: {
const isEdgeServer = searchParams.get('isEdgeServer') === 'true' const isEdgeServer = searchParams.get('isEdgeServer') === 'true'
const isAppDirectory = searchParams.get('isAppDirectory') === 'true' const isAppDirectory = searchParams.get('isAppDirectory') === 'true'
const frame = createStackFrame(searchParams) const frame = createStackFrame(searchParams)
const formattedFilePath = formatFrameSourceFile(frame.file)
const filePath = path.join(rootDirectory, formattedFilePath)
const isNextjsSource = filePath.startsWith(NEXT_PROJECT_ROOT)
let sourcePackage = findSourcePackage(frame)
let source: Source | undefined let source: Source | undefined
if (isNextjsSource) {
sourcePackage = 'next'
return json(res, { sourcePackage })
}
try { try {
source = await getSource(frame.file, { source = await getSource(frame.file, {
getCompilations: () => { getCompilations: () => {
...@@ -426,7 +414,6 @@ export function getOverlayMiddleware(options: { ...@@ -426,7 +414,6 @@ export function getOverlayMiddleware(options: {
} }
if (!source) { if (!source) {
if (sourcePackage) return json(res, { sourcePackage })
return noContent(res) return noContent(res)
} }
...@@ -438,7 +425,6 @@ export function getOverlayMiddleware(options: { ...@@ -438,7 +425,6 @@ export function getOverlayMiddleware(options: {
}) })
if (!originalStackFrameResponse) { if (!originalStackFrameResponse) {
if (sourcePackage) return json(res, { sourcePackage })
return noContent(res) return noContent(res)
} }
......
...@@ -4,7 +4,7 @@ import { FileRef, nextTestSetup } from 'e2e-utils' ...@@ -4,7 +4,7 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import { import {
check, check,
describeVariants as describe, describeVariants as describe,
getRedboxCallStackCollapsed, getStackFramesContent,
retry, retry,
} from 'next-test-utils' } from 'next-test-utils'
import path from 'path' import path from 'path'
...@@ -860,10 +860,11 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -860,10 +860,11 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
// Should still show the errored line in source code // Should still show the errored line in source code
const source = await session.getRedboxSource() const source = await session.getRedboxSource()
expect(source).toContain('app/page.js') if (isTurbopack) {
expect(source).toContain( expect(source).toMatchSnapshot()
`throw new Error("This is an error from an anonymous function")` } else {
) expect(source).toMatchSnapshot()
}
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
...@@ -872,33 +873,19 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -872,33 +873,19 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
stackFrameElements.map((f) => f.innerText()) stackFrameElements.map((f) => f.innerText())
) )
expect(stackFrames).toEqual( expect(stackFrames).toEqual(
// TODO: investigate the column number is off by 1 between turbo and webpack
process.env.TURBOPACK process.env.TURBOPACK
? [ ? [
// TODO: Why is Turbopack off by one in the column?
outdent` outdent`
Page Page
app/page.js (5:6) app/page.js (5:6)
`, `,
// TODO: Show useful stack
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
'',
'',
'',
'',
] ]
: [ : [
outdent` outdent`
Page Page
app/page.js (5:5) app/page.js (5:5)
`, `,
// TODO: Show useful stack
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
'',
'',
'',
'',
] ]
) )
}) })
...@@ -923,8 +910,11 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -923,8 +910,11 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
// Should still show the errored line in source code // Should still show the errored line in source code
const source = await session.getRedboxSource() const source = await session.getRedboxSource()
expect(source).toContain('app/page.js') if (isTurbopack) {
expect(source).toContain(`new URL("/", "invalid")`) expect(source).toMatchSnapshot()
} else {
expect(source).toMatchSnapshot()
}
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
...@@ -932,17 +922,9 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -932,17 +922,9 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
const stackFrames = await Promise.all( const stackFrames = await Promise.all(
stackFrameElements.map((f) => f.innerText()) stackFrameElements.map((f) => f.innerText())
) )
expect(stackFrames).toEqual(
// TODO: Show useful stack // No following rest of displayed stack frames by default
[ expect(stackFrames.length).toBe(0)
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
'',
'',
'',
'',
]
)
}) })
test('Server component errors should open up in fullscreen', async () => { test('Server component errors should open up in fullscreen', async () => {
...@@ -1177,7 +1159,7 @@ export default function Home() { ...@@ -1177,7 +1159,7 @@ export default function Home() {
}) })
}) })
test('Should collapse bundler internal stack frames', async () => { test('should collapse bundler internal stack frames', async () => {
await using sandbox = await createSandbox( await using sandbox = await createSandbox(
next, next,
new Map([ new Map([
...@@ -1199,42 +1181,51 @@ export default function Home() { ...@@ -1199,42 +1181,51 @@ export default function Home() {
], ],
]) ])
) )
const { session, browser } = sandbox const { session, browser } = sandbox
await session.assertHasRedbox() await session.assertHasRedbox()
let stack = next.normalizeTestDirContent( const source = await session.getRedboxSource()
await getRedboxCallStackCollapsed(browser) const stackFrames = await getStackFramesContent(browser)
)
if (isTurbopack) { if (isTurbopack) {
expect(stack).toMatchInlineSnapshot(` expect(source).toMatchInlineSnapshot(`
"app/utils.ts (1:7) @ [project]/app/utils.ts [app-client] (ecmascript) "app/utils.ts (1:7) @ [project]/app/utils.ts [app-client] (ecmascript)
---
Next.js > 1 | throw new Error('utils error')
--- | ^
[project]/app/page.js [app-client] (ecmascript) 2 | export function foo(){}
app/page.js (2:1) 3 | "
---
Next.js
---
React"
`) `)
} else { } else {
expect(stack).toMatchInlineSnapshot(` expect(source).toMatchInlineSnapshot(`
"app/utils.ts (1:7) @ eval "app/utils.ts (1:7) @ eval
---
./app/utils.ts > 1 | throw new Error('utils error')
file://TEST_DIR/.next/static/chunks/app/page.js (39:1) | ^
--- 2 | export function foo(){}
Next.js 3 | "
--- `)
eval }
./app/page.js
--- if (isTurbopack) {
./app/page.js // FIXME: display the sourcemapped stack frames
file://TEST_DIR/.next/static/chunks/app/page.js (28:1) expect(stackFrames).toMatchInlineSnapshot(
--- `"at [project]/app/page.js [app-client] (ecmascript) (app/page.js (2:1))"`
Next.js" )
} else {
// FIXME: Webpack stack frames are not source mapped
expect(stackFrames).toMatchInlineSnapshot(`
"at ./app/utils.ts ()
at options.factory ()
at __webpack_require__ ()
at fn ()
at eval ()
at ./app/page.js ()
at options.factory ()
at __webpack_require__ ()
at fn ()"
`) `)
} }
}) })
......
...@@ -76,6 +76,27 @@ exports[`ReactRefreshLogBox app default module init error not shown 1`] = ` ...@@ -76,6 +76,27 @@ exports[`ReactRefreshLogBox app default module init error not shown 1`] = `
6 | return <h1>Default Export</h1>;" 6 | return <h1>Default Export</h1>;"
`; `;
exports[`ReactRefreshLogBox app default should hide unrelated frames in stack trace with nodejs internal calls 1`] = `
"app/page.js (2:3) @ Page
1 | export default function Page() {
> 2 | new URL("/", "invalid");
| ^
3 | }"
`;
exports[`ReactRefreshLogBox app default should hide unrelated frames in stack trace with unknown anonymous calls 1`] = `
"app/page.js (4:13) @ eval
2 | try {
3 | (function() {
> 4 | throw new Error("This is an error from an anonymous function");
| ^
5 | })();
6 | } catch (e) {
7 | throw e"
`;
exports[`ReactRefreshLogBox app default should strip whitespace correctly with newline 1`] = ` exports[`ReactRefreshLogBox app default should strip whitespace correctly with newline 1`] = `
"index.js (7:15) @ onClick "index.js (7:15) @ onClick
...@@ -159,6 +180,27 @@ exports[`ReactRefreshLogBox app turbo module init error not shown 1`] = ` ...@@ -159,6 +180,27 @@ exports[`ReactRefreshLogBox app turbo module init error not shown 1`] = `
6 | return <h1>Default Export</h1>;" 6 | return <h1>Default Export</h1>;"
`; `;
exports[`ReactRefreshLogBox app turbo should hide unrelated frames in stack trace with nodejs internal calls 1`] = `
"app/page.js (2:3) @ Page
1 | export default function Page() {
> 2 | new URL("/", "invalid");
| ^
3 | }"
`;
exports[`ReactRefreshLogBox app turbo should hide unrelated frames in stack trace with unknown anonymous calls 1`] = `
"app/page.js (4:13) @ <anonymous>
2 | try {
3 | (function() {
> 4 | throw new Error("This is an error from an anonymous function");
| ^
5 | })();
6 | } catch (e) {
7 | throw e"
`;
exports[`ReactRefreshLogBox app turbo should strip whitespace correctly with newline 1`] = ` exports[`ReactRefreshLogBox app turbo should strip whitespace correctly with newline 1`] = `
"index.js (7:15) @ onClick "index.js (7:15) @ onClick
......
/* eslint-env jest */ /* eslint-env jest */
import { createSandbox } from 'development-sandbox' import { createSandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import { describeVariants as describe } from 'next-test-utils' import {
describeVariants as describe,
toggleCollapseCallStackFrames,
} from 'next-test-utils'
import path from 'path' import path from 'path'
import { outdent } from 'outdent' import { outdent } from 'outdent'
...@@ -756,6 +759,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => { ...@@ -756,6 +759,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
const { session, browser } = sandbox const { session, browser } = sandbox
await session.assertHasRedbox() await session.assertHasRedbox()
await toggleCollapseCallStackFrames(browser)
// Expect more than the default amount of frames // Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements // The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
const callStackFrames = await browser.elementsByCss( const callStackFrames = await browser.elementsByCss(
...@@ -763,12 +768,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => { ...@@ -763,12 +768,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
) )
expect(callStackFrames.length).toBeGreaterThan(9) expect(callStackFrames.length).toBeGreaterThan(9)
const moduleGroup = await browser.elementsByCss(
'[data-nextjs-collapsed-call-stack-details]'
)
// Expect some of the call stack frames to be grouped (by React or Next.js)
expect(moduleGroup.length).toBeGreaterThan(0)
}) })
test('should hide unrelated frames in stack trace with unknown anonymous calls', async () => { test('should hide unrelated frames in stack trace with unknown anonymous calls', async () => {
...@@ -793,6 +792,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => { ...@@ -793,6 +792,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
) )
const { session, browser } = sandbox const { session, browser } = sandbox
await session.assertHasRedbox() await session.assertHasRedbox()
await toggleCollapseCallStackFrames(browser)
let callStackFrames = await browser.elementsByCss( let callStackFrames = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
...@@ -6,12 +6,15 @@ import { ...@@ -6,12 +6,15 @@ import {
getRedboxSource, getRedboxSource,
getRedboxTotalErrorCount, getRedboxTotalErrorCount,
openRedbox, openRedbox,
hasRedboxCallStack,
} from 'next-test-utils' } from 'next-test-utils'
async function getRedboxResult(browser: any) { async function getRedboxResult(browser: any) {
const title = await getRedboxTitle(browser) const title = await getRedboxTitle(browser)
const description = await getRedboxDescription(browser) const description = await getRedboxDescription(browser)
const callStacks = await getRedboxCallStack(browser) const callStacks = (await hasRedboxCallStack(browser))
? await getRedboxCallStack(browser)
: ''
const count = await getRedboxTotalErrorCount(browser) const count = await getRedboxTotalErrorCount(browser)
const source = await getRedboxSource(browser) const source = await getRedboxSource(browser)
const result = { const result = {
......
...@@ -6,12 +6,15 @@ import { ...@@ -6,12 +6,15 @@ import {
getRedboxSource, getRedboxSource,
getRedboxTotalErrorCount, getRedboxTotalErrorCount,
openRedbox, openRedbox,
hasRedboxCallStack,
} from 'next-test-utils' } from 'next-test-utils'
async function getRedboxResult(browser: any) { async function getRedboxResult(browser: any) {
const title = await getRedboxTitle(browser) const title = await getRedboxTitle(browser)
const description = await getRedboxDescription(browser) const description = await getRedboxDescription(browser)
const callStacks = await getRedboxCallStack(browser) const callStacks = (await hasRedboxCallStack(browser))
? await getRedboxCallStack(browser)
: ''
const count = await getRedboxTotalErrorCount(browser) const count = await getRedboxTotalErrorCount(browser)
const source = await getRedboxSource(browser) const source = await getRedboxSource(browser)
const result = { const result = {
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
retry, retry,
openRedbox, openRedbox,
getRedboxSource, getRedboxSource,
toggleCollapseCallStackFrames,
} from 'next-test-utils' } from 'next-test-utils'
import { createSandbox } from 'development-sandbox' import { createSandbox } from 'development-sandbox'
import { outdent } from 'outdent' import { outdent } from 'outdent'
...@@ -64,11 +65,15 @@ describe('Dynamic IO Dev Errors', () => { ...@@ -64,11 +65,15 @@ describe('Dynamic IO Dev Errors', () => {
) )
const description = await getRedboxDescription(browser) const description = await getRedboxDescription(browser)
const stack = await getRedboxCallStack(browser)
expect(description).toMatchInlineSnapshot( expect(description).toMatchInlineSnapshot(
`"[ Server ] Error: Route "/no-accessed-data": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a "use cache" above it. We don't have the exact line number added to error messages yet but you can see which component in the stack below. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense"` `"[ Server ] Error: Route "/no-accessed-data": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a "use cache" above it. We don't have the exact line number added to error messages yet but you can see which component in the stack below. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense"`
) )
// Expand the stack frames, since the first frame `Page [Server] <anonymous>` is treated as ignored.
// TODO: Remove the filter of anonymous frames when we have a better way to handle them.
await toggleCollapseCallStackFrames(browser)
const stack = await getRedboxCallStack(browser)
// TODO: use snapshot testing for stack // TODO: use snapshot testing for stack
// FIXME: avoid `next` code to be mapped to source code and filter them out even when sourcemap is enabled. // FIXME: avoid `next` code to be mapped to source code and filter them out even when sourcemap is enabled.
expect(stack).toContain('Page [Server]') expect(stack).toContain('Page [Server]')
......
'use client'
export default function Page() {
throw new Error('client error')
return <p>hello world</p>
}
'use client'
import { invokeCallback } from 'interleave'
export default function Page() {
const throwError = invokeCallback(() => {
throw new Error('interleaved error')
}, [])
throwError()
return <p>fail</p>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
throw new Error('server error')
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
getStackFramesContent,
toggleCollapseCallStackFrames,
} from 'next-test-utils'
describe('error-ignored-frames', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// TODO: remove this when reactOwnerStack is enabled by default
if (process.env.__NEXT_EXPERIMENTAL_PPR === 'true') {
// Since PPR mode is just going to add owner stack, skip this test for now
it('skip ppr test', () => {})
return
}
it('should be able to collapse ignored frames in server component', async () => {
const browser = await next.browser('/')
await assertHasRedbox(browser)
const defaultStack = await getStackFramesContent(browser)
expect(defaultStack).toMatchInlineSnapshot(`""`)
await toggleCollapseCallStackFrames(browser)
const expendedStack = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(expendedStack).toMatchInlineSnapshot(`
"at resolveErrorDev ()
at processFullStringRow ()
at processFullBinaryRow ()
at progress ()"
`)
} else {
expect(expendedStack).toMatchInlineSnapshot(`
"at resolveErrorDev ()
at processFullStringRow ()
at processFullBinaryRow ()
at progress ()"
`)
}
})
it('should be able to collapse ignored frames in client component', async () => {
const browser = await next.browser('/client')
await assertHasRedbox(browser)
const defaultStack = await getStackFramesContent(browser)
expect(defaultStack).toMatchInlineSnapshot(`""`)
await toggleCollapseCallStackFrames(browser)
const expendedStack = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(expendedStack).toMatchInlineSnapshot(`
"at react-stack-bottom-frame ()
at renderWithHooks ()
at updateFunctionComponent ()
at beginWork ()
at runWithFiberInDEV ()
at performUnitOfWork ()
at workLoopSync ()
at renderRootSync ()
at performWorkOnRoot ()
at performWorkOnRootViaSchedulerTask ()
at MessagePort.performWorkUntilDeadline ()"
`)
} else {
expect(expendedStack).toMatchInlineSnapshot(`
"at react-stack-bottom-frame ()
at renderWithHooks ()
at updateFunctionComponent ()
at beginWork ()
at runWithFiberInDEV ()
at performUnitOfWork ()
at workLoopSync ()
at renderRootSync ()
at performWorkOnRoot ()
at performWorkOnRootViaSchedulerTask ()
at MessagePort.performWorkUntilDeadline ()"
`)
}
})
it('should be able to collapse ignored frames in interleaved call stack', async () => {
const browser = await next.browser('/interleaved')
await assertHasRedbox(browser)
const defaultStack = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(defaultStack).toMatchInlineSnapshot(
`"at Page (app/interleaved/page.tsx (6:35))"`
)
} else {
expect(defaultStack).toMatchInlineSnapshot(
`"at Page (app/interleaved/page.tsx (6:37))"`
)
}
await toggleCollapseCallStackFrames(browser)
const expendedStack = await getStackFramesContent(browser)
if (process.env.TURBOPACK) {
expect(expendedStack).toMatchInlineSnapshot(`
"at invokeCallback ()
at Page (app/interleaved/page.tsx (6:35))
at react-stack-bottom-frame ()
at renderWithHooks ()
at updateFunctionComponent ()
at beginWork ()
at runWithFiberInDEV ()
at performUnitOfWork ()
at workLoopSync ()
at renderRootSync ()
at performWorkOnRoot ()
at performWorkOnRootViaSchedulerTask ()
at MessagePort.performWorkUntilDeadline ()"
`)
} else {
expect(expendedStack).toMatchInlineSnapshot(`
"at invokeCallback (node_modules/interleave/index.js (2:1))
at Page (app/interleaved/page.tsx (6:37))
at react-stack-bottom-frame ()
at renderWithHooks ()
at updateFunctionComponent ()
at beginWork ()
at runWithFiberInDEV ()
at performUnitOfWork ()
at workLoopSync ()
at renderRootSync ()
at performWorkOnRoot ()
at performWorkOnRootViaSchedulerTask ()
at MessagePort.performWorkUntilDeadline ()"
`)
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -26,7 +26,7 @@ import _pkg from 'next/package.json' ...@@ -26,7 +26,7 @@ import _pkg from 'next/package.json'
import type { SpawnOptions, ChildProcess } from 'child_process' import type { SpawnOptions, ChildProcess } from 'child_process'
import type { RequestInit, Response } from 'node-fetch' import type { RequestInit, Response } from 'node-fetch'
import type { NextServer } from 'next/dist/server/next' import type { NextServer } from 'next/dist/server/next'
import type { BrowserInterface } from './browsers/base' import { BrowserInterface } from './browsers/base'
import { getTurbopackFlag, shouldRunTurboDevTest } from './turbo' import { getTurbopackFlag, shouldRunTurboDevTest } from './turbo'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
...@@ -1234,6 +1234,17 @@ export async function toggleCollapseComponentStack( ...@@ -1234,6 +1234,17 @@ export async function toggleCollapseComponentStack(
.click() .click()
} }
export async function hasRedboxCallStack(browser: BrowserInterface) {
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-body]'))
const root = portal?.shadowRoot
return root?.querySelectorAll('[data-nextjs-call-stack-frame]').length > 0
})
}
export async function getRedboxCallStack( export async function getRedboxCallStack(
browser: BrowserInterface browser: BrowserInterface
): Promise<string | null> { ): Promise<string | null> {
...@@ -1500,3 +1511,14 @@ export async function getStackFramesContent(browser) { ...@@ -1500,3 +1511,14 @@ export async function getStackFramesContent(browser) {
return stackFramesContent return stackFramesContent
} }
export async function toggleCollapseCallStackFrames(browser: BrowserInterface) {
const button = await browser.elementByCss('[data-expand-ignore-button]')
const lastExpanded = await button.getAttribute('data-expand-ignore-button')
await button.click()
await retry(async () => {
const currExpanded = await button.getAttribute('data-expand-ignore-button')
expect(currExpanded).not.toBe(lastExpanded)
})
}
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