Unverified Commit 2aa2eaad authored by Jude Gao's avatar Jude Gao Committed by GitHub

dev error overlay: async boundary for original stack frame call (#75718)

parent 3fdf51cf
...@@ -633,5 +633,7 @@ ...@@ -633,5 +633,7 @@
"632": "Invariant (SlowModuleDetectionPlugin): Module is missing a required debugId. This is a Next.js internal bug.", "632": "Invariant (SlowModuleDetectionPlugin): Module is missing a required debugId. This is a Next.js internal bug.",
"633": "Dynamic route not found", "633": "Dynamic route not found",
"634": "Route %s used \"searchParams\" inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"searchParams\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache", "634": "Route %s used \"searchParams\" inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"searchParams\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"635": "%s: Invalid source map. Only conformant source maps can be used to find the original code." "635": "%s: Invalid source map. Only conformant source maps can be used to find the original code.",
"636": "Invariant: frames must be a function when the React version has React.use. This is a bug in Next.js.",
"637": "Invariant: frames must be an array when the React version does not have React.use. This is a bug in Next.js."
} }
...@@ -20,19 +20,19 @@ export const Default: Story = { ...@@ -20,19 +20,19 @@ export const Default: Story = {
id: 0, id: 0,
runtime: true, runtime: true,
error: new Error('First error message'), error: new Error('First error message'),
frames: [], frames: () => Promise.resolve([]),
}, },
{ {
id: 1, id: 1,
runtime: true, runtime: true,
error: new Error('Second error message'), error: new Error('Second error message'),
frames: [], frames: () => Promise.resolve([]),
}, },
{ {
id: 2, id: 2,
runtime: true, runtime: true,
error: new Error('Third error message'), error: new Error('Third error message'),
frames: [], frames: () => Promise.resolve([]),
}, },
], ],
activeIdx: 1, activeIdx: 1,
......
...@@ -20,19 +20,19 @@ const mockErrors = [ ...@@ -20,19 +20,19 @@ const mockErrors = [
id: 1, id: 1,
runtime: true as const, runtime: true as const,
error: new Error('First error'), error: new Error('First error'),
frames: [], frames: () => Promise.resolve([]),
}, },
{ {
id: 2, id: 2,
runtime: true as const, runtime: true as const,
error: new Error('Second error'), error: new Error('Second error'),
frames: [], frames: () => Promise.resolve([]),
}, },
{ {
id: 3, id: 3,
runtime: true as const, runtime: true as const,
error: new Error('Third error'), error: new Error('Third error'),
frames: [], frames: () => Promise.resolve([]),
}, },
] ]
......
import { useCallback, useEffect, useRef, useState } from 'react' import {
startTransition,
useCallback,
useEffect,
useRef,
useState,
} from 'react'
import { noop as css } from '../../../helpers/noop-template' import { noop as css } from '../../../helpers/noop-template'
import { LeftArrow } from '../../../icons/left-arrow' import { LeftArrow } from '../../../icons/left-arrow'
import { RightArrow } from '../../../icons/right-arrow' import { RightArrow } from '../../../icons/right-arrow'
...@@ -17,17 +23,23 @@ export function ErrorOverlayPagination({ ...@@ -17,17 +23,23 @@ export function ErrorOverlayPagination({
}: ErrorPaginationProps) { }: ErrorPaginationProps) {
const handlePrevious = useCallback( const handlePrevious = useCallback(
() => () =>
activeIdx > 0 ? onActiveIndexChange(Math.max(0, activeIdx - 1)) : null, startTransition(() => {
if (activeIdx > 0) {
onActiveIndexChange(Math.max(0, activeIdx - 1))
}
}),
[activeIdx, onActiveIndexChange] [activeIdx, onActiveIndexChange]
) )
const handleNext = useCallback( const handleNext = useCallback(
() => () =>
activeIdx < readyErrors.length - 1 startTransition(() => {
? onActiveIndexChange( if (activeIdx < readyErrors.length - 1) {
onActiveIndexChange(
Math.max(0, Math.min(readyErrors.length - 1, activeIdx + 1)) Math.max(0, Math.min(readyErrors.length - 1, activeIdx + 1))
) )
: null, }
}),
[activeIdx, readyErrors.length, onActiveIndexChange] [activeIdx, readyErrors.length, onActiveIndexChange]
) )
......
...@@ -74,74 +74,78 @@ const readyErrors: ReadyRuntimeError[] = [ ...@@ -74,74 +74,78 @@ const readyErrors: ReadyRuntimeError[] = [
id: 1, id: 1,
runtime: true, runtime: true,
error: new Error('First error message'), error: new Error('First error message'),
frames: [ frames: () =>
frame, Promise.resolve([
{ frame,
...frame, {
originalStackFrame: { ...frame,
...frame.originalStackFrame, originalStackFrame: {
methodName: 'ParentComponent', ...frame.originalStackFrame,
lineNumber: 5, methodName: 'ParentComponent',
lineNumber: 5,
},
}, },
}, {
{ ...frame,
...frame, originalStackFrame: {
originalStackFrame: { ...frame.originalStackFrame,
...frame.originalStackFrame, methodName: 'GrandparentComponent',
methodName: 'GrandparentComponent', lineNumber: 1,
lineNumber: 1, },
}, },
}, ...Array(20).fill(ignoredFrame),
...Array(20).fill(ignoredFrame), ]),
],
}, },
{ {
id: 2, id: 2,
runtime: true, runtime: true,
error: new Error('Second error message'), error: new Error('Second error message'),
frames: [ frames: () =>
{ Promise.resolve([
error: true, {
reason: 'Second error message', error: true,
external: false, reason: 'Second error message',
ignored: false, external: false,
sourceStackFrame, ignored: false,
originalStackFrame, sourceStackFrame,
originalCodeFrame: originalCodeFrame('Second error message'), originalStackFrame,
}, originalCodeFrame: originalCodeFrame('Second error message'),
], },
]),
}, },
{ {
id: 3, id: 3,
runtime: true, runtime: true,
error: new Error('Third error message'), error: new Error('Third error message'),
frames: [ frames: () =>
{ Promise.resolve([
error: true, {
reason: 'Third error message', error: true,
external: false, reason: 'Third error message',
ignored: false, external: false,
sourceStackFrame, ignored: false,
originalStackFrame, sourceStackFrame,
originalCodeFrame: originalCodeFrame('Third error message'), originalStackFrame,
}, originalCodeFrame: originalCodeFrame('Third error message'),
], },
]),
}, },
{ {
id: 4, id: 4,
runtime: true, runtime: true,
error: new Error('Fourth error message'), error: new Error('Fourth error message'),
frames: [ frames: () =>
{ Promise.resolve([
error: true, {
reason: 'Fourth error message', error: true,
external: false, reason: 'Fourth error message',
ignored: false, external: false,
sourceStackFrame, ignored: false,
originalStackFrame, sourceStackFrame,
originalCodeFrame: originalCodeFrame('Fourth error message'), originalStackFrame,
}, originalCodeFrame: originalCodeFrame('Fourth error message'),
], },
]),
}, },
] ]
...@@ -205,21 +209,22 @@ export const WithHydrationWarning: Story = { ...@@ -205,21 +209,22 @@ export const WithHydrationWarning: Story = {
}, },
], ],
}), }),
frames: [ frames: () =>
{ Promise.resolve([
error: true, {
reason: 'First error message', error: true,
external: false, reason: 'First error message',
ignored: false, external: false,
sourceStackFrame: { ignored: false,
file: 'app/page.tsx', sourceStackFrame: {
methodName: 'Home', file: 'app/page.tsx',
arguments: [], methodName: 'Home',
lineNumber: 10, arguments: [],
column: 5, lineNumber: 10,
column: 5,
},
}, },
}, ]),
],
}, },
], ],
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
......
import { useState, useMemo, useEffect, useRef } from 'react' import { useState, useMemo, useEffect, useRef, Suspense } from 'react'
import type { DebugInfo } from '../../../types' import type { DebugInfo } from '../../../types'
import { Overlay } from '../components/overlay' import { Overlay } from '../components/overlay'
import { noop as css } from '../helpers/noop-template' import { noop as css } from '../helpers/noop-template'
...@@ -192,11 +192,13 @@ export function Errors({ ...@@ -192,11 +192,13 @@ export function Errors({
reactOutputComponentDiff={errorDetails.reactOutputComponentDiff} reactOutputComponentDiff={errorDetails.reactOutputComponentDiff}
/> />
) : null} ) : null}
<RuntimeError <Suspense fallback={<div data-nextjs-error-suspended />}>
key={activeError.id.toString()} <RuntimeError
error={activeError} key={activeError.id.toString()}
dialogResizerRef={dialogResizerRef} error={activeError}
/> dialogResizerRef={dialogResizerRef}
/>
</Suspense>
</ErrorOverlayLayout> </ErrorOverlayLayout>
) )
} }
......
...@@ -3,7 +3,10 @@ import { CodeFrame } from '../../components/code-frame/code-frame' ...@@ -3,7 +3,10 @@ import { CodeFrame } from '../../components/code-frame/code-frame'
import { CallStack } from '../../components/errors/call-stack/call-stack' import { CallStack } from '../../components/errors/call-stack/call-stack'
import { noop as css } from '../../helpers/noop-template' import { noop as css } from '../../helpers/noop-template'
import { PSEUDO_HTML_DIFF_STYLES } from './component-stack-pseudo-html' import { PSEUDO_HTML_DIFF_STYLES } from './component-stack-pseudo-html'
import type { ReadyRuntimeError } from '../../../../internal/helpers/get-error-by-type' import {
useFrames,
type ReadyRuntimeError,
} from '../../../../internal/helpers/get-error-by-type'
export type RuntimeErrorProps = { export type RuntimeErrorProps = {
error: ReadyRuntimeError error: ReadyRuntimeError
...@@ -11,16 +14,18 @@ export type RuntimeErrorProps = { ...@@ -11,16 +14,18 @@ export type RuntimeErrorProps = {
} }
export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) { export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
const frames = useFrames(error)
const firstFrame = useMemo(() => { const firstFrame = useMemo(() => {
const firstFirstPartyFrameIndex = error.frames.findIndex( const firstFirstPartyFrameIndex = frames.findIndex(
(entry) => (entry) =>
!entry.ignored && !entry.ignored &&
Boolean(entry.originalCodeFrame) && Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame) Boolean(entry.originalStackFrame)
) )
return error.frames[firstFirstPartyFrameIndex] ?? null return frames[firstFirstPartyFrameIndex] ?? null
}, [error.frames]) }, [frames])
return ( return (
<> <>
...@@ -31,8 +36,8 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) { ...@@ -31,8 +36,8 @@ export function RuntimeError({ error, dialogResizerRef }: RuntimeErrorProps) {
/> />
)} )}
{error.frames.length > 0 && ( {frames.length > 0 && (
<CallStack dialogResizerRef={dialogResizerRef} frames={error.frames} /> <CallStack dialogResizerRef={dialogResizerRef} frames={frames} />
)} )}
</> </>
) )
......
...@@ -76,21 +76,17 @@ export function useErrorHook({ ...@@ -76,21 +76,17 @@ export function useErrorHook({
if (nextError == null) { if (nextError == null) {
return return
} }
let mounted = true let mounted = true
getErrorByType(nextError, isAppDir).then( getErrorByType(nextError, isAppDir).then((resolved) => {
(resolved) => { if (mounted) {
// We don't care if the desired error changed while we were resolving, // We don't care if the desired error changed while we were resolving,
// thus we're not tracking it using a ref. Once the work has been done, // thus we're not tracking it using a ref. Once the work has been done,
// we'll store it. // we'll store it.
if (mounted) { setLookups((m) => ({ ...m, [resolved.id]: resolved }))
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
},
() => {
// TODO: handle this, though an edge case
} }
) })
return () => { return () => {
mounted = false mounted = false
......
import { useState, useEffect, useMemo, useCallback } from 'react' import { useState, useEffect, useMemo, useCallback, Suspense } from 'react'
import { import {
ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION, ACTION_UNHANDLED_REJECTION,
...@@ -162,21 +162,16 @@ export function Errors({ ...@@ -162,21 +162,16 @@ export function Errors({
if (nextError == null) { if (nextError == null) {
return return
} }
let mounted = true
getErrorByType(nextError, isAppDir).then( let mounted = true
(resolved) => { getErrorByType(nextError, isAppDir).then((resolved) => {
if (mounted) {
// We don't care if the desired error changed while we were resolving, // We don't care if the desired error changed while we were resolving,
// thus we're not tracking it using a ref. Once the work has been done, // thus we're not tracking it using a ref. Once the work has been done,
// we'll store it. // we'll store it.
if (mounted) { setLookups((m) => ({ ...m, [resolved.id]: resolved }))
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
},
() => {
// TODO: handle this, though an edge case
} }
) })
return () => { return () => {
mounted = false mounted = false
...@@ -401,9 +396,14 @@ export function Errors({ ...@@ -401,9 +396,14 @@ export function Errors({
</div> </div>
) : undefined} ) : undefined}
</DialogHeader> </DialogHeader>
<DialogBody className="nextjs-container-errors-body"> <Suspense fallback={<div data-nextjs-error-suspended />}>
<RuntimeError key={activeError.id.toString()} error={activeError} /> <DialogBody className="nextjs-container-errors-body">
</DialogBody> <RuntimeError
key={activeError.id.toString()}
error={activeError}
/>
</DialogBody>
</Suspense>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</Overlay> </Overlay>
......
import * as React from 'react' 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 {
useFrames,
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 { CallStackFrame } from './CallStackFrame' import { CallStackFrame } from './CallStackFrame'
...@@ -8,13 +11,15 @@ export type RuntimeErrorProps = { error: ReadyRuntimeError } ...@@ -8,13 +11,15 @@ export type RuntimeErrorProps = { error: ReadyRuntimeError }
export function RuntimeError({ error }: RuntimeErrorProps) { export function RuntimeError({ error }: RuntimeErrorProps) {
const [isIgnoredExpanded, setIsIgnoredExpanded] = React.useState(false) const [isIgnoredExpanded, setIsIgnoredExpanded] = React.useState(false)
const frames = useFrames(error)
const { const {
firstFrame, firstFrame,
allLeadingFrames, allLeadingFrames,
trailingCallStackFrames, trailingCallStackFrames,
displayedFramesCount, displayedFramesCount,
} = React.useMemo(() => { } = React.useMemo(() => {
const filteredFrames = error.frames.filter((frame) => const filteredFrames = frames.filter((frame) =>
isIgnoredExpanded ? true : !frame.ignored isIgnoredExpanded ? true : !frame.ignored
) )
...@@ -36,10 +41,10 @@ export function RuntimeError({ error }: RuntimeErrorProps) { ...@@ -36,10 +41,10 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
firstFirstPartyFrameIndex < 0 ? 0 : firstFirstPartyFrameIndex firstFirstPartyFrameIndex < 0 ? 0 : firstFirstPartyFrameIndex
), ),
} }
}, [error.frames, isIgnoredExpanded]) }, [frames, isIgnoredExpanded])
return ( return (
<React.Fragment> <>
{firstFrame ? ( {firstFrame ? (
<> <>
<h2>Source</h2> <h2>Source</h2>
...@@ -64,8 +69,7 @@ export function RuntimeError({ error }: RuntimeErrorProps) { ...@@ -64,8 +69,7 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
))} ))}
{ {
// if the default displayed ignored frames count is equal equal to the total frames count, hide the button // if the default displayed ignored frames count is equal equal to the total frames count, hide the button
displayedFramesCount === error.frames.length && displayedFramesCount === frames.length && !isIgnoredExpanded ? null : (
!isIgnoredExpanded ? null : (
<button <button
data-expand-ignore-button={isIgnoredExpanded} data-expand-ignore-button={isIgnoredExpanded}
onClick={() => setIsIgnoredExpanded(!isIgnoredExpanded)} onClick={() => setIsIgnoredExpanded(!isIgnoredExpanded)}
...@@ -74,7 +78,7 @@ export function RuntimeError({ error }: RuntimeErrorProps) { ...@@ -74,7 +78,7 @@ export function RuntimeError({ error }: RuntimeErrorProps) {
</button> </button>
) )
} }
</React.Fragment> </>
) )
} }
......
...@@ -7,15 +7,38 @@ import { getOriginalStackFrames } from './stack-frame' ...@@ -7,15 +7,38 @@ import { getOriginalStackFrames } from './stack-frame'
import type { OriginalStackFrame } from './stack-frame' import type { OriginalStackFrame } from './stack-frame'
import type { ComponentStackFrame } from './parse-component-stack' import type { ComponentStackFrame } from './parse-component-stack'
import { getErrorSource } from '../../../../../shared/lib/error-source' import { getErrorSource } from '../../../../../shared/lib/error-source'
import React from 'react'
export type ReadyRuntimeError = { export type ReadyRuntimeError = {
id: number id: number
runtime: true runtime: true
error: Error error: Error
frames: OriginalStackFrame[] frames: OriginalStackFrame[] | (() => Promise<OriginalStackFrame[]>)
componentStackFrames?: ComponentStackFrame[] componentStackFrames?: ComponentStackFrame[]
} }
export const useFrames = (error: ReadyRuntimeError): OriginalStackFrame[] => {
if ('use' in React) {
const frames = error.frames
if (typeof frames !== 'function') {
throw new Error(
'Invariant: frames must be a function when the React version has React.use. This is a bug in Next.js.'
)
}
return React.use((frames as () => Promise<OriginalStackFrame[]>)())
} else {
if (!Array.isArray(error.frames)) {
throw new Error(
'Invariant: frames must be an array when the React version does not have React.use. This is a bug in Next.js.'
)
}
return error.frames
}
}
export async function getErrorByType( export async function getErrorByType(
ev: SupportedErrorEvent, ev: SupportedErrorEvent,
isAppDir: boolean isAppDir: boolean
...@@ -24,20 +47,43 @@ export async function getErrorByType( ...@@ -24,20 +47,43 @@ export async function getErrorByType(
switch (event.type) { switch (event.type) {
case ACTION_UNHANDLED_ERROR: case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION: { case ACTION_UNHANDLED_REJECTION: {
const readyRuntimeError: ReadyRuntimeError = { const baseError = {
id, id,
runtime: true, runtime: true,
error: event.reason, error: event.reason,
frames: await getOriginalStackFrames( } as const
event.frames,
getErrorSource(event.reason), if ('use' in React) {
isAppDir const readyRuntimeError: ReadyRuntimeError = {
), ...baseError,
} // createMemoizedPromise dedups calls to getOriginalStackFrames
if (event.type === ACTION_UNHANDLED_ERROR) { frames: createMemoizedPromise(async () => {
readyRuntimeError.componentStackFrames = event.componentStackFrames return await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
)
}),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
}
return readyRuntimeError
} else {
const readyRuntimeError: ReadyRuntimeError = {
...baseError,
// createMemoizedPromise dedups calls to getOriginalStackFrames
frames: await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
isAppDir
),
}
if (event.type === ACTION_UNHANDLED_ERROR) {
readyRuntimeError.componentStackFrames = event.componentStackFrames
}
return readyRuntimeError
} }
return readyRuntimeError
} }
default: { default: {
break break
...@@ -47,3 +93,12 @@ export async function getErrorByType( ...@@ -47,3 +93,12 @@ export async function getErrorByType(
const _: never = event const _: never = event
throw new Error('type system invariant violation') throw new Error('type system invariant violation')
} }
function createMemoizedPromise<T>(
promiseFactory: () => Promise<T>
): () => Promise<T> {
const cachedPromise = promiseFactory()
return function (): Promise<T> {
return cachedPromise
}
}
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
describeVariants as describe, describeVariants as describe,
getStackFramesContent, getStackFramesContent,
retry, retry,
getRedboxCallStack,
} from 'next-test-utils' } from 'next-test-utils'
import path from 'path' import path from 'path'
import { outdent } from 'outdent' import { outdent } from 'outdent'
...@@ -793,6 +794,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -793,6 +794,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toContain('app/page.js') expect(source).toContain('app/page.js')
expect(source).toContain(`throw new Error('Client error')`) expect(source).toContain(`throw new Error('Client error')`)
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
...@@ -830,6 +833,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -830,6 +833,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toContain('app/page.js') expect(source).toContain('app/page.js')
expect(source).toContain(`throw new Error('Server error')`) expect(source).toContain(`throw new Error('Server error')`)
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
...@@ -876,6 +881,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -876,6 +881,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toMatchSnapshot() expect(source).toMatchSnapshot()
} }
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
...@@ -934,6 +941,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => { ...@@ -934,6 +941,8 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
expect(source).toMatchSnapshot() expect(source).toMatchSnapshot()
} }
await getRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
describeVariants as describe, describeVariants as describe,
getStackFramesContent, getStackFramesContent,
toggleCollapseCallStackFrames, toggleCollapseCallStackFrames,
hasRedboxCallStack,
} from 'next-test-utils' } from 'next-test-utils'
import path from 'path' import path from 'path'
import { outdent } from 'outdent' import { outdent } from 'outdent'
...@@ -764,6 +765,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => { ...@@ -764,6 +765,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
// 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
await hasRedboxCallStack(browser)
const callStackFrames = await browser.elementsByCss( const callStackFrames = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { assertHasRedbox, getRedboxSource } from 'next-test-utils' import {
assertHasRedbox,
getRedboxSource,
hasRedboxCallStack,
} from 'next-test-utils'
import { outdent } from 'outdent' import { outdent } from 'outdent'
function normalizeStackTrace(trace) { function normalizeStackTrace(trace) {
...@@ -24,6 +28,7 @@ describe('app dir - dynamic error trace', () => { ...@@ -24,6 +28,7 @@ describe('app dir - dynamic error trace', () => {
) )
).resolves.toEqual(false) ).resolves.toEqual(false)
await hasRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getRedboxSource, openRedbox } from 'next-test-utils' import {
getRedboxSource,
openRedbox,
hasRedboxCallStack,
} from 'next-test-utils'
// TODO: When owner stack is enabled by default, remove the condition and only keep one test // TODO: When owner stack is enabled by default, remove the condition and only keep one test
const isOwnerStackEnabled = process.env.__NEXT_EXPERIMENTAL_PPR === 'true' const isOwnerStackEnabled = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
async function getStackFramesContent(browser) { async function getStackFramesContent(browser) {
await hasRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
assertNoRedbox, assertNoRedbox,
openRedbox, openRedbox,
getRedboxDescription, getRedboxDescription,
hasRedboxCallStack,
} from 'next-test-utils' } from 'next-test-utils'
// TODO: parse the location and assert them in the future // TODO: parse the location and assert them in the future
...@@ -18,6 +19,7 @@ function normalizeStackTrace(trace: string) { ...@@ -18,6 +19,7 @@ function normalizeStackTrace(trace: string) {
} }
async function getStackFramesContent(browser) { async function getStackFramesContent(browser) {
await hasRedboxCallStack(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
...@@ -825,6 +825,21 @@ export async function retry<T>( ...@@ -825,6 +825,21 @@ export async function retry<T>(
} }
} }
async function ensureNoSuspendedComponentsInRedBox(browser: BrowserInterface) {
await retry(async () => {
const suspended = await browser.eval(() => {
return Boolean(
[].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) =>
p.shadowRoot.querySelector('[data-nextjs-error-suspended]')
)
)
})
expect(suspended).toBe(false)
}, 10000)
}
export async function assertHasRedbox(browser: BrowserInterface) { export async function assertHasRedbox(browser: BrowserInterface) {
try { try {
await retry( await retry(
...@@ -845,6 +860,8 @@ export async function assertHasRedbox(browser: BrowserInterface) { ...@@ -845,6 +860,8 @@ export async function assertHasRedbox(browser: BrowserInterface) {
5000, 5000,
200 200
) )
await ensureNoSuspendedComponentsInRedBox(browser)
} catch (errorCause) { } catch (errorCause) {
const error = new Error('Expected Redbox but found none') const error = new Error('Expected Redbox but found none')
Error.captureStackTrace(error, assertHasRedbox) Error.captureStackTrace(error, assertHasRedbox)
...@@ -1014,7 +1031,9 @@ export async function getRedboxTotalErrorCount(browser: BrowserInterface) { ...@@ -1014,7 +1031,9 @@ export async function getRedboxTotalErrorCount(browser: BrowserInterface) {
return parseInt(header.match(/\d+ of (\d+) issue/)?.[1], 10) return parseInt(header.match(/\d+ of (\d+) issue/)?.[1], 10)
} }
export function getRedboxSource(browser: BrowserInterface) { export async function getRedboxSource(browser: BrowserInterface) {
await ensureNoSuspendedComponentsInRedBox(browser)
return browser.eval(() => { return browser.eval(() => {
const portal = [].slice const portal = [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
...@@ -1330,6 +1349,7 @@ export async function toggleCollapseComponentStack( ...@@ -1330,6 +1349,7 @@ export async function toggleCollapseComponentStack(
} }
export async function hasRedboxCallStack(browser: BrowserInterface) { export async function hasRedboxCallStack(browser: BrowserInterface) {
await ensureNoSuspendedComponentsInRedBox(browser)
return browser.eval(() => { return browser.eval(() => {
const portal = [].slice const portal = [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
...@@ -1343,8 +1363,7 @@ export async function hasRedboxCallStack(browser: BrowserInterface) { ...@@ -1343,8 +1363,7 @@ export async function hasRedboxCallStack(browser: BrowserInterface) {
export async function getRedboxCallStack( export async function getRedboxCallStack(
browser: BrowserInterface browser: BrowserInterface
): Promise<string | null> { ): Promise<string | null> {
await browser.waitForElementByCss('[data-nextjs-call-stack-frame]', 30000) await ensureNoSuspendedComponentsInRedBox(browser)
const callStackFrameElements = await browser.elementsByCss( const callStackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
...@@ -1358,8 +1377,7 @@ export async function getRedboxCallStack( ...@@ -1358,8 +1377,7 @@ export async function getRedboxCallStack(
export async function getRedboxCallStackCollapsed( export async function getRedboxCallStackCollapsed(
browser: BrowserInterface browser: BrowserInterface
): Promise<string> { ): Promise<string> {
await browser.waitForElementByCss('.nextjs-container-errors-body', 30000) await ensureNoSuspendedComponentsInRedBox(browser)
const callStackFrameElements = await browser.elementsByCss( const callStackFrameElements = await browser.elementsByCss(
'.nextjs-container-errors-body > [data-nextjs-codeframe] > :first-child, ' + '.nextjs-container-errors-body > [data-nextjs-codeframe] > :first-child, ' +
'.nextjs-container-errors-body > [data-nextjs-call-stack-frame], ' + '.nextjs-container-errors-body > [data-nextjs-call-stack-frame], ' +
...@@ -1581,6 +1599,7 @@ export const checkLink = ( ...@@ -1581,6 +1599,7 @@ export const checkLink = (
) => checkMeta(browser, rel, content, 'rel', 'link', 'href') ) => checkMeta(browser, rel, content, 'rel', 'link', 'href')
export async function getStackFramesContent(browser) { export async function getStackFramesContent(browser) {
await ensureNoSuspendedComponentsInRedBox(browser)
const stackFrameElements = await browser.elementsByCss( const stackFrameElements = await browser.elementsByCss(
'[data-nextjs-call-stack-frame]' '[data-nextjs-call-stack-frame]'
) )
......
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