Unverified Commit 64665380 authored by Leah's avatar Leah Committed by GitHub

allow turbopack HMR to recover from react errors without hard refresh (#47771)

parent be2237fc
......@@ -8,97 +8,95 @@ import type {
Issue,
ResourceIdentifier,
ServerMessage,
} from "@vercel/turbopack-dev-runtime/types/protocol";
} from '@vercel/turbopack-dev-runtime/types/protocol'
import type {
ChunkPath,
ModuleId,
UpdateCallback,
TurbopackGlobals,
} from "@vercel/turbopack-dev-runtime/types";
import stripAnsi from "@vercel/turbopack-next/compiled/strip-ansi";
} from '@vercel/turbopack-dev-runtime/types'
import {
onBeforeRefresh,
onBuildOk,
onRefresh,
onTurbopackIssues,
} from "../overlay/client";
import { addEventListener, sendMessage } from "./websocket";
} from '../overlay/client'
import { addEventListener, sendMessage } from './websocket'
declare var globalThis: TurbopackGlobals;
declare var globalThis: TurbopackGlobals
export type ClientOptions = {
assetPrefix: string;
};
assetPrefix: string
}
export function connect({ assetPrefix }: ClientOptions) {
addEventListener((event) => {
switch (event.type) {
case "connected":
handleSocketConnected();
break;
case "message":
const msg: ServerMessage = JSON.parse(event.message.data);
handleSocketMessage(msg);
break;
case 'connected':
handleSocketConnected()
break
case 'message':
const msg: ServerMessage = JSON.parse(event.message.data)
handleSocketMessage(msg)
break
}
});
})
const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS;
const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS
if (queued != null && !Array.isArray(queued)) {
throw new Error("A separate HMR handler was already registered");
throw new Error('A separate HMR handler was already registered')
}
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = {
push: ([chunkPath, callback]: [ChunkPath, UpdateCallback]) => {
subscribeToChunkUpdate(chunkPath, callback);
subscribeToChunkUpdate(chunkPath, callback)
},
};
}
if (Array.isArray(queued)) {
for (const [chunkPath, callback] of queued) {
subscribeToChunkUpdate(chunkPath, callback);
subscribeToChunkUpdate(chunkPath, callback)
}
}
}
type UpdateCallbackSet = {
callbacks: Set<UpdateCallback>;
unsubscribe: () => void;
};
callbacks: Set<UpdateCallback>
unsubscribe: () => void
}
const updateCallbackSets: Map<ResourceKey, UpdateCallbackSet> = new Map();
const updateCallbackSets: Map<ResourceKey, UpdateCallbackSet> = new Map()
function sendJSON(message: ClientMessage) {
sendMessage(JSON.stringify(message));
sendMessage(JSON.stringify(message))
}
type ResourceKey = string;
type ResourceKey = string
function resourceKey(resource: ResourceIdentifier): ResourceKey {
return JSON.stringify({
path: resource.path,
headers: resource.headers || null,
});
})
}
function subscribeToUpdates(resource: ResourceIdentifier): () => void {
sendJSON({
type: "subscribe",
type: 'subscribe',
...resource,
});
})
return () => {
sendJSON({
type: "unsubscribe",
type: 'unsubscribe',
...resource,
});
};
})
}
}
function handleSocketConnected() {
for (const key of updateCallbackSets.keys()) {
subscribeToUpdates(JSON.parse(key));
subscribeToUpdates(JSON.parse(key))
}
}
......@@ -106,136 +104,136 @@ function handleSocketConnected() {
const chunkListsWithPendingUpdates: Map<
ResourceKey,
{ update: ChunkListUpdate; resource: ResourceIdentifier }
> = new Map();
> = new Map()
function aggregateUpdates(
msg: ServerMessage,
aggregate: boolean
): ServerMessage {
const key = resourceKey(msg.resource);
let aggregated = chunkListsWithPendingUpdates.get(key);
const key = resourceKey(msg.resource)
let aggregated = chunkListsWithPendingUpdates.get(key)
if (msg.type === "issues" && aggregated != null) {
if (msg.type === 'issues' && aggregated != null) {
if (!aggregate) {
chunkListsWithPendingUpdates.delete(key);
chunkListsWithPendingUpdates.delete(key)
}
return {
...msg,
type: "partial",
type: 'partial',
instruction: aggregated.update,
};
}
}
if (msg.type !== "partial") return msg;
if (msg.type !== 'partial') return msg
if (aggregated == null) {
if (aggregate) {
chunkListsWithPendingUpdates.set(key, {
resource: msg.resource,
update: msg.instruction,
});
})
}
return msg;
return msg
}
aggregated = {
resource: msg.resource,
update: mergeChunkListUpdates(aggregated.update, msg.instruction),
};
}
if (aggregate) {
chunkListsWithPendingUpdates.set(key, aggregated);
chunkListsWithPendingUpdates.set(key, aggregated)
} else {
// Once we receive a partial update with no critical issues, we can stop aggregating updates.
// The aggregated update will be applied.
chunkListsWithPendingUpdates.delete(key);
chunkListsWithPendingUpdates.delete(key)
}
return {
...msg,
instruction: aggregated.update,
};
}
}
function mergeChunkListUpdates(
updateA: ChunkListUpdate,
updateB: ChunkListUpdate
): ChunkListUpdate {
let chunks;
let chunks
if (updateA.chunks != null) {
if (updateB.chunks == null) {
chunks = updateA.chunks;
chunks = updateA.chunks
} else {
chunks = mergeChunkListChunks(updateA.chunks, updateB.chunks);
chunks = mergeChunkListChunks(updateA.chunks, updateB.chunks)
}
} else if (updateB.chunks != null) {
chunks = updateB.chunks;
chunks = updateB.chunks
}
let merged;
let merged
if (updateA.merged != null) {
if (updateB.merged == null) {
merged = updateA.merged;
merged = updateA.merged
} else {
// Since `merged` is an array of updates, we need to merge them all into
// one, consistent update.
// Since there can only be `EcmascriptMergeUpdates` in the array, there is
// no need to key on the `type` field.
let update = updateA.merged[0];
let update = updateA.merged[0]
for (let i = 1; i < updateA.merged.length; i++) {
update = mergeChunkListEcmascriptMergedUpdates(
update,
updateA.merged[i]
);
)
}
for (let i = 0; i < updateB.merged.length; i++) {
update = mergeChunkListEcmascriptMergedUpdates(
update,
updateB.merged[i]
);
)
}
merged = [update];
merged = [update]
}
} else if (updateB.merged != null) {
merged = updateB.merged;
merged = updateB.merged
}
return {
type: "ChunkListUpdate",
type: 'ChunkListUpdate',
chunks,
merged,
};
}
}
function mergeChunkListChunks(
chunksA: Record<ChunkPath, ChunkUpdate>,
chunksB: Record<ChunkPath, ChunkUpdate>
): Record<ChunkPath, ChunkUpdate> {
const chunks: Record<ChunkPath, ChunkUpdate> = {};
const chunks: Record<ChunkPath, ChunkUpdate> = {}
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) {
const chunkUpdateB = chunksB[chunkPath];
const chunkUpdateB = chunksB[chunkPath]
if (chunkUpdateB != null) {
const mergedUpdate = mergeChunkUpdates(chunkUpdateA, chunkUpdateB);
const mergedUpdate = mergeChunkUpdates(chunkUpdateA, chunkUpdateB)
if (mergedUpdate != null) {
chunks[chunkPath] = mergedUpdate;
chunks[chunkPath] = mergedUpdate
}
} else {
chunks[chunkPath] = chunkUpdateA;
chunks[chunkPath] = chunkUpdateA
}
}
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) {
if (chunks[chunkPath] == null) {
chunks[chunkPath] = chunkUpdateB;
chunks[chunkPath] = chunkUpdateB
}
}
return chunks;
return chunks
}
function mergeChunkUpdates(
......@@ -243,42 +241,42 @@ function mergeChunkUpdates(
updateB: ChunkUpdate
): ChunkUpdate | undefined {
if (
(updateA.type === "added" && updateB.type === "deleted") ||
(updateA.type === "deleted" && updateB.type === "added")
(updateA.type === 'added' && updateB.type === 'deleted') ||
(updateA.type === 'deleted' && updateB.type === 'added')
) {
return undefined;
return undefined
}
if (updateA.type === "partial") {
invariant(updateA.instruction, "Partial updates are unsupported");
if (updateA.type === 'partial') {
invariant(updateA.instruction, 'Partial updates are unsupported')
}
if (updateB.type === "partial") {
invariant(updateB.instruction, "Partial updates are unsupported");
if (updateB.type === 'partial') {
invariant(updateB.instruction, 'Partial updates are unsupported')
}
return undefined;
return undefined
}
function mergeChunkListEcmascriptMergedUpdates(
mergedA: EcmascriptMergedUpdate,
mergedB: EcmascriptMergedUpdate
): EcmascriptMergedUpdate {
const entries = mergeEcmascriptChunkEntries(mergedA.entries, mergedB.entries);
const chunks = mergeEcmascriptChunksUpdates(mergedA.chunks, mergedB.chunks);
const entries = mergeEcmascriptChunkEntries(mergedA.entries, mergedB.entries)
const chunks = mergeEcmascriptChunksUpdates(mergedA.chunks, mergedB.chunks)
return {
type: "EcmascriptMergedUpdate",
type: 'EcmascriptMergedUpdate',
entries,
chunks,
};
}
}
function mergeEcmascriptChunkEntries(
entriesA: Record<ModuleId, EcmascriptModuleEntry> | undefined,
entriesB: Record<ModuleId, EcmascriptModuleEntry> | undefined
): Record<ModuleId, EcmascriptModuleEntry> {
return { ...entriesA, ...entriesB };
return { ...entriesA, ...entriesB }
}
function mergeEcmascriptChunksUpdates(
......@@ -286,245 +284,244 @@ function mergeEcmascriptChunksUpdates(
chunksB: Record<ChunkPath, EcmascriptMergedChunkUpdate> | undefined
): Record<ChunkPath, EcmascriptMergedChunkUpdate> | undefined {
if (chunksA == null) {
return chunksB;
return chunksB
}
if (chunksB == null) {
return chunksA;
return chunksA
}
const chunks: Record<ChunkPath, EcmascriptMergedChunkUpdate> = {};
const chunks: Record<ChunkPath, EcmascriptMergedChunkUpdate> = {}
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) {
const chunkUpdateB = chunksB[chunkPath];
const chunkUpdateB = chunksB[chunkPath]
if (chunkUpdateB != null) {
const mergedUpdate = mergeEcmascriptChunkUpdates(
chunkUpdateA,
chunkUpdateB
);
)
if (mergedUpdate != null) {
chunks[chunkPath] = mergedUpdate;
chunks[chunkPath] = mergedUpdate
}
} else {
chunks[chunkPath] = chunkUpdateA;
chunks[chunkPath] = chunkUpdateA
}
}
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) {
if (chunks[chunkPath] == null) {
chunks[chunkPath] = chunkUpdateB;
chunks[chunkPath] = chunkUpdateB
}
}
if (Object.keys(chunks).length === 0) {
return undefined;
return undefined
}
return chunks;
return chunks
}
function mergeEcmascriptChunkUpdates(
updateA: EcmascriptMergedChunkUpdate,
updateB: EcmascriptMergedChunkUpdate
): EcmascriptMergedChunkUpdate | undefined {
if (updateA.type === "added" && updateB.type === "deleted") {
if (updateA.type === 'added' && updateB.type === 'deleted') {
// These two completely cancel each other out.
return undefined;
return undefined
}
if (updateA.type === "deleted" && updateB.type === "added") {
const added = [];
const deleted = [];
const deletedModules = new Set(updateA.modules ?? []);
const addedModules = new Set(updateB.modules ?? []);
if (updateA.type === 'deleted' && updateB.type === 'added') {
const added = []
const deleted = []
const deletedModules = new Set(updateA.modules ?? [])
const addedModules = new Set(updateB.modules ?? [])
for (const moduleId of addedModules) {
if (!deletedModules.has(moduleId)) {
added.push(moduleId);
added.push(moduleId)
}
}
for (const moduleId of deletedModules) {
if (!addedModules.has(moduleId)) {
deleted.push(moduleId);
deleted.push(moduleId)
}
}
if (added.length === 0 && deleted.length === 0) {
return undefined;
return undefined
}
return {
type: "partial",
type: 'partial',
added,
deleted,
};
}
}
if (updateA.type === "partial" && updateB.type === "partial") {
const added = new Set([...(updateA.added ?? []), ...(updateB.added ?? [])]);
if (updateA.type === 'partial' && updateB.type === 'partial') {
const added = new Set([...(updateA.added ?? []), ...(updateB.added ?? [])])
const deleted = new Set([
...(updateA.deleted ?? []),
...(updateB.deleted ?? []),
]);
])
if (updateB.added != null) {
for (const moduleId of updateB.added) {
deleted.delete(moduleId);
deleted.delete(moduleId)
}
}
if (updateB.deleted != null) {
for (const moduleId of updateB.deleted) {
added.delete(moduleId);
added.delete(moduleId)
}
}
return {
type: "partial",
type: 'partial',
added: [...added],
deleted: [...deleted],
};
}
}
if (updateA.type === "added" && updateB.type === "partial") {
if (updateA.type === 'added' && updateB.type === 'partial') {
const modules = new Set([
...(updateA.modules ?? []),
...(updateB.added ?? []),
]);
])
for (const moduleId of updateB.deleted ?? []) {
modules.delete(moduleId);
modules.delete(moduleId)
}
return {
type: "added",
type: 'added',
modules: [...modules],
};
}
}
if (updateA.type === "partial" && updateB.type === "deleted") {
if (updateA.type === 'partial' && updateB.type === 'deleted') {
// We could eagerly return `updateB` here, but this would potentially be
// incorrect if `updateA` has added modules.
const modules = new Set(updateB.modules ?? []);
const modules = new Set(updateB.modules ?? [])
if (updateA.added != null) {
for (const moduleId of updateA.added) {
modules.delete(moduleId);
modules.delete(moduleId)
}
}
return {
type: "deleted",
type: 'deleted',
modules: [...modules],
};
}
}
// Any other update combination is invalid.
return undefined;
return undefined
}
function invariant(never: never, message: string): never {
throw new Error(`Invariant: ${message}`);
throw new Error(`Invariant: ${message}`)
}
const CRITICAL = ["bug", "error", "fatal"];
const CRITICAL = ['bug', 'error', 'fatal']
function compareByList(list: any[], a: any, b: any) {
const aI = list.indexOf(a) + 1 || list.length;
const bI = list.indexOf(b) + 1 || list.length;
return aI - bI;
const aI = list.indexOf(a) + 1 || list.length
const bI = list.indexOf(b) + 1 || list.length
return aI - bI
}
const chunksWithIssues: Map<ResourceKey, Issue[]> = new Map();
const chunksWithIssues: Map<ResourceKey, Issue[]> = new Map()
function emitIssues() {
const issues = [];
const deduplicationSet = new Set();
const issues = []
const deduplicationSet = new Set()
for (const [_, chunkIssues] of chunksWithIssues) {
for (const chunkIssue of chunkIssues) {
if (deduplicationSet.has(chunkIssue.formatted)) continue;
if (deduplicationSet.has(chunkIssue.formatted)) continue
issues.push(chunkIssue);
deduplicationSet.add(chunkIssue.formatted);
issues.push(chunkIssue)
deduplicationSet.add(chunkIssue.formatted)
}
}
sortIssues(issues);
sortIssues(issues)
onTurbopackIssues(issues);
onTurbopackIssues(issues)
}
function handleIssues(msg: ServerMessage): boolean {
const key = resourceKey(msg.resource);
let hasCriticalIssues = false;
const key = resourceKey(msg.resource)
let hasCriticalIssues = false
for (const issue of msg.issues) {
if (CRITICAL.includes(issue.severity)) {
console.error(stripAnsi(issue.formatted));
hasCriticalIssues = true;
hasCriticalIssues = true
}
}
if (msg.issues.length > 0) {
chunksWithIssues.set(key, msg.issues);
chunksWithIssues.set(key, msg.issues)
} else if (chunksWithIssues.has(key)) {
chunksWithIssues.delete(key);
chunksWithIssues.delete(key)
}
emitIssues();
emitIssues()
return hasCriticalIssues;
return hasCriticalIssues
}
const SEVERITY_ORDER = ["bug", "fatal", "error", "warning", "info", "log"];
const SEVERITY_ORDER = ['bug', 'fatal', 'error', 'warning', 'info', 'log']
const CATEGORY_ORDER = [
"parse",
"resolve",
"code generation",
"rendering",
"typescript",
"other",
];
'parse',
'resolve',
'code generation',
'rendering',
'typescript',
'other',
]
function sortIssues(issues: Issue[]) {
issues.sort((a, b) => {
const first = compareByList(SEVERITY_ORDER, a.severity, b.severity);
if (first !== 0) return first;
return compareByList(CATEGORY_ORDER, a.category, b.category);
});
const first = compareByList(SEVERITY_ORDER, a.severity, b.severity)
if (first !== 0) return first
return compareByList(CATEGORY_ORDER, a.category, b.category)
})
}
function handleSocketMessage(msg: ServerMessage) {
sortIssues(msg.issues);
sortIssues(msg.issues)
const hasCriticalIssues = handleIssues(msg);
const hasCriticalIssues = handleIssues(msg)
// TODO(WEB-582) Disable update aggregation for now.
const aggregate = /* hasCriticalIssues */ false;
const aggregatedMsg = aggregateUpdates(msg, aggregate);
const aggregate = /* hasCriticalIssues */ false
const aggregatedMsg = aggregateUpdates(msg, aggregate)
if (aggregate) return;
if (aggregate) return
const runHooks = chunkListsWithPendingUpdates.size === 0;
const runHooks = chunkListsWithPendingUpdates.size === 0
if (aggregatedMsg.type !== "issues") {
if (runHooks) onBeforeRefresh();
triggerUpdate(aggregatedMsg);
if (runHooks) onRefresh();
if (aggregatedMsg.type !== 'issues') {
if (runHooks) onBeforeRefresh()
triggerUpdate(aggregatedMsg)
if (runHooks) onRefresh()
}
if (runHooks) onBuildOk();
if (runHooks) onBuildOk()
// This is used by the Next.js integration test suite to notify it when HMR
// updates have been completed.
// TODO: Only run this in test environments (gate by `process.env.__NEXT_TEST_MODE`)
if (globalThis.__NEXT_HMR_CB) {
globalThis.__NEXT_HMR_CB();
globalThis.__NEXT_HMR_CB = null;
globalThis.__NEXT_HMR_CB()
globalThis.__NEXT_HMR_CB = null
}
}
......@@ -537,63 +534,63 @@ export function subscribeToChunkUpdate(
path: chunkPath,
},
callback
);
)
}
export function subscribeToUpdate(
resource: ResourceIdentifier,
callback: UpdateCallback
) {
const key = resourceKey(resource);
let callbackSet: UpdateCallbackSet;
const existingCallbackSet = updateCallbackSets.get(key);
const key = resourceKey(resource)
let callbackSet: UpdateCallbackSet
const existingCallbackSet = updateCallbackSets.get(key)
if (!existingCallbackSet) {
callbackSet = {
callbacks: new Set([callback]),
unsubscribe: subscribeToUpdates(resource),
};
updateCallbackSets.set(key, callbackSet);
}
updateCallbackSets.set(key, callbackSet)
} else {
existingCallbackSet.callbacks.add(callback);
callbackSet = existingCallbackSet;
existingCallbackSet.callbacks.add(callback)
callbackSet = existingCallbackSet
}
return () => {
callbackSet.callbacks.delete(callback);
callbackSet.callbacks.delete(callback)
if (callbackSet.callbacks.size === 0) {
callbackSet.unsubscribe();
updateCallbackSets.delete(key);
callbackSet.unsubscribe()
updateCallbackSets.delete(key)
}
};
}
}
function triggerUpdate(msg: ServerMessage) {
const key = resourceKey(msg.resource);
const callbackSet = updateCallbackSets.get(key);
const key = resourceKey(msg.resource)
const callbackSet = updateCallbackSets.get(key)
if (!callbackSet) {
return;
return
}
try {
for (const callback of callbackSet.callbacks) {
callback(msg);
callback(msg)
}
if (msg.type === "notFound") {
if (msg.type === 'notFound') {
// This indicates that the resource which we subscribed to either does not exist or
// has been deleted. In either case, we should clear all update callbacks, so if a
// new subscription is created for the same resource, it will send a new "subscribe"
// message to the server.
// No need to send an "unsubscribe" message to the server, it will have already
// dropped the update stream before sending the "notFound" message.
updateCallbackSets.delete(key);
updateCallbackSets.delete(key)
}
} catch (err) {
console.error(
`An error occurred during the update of resource \`${msg.resource.path}\``,
err
);
location.reload();
)
location.reload()
}
}
import "@vercel/turbopack-next/internal/shims-client";
import '@vercel/turbopack-next/internal/shims-client'
import { createRoot } from "react-dom/client";
import { createRoot } from 'react-dom/client'
import {
initializeHMR,
ReactDevOverlay,
} from "@vercel/turbopack-next/dev/client";
import { subscribeToUpdate } from "@vercel/turbopack-next/dev/hmr-client";
} from '@vercel/turbopack-next/dev/client'
import { subscribeToUpdate } from '@vercel/turbopack-next/dev/hmr-client'
const pageChunkPath = location.pathname.slice(1);
const pageChunkPath = location.pathname.slice(1)
subscribeToUpdate(
{
path: pageChunkPath,
headers: {
accept: "text/html",
accept: 'text/html',
},
},
(update) => {
if (update.type === "restart" || update.type === "notFound") {
location.reload();
if (update.type === 'restart' || update.type === 'notFound') {
location.reload()
}
}
);
)
initializeHMR({
assetPrefix: "",
});
assetPrefix: '',
})
const el = document.getElementById("__next")!;
el.innerText = "";
const el = document.getElementById('__next')!
createRoot(el).render(<ReactDevOverlay />);
const innerHtml = {
__html: el.innerHTML,
}
createRoot(el).render(
<ReactDevOverlay>
<div dangerouslySetInnerHTML={innerHtml}></div>
</ReactDevOverlay>
)
import React from "react";
import React from 'react'
type ErrorBoundaryProps = {
onError: (error: Error, componentStack: string | null) => void;
fallback: React.ReactNode | null;
children?: React.ReactNode;
};
error: Error | null
onError: (error: Error, componentStack: string | null) => void
fallback: React.ReactNode | null
children?: React.ReactNode
}
type ErrorBoundaryState = { error: Error | null };
type ErrorBoundaryState = {
error: Error | null
lastPropsError: Error | null
}
class ErrorBoundary extends React.PureComponent<
ErrorBoundaryProps,
ErrorBoundaryState
> {
static getDerivedStateFromError(error: Error) {
return { error };
return { error }
}
state = { error: null };
state = {
error: null,
lastPropsError: null,
}
componentDidCatch(
error: Error,
......@@ -24,21 +31,48 @@ class ErrorBoundary extends React.PureComponent<
// accidentally excluded in some versions.
errorInfo?: { componentStack?: string | null }
) {
this.props.onError(error, errorInfo?.componentStack ?? null);
this.props.onError(error, errorInfo?.componentStack ?? null)
}
// I don't like this, but it works to clear the error boundary
//
// props.error is only set 1 render after state.error, so we can't treat it as the source of truth all the time.
// to get around this we store the error from props in state and only accept updates if the stored error from props
// matches the error in state.
//
// this is definitely not a controlled component and it only works if the error matches exactly
static getDerivedStateFromProps(
props: ErrorBoundaryProps,
state: ErrorBoundaryState
): ErrorBoundaryState | null {
if (state.lastPropsError === props.error) {
return null
}
let error = state.error
if (state.error === state.lastPropsError) {
error = props.error
}
return {
error,
lastPropsError: props.error,
}
}
render() {
const { error } = this.state;
const { error } = this.state
const { fallback } = this.props;
const { fallback } = this.props
// The component has to be unmounted or else it would continue to error
if (error != null) {
return fallback;
return fallback
}
return this.props.children;
return this.props.children
}
}
export { ErrorBoundary };
export { ErrorBoundary }
import * as React from "react";
import * as React from 'react'
import type { Issue } from "@vercel/turbopack-dev-runtime/types/protocol";
import type { Issue } from '@vercel/turbopack-dev-runtime/types/protocol'
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";
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 RefreshState =
| {
// No refresh in progress.
type: "idle";
type: 'idle'
}
| {
// The refresh process has been triggered, but the new code has not been
// executed yet.
type: "pending";
errors: SupportedErrorEvent[];
};
type: 'pending'
errors: SupportedErrorEvent[]
reactError: Error | null
}
type OverlayState = {
nextId: number;
nextId: number
// issues are from turbopack
issues: Issue[];
issues: Issue[]
// errors are client side
errors: SupportedErrorEvent[];
errors: SupportedErrorEvent[]
refreshState: RefreshState;
refreshState: RefreshState
reactError: Error | null;
};
reactError: Error | null
}
function pushErrorFilterDuplicates(
errors: SupportedErrorEvent[],
......@@ -43,29 +44,25 @@ function pushErrorFilterDuplicates(
return [
...errors.filter((e) => {
// Filter out duplicate errors
return e.event.reason !== err.event.reason;
return e.event.reason !== err.event.reason
}),
err,
];
]
}
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) {
case Bus.TYPE_BUILD_OK: {
if (state.reactError != null) {
console.warn(
"[Fast Refresh] performing full reload because your application had an unrecoverable error"
);
window.location.reload();
}
return { ...state };
return { ...state }
}
case Bus.TYPE_TURBOPACK_ISSUES: {
return { ...state, issues: ev.issues };
return { ...state, issues: ev.issues }
}
case Bus.TYPE_BEFORE_REFRESH: {
return { ...state, refreshState: { type: "pending", errors: [] } };
return {
...state,
refreshState: { type: 'pending', errors: [], reactError: null },
}
}
case Bus.TYPE_REFRESH: {
return {
......@@ -77,16 +74,20 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
// around until the next refresh. Otherwise we run into a race
// condition where those errors would be cleared on refresh completion
// before they can be displayed.
state.refreshState.type === "pending"
state.refreshState.type === 'pending'
? state.refreshState.errors
: [],
refreshState: { type: "idle" },
};
reactError:
state.refreshState.type === 'pending'
? state.refreshState.reactError
: null,
refreshState: { type: 'idle' },
}
}
case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: {
switch (state.refreshState.type) {
case "idle": {
case 'idle': {
return {
...state,
nextId: state.nextId + 1,
......@@ -94,9 +95,9 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
id: state.nextId,
event: ev,
}),
};
}
}
case "pending": {
case 'pending': {
return {
...state,
nextId: state.nextId + 1,
......@@ -107,38 +108,56 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
event: ev,
}),
},
};
}
}
default:
return state;
return state
}
}
case Bus.TYPE_REACT_ERROR: {
return { ...state, reactError: ev.error };
switch (state.refreshState.type) {
case 'idle': {
return {
...state,
reactError: ev.error,
}
}
case 'pending': {
return {
...state,
refreshState: {
...state.refreshState,
reactError: ev.error,
},
}
}
default:
return state
}
}
default: {
return state;
return state
}
}
}
type ErrorType = "runtime" | "build";
type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false;
return false
}
return preventType.includes(errorType);
};
return preventType.includes(errorType)
}
type ReactDevOverlayProps = {
globalOverlay?: boolean;
preventDisplay?: ErrorType[];
children?: React.ReactNode;
};
globalOverlay?: boolean
preventDisplay?: ErrorType[]
children?: React.ReactNode
}
export default function ReactDevOverlay({
children,
......@@ -152,17 +171,17 @@ export default function ReactDevOverlay({
issues: [],
errors: [],
refreshState: {
type: "idle",
type: 'idle',
},
reactError: null,
});
})
React.useEffect(() => {
Bus.on(dispatch);
Bus.on(dispatch)
return function () {
Bus.off(dispatch);
};
}, [dispatch]);
Bus.off(dispatch)
}
}, [dispatch])
const onComponentError = React.useCallback(
(error: Error, componentStack: string | null) => {
......@@ -170,25 +189,26 @@ export default function ReactDevOverlay({
type: Bus.TYPE_REACT_ERROR,
error,
componentStack,
});
})
},
[]
);
)
const hasBuildError = state.issues.length > 0;
const hasRuntimeErrors = state.errors.length > 0;
const hasBuildError = state.issues.length > 0
const hasRuntimeErrors = state.errors.length > 0
const errorType = hasBuildError
? "build"
? 'build'
: hasRuntimeErrors
? "runtime"
: null;
? 'runtime'
: null
const isMounted = hasBuildError || hasRuntimeErrors;
const isMounted = hasBuildError || hasRuntimeErrors
return (
<React.Fragment>
<ErrorBoundary
error={state.reactError}
onError={onComponentError}
fallback={
// When the overlay is global for the application and it wraps a component rendering `<html>`
......@@ -214,5 +234,5 @@ export default function ReactDevOverlay({
</ShadowPortal>
) : null}
</React.Fragment>
);
)
}
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