Unverified Commit fbea795a authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

[Fast Refresh] Redesigned Runtime Error Experience (#12222)

parent 4c8ff7c8
......@@ -6,4 +6,5 @@ examples/with-ioc/**
examples/with-kea/**
packages/next/compiled/**/*
packages/react-refresh-utils/**/*.js
packages/react-dev-overlay/lib/**
**/__tmp__/**
......@@ -5,4 +5,5 @@ node_modules
packages/next/compiled/**
packages/react-refresh-utils/**/*.js
packages/react-refresh-utils/**/*.d.ts
packages/react-dev-overlay/lib/**
**/__tmp__/**
......@@ -37,5 +37,5 @@ code:after {
hr {
border: none;
border-bottom: 1px solid #efefef;
margin: 6em auto;
margin: 5em auto;
}
import { useCallback, useEffect, useState } from 'react'
import ClickCount from '../components/ClickCount'
import styles from '../components/ClickCount.module.css'
function a() {
console.log(
// hello
document.body()
)
}
function foo() {
a()
}
function Home() {
const [count, setCount] = useState(0)
......@@ -28,6 +40,19 @@ function Home() {
<p>Component with State</p>
<ClickCount />
</div>
<hr />
<div>
<button
className={styles.btn}
type="button"
onClick={e => {
setTimeout(() => document.parentNode(), 0)
foo()
}}
>
Throw an Error
</button>
</div>
</main>
)
}
......
......@@ -846,6 +846,7 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_FID_POLYFILL': JSON.stringify(
config.experimental.measureFid
),
'process.env.__NEXT_FAST_REFRESH': JSON.stringify(hasReactRefresh),
...(isServer
? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
......@@ -1031,6 +1032,7 @@ export default async function getBaseWebpackConfig(
customAppFile,
isDevelopment: dev,
isServer,
hasReactRefresh,
assetPrefix: config.assetPrefix || '',
sassOptions: config.experimental.sassOptions,
})
......
......@@ -10,8 +10,16 @@ export const base = curry(function base(
config.name = ctx.isServer ? 'server' : 'client'
config.target = ctx.isServer ? 'node' : 'web'
// https://webpack.js.org/configuration/devtool/#development
config.devtool = ctx.isDevelopment
? 'cheap-module-source-map'
? ctx.hasReactRefresh
? // `eval-source-map` results in the fastest rebuilds during dev. The
// only drawback is cold boot time, but this is mitigated by the fact
// that we load entries on-demand.
'eval-source-map'
: // `cheap-module-source-map` is the old preferred format that was
// required for `react-error-overlay`.
'cheap-module-source-map'
: ctx.isProduction
? false
: false
......
......@@ -10,6 +10,7 @@ export async function build(
customAppFile,
isDevelopment,
isServer,
hasReactRefresh,
assetPrefix,
sassOptions,
}: {
......@@ -17,6 +18,7 @@ export async function build(
customAppFile: string | null
isDevelopment: boolean
isServer: boolean
hasReactRefresh: boolean
assetPrefix: string
sassOptions: any
}
......@@ -26,6 +28,7 @@ export async function build(
customAppFile,
isDevelopment,
isProduction: !isDevelopment,
hasReactRefresh,
isServer,
isClient: !isServer,
assetPrefix: assetPrefix
......
......@@ -6,6 +6,7 @@ export type ConfigurationContext = {
isDevelopment: boolean
isProduction: boolean
hasReactRefresh: boolean
isServer: boolean
isClient: boolean
......
......@@ -26,6 +26,7 @@
// can be found here:
// https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js
import * as DevOverlay from '@next/react-dev-overlay/lib/client'
import fetch from 'next/dist/build/polyfills/unfetch'
import * as ErrorOverlay from 'next/dist/compiled/react-error-overlay'
import stripAnsi from 'next/dist/compiled/strip-ansi'
......@@ -61,6 +62,10 @@ export default function connect(options) {
)
})
if (process.env.__NEXT_FAST_REFRESH) {
DevOverlay.register()
}
// We need to keep track of if there has been a runtime error.
// Essentially, we cannot guarantee application state was not corrupted by the
// runtime error. To prevent confusing behavior, we forcibly reload the entire
......@@ -69,6 +74,10 @@ export default function connect(options) {
// See https://github.com/facebook/create-react-app/issues/3096
ErrorOverlay.startReportingRuntimeErrors({
onError: function() {
if (process.env.__NEXT_FAST_REFRESH) {
return
}
hadRuntimeError = true
},
})
......@@ -97,7 +106,15 @@ export default function connect(options) {
customHmrEventHandler = handler
},
reportRuntimeError(err) {
ErrorOverlay.reportRuntimeError(err)
if (process.env.__NEXT_FAST_REFRESH) {
// FIXME: this code branch should be eliminated
setTimeout(() => {
// An unhandled rendering error occurred
throw err
})
} else {
ErrorOverlay.reportRuntimeError(err)
}
},
prepareError(err) {
// Temporary workaround for https://github.com/facebook/create-react-app/issues/4760
......@@ -139,10 +156,10 @@ function handleSuccess() {
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onHotUpdateSuccess() {
tryApplyUpdates(function onSuccessfulHotUpdate(hasUpdates) {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay()
onFastRefresh(hasUpdates)
})
}
}
......@@ -180,10 +197,10 @@ function handleWarnings(warnings) {
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onSuccessfulHotUpdate() {
tryApplyUpdates(function onSuccessfulHotUpdate(hasUpdates) {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay()
onFastRefresh(hasUpdates)
})
}
}
......@@ -227,6 +244,15 @@ function tryDismissErrorOverlay() {
}
}
function onFastRefresh(hasUpdates) {
tryDismissErrorOverlay()
if (hasUpdates) {
if (process.env.__NEXT_FAST_REFRESH) {
DevOverlay.onRefresh()
}
}
}
// There is a newer version of the code available.
function handleAvailableHash(hash) {
// Update last known compilation hash.
......@@ -363,14 +389,15 @@ function tryApplyUpdates(onHotUpdateSuccess) {
return
}
const hasUpdates = Boolean(updatedModules.length)
if (typeof onHotUpdateSuccess === 'function') {
// Maybe we want to do something.
onHotUpdateSuccess()
onHotUpdateSuccess(hasUpdates)
}
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdates()
tryApplyUpdates(hasUpdates ? undefined : onHotUpdateSuccess)
} else {
if (process.env.__NEXT_TEST_MODE) {
afterApplyUpdates(() => {
......
......@@ -152,7 +152,18 @@ class Container extends React.Component {
}
render() {
return this.props.children
if (process.env.NODE_ENV === 'production') {
return this.props.children
}
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_FAST_REFRESH) {
const {
ReactDevOverlay,
} = require('@next/react-dev-overlay/lib/client')
return <ReactDevOverlay>{this.props.children}</ReactDevOverlay>
}
return this.props.children
}
}
}
......
......@@ -74,6 +74,7 @@
"@babel/preset-react": "7.7.0",
"@babel/preset-typescript": "7.7.2",
"@babel/runtime": "7.7.2",
"@next/react-dev-overlay": "9.3.7-canary.1",
"@next/react-refresh-utils": "9.3.7-canary.1",
"babel-plugin-syntax-jsx": "6.18.0",
"babel-plugin-transform-define": "2.0.0",
......
......@@ -23,6 +23,7 @@ import { route } from '../next-server/server/router'
import errorOverlayMiddleware from './lib/error-overlay-middleware'
import { findPageFile } from './lib/find-page-file'
import onDemandEntryHandler, { normalizePage } from './on-demand-entry-handler'
import reactDevOverlayMiddleware from '@next/react-dev-overlay/lib/middleware'
export async function renderScriptError(res: ServerResponse, error: Error) {
// Asks CDNs and others to not to cache the errored page
......@@ -353,6 +354,10 @@ export default class HotReloader {
onDemandEntries.middleware(),
webpackHotMiddleware,
errorOverlayMiddleware({ dir: this.dir }),
reactDevOverlayMiddleware({
rootDirectory: this.dir,
stats: () => this.stats,
}),
]
}
......
# `@next/react-dev-overlay`
A development-only overlay for developing React applications.
{
"name": "@next/react-dev-overlay",
"version": "9.3.7-canary.1",
"description": "A development-only overlay for developing React applications.",
"repository": {
"url": "zeit/next.js",
"directory": "packages/react-dev-overlay"
},
"files": [
"lib/"
],
"author": "Joe Haddad <timer@vercel.com>",
"license": "MIT",
"scripts": {
"prepublish": "tsc -d -p tsconfig.json",
"build": "tsc -d -w -p tsconfig.json"
},
"dependencies": {
"@babel/code-frame": "7.8.3",
"anser": "1.4.9",
"classnames": "2.2.6",
"source-map": "0.7.3",
"stacktrace-parser": "0.1.9",
"strip-ansi": "6.0.0"
},
"peerDependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0"
},
"devDependencies": {}
}
import { parse as parseStack } from 'stacktrace-parser'
import * as Bus from './internal/bus'
let isRegistered = false
let stackTraceLimit: number | undefined = undefined
function onUnhandledError(ev: ErrorEvent) {
const error = ev?.error
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
}
const e = error
Bus.emit({
type: Bus.TYPE_UNHANDLED_ERROR,
reason: error,
frames: parseStack(e.stack),
})
}
function onUnhandledRejection(ev: PromiseRejectionEvent) {
const reason = ev?.reason
if (
!reason ||
!(reason instanceof Error) ||
typeof reason.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}
const e = reason
Bus.emit({
type: Bus.TYPE_UNHANDLED_REJECTION,
reason: reason,
frames: parseStack(e.stack),
})
}
function register() {
if (isRegistered) {
return
}
isRegistered = true
try {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 50
stackTraceLimit = limit
} catch {}
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
}
function unregister() {
if (!isRegistered) {
return
}
isRegistered = false
if (stackTraceLimit !== undefined) {
try {
Error.stackTraceLimit = stackTraceLimit
} catch {}
stackTraceLimit = undefined
}
window.removeEventListener('error', onUnhandledError)
window.removeEventListener('unhandledrejection', onUnhandledRejection)
}
function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFFRESH })
}
export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { register, unregister, onRefresh }
import React from 'react'
type ErrorBoundaryProps = {
onError: (error: Error, componentStack: string | null) => void
}
type ErrorBoundaryState = { error: Error | null }
class ErrorBoundary extends React.PureComponent<
ErrorBoundaryProps,
ErrorBoundaryState
> {
state = { error: null }
componentDidCatch(
error: Error,
// Loosely typed because it depends on the React version and was
// accidentally excluded in some versions.
errorInfo?: { componentStack?: string | null }
) {
this.props.onError(error, errorInfo?.componentStack || null)
this.setState({ error })
}
render() {
return this.state.error
? // The component has to be unmounted or else it would continue to error
null
: this.props.children
}
}
export { ErrorBoundary }
import * as React from 'react'
import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal'
import { Errors, SupportedErrorEvent } from './container/Errors'
import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset'
type OverlayState = {
nextId: number
errors: SupportedErrorEvent[]
}
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) {
case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: {
return {
...state,
nextId: state.nextId + 1,
errors: [...state.errors, { id: state.nextId, event: ev }],
}
}
case Bus.TYPE_REFFRESH: {
return { ...state, errors: [] }
}
default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = ev
return state
}
}
}
function ReactDevOverlay({ children }) {
const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, { nextId: 1, errors: [] })
React.useEffect(() => {
Bus.on(dispatch)
return function() {
Bus.off(dispatch)
}
}, [dispatch])
const onComponentError = React.useCallback(
(error: Error, componentStack: string | null) => {
// TODO: special handling
},
[]
)
return (
<React.Fragment>
<ErrorBoundary onError={onComponentError}>{children}</ErrorBoundary>
{state.errors.length ? (
<ShadowPortal>
<CssReset />
<Base />
<ComponentStyles />
<Errors errors={state.errors} />
</ShadowPortal>
) : (
undefined
)}
</React.Fragment>
)
}
export default ReactDevOverlay
import { StackFrame } from 'stacktrace-parser'
export const TYPE_REFFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection'
export type FastRefresh = { type: typeof TYPE_REFFRESH }
export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR
reason: Error
frames: StackFrame[]
}
export type UnhandledRejection = {
type: typeof TYPE_UNHANDLED_REJECTION
reason: Error
frames: StackFrame[]
}
export type BusEvent = UnhandledError | UnhandledRejection | FastRefresh
export type BusEventHandler = (ev: BusEvent) => void
let handlers: Set<BusEventHandler> = new Set()
let queue: BusEvent[] = []
function drain() {
// Draining should never happen synchronously in case multiple handlers are
// registered.
setTimeout(function() {
while (
// Until we are out of events:
Boolean(queue.length) &&
// Or, if all handlers removed themselves as a result of handling the
// event(s)
Boolean(handlers.size)
) {
const ev = queue.shift()
handlers.forEach(handler => handler(ev))
}
}, 1)
}
export function emit(ev: BusEvent): void {
queue.push(Object.freeze({ ...ev }))
drain()
}
export function on(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
return false
}
handlers.add(fn)
drain()
return true
}
export function off(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
handlers.delete(fn)
return true
}
return false
}
import Anser from 'anser'
import * as React from 'react'
import { StackFrame } from 'stacktrace-parser'
import stripAnsi from 'strip-ansi'
import { getFrameSource } from '../../helpers/stack-frame'
export type CodeFrameProps = { stackFrame: StackFrame; codeFrame: string }
export const CodeFrame: React.FC<CodeFrameProps> = function CodeFrame({
stackFrame,
codeFrame,
}) {
// Strip leading spaces out of the code frame:
const formattedFrame = React.useMemo<string>(() => {
const lines = codeFrame.split(/\r?\n/g)
const prefixLength = lines
.map(line => /^>? +\d+ +\| ( *)/.exec(stripAnsi(line)))
.filter(Boolean)
.map(v => v.pop())
.reduce((c, n) => (isNaN(c) ? n.length : Math.min(c, n.length)), NaN)
if (prefixLength > 1) {
const p = ' '.repeat(prefixLength)
return lines
.map((line, a) =>
~(a = line.indexOf('|'))
? line.substring(0, a) + line.substring(a).replace(p, '')
: line
)
.join('\n')
}
return lines.join('\n')
}, [codeFrame])
const decoded = React.useMemo(() => {
return Anser.ansiToJson(formattedFrame, {
json: true,
use_classes: true,
remove_empty: true,
})
}, [formattedFrame])
// TODO: make the caret absolute
return (
<div data-nextjs-codeframe>
<p>
{getFrameSource(stackFrame)} @ {stackFrame.methodName}
</p>
<hr />
<pre>
{decoded.map((entry, index) => (
<span
key={`frame-${index}`}
style={{
color: entry.fg ? `var(--color-${entry.fg})` : undefined,
...(entry.decoration === 'bold'
? { fontWeight: 800 }
: entry.decoration === 'italic'
? { fontStyle: 'italic' }
: undefined),
}}
>
{entry.content}
</span>
))}
</pre>
</div>
)
}
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-codeframe] {
border-radius: 0.3rem;
background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg);
}
[data-nextjs-codeframe]:not(:last-child) {
margin-bottom: 1rem;
}
[data-nextjs-codeframe]::selection,
[data-nextjs-codeframe] *::selection {
background-color: var(--color-ansi-selection);
}
[data-nextjs-codeframe] * {
color: inherit;
background-color: transparent;
font-family: var(--font-stack-monospace);
}
[data-nextjs-codeframe] > * {
margin: 0;
padding: 0.5rem;
}
[data-nextjs-codeframe] > hr {
margin: 0 0.3rem;
padding: 0;
border: none;
border-style: solid;
border-width: 0;
border-bottom-width: 1px;
border-color: var(--color-ansi-fg);
}
`
export { styles }
import * as React from 'react'
import { useOnClickOutside } from '../../hooks/use-on-click-outside'
export type DialogProps = {
type: 'error' | 'warning'
'aria-labelledby': string
'aria-describedby': string
onClose: (e: MouseEvent | TouchEvent) => void
}
const Dialog: React.FC<DialogProps> = function Dialog({
children,
type,
onClose,
...props
}) {
const [dialog, setDialog] = React.useState<HTMLDivElement>(null)
const onDialog = React.useCallback(node => {
setDialog(node)
}, [])
useOnClickOutside(dialog, onClose)
return (
<div
ref={onDialog}
data-nextjs-dialog
tabIndex={-1}
role="dialog"
aria-labelledby={props['aria-labelledby']}
aria-describedby={props['aria-describedby']}
aria-modal="true"
>
<div data-nextjs-dialog-banner className={`banner-${type}`} />
{children}
</div>
)
}
export { Dialog }
import * as React from 'react'
export type DialogBodyProps = {
className?: string
}
const DialogBody: React.FC<DialogBodyProps> = function DialogBody({
children,
className,
}) {
return (
<div data-nextjs-dialog-body className={className}>
{children}
</div>
)
}
export { DialogBody }
import * as React from 'react'
export type DialogContentProps = {
className?: string
}
const DialogContent: React.FC<DialogContentProps> = function DialogContent({
children,
className,
}) {
return (
<div data-nextjs-dialog-content className={className}>
{children}
</div>
)
}
export { DialogContent }
import * as React from 'react'
export type DialogHeaderProps = {
className?: string
}
const DialogHeader: React.FC<DialogHeaderProps> = function DialogHeader({
children,
className,
}) {
return (
<div data-nextjs-dialog-header className={className}>
{children}
</div>
)
}
export { DialogHeader }
export { Dialog } from './Dialog'
export { DialogBody } from './DialogBody'
export { DialogContent } from './DialogContent'
export { DialogHeader } from './DialogHeader'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog] {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: 0.5rem;
box-shadow: 0 0.25rem 0.5rem rgba(22, 28, 45, 0.5);
max-height: calc(100% - 3.5rem);
overflow-y: hidden;
}
@media (min-width: 576px) {
[data-nextjs-dialog] {
max-width: 540px;
box-shadow: 0 0.5rem 1rem rgba(22, 28, 45, 0.5);
}
}
@media (min-width: 768px) {
[data-nextjs-dialog] {
max-width: 720px;
}
}
@media (min-width: 992px) {
[data-nextjs-dialog] {
max-width: 960px;
}
}
[data-nextjs-dialog-banner] {
position: relative;
}
[data-nextjs-dialog-banner].banner-warning {
border-color: var(--color-ansi-bright-yellow);
}
[data-nextjs-dialog-banner].banner-error {
border-color: var(--color-ansi-bright-red);
}
[data-nextjs-dialog-banner]::after {
content: '';
position: absolute;
top: 0;
right: 0;
width: 100%;
border-top-width: 5px;
border-bottom-width: calc(0.375rem - 5px);
border-top-style: solid;
border-bottom-style: solid;
border-top-color: inherit;
border-bottom-color: transparent;
border-top-left-radius: 0.375rem;
border-top-right-radius: 0.375rem;
}
[data-nextjs-dialog-content] {
border: none;
margin: 0;
padding: 1rem;
height: 100%;
display: flex;
flex-direction: column;
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-header] {
flex-shrink: 0;
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-body] {
position: relative;
flex: 1 1 auto;
overflow-y: auto;
}
`
export { styles }
import * as React from 'react'
export type LeftRightDialogHeaderProps = {
className?: string
previous: (() => void) | null
next: (() => void) | null
close: () => void
}
const LeftRightDialogHeader: React.FC<LeftRightDialogHeaderProps> = function LeftRightDialogHeader({
children,
className,
previous,
next,
close,
}) {
const buttonLeft = React.useRef<HTMLButtonElement>()
const buttonRight = React.useRef<HTMLButtonElement>()
const buttonClose = React.useRef<HTMLButtonElement>()
const [nav, setNav] = React.useState<HTMLElement | null>(null)
const onNav = React.useCallback((el: HTMLElement) => {
setNav(el)
}, [])
React.useEffect(() => {
if (nav == null) {
return
}
const root = nav.getRootNode()
const d = self.document
function handler(e: KeyboardEvent) {
if (e.key === 'ArrowLeft') {
e.stopPropagation()
if (buttonLeft.current) {
buttonLeft.current.focus()
}
previous && previous()
} else if (e.key === 'ArrowRight') {
e.stopPropagation()
if (buttonRight.current) {
buttonRight.current.focus()
}
next && next()
} else if (e.key === 'Escape') {
e.stopPropagation()
if (root instanceof ShadowRoot) {
const a = root.activeElement
if (a !== buttonClose.current && a instanceof HTMLElement) {
if (buttonClose.current) {
buttonClose.current.focus()
} else {
a.blur()
}
return
}
}
close()
}
}
root.addEventListener('keydown', handler)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function() {
root.removeEventListener('keydown', handler)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
}
}, [close, nav, next, previous])
return (
<div data-nextjs-dialog-left-right className={className}>
<nav ref={onNav}>
<button
ref={buttonLeft}
type="button"
aria-disabled={previous == null ? true : undefined}
onClick={previous ?? undefined}
>
&larr;
</button>
<button
ref={buttonRight}
type="button"
aria-disabled={next == null ? true : undefined}
onClick={next ?? undefined}
>
&rarr;
</button>
&nbsp;
{children}
</nav>
<button
ref={buttonClose}
type="button"
onClick={close}
aria-label="Close"
>
<span aria-hidden="true">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</span>
</button>
</div>
)
}
export { LeftRightDialogHeader }
export { LeftRightDialogHeader } from './LeftRightDialogHeader'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog-left-right] {
display: flex;
flex-direction: row;
align-content: center;
align-items: center;
justify-content: space-between;
}
[data-nextjs-dialog-left-right] > nav > button {
border: none;
border-radius: 4px;
background-color: rgba(230, 0, 0, 0.1);
color: rgba(230, 0, 0, 1);
padding: 3px 9px;
cursor: pointer;
font-weight: 500;
transition: background-color 0.25s ease;
}
[data-nextjs-dialog-left-right] > nav > button:hover {
background-color: rgba(230, 0, 0, 0.2);
}
[data-nextjs-dialog-left-right] > nav > button[aria-disabled] {
background-color: rgba(230, 0, 0, 0.1);
color: rgba(230, 0, 0, 0.2);
cursor: not-allowed;
}
[data-nextjs-dialog-left-right] > nav > button:first-of-type {
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
margin-right: 1px;
}
[data-nextjs-dialog-left-right] > nav > button:last-of-type {
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
}
[data-nextjs-dialog-left-right] > button:last-of-type {
border: 0;
padding: 0;
background-color: transparent;
appearance: none;
opacity: 0.4;
transition: opacity 0.25s ease;
}
[data-nextjs-dialog-left-right] > button:last-of-type:hover {
opacity: 0.7;
}
`
export { styles }
import * as React from 'react'
import { lock, unlock } from './body-locker'
export type OverlayProps = { className?: string }
const Overlay: React.FC<OverlayProps> = function Overlay({
className,
children,
}) {
React.useEffect(() => {
lock()
return () => {
unlock()
}
}, [])
return (
<div data-nextjs-dialog-overlay className={className}>
<div data-nextjs-dialog-backdrop />
{children}
</div>
)
}
export { Overlay }
let previousBodyPaddingRight: string | undefined
let previousBodyOverflowSetting: string | undefined
let activeLocks = 0
export function lock() {
setTimeout(() => {
if (activeLocks++ > 0) {
return
}
const scrollBarGap =
window.innerWidth - document.documentElement.clientWidth
if (scrollBarGap > 0) {
previousBodyPaddingRight = document.body.style.paddingRight
document.body.style.paddingRight = `${scrollBarGap}px`
}
previousBodyOverflowSetting = document.body.style.overflow
document.body.style.overflow = 'hidden'
})
}
export function unlock() {
setTimeout(() => {
if (activeLocks === 0 || --activeLocks !== 0) {
return
}
if (previousBodyPaddingRight !== undefined) {
document.body.style.paddingRight = previousBodyPaddingRight
previousBodyPaddingRight = undefined
}
if (previousBodyOverflowSetting !== undefined) {
document.body.style.overflow = previousBodyOverflowSetting
previousBodyOverflowSetting = undefined
}
})
}
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog-overlay] {
position: fixed;
top: 10vh;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
z-index: 9000;
display: flex;
align-content: center;
align-items: center;
flex-direction: column;
padding: 0 15px;
}
[data-nextjs-dialog-backdrop] {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(17, 17, 17, 0.2);
pointer-events: all;
z-index: -1;
}
`
export { styles }
import * as React from 'react'
import { createPortal } from 'react-dom'
export type ShadowPortalProps = {
children: React.ReactNode
}
export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({
children,
}) {
let mountNode = React.useRef<HTMLDivElement | null>(null)
let portalNode = React.useRef<HTMLElement | null>(null)
let shadowNode = React.useRef<ShadowRoot | null>(null)
let [, forceUpdate] = React.useState()
React.useLayoutEffect(() => {
const ownerDocument = mountNode.current.ownerDocument
portalNode.current = ownerDocument.createElement('nextjs-portal')
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current)
forceUpdate({})
return () => {
if (portalNode.current && portalNode.current.ownerDocument) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current)
}
}
}, [])
return shadowNode.current ? (
createPortal(children, shadowNode.current as any)
) : (
<span ref={mountNode} />
)
}
import * as React from 'react'
export type ToastProps = {
onClick?: (ev: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
className?: string
}
export const Toast: React.FC<ToastProps> = function Toast({
onClick,
children,
className,
}) {
return (
<div data-nextjs-toast onClick={onClick} className={className}>
<div data-nextjs-toast-wrapper>{children}</div>
</div>
)
}
export { styles } from './styles'
export { Toast } from './Toast'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-toast] {
position: fixed;
bottom: 1rem;
left: 1rem;
max-width: 420px;
z-index: 9000;
}
@media (max-width: 440px) {
[data-nextjs-toast] {
max-width: 90vw;
left: 5vw;
}
}
[data-nextjs-toast-wrapper] {
padding: 1rem;
border-radius: 5px;
font-weight: 600;
color: var(--color-ansi-white);
background-color: var(--color-ansi-red);
box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.12);
}
`
export { styles }
import * as React from 'react'
import {
TYPE_UNHANDLED_ERROR,
TYPE_UNHANDLED_REJECTION,
UnhandledError,
UnhandledRejection,
} from '../bus'
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
} from '../components/Dialog'
import { LeftRightDialogHeader } from '../components/LeftRightDialogHeader'
import { Overlay } from '../components/Overlay'
import { Toast } from '../components/Toast'
import { noop as css } from '../helpers/noop-template'
import {
getOriginalStackFrames,
OriginalStackFrame,
} from '../helpers/stack-frame'
import { RuntimeError } from './RuntimeError'
export type SupportedErrorEvent = {
id: number
event: UnhandledError | UnhandledRejection
}
export type ErrorsProps = { errors: SupportedErrorEvent[] }
export type ReadyRuntimeError = {
id: number
runtime: true
error: Error
frames: OriginalStackFrame[]
}
type ReadyErrorEvent = ReadyRuntimeError
function getErrorSignature(ev: SupportedErrorEvent): string {
const { event } = ev
switch (event.type) {
case TYPE_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: {
return `${event.reason.name}::${event.reason.message}`
}
default: {
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = event
return ''
}
async function getErrorByType(
ev: SupportedErrorEvent
): Promise<ReadyErrorEvent> {
const { id, event } = ev
switch (event.type) {
case TYPE_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: {
return {
id,
runtime: true,
error: event.reason,
frames: await getOriginalStackFrames(event.frames),
}
}
default: {
break
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = event
throw new Error('type system invariant violation')
}
export const Errors: React.FC<ErrorsProps> = function Errors({ errors }) {
const [lookups, setLookups] = React.useState(
{} as { [eventId: string]: ReadyErrorEvent }
)
const [readyErrors, nextError] = React.useMemo<
[ReadyErrorEvent[], SupportedErrorEvent | null]
>(() => {
let ready: ReadyErrorEvent[] = []
let next: SupportedErrorEvent | null = null
// Ensure errors are displayed in the order they occurred in:
for (let idx = 0; idx < errors.length; ++idx) {
const e = errors[idx]
const { id } = e
if (id in lookups) {
ready.push(lookups[id])
continue
}
// Check for duplicate errors
if (idx > 0) {
const prev = errors[idx - 1]
if (getErrorSignature(prev) === getErrorSignature(e)) {
continue
}
}
next = e
break
}
return [ready, next]
}, [errors, lookups])
const isLoading = React.useMemo<boolean>(() => {
return readyErrors.length < 1 && Boolean(errors.length)
}, [errors.length, readyErrors.length])
React.useEffect(() => {
if (nextError == null) {
return
}
getErrorByType(nextError).then(
resolved => {
// 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,
// we'll store it.
setLookups(m => ({ ...m, [resolved.id]: resolved }))
},
() => {
// TODO: handle this, though an edge case
}
)
}, [nextError])
const [isMinimized, setMinimized] = React.useState<boolean>(false)
const [activeIdx, setActiveIndex] = React.useState<number>(0)
const previous = React.useCallback((e?: MouseEvent | TouchEvent) => {
e?.preventDefault()
setActiveIndex(v => Math.max(0, v - 1))
}, [])
const next = React.useCallback(
(e?: MouseEvent | TouchEvent) => {
e?.preventDefault()
setActiveIndex(v => Math.max(0, Math.min(readyErrors.length - 1, v + 1)))
},
[readyErrors.length]
)
const activeError = React.useMemo<ReadyErrorEvent | null>(
() => readyErrors[activeIdx] ?? null,
[activeIdx, readyErrors]
)
// Reset component state when there are no errors to be displayed.
// This should never happen, but lets handle it.
React.useEffect(() => {
if (errors.length < 1) {
setLookups({})
setMinimized(false)
setActiveIndex(0)
}
}, [errors.length])
const minimize = React.useCallback((e?: MouseEvent | TouchEvent) => {
e?.preventDefault()
setMinimized(true)
}, [])
const reopen = React.useCallback(
(e?: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
e?.preventDefault()
setMinimized(false)
},
[]
)
// This component shouldn't be rendered with no errors, but if it is, let's
// handle it gracefully by rendering nothing.
if (errors.length < 1) {
return null
}
if (isLoading) {
// TODO: better loading state
return <Overlay />
}
if (isMinimized) {
return (
<Toast className="nextjs-toast-errors-parent" onClick={reopen}>
<div className="nextjs-toast-errors">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="12"></line>
<line x1="12" y1="16" x2="12.01" y2="16"></line>
</svg>
<span>{readyErrors.length} errors</span>
</div>
</Toast>
)
}
return (
<Overlay>
<Dialog
type="error"
aria-labelledby="nextjs__container_errors_label"
aria-describedby="nextjs__container_errors_desc"
onClose={minimize}
>
<DialogContent>
<DialogHeader className="nextjs-container-errors-header">
<LeftRightDialogHeader
previous={activeIdx > 0 ? previous : null}
next={activeIdx < readyErrors.length - 1 ? next : null}
close={minimize}
>
<small
style={{
fontFamily: 'var(--font-stack-monospace)',
color: '#757575',
marginLeft: 9,
}}
>
{activeIdx + 1} of {readyErrors.length} unhandled error
{readyErrors.length < 2 ? '' : 's'}
</small>
</LeftRightDialogHeader>
<h4 id="nextjs__container_errors_label">Unhandled Runtime Error</h4>
<p id="nextjs__container_errors_desc">
{activeError.error.name}: {activeError.error.message}
</p>
</DialogHeader>
<DialogBody className="nextjs-container-errors-body">
<RuntimeError error={activeError} />
</DialogBody>
</DialogContent>
</Dialog>
</Overlay>
)
}
export const styles = css`
.nextjs-container-errors-header > h4 {
line-height: 1.5;
margin: 0;
margin-top: 1rem;
}
.nextjs-container-errors-header > p {
font-family: var(--font-stack-monospace);
margin: 0;
color: #6a6a6a;
}
.nextjs-container-errors-body {
margin-top: 1.5rem;
}
.nextjs-toast-errors-parent {
cursor: pointer;
transition: transform 0.2s ease;
}
.nextjs-toast-errors-parent:hover {
transform: scale(1.1);
}
.nextjs-toast-errors {
display: flex;
align-items: center;
justify-content: flex-start;
}
.nextjs-toast-errors > svg {
margin-right: 0.5rem;
}
`
import * as React from 'react'
import { StackFrame } from 'stacktrace-parser'
import { CodeFrame } from '../components/CodeFrame'
import { noop as css } from '../helpers/noop-template'
import { getFrameSource, OriginalStackFrame } from '../helpers/stack-frame'
import { ReadyRuntimeError } from './Errors'
export type RuntimeErrorProps = { className?: string; error: ReadyRuntimeError }
const CallStackFrame: React.FC<{
frame: OriginalStackFrame
}> = function CallStackFrame({ frame }) {
// TODO: ability to expand resolved frames
// TODO: render error or external indicator
const f: StackFrame = frame.originalStackFrame ?? frame.sourceStackFrame
return (
<div data-nextjs-call-stack-frame>
<h6>{f.methodName}</h6>
<p>{getFrameSource(f)}</p>
</div>
)
}
const RuntimeError: React.FC<RuntimeErrorProps> = function RuntimeError({
className,
error,
}) {
const firstFirstPartyFrameIndex = React.useMemo<number>(() => {
return error.frames.findIndex(
entry =>
entry.expanded &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
}, [error.frames])
const firstFrame = React.useMemo<OriginalStackFrame | null>(() => {
return error.frames[firstFirstPartyFrameIndex] ?? null
}, [error.frames, firstFirstPartyFrameIndex])
const allLeadingFrames = React.useMemo<OriginalStackFrame[]>(
() =>
firstFirstPartyFrameIndex < 0
? []
: error.frames.slice(0, firstFirstPartyFrameIndex),
[error.frames, firstFirstPartyFrameIndex]
)
// FIXME: allow collapsed frames to be toggled
const [all] = React.useState(false)
const leadingFrames = React.useMemo(
() => allLeadingFrames.filter(f => f.expanded || all),
[all, allLeadingFrames]
)
const callStackFrames = React.useMemo(
() =>
error.frames
.slice(firstFirstPartyFrameIndex + 1)
.filter(f => f.expanded || all),
[all, error.frames, firstFirstPartyFrameIndex]
)
return (
<div className={className}>
{firstFrame ? (
<React.Fragment>
<h5>Source</h5>
{leadingFrames.map((frame, index) => (
<CallStackFrame
key={`leading-frame-${index}-${all}`}
frame={frame}
/>
))}
<CodeFrame
stackFrame={firstFrame.originalStackFrame}
codeFrame={firstFrame.originalCodeFrame}
/>
</React.Fragment>
) : (
undefined
)}
{callStackFrames.length ? (
<React.Fragment>
<h5>Call Stack</h5>
{callStackFrames.map((frame, index) => (
<CallStackFrame key={`call-stack-${index}-${all}`} frame={frame} />
))}
</React.Fragment>
) : (
undefined
)}
</div>
)
}
export const styles = css`
[data-nextjs-call-stack-frame] > h6 {
font-family: var(--font-stack-monospace);
color: rgba(25, 25, 25, 1);
}
[data-nextjs-call-stack-frame] > p {
padding-left: 0.75rem;
font-size: 0.875rem;
color: rgba(25, 25, 25, 0.5);
}
`
export { RuntimeError }
export function noop(
strings: TemplateStringsArray,
...keys: readonly string[]
) {
const lastIndex = strings.length - 1
return (
strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +
strings[lastIndex]
)
}
import { StackFrame } from 'stacktrace-parser'
import { OriginalStackFrameResponse } from '../../middleware'
export type OriginalStackFrame =
| {
error: true
reason: string
external: false
expanded: false
sourceStackFrame: StackFrame
originalStackFrame: null
originalCodeFrame: null
}
| {
error: false
reason: null
external: false
expanded: boolean
sourceStackFrame: StackFrame
originalStackFrame: StackFrame
originalCodeFrame: string | null
}
| {
error: false
reason: null
external: true
expanded: false
sourceStackFrame: StackFrame
originalStackFrame: null
originalCodeFrame: null
}
export function getOriginalStackFrames(frames: StackFrame[]) {
return Promise.all(frames.map(frame => getOriginalStackFrame(frame)))
}
export function getOriginalStackFrame(
source: StackFrame
): Promise<OriginalStackFrame> {
async function _getOriginalStackFrame(): Promise<OriginalStackFrame> {
const params = new URLSearchParams()
for (const key in source) {
params.append(key, (source[key] ?? '').toString())
}
const controller = new AbortController()
const tm = setTimeout(() => controller.abort(), 3000)
const res = await self
.fetch(`/__nextjs_original-stack-frame?${params.toString()}`, {
signal: controller.signal,
})
.finally(() => {
clearTimeout(tm)
})
if (!res.ok) {
return Promise.reject(new Error(await res.text()))
}
const body: OriginalStackFrameResponse = await res.json()
return {
error: false,
reason: null,
external: false,
expanded:
body.originalStackFrame?.file &&
!body.originalStackFrame.file.includes('node_modules'),
sourceStackFrame: source,
originalStackFrame: body.originalStackFrame,
originalCodeFrame: body.originalCodeFrame || null,
}
}
if (!source.file?.startsWith('webpack-internal:')) {
return Promise.resolve({
error: false,
reason: null,
external: true,
expanded: false,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
})
}
return _getOriginalStackFrame().catch((err: Error) => ({
error: true,
reason: err?.message ?? err?.toString() ?? 'Unknown Error',
external: false,
expanded: false,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
}))
}
export function getFrameSource(frame: StackFrame): string {
let str = ''
try {
const u = new URL(frame.file)
// Strip the origin for same-origin scripts.
if (
typeof globalThis !== 'undefined' &&
globalThis.location?.origin !== u.origin
) {
str += u.origin
}
// Strip query string information as it's typically too verbose to be
// meaningful.
str += u.pathname
str += ' '
} catch {
str += (frame.file || '(unknown)') + ' '
}
if (frame.lineNumber != null) {
if (frame.column != null) {
str += `(${frame.lineNumber}:${frame.column}) `
} else {
str += `(${frame.lineNumber}) `
}
}
return str.slice(0, -1)
}
import * as React from 'react'
export function useOnClickOutside(
el: Node | null,
handler: (e: MouseEvent | TouchEvent) => void
) {
React.useEffect(() => {
if (el == null) {
return
}
const listener = (e: MouseEvent | TouchEvent) => {
// Do nothing if clicking ref's element or descendent elements
if (!el || el.contains(e.target as Element)) {
return
}
handler(e)
}
const root = el.getRootNode()
root.addEventListener('mousedown', listener)
root.addEventListener('touchstart', listener)
return function() {
root.removeEventListener('mousedown', listener)
root.removeEventListener('touchstart', listener)
}
}, [handler, el])
}
import * as React from 'react'
import { noop as css } from '../helpers/noop-template'
export function Base() {
return (
<style
dangerouslySetInnerHTML={{
__html: css`
:host {
--font-stack-monospace: 'SFMono-Regular', Consolas,
'Liberation Mono', Menlo, Courier, monospace;
--color-ansi-selection: rgba(95, 126, 151, 0.48);
--color-ansi-bg: #011627;
--color-ansi-fg: #d6deeb;
--color-ansi-white: #ffffff;
--color-ansi-black: #011627;
--color-ansi-blue: #82aaff;
--color-ansi-cyan: #21c7a8;
--color-ansi-green: #22da6e;
--color-ansi-magenta: #c792ea;
--color-ansi-red: #ef5350;
--color-ansi-yellow: #addb67;
--color-ansi-bright-white: #ffffff;
--color-ansi-bright-black: #575656;
--color-ansi-bright-blue: #82aaff;
--color-ansi-bright-cyan: #7fdbca;
--color-ansi-bright-green: #22da6e;
--color-ansi-bright-magenta: #c792ea;
--color-ansi-bright-red: #ef5350;
--color-ansi-bright-yellow: #ffeb95;
}
.mono {
font-family: var(--font-stack-monospace);
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2rem;
}
h3 {
font-size: 1.75rem;
}
h4 {
font-size: 1.5rem;
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
`,
}}
/>
)
}
import * as React from 'react'
import { styles as codeFrame } from '../components/CodeFrame/styles'
import { styles as dialog } from '../components/Dialog'
import { styles as leftRightDialogHeader } from '../components/LeftRightDialogHeader/styles'
import { styles as overlay } from '../components/Overlay/styles'
import { styles as toast } from '../components/Toast'
import { styles as containerErrorStyles } from '../container/Errors'
import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError'
import { noop as css } from '../helpers/noop-template'
export function ComponentStyles() {
return (
<style
dangerouslySetInnerHTML={{
__html: css`
${overlay}
${toast}
${dialog}
${leftRightDialogHeader}
${codeFrame}
${containerErrorStyles}
${containerRuntimeErrorStyles}
`,
}}
/>
)
}
import * as React from 'react'
import { noop as css } from '../helpers/noop-template'
export function CssReset() {
return (
<style
dangerouslySetInnerHTML={{
__html: css`
:host {
all: initial;
}
/*!
* Bootstrap Reboot v4.4.1 (https://getbootstrap.com/)
* Copyright 2011-2019 The Bootstrap Authors
* Copyright 2011-2019 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
:host {
font-family: sans-serif;
line-height: 1.15;
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
article,
aside,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section {
display: block;
}
:host {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Helvetica Neue', Arial, 'Noto Sans', sans-serif,
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji';
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
text-align: left;
background-color: #fff;
}
[tabindex='-1']:focus:not(:focus-visible) {
outline: 0 !important;
}
hr {
box-sizing: content-box;
height: 0;
overflow: visible;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 0;
margin-bottom: 0.5rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-original-title] {
text-decoration: underline;
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
border-bottom: 0;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #007bff;
text-decoration: none;
background-color: transparent;
}
a:hover {
color: #0056b3;
text-decoration: underline;
}
a:not([href]) {
color: inherit;
text-decoration: none;
}
a:not([href]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas,
'Liberation Mono', 'Courier New', monospace;
font-size: 1em;
}
pre {
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
}
figure {
margin: 0 0 1rem;
}
img {
vertical-align: middle;
border-style: none;
}
svg {
overflow: hidden;
vertical-align: middle;
}
table {
border-collapse: collapse;
}
caption {
padding-top: 0.75rem;
padding-bottom: 0.75rem;
color: #6c757d;
text-align: left;
caption-side: bottom;
}
th {
text-align: inherit;
}
label {
display: inline-block;
margin-bottom: 0.5rem;
}
button {
border-radius: 0;
}
button:focus {
outline: 1px dotted;
outline: 5px auto -webkit-focus-ring-color;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
input {
overflow: visible;
}
button,
select {
text-transform: none;
}
select {
word-wrap: normal;
}
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
}
button:not(:disabled),
[type='button']:not(:disabled),
[type='reset']:not(:disabled),
[type='submit']:not(:disabled) {
cursor: pointer;
}
button::-moz-focus-inner,
[type='button']::-moz-focus-inner,
[type='reset']::-moz-focus-inner,
[type='submit']::-moz-focus-inner {
padding: 0;
border-style: none;
}
input[type='radio'],
input[type='checkbox'] {
box-sizing: border-box;
padding: 0;
}
input[type='date'],
input[type='time'],
input[type='datetime-local'],
input[type='month'] {
-webkit-appearance: listbox;
}
textarea {
overflow: auto;
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
max-width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: 1.5rem;
line-height: inherit;
color: inherit;
white-space: normal;
}
progress {
vertical-align: baseline;
}
[type='number']::-webkit-inner-spin-button,
[type='number']::-webkit-outer-spin-button {
height: auto;
}
[type='search'] {
outline-offset: -2px;
-webkit-appearance: none;
}
[type='search']::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
summary {
display: list-item;
cursor: pointer;
}
template {
display: none;
}
[hidden] {
display: none !important;
}
`,
}}
/>
)
}
import { codeFrameColumns } from '@babel/code-frame'
import { promises as fs } from 'fs'
import { IncomingMessage, ServerResponse } from 'http'
import path from 'path'
import { NullableMappedPosition, SourceMapConsumer } from 'source-map'
import { StackFrame } from 'stacktrace-parser'
import url from 'url'
import webpack from 'webpack'
import { OriginalSource } from 'webpack-sources'
type OverlayMiddlewareOptions = {
rootDirectory: string
stats(): webpack.Stats
}
export type OriginalStackFrameResponse = {
originalStackFrame: StackFrame
originalCodeFrame: string | null
}
function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
function getSourceById(id: string): OriginalSource | null {
try {
const compilation = options.stats()?.compilation
const m = compilation?.modules?.find(m => m.id === id)
return (
m?.source(
compilation.dependencyTemplates,
compilation.runtimeTemplate
) ?? null
)
} catch (err) {
console.error(`Failed to lookup module by ID ("${id}"):`, err)
return null
}
}
return async function(
req: IncomingMessage,
res: ServerResponse,
next: Function
) {
const { pathname, query } = url.parse(req.url, true)
if (pathname === '/__nextjs_original-stack-frame') {
const frame = (query as unknown) as StackFrame
if (
frame.file?.startsWith('webpack-internal:///') ||
!parseInt(frame.lineNumber?.toString() ?? '', 10)
) {
const moduleId = frame.file.slice(20)
const source = getSourceById(moduleId)
if (source == null) {
res.statusCode = 404
res.write('Not Found')
return res.end()
}
const frameLine = parseInt(frame.lineNumber?.toString() ?? '', 10)
let frameColumn: number | null = parseInt(
frame.column?.toString() ?? '',
10
)
if (!frameColumn) {
frameColumn = null
}
let pos: NullableMappedPosition
try {
const consumer = await new SourceMapConsumer(source.map())
pos = consumer.originalPositionFor({
line: frameLine,
column: frameColumn,
})
consumer.destroy()
} catch (err) {
res.statusCode = 500
res.write('Internal Server Error')
return res.end()
}
if (pos.source == null) {
res.statusCode = 404
res.write('Not Found')
return res.end()
}
const filePath = path.resolve(options.rootDirectory, pos.source)
const fileContent: string | null = await fs
.readFile(filePath, 'utf-8')
.catch(() => null)
const originalFrame: StackFrame = {
file: fileContent
? path.relative(options.rootDirectory, filePath)
: pos.source,
lineNumber: pos.line,
column: pos.column,
methodName: frame.methodName, // TODO: resolve original method name (?)
arguments: [],
}
const originalCodeFrame: string | null =
fileContent && pos.line
? (codeFrameColumns(
fileContent,
{ start: { line: pos.line, column: pos.column } },
{ forceColor: true }
) as string)
: null
const o: OriginalStackFrameResponse = {
originalStackFrame: originalFrame,
originalCodeFrame,
}
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.write(Buffer.from(JSON.stringify(o)))
return res.end()
}
res.statusCode = 400
res.write('Bad Request')
return res.end()
}
return next()
}
}
export default getOverlayMiddleware
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es3",
"lib": ["dom"],
"downlevelIteration": true,
"preserveWatchOutput": true,
"outDir": "lib",
"jsx": "react",
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules"]
}
......@@ -271,3 +271,152 @@ test('cyclic dependencies', async () => {
await cleanup()
})
test('logbox: can recover from a event handler error', async () => {
const [session, cleanup] = await sandbox()
await session.patch(
'index.js',
`
import { useCallback, useState } from 'react'
export default function Index() {
const [count, setCount] = useState(0)
const increment = useCallback(() => {
setCount(c => c + 1)
throw new Error('oops')
}, [setCount])
return (
<main>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</main>
)
}
`
)
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('0')
await session.evaluate(() => document.querySelector('button').click())
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('1')
expect(await session.hasRedbox(true)).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"index.js (8:16) @ eval
6 | const increment = useCallback(() => {
7 | setCount(c => c + 1)
> 8 | throw new Error('oops')
| ^
9 | }, [setCount])
10 | return (
11 | <main>"
`)
await session.patch(
'index.js',
`
import { useCallback, useState } from 'react'
export default function Index() {
const [count, setCount] = useState(0)
const increment = useCallback(() => setCount(c => c + 1), [setCount])
return (
<main>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</main>
)
}
`
)
expect(await session.hasRedbox()).toBe(false)
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('Count: 1')
await session.evaluate(() => document.querySelector('button').click())
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('Count: 2')
expect(await session.hasRedbox()).toBe(false)
await cleanup()
})
test('logbox: can recover from a component error', async () => {
const [session, cleanup] = await sandbox()
await session.write(
'child.js',
`
export default function Child() {
return <p>Hello</p>;
}
`
)
await session.patch(
'index.js',
`
import Child from './child'
export default function Index() {
return (
<main>
<Child />
</main>
)
}
`
)
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('Hello')
await session.patch(
'child.js',
`
// hello
export default function Child() {
throw new Error('oops')
}
`
)
expect(await session.hasRedbox(true)).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"child.js (4:14) @ Child
2 | // hello
3 | export default function Child() {
> 4 | throw new Error('oops')
| ^
5 | }
6 | "
`)
const didNotReload = await session.patch(
'child.js',
`
export default function Child() {
return <p>Hello</p>;
}
`
)
expect(didNotReload).toBe(true)
expect(await session.hasRedbox()).toBe(false)
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('Hello')
await cleanup()
})
......@@ -116,6 +116,40 @@ export async function sandbox(id = nanoid()) {
`document.querySelector('iframe').contentWindow.document.body.innerHTML`
)
},
async hasRedbox(expected = false) {
let attempts = 3
do {
const has = await this.evaluate(() => {
return Boolean(
[].slice
.call(document.querySelectorAll('nextjs-portal'))
.find(p =>
p.shadowRoot.querySelector('#nextjs__container_errors_label')
)
)
})
if (has) {
return true
}
if (--attempts < 0) {
break
}
await new Promise(resolve => setTimeout(resolve, 1000))
} while (expected)
return false
},
async getRedboxSource() {
return this.evaluate(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find(p =>
p.shadowRoot.querySelector('#nextjs__container_errors_label')
)
const root = portal.shadowRoot
return root.querySelector('[data-nextjs-codeframe]').innerText
})
},
},
function cleanup() {
async function _cleanup() {
......
......@@ -45,7 +45,7 @@
dependencies:
cross-fetch "3.0.4"
"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.5.5", "@babel/code-frame@^7.8.3":
"@babel/code-frame@7.8.3", "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.5.5", "@babel/code-frame@^7.8.3":
version "7.8.3"
resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.8.3.tgz#33e25903d7481181534e12ec0a25f16b6fcf419e"
integrity sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==
......@@ -3253,6 +3253,11 @@ amphtml-validator@1.0.30:
commander "2.15.1"
promise "8.0.1"
anser@1.4.9:
version "1.4.9"
resolved "https://registry.yarnpkg.com/anser/-/anser-1.4.9.tgz#1f85423a5dcf8da4631a341665ff675b96845760"
integrity sha512-AI+BjTeGt2+WFk4eWcqbQ7snZpDBt8SaLlj0RT2h5xfdWaiy51OjYvqwMrNzJLGy8iOAL6nKDITWO+rd4MkYEA==
ansi-colors@^3.0.0:
version "3.2.4"
resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-3.2.4.tgz#e3a3da4bfbae6c86a9c285625de124a234026fbf"
......@@ -4638,6 +4643,11 @@ class-utils@^0.3.5:
isobject "^3.0.0"
static-extend "^0.1.1"
classnames@2.2.6:
version "2.2.6"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.2.6.tgz#43935bffdd291f326dad0a205309b38d00f650ce"
integrity sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q==
clean-stack@^2.0.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b"
......@@ -15366,6 +15376,13 @@ stack-utils@^1.0.1:
resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-1.0.2.tgz#33eba3897788558bebfc2db059dc158ec36cebb8"
integrity sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==
stacktrace-parser@0.1.9:
version "0.1.9"
resolved "https://registry.yarnpkg.com/stacktrace-parser/-/stacktrace-parser-0.1.9.tgz#11e6d61d42e8cfc87293143d0766408b7a87b00f"
integrity sha512-DRy03ljj0367Ud3OAJHD6eVS/+CvMK2u/djVYuU37fHYcYHoZ8tkFyhbRf7PNG1h3bWLsw+SNTSXrPFe07A7aQ==
dependencies:
type-fest "^0.7.1"
state-toggle@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/state-toggle/-/state-toggle-1.0.2.tgz#75e93a61944116b4959d665c8db2d243631d6ddc"
......@@ -16327,6 +16344,11 @@ type-fest@^0.3.0:
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1"
integrity sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ==
type-fest@^0.7.1:
version "0.7.1"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.7.1.tgz#8dda65feaf03ed78f0a3f9678f1869147f7c5c48"
integrity sha512-Ne2YiiGN8bmrmJJEuTWTLJR32nh/JdL1+PSicowtNb0WFpn59GK8/lfD61bVtzguz7b3PBt74nxpv/Pw5po5Rg==
type-fest@^0.8.1:
version "0.8.1"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d"
......
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