Unverified Commit c37a39bf authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

chore(HMR clients): Clean up and share code between app and pages router (#76960)

# Do not review this PR in Graphite, review it one commit at a time: https://github.com/vercel/next.js/pull/76960/commits

This is a series of very small changes to the hot reloader clients in both app and pages router to share more code and unify some of the logic or behavior between the two.

This code is very fragile, so lots of small commits have been useful in bisecting test failures.

These changes are too small to be practical as separate stacked graphite PRs.
parent 8bc202ba
...@@ -21,6 +21,8 @@ import { ...@@ -21,6 +21,8 @@ import {
ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION, ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO, ACTION_VERSION_INFO,
REACT_REFRESH_FULL_RELOAD,
reportInvalidHmrMessage,
useErrorOverlayReducer, useErrorOverlayReducer,
} from '../shared' } from '../shared'
import { parseStack } from '../utils/parse-stack' import { parseStack } from '../utils/parse-stack'
...@@ -50,6 +52,7 @@ import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown- ...@@ -50,6 +52,7 @@ import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-
import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events' import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events'
import type { GlobalErrorComponent } from '../../error-boundary' import type { GlobalErrorComponent } from '../../error-boundary'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state' import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import reportHmrLatency from '../utils/report-hmr-latency'
export interface Dispatcher { export interface Dispatcher {
onBuildOk(): void onBuildOk(): void
...@@ -83,15 +86,6 @@ export function waitForWebpackRuntimeHotUpdate() { ...@@ -83,15 +86,6 @@ export function waitForWebpackRuntimeHotUpdate() {
return pendingHotUpdateWebpack return pendingHotUpdateWebpack
} }
function handleBeforeHotUpdateWebpack(
dispatcher: Dispatcher,
hasUpdates: boolean
) {
if (hasUpdates) {
dispatcher.onBeforeRefresh()
}
}
function handleSuccessfulHotUpdateWebpack( function handleSuccessfulHotUpdateWebpack(
dispatcher: Dispatcher, dispatcher: Dispatcher,
sendMessage: (message: string) => void, sendMessage: (message: string) => void,
...@@ -99,36 +93,11 @@ function handleSuccessfulHotUpdateWebpack( ...@@ -99,36 +93,11 @@ function handleSuccessfulHotUpdateWebpack(
) { ) {
resolvePendingHotUpdateWebpack() resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk() dispatcher.onBuildOk()
reportHmrLatency(sendMessage, updatedModules) reportHmrLatency(sendMessage, updatedModules, startLatency!, Date.now())
dispatcher.onRefresh() dispatcher.onRefresh()
} }
function reportHmrLatency(
sendMessage: (message: string) => void,
updatedModules: ReadonlyArray<string>
) {
if (!startLatency) return
// turbopack has a debounce for the "built" event which we don't want to
// incorrectly show in this number, use the last TURBOPACK_MESSAGE time
let endLatency = turbopackLastUpdateLatency ?? Date.now()
const latency = endLatency - startLatency
console.log(`[Fast Refresh] done in ${latency}ms`)
sendMessage(
JSON.stringify({
event: 'client-hmr-latency',
id: window.__nextDevClientId,
startTime: startLatency,
endTime: endLatency,
page: window.location.pathname,
updatedModules,
// Whether the page (tab) was hidden at the time the event occurred.
// This can impact the accuracy of the event's timing.
isPageHidden: document.visibilityState === 'hidden',
})
)
}
// There is a newer version of the code available. // There is a newer version of the code available.
function handleAvailableHash(hash: string) { function handleAvailableHash(hash: string) {
// Update last known compilation hash. // Update last known compilation hash.
...@@ -203,21 +172,14 @@ function tryApplyUpdates( ...@@ -203,21 +172,14 @@ function tryApplyUpdates(
if (!isUpdateAvailable() || !canApplyUpdates()) { if (!isUpdateAvailable() || !canApplyUpdates()) {
resolvePendingHotUpdateWebpack() resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk() dispatcher.onBuildOk()
reportHmrLatency(sendMessage, []) reportHmrLatency(sendMessage, [], startLatency!, Date.now())
return return
} }
function handleApplyUpdates(err: any, updatedModules: string[] | null) { function handleApplyUpdates(err: any, updatedModules: string[] | null) {
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) { if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) {
if (err) { if (err) {
console.warn( console.warn(REACT_REFRESH_FULL_RELOAD)
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
)
} else if (RuntimeErrorHandler.hadRuntimeError) { } else if (RuntimeErrorHandler.hadRuntimeError) {
console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR) console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR)
} }
...@@ -321,11 +283,18 @@ function processMessage( ...@@ -321,11 +283,18 @@ function processMessage(
function handleHotUpdate() { function handleHotUpdate() {
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
dispatcher.onBuildOk() dispatcher.onBuildOk()
reportHmrLatency(sendMessage, [...turbopackUpdatedModules]) reportHmrLatency(
sendMessage,
[...turbopackUpdatedModules],
startLatency!,
turbopackLastUpdateLatency ?? Date.now()
)
} else { } else {
tryApplyUpdates( tryApplyUpdates(
function onBeforeHotUpdate(hasUpdates: boolean) { function onBeforeHotUpdate(hasUpdates: boolean) {
handleBeforeHotUpdateWebpack(dispatcher, hasUpdates) if (hasUpdates) {
dispatcher.onBeforeRefresh()
}
}, },
function onSuccessfulHotUpdate(webpackUpdatedModules: string[]) { function onSuccessfulHotUpdate(webpackUpdatedModules: string[]) {
// Only dismiss it when we're sure it's a hot update. // Only dismiss it when we're sure it's a hot update.
...@@ -437,7 +406,6 @@ function processMessage( ...@@ -437,7 +406,6 @@ function processMessage(
) )
if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.BUILT) { if (obj.action === HMR_ACTIONS_SENT_TO_BROWSER.BUILT) {
// Handle hot updates
handleHotUpdate() handleHotUpdate()
} }
return return
...@@ -691,13 +659,8 @@ export default function HotReload({ ...@@ -691,13 +659,8 @@ export default function HotReload({
appIsrManifestRef, appIsrManifestRef,
pathnameRef pathnameRef
) )
} catch (err: any) { } catch (err: unknown) {
console.warn( reportInvalidHmrMessage(event, err)
'[HMR] Invalid message: ' +
JSON.stringify(event.data) +
'\n' +
(err?.stack ?? '')
)
} }
} }
......
...@@ -47,8 +47,13 @@ import type { ...@@ -47,8 +47,13 @@ import type {
TurbopackMsgToBrowser, TurbopackMsgToBrowser,
} from '../../../../server/dev/hot-reloader-types' } from '../../../../server/dev/hot-reloader-types'
import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message' import { extractModulesFromTurbopackMessage } from '../../../../server/dev/extract-modules-from-turbopack-message'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared' import {
REACT_REFRESH_FULL_RELOAD,
REACT_REFRESH_FULL_RELOAD_FROM_ERROR,
reportInvalidHmrMessage,
} from '../shared'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler' import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import reportHmrLatency from '../utils/report-hmr-latency'
// This alternative WebpackDevServer combines the functionality of: // This alternative WebpackDevServer combines the functionality of:
// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js
// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js
...@@ -62,7 +67,6 @@ declare global { ...@@ -62,7 +67,6 @@ declare global {
const __webpack_hash__: string const __webpack_hash__: string
interface Window { interface Window {
__nextDevClientId: number __nextDevClientId: number
__NEXT_HMR_LATENCY_CB: any
} }
} }
...@@ -70,9 +74,7 @@ window.__nextDevClientId = Math.round(Math.random() * 100 + Date.now()) ...@@ -70,9 +74,7 @@ window.__nextDevClientId = Math.round(Math.random() * 100 + Date.now())
let customHmrEventHandler: any let customHmrEventHandler: any
let turbopackMessageListeners: ((msg: TurbopackMsgToBrowser) => void)[] = [] let turbopackMessageListeners: ((msg: TurbopackMsgToBrowser) => void)[] = []
let MODE: 'webpack' | 'turbopack' = 'webpack' export default function connect() {
export default function connect(mode: 'webpack' | 'turbopack') {
MODE = mode
register() register()
addMessageListener((payload) => { addMessageListener((payload) => {
...@@ -82,13 +84,8 @@ export default function connect(mode: 'webpack' | 'turbopack') { ...@@ -82,13 +84,8 @@ export default function connect(mode: 'webpack' | 'turbopack') {
try { try {
processMessage(payload) processMessage(payload)
} catch (err: any) { } catch (err: unknown) {
console.warn( reportInvalidHmrMessage(payload, err)
'[HMR] Invalid message: ' +
JSON.stringify(payload) +
'\n' +
(err?.stack ?? '')
)
} }
}) })
...@@ -129,7 +126,15 @@ function clearOutdatedErrors() { ...@@ -129,7 +126,15 @@ function clearOutdatedErrors() {
function handleSuccess() { function handleSuccess() {
clearOutdatedErrors() clearOutdatedErrors()
if (MODE === 'webpack') { if (process.env.TURBOPACK) {
reportHmrLatency(
sendMessage,
[...turbopackUpdatedModules],
startLatency!,
turbopackLastUpdateLatency ?? Date.now()
)
onBuildOk()
} else {
const isHotUpdate = const isHotUpdate =
!isFirstCompilation || !isFirstCompilation ||
(window.__NEXT_DATA__.page !== '/_error' && isUpdateAvailable()) (window.__NEXT_DATA__.page !== '/_error' && isUpdateAvailable())
...@@ -140,9 +145,6 @@ function handleSuccess() { ...@@ -140,9 +145,6 @@ function handleSuccess() {
if (isHotUpdate) { if (isHotUpdate) {
tryApplyUpdates(onBeforeFastRefresh, onFastRefresh) tryApplyUpdates(onBeforeFastRefresh, onFastRefresh)
} }
} else {
reportHmrLatency([...turbopackUpdatedModules])
onBuildOk()
} }
} }
...@@ -238,32 +240,12 @@ function onFastRefresh(updatedModules: ReadonlyArray<string> = []) { ...@@ -238,32 +240,12 @@ function onFastRefresh(updatedModules: ReadonlyArray<string> = []) {
onRefresh() onRefresh()
reportHmrLatency() reportHmrLatency(
} sendMessage,
updatedModules,
function reportHmrLatency(updatedModules: ReadonlyArray<string> = []) { startLatency!,
if (!startLatency) return turbopackLastUpdateLatency ?? Date.now()
// turbopack has a debounce for the BUILT event which we don't want to
// incorrectly show in this number, use the last TURBOPACK_MESSAGE time
let endLatency = turbopackLastUpdateLatency ?? Date.now()
const latency = endLatency - startLatency
console.log(`[Fast Refresh] done in ${latency}ms`)
sendMessage(
JSON.stringify({
event: 'client-hmr-latency',
id: window.__nextDevClientId,
startTime: startLatency,
endTime: endLatency,
page: window.location.pathname,
updatedModules,
// Whether the page (tab) was hidden at the time the event occurred.
// This can impact the accuracy of the event's timing.
isPageHidden: document.visibilityState === 'hidden',
})
) )
if (self.__NEXT_HMR_LATENCY_CB) {
self.__NEXT_HMR_LATENCY_CB(latency)
}
} }
// There is a newer version of the code available. // There is a newer version of the code available.
...@@ -278,7 +260,7 @@ export function handleStaticIndicator() { ...@@ -278,7 +260,7 @@ export function handleStaticIndicator() {
const pageComponent = routeInfo?.Component const pageComponent = routeInfo?.Component
const appComponent = window.next.router.components['/_app']?.Component const appComponent = window.next.router.components['/_app']?.Component
const isDynamicPage = const isDynamicPage =
Boolean(pageComponent?.getInitialProps) || Boolean(routeInfo.__N_SSP) Boolean(pageComponent?.getInitialProps) || Boolean(routeInfo?.__N_SSP)
const hasAppGetInitialProps = const hasAppGetInitialProps =
Boolean(appComponent?.getInitialProps) && Boolean(appComponent?.getInitialProps) &&
appComponent?.getInitialProps !== appComponent?.origGetInitialProps appComponent?.getInitialProps !== appComponent?.origGetInitialProps
...@@ -297,7 +279,6 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -297,7 +279,6 @@ function processMessage(obj: HMR_ACTION_TYPES) {
return return
} }
// Use turbopack message for analytics, (still need built for webpack)
switch (obj.action) { switch (obj.action) {
case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST: { case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST: {
isrManifest = obj.data isrManifest = obj.data
...@@ -458,18 +439,9 @@ function tryApplyUpdates( ...@@ -458,18 +439,9 @@ function tryApplyUpdates(
function handleApplyUpdates(err: any, updatedModules: string[] | null) { function handleApplyUpdates(err: any, updatedModules: string[] | null) {
if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) { if (err || RuntimeErrorHandler.hadRuntimeError || !updatedModules) {
if (err) { if (err) {
console.warn( console.warn(REACT_REFRESH_FULL_RELOAD)
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
)
} else if (RuntimeErrorHandler.hadRuntimeError) { } else if (RuntimeErrorHandler.hadRuntimeError) {
console.warn( console.warn(REACT_REFRESH_FULL_RELOAD_FROM_ERROR)
'[Fast Refresh] performing full reload because your application had an unrecoverable error'
)
} }
performFullReload(err) performFullReload(err)
return return
......
...@@ -6,6 +6,7 @@ import type { SupportedErrorEvent } from './ui/container/runtime-error/render-er ...@@ -6,6 +6,7 @@ import type { SupportedErrorEvent } from './ui/container/runtime-error/render-er
import type { ComponentStackFrame } from './utils/parse-component-stack' import type { ComponentStackFrame } from './utils/parse-component-stack'
import type { DebugInfo } from './types' import type { DebugInfo } from './types'
import type { DevIndicatorServerState } from '../../../server/dev/dev-indicator-server-state' import type { DevIndicatorServerState } from '../../../server/dev/dev-indicator-server-state'
import type { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types'
type FastRefreshState = type FastRefreshState =
/** No refresh in progress. */ /** No refresh in progress. */
...@@ -224,5 +225,25 @@ export function useErrorOverlayReducer(routerType: 'pages' | 'app') { ...@@ -224,5 +225,25 @@ export function useErrorOverlayReducer(routerType: 'pages' | 'app') {
}, getInitialState(routerType)) }, getInitialState(routerType))
} }
export const REACT_REFRESH_FULL_RELOAD =
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
export const REACT_REFRESH_FULL_RELOAD_FROM_ERROR = export const REACT_REFRESH_FULL_RELOAD_FROM_ERROR =
'[Fast Refresh] performing full reload because your application had an unrecoverable error' '[Fast Refresh] performing full reload because your application had an unrecoverable error'
export function reportInvalidHmrMessage(
message: HMR_ACTION_TYPES | MessageEvent<unknown>,
err: unknown
) {
console.warn(
'[HMR] Invalid message: ' +
JSON.stringify(message) +
'\n' +
((err instanceof Error && err?.stack) || '')
)
}
declare global {
interface Window {
__NEXT_HMR_LATENCY_CB: ((latencyMs: number) => void) | undefined
}
}
export default function reportHmrLatency(
sendMessage: (message: string) => void,
updatedModules: ReadonlyArray<string>,
startMsSinceEpoch: number,
endMsSinceEpoch: number
) {
const latencyMs = endMsSinceEpoch - startMsSinceEpoch
console.log(`[Fast Refresh] done in ${latencyMs}ms`)
sendMessage(
JSON.stringify({
event: 'client-hmr-latency',
id: window.__nextDevClientId,
startTime: startMsSinceEpoch,
endTime: endMsSinceEpoch,
page: window.location.pathname,
updatedModules,
// Whether the page (tab) was hidden at the time the event occurred.
// This can impact the accuracy of the event's timing.
isPageHidden: document.visibilityState === 'hidden',
})
)
if (self.__NEXT_HMR_LATENCY_CB) {
self.__NEXT_HMR_LATENCY_CB(latencyMs)
}
}
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
connectHMR, connectHMR,
} from '../components/react-dev-overlay/pages/websocket' } from '../components/react-dev-overlay/pages/websocket'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types' import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types'
import { reportInvalidHmrMessage } from '../components/react-dev-overlay/shared'
declare global { declare global {
const __webpack_runtime_id__: string const __webpack_runtime_id__: string
...@@ -106,13 +107,8 @@ addMessageListener((message) => { ...@@ -106,13 +107,8 @@ addMessageListener((message) => {
} else if (message.action === HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE) { } else if (message.action === HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE) {
window.location.reload() window.location.reload()
} }
} catch (err: any) { } catch (err: unknown) {
console.warn( reportInvalidHmrMessage(message, err)
'[HMR] Invalid message: ' +
JSON.stringify(message) +
'\n' +
(err?.stack ?? '')
)
} }
}) })
......
...@@ -20,8 +20,8 @@ declare const window: NextWindow ...@@ -20,8 +20,8 @@ declare const window: NextWindow
let reloading = false let reloading = false
export default (mode: 'webpack' | 'turbopack') => { export default () => {
const devClient = connect(mode) const devClient = connect()
devClient.subscribeToHmrEvent((obj: any) => { devClient.subscribeToHmrEvent((obj: any) => {
if (reloading) return if (reloading) return
......
...@@ -21,7 +21,7 @@ window.next = { ...@@ -21,7 +21,7 @@ window.next = {
// for the page loader // for the page loader
declare let __turbopack_load__: any declare let __turbopack_load__: any
const devClient = initHMR('turbopack') const devClient = initHMR()
initialize({ initialize({
devClient, devClient,
}) })
......
...@@ -13,7 +13,7 @@ window.next = { ...@@ -13,7 +13,7 @@ window.next = {
emitter, emitter,
} }
const devClient = initHMR('webpack') const devClient = initHMR()
initialize({ devClient }) initialize({ devClient })
.then(({ assetPrefix }) => { .then(({ assetPrefix }) => {
return pageBootstrap(assetPrefix) return pageBootstrap(assetPrefix)
......
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