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

refactor: separate forward browser logs utils (#84151)

parent 33e4a5bc
...@@ -12,10 +12,7 @@ import { ...@@ -12,10 +12,7 @@ import {
processMessage, processMessage,
type StaticIndicatorState, type StaticIndicatorState,
} from './hot-reloader-app' } from './hot-reloader-app'
import { import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs'
isTerminalLoggingEnabled,
logQueue,
} from '../../../../next-devtools/userspace/app/forward-logs'
import { InvariantError } from '../../../../shared/lib/invariant-error' import { InvariantError } from '../../../../shared/lib/invariant-error'
import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants' import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants'
...@@ -57,9 +54,7 @@ export function createWebSocket( ...@@ -57,9 +54,7 @@ export function createWebSocket(
newWebSocket.binaryType = 'arraybuffer' newWebSocket.binaryType = 'arraybuffer'
function handleOnline() { function handleOnline() {
if (isTerminalLoggingEnabled) { logQueue.onSocketReady(newWebSocket)
logQueue.onSocketReady(newWebSocket)
}
reconnections = 0 reconnections = 0
window.console.log('[HMR] connected') window.console.log('[HMR] connected')
......
import { import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs'
isTerminalLoggingEnabled,
logQueue,
} from '../../../../next-devtools/userspace/app/forward-logs'
import { import {
HMR_MESSAGE_SENT_TO_BROWSER, HMR_MESSAGE_SENT_TO_BROWSER,
type HmrMessageSentToBrowser, type HmrMessageSentToBrowser,
...@@ -35,9 +32,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) { ...@@ -35,9 +32,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
if (source) source.close() if (source) source.close()
function handleOnline() { function handleOnline() {
if (isTerminalLoggingEnabled) { logQueue.onSocketReady(source)
logQueue.onSocketReady(source)
}
reconnections = 0 reconnections = 0
window.console.log('[HMR] connected') window.console.log('[HMR] connected')
} }
......
import { patchConsoleError } from './errors/intercept-console-error' import { patchConsoleError } from './errors/intercept-console-error'
import { handleGlobalErrors } from './errors/use-error-handler' import { handleGlobalErrors } from './errors/use-error-handler'
import { import { initializeDebugLogForwarding } from './forward-logs'
initializeDebugLogForwarding,
isTerminalLoggingEnabled,
} from './forward-logs'
handleGlobalErrors() handleGlobalErrors()
patchConsoleError() patchConsoleError()
if (isTerminalLoggingEnabled) { initializeDebugLogForwarding('app')
initializeDebugLogForwarding('app')
}
...@@ -2,7 +2,7 @@ import isError from '../../../../lib/is-error' ...@@ -2,7 +2,7 @@ import isError from '../../../../lib/is-error'
import { isNextRouterError } from '../../../../client/components/is-next-router-error' import { isNextRouterError } from '../../../../client/components/is-next-router-error'
import { handleConsoleError } from './use-error-handler' import { handleConsoleError } from './use-error-handler'
import { parseConsoleArgs } from '../../../../client/lib/console' import { parseConsoleArgs } from '../../../../client/lib/console'
import { forwardErrorLog, isTerminalLoggingEnabled } from '../forward-logs' import { forwardErrorLog } from '../forward-logs'
export const originConsoleError = globalThis.console.error export const originConsoleError = globalThis.console.error
...@@ -37,9 +37,7 @@ export function patchConsoleError() { ...@@ -37,9 +37,7 @@ export function patchConsoleError() {
args args
) )
} }
if (isTerminalLoggingEnabled) { forwardErrorLog(args)
forwardErrorLog(args)
}
originConsoleError.apply(window.console, args) originConsoleError.apply(window.console, args)
} }
......
...@@ -7,11 +7,7 @@ import { ...@@ -7,11 +7,7 @@ import {
import isError from '../../../../lib/is-error' import isError from '../../../../lib/is-error'
import { createConsoleError } from '../../../shared/console-error' import { createConsoleError } from '../../../shared/console-error'
import { coerceError, setOwnerStackIfAvailable } from './stitched-error' import { coerceError, setOwnerStackIfAvailable } from './stitched-error'
import { import { forwardUnhandledError, logUnhandledRejection } from '../forward-logs'
forwardUnhandledError,
isTerminalLoggingEnabled,
logUnhandledRejection,
} from '../forward-logs'
const queueMicroTask = const queueMicroTask =
globalThis.queueMicrotask || ((cb: () => void) => Promise.resolve().then(cb)) globalThis.queueMicrotask || ((cb: () => void) => Promise.resolve().then(cb))
...@@ -100,9 +96,7 @@ function onUnhandledError(event: WindowEventMap['error']): void | boolean { ...@@ -100,9 +96,7 @@ function onUnhandledError(event: WindowEventMap['error']): void | boolean {
const error = coerceError(thrownValue) const error = coerceError(thrownValue)
setOwnerStackIfAvailable(error) setOwnerStackIfAvailable(error)
handleClientError(error) handleClientError(error)
if (isTerminalLoggingEnabled) { forwardUnhandledError(error)
forwardUnhandledError(error)
}
} }
} }
...@@ -121,9 +115,7 @@ function onUnhandledRejection(ev: WindowEventMap['unhandledrejection']): void { ...@@ -121,9 +115,7 @@ function onUnhandledRejection(ev: WindowEventMap['unhandledrejection']): void {
handler(error) handler(error)
} }
if (isTerminalLoggingEnabled) { logUnhandledRejection(reason)
logUnhandledRejection(reason)
}
} }
export function handleGlobalErrors() { export function handleGlobalErrors() {
......
import { configure } from 'next/dist/compiled/safe-stable-stringify'
import { getTerminalLoggingConfig } from './terminal-logging-config'
import { UNDEFINED_MARKER } from '../../shared/forward-logs-shared'
const terminalLoggingConfig = getTerminalLoggingConfig()
const PROMISE_MARKER = 'Promise {}'
const UNAVAILABLE_MARKER = '[Unable to view]'
const maximumDepth =
typeof terminalLoggingConfig === 'object' && terminalLoggingConfig.depthLimit
? terminalLoggingConfig.depthLimit
: 5
const maximumBreadth =
typeof terminalLoggingConfig === 'object' && terminalLoggingConfig.edgeLimit
? terminalLoggingConfig.edgeLimit
: 100
const stringify = configure({
maximumDepth,
maximumBreadth,
})
/**
* allows us to:
* - revive the undefined log in the server as it would look in the browser
* - not read/attempt to serialize promises (next will console error if you do that, and will cause this program to infinitely recurse)
* - if we read a proxy that throws (no way to detect if something is a proxy), explain to the user we can't read this data
*/
export function preLogSerializationClone<T>(
value: T,
seen = new WeakMap()
): any {
if (value === undefined) return UNDEFINED_MARKER
if (value === null || typeof value !== 'object') return value
if (seen.has(value as object)) return seen.get(value as object)
try {
Object.keys(value as object)
} catch {
return UNAVAILABLE_MARKER
}
try {
if (typeof (value as any).then === 'function') return PROMISE_MARKER
} catch {
return UNAVAILABLE_MARKER
}
if (Array.isArray(value)) {
const out: any[] = []
seen.set(value, out)
for (const item of value) {
try {
out.push(preLogSerializationClone(item, seen))
} catch {
out.push(UNAVAILABLE_MARKER)
}
}
return out
}
const proto = Object.getPrototypeOf(value)
if (proto === Object.prototype || proto === null) {
const out: Record<string, unknown> = {}
seen.set(value as object, out)
for (const key of Object.keys(value as object)) {
try {
out[key] = preLogSerializationClone((value as any)[key], seen)
} catch {
out[key] = UNAVAILABLE_MARKER
}
}
return out
}
return Object.prototype.toString.call(value)
}
// only safe if passed safeClone data
export const logStringify = (data: unknown): string => {
try {
const result = stringify(data)
return result ?? `"${UNAVAILABLE_MARKER}"`
} catch {
return `"${UNAVAILABLE_MARKER}"`
}
}
import { UNDEFINED_MARKER } from '../../shared/forward-logs-shared' import { preLogSerializationClone, logStringify } from './forward-logs-utils'
import {
preLogSerializationClone,
PROMISE_MARKER,
UNAVAILABLE_MARKER,
logStringify,
} from './forward-logs'
const safeStringify = (data: unknown) => const safeStringify = (data: unknown) =>
logStringify(preLogSerializationClone(data)) logStringify(preLogSerializationClone(data))
...@@ -16,7 +10,9 @@ describe('forward-logs serialization', () => { ...@@ -16,7 +10,9 @@ describe('forward-logs serialization', () => {
expect(preLogSerializationClone('hello')).toBe('hello') expect(preLogSerializationClone('hello')).toBe('hello')
expect(preLogSerializationClone(true)).toBe(true) expect(preLogSerializationClone(true)).toBe(true)
expect(preLogSerializationClone(null)).toBe(null) expect(preLogSerializationClone(null)).toBe(null)
expect(preLogSerializationClone(undefined)).toBe(UNDEFINED_MARKER) expect(preLogSerializationClone(undefined)).toBe(
'__next_tagged_undefined'
)
}) })
it('should handle circular references', () => { it('should handle circular references', () => {
...@@ -29,19 +25,19 @@ describe('forward-logs serialization', () => { ...@@ -29,19 +25,19 @@ describe('forward-logs serialization', () => {
it('should handle promises', () => { it('should handle promises', () => {
const promise = Promise.resolve(42) const promise = Promise.resolve(42)
expect(preLogSerializationClone(promise)).toBe(PROMISE_MARKER) expect(preLogSerializationClone(promise)).toBe('Promise {}')
}) })
it('should handle arrays', () => { it('should handle arrays', () => {
const arr = [1, 'test', undefined, null] const arr = [1, 'test', undefined, null]
const cloned = preLogSerializationClone(arr) const cloned = preLogSerializationClone(arr)
expect(cloned).toEqual([1, 'test', UNDEFINED_MARKER, null]) expect(cloned).toEqual([1, 'test', '__next_tagged_undefined', null])
}) })
it('should handle plain objects', () => { it('should handle plain objects', () => {
const obj = { a: 1, b: undefined, c: 'test' } const obj = { a: 1, b: undefined, c: 'test' }
const cloned = preLogSerializationClone(obj) const cloned = preLogSerializationClone(obj)
expect(cloned).toEqual({ a: 1, b: UNDEFINED_MARKER, c: 'test' }) expect(cloned).toEqual({ a: 1, b: '__next_tagged_undefined', c: 'test' })
}) })
it('should handle objects with getters that throw', () => { it('should handle objects with getters that throw', () => {
...@@ -54,7 +50,7 @@ describe('forward-logs serialization', () => { ...@@ -54,7 +50,7 @@ describe('forward-logs serialization', () => {
const cloned = preLogSerializationClone(obj) const cloned = preLogSerializationClone(obj)
expect(cloned.normalProp).toBe('works') expect(cloned.normalProp).toBe('works')
expect(cloned.throwingGetter).toBe(UNAVAILABLE_MARKER) expect(cloned.throwingGetter).toBe('[Unable to view]')
}) })
it('should handle non-plain objects as toString', () => { it('should handle non-plain objects as toString', () => {
...@@ -80,7 +76,7 @@ describe('forward-logs serialization', () => { ...@@ -80,7 +76,7 @@ describe('forward-logs serialization', () => {
const arr = [1, throwingProxy, 'normal'] const arr = [1, throwingProxy, 'normal']
const cloned = preLogSerializationClone(arr) const cloned = preLogSerializationClone(arr)
expect(cloned).toEqual([1, UNAVAILABLE_MARKER, 'normal']) expect(cloned).toEqual([1, '[Unable to view]', 'normal'])
}) })
}) })
...@@ -89,7 +85,7 @@ describe('forward-logs serialization', () => { ...@@ -89,7 +85,7 @@ describe('forward-logs serialization', () => {
expect(safeStringify(42)).toBe('42') expect(safeStringify(42)).toBe('42')
expect(safeStringify('hello')).toBe('"hello"') expect(safeStringify('hello')).toBe('"hello"')
expect(safeStringify(null)).toBe('null') expect(safeStringify(null)).toBe('null')
expect(safeStringify(undefined)).toBe(`"${UNDEFINED_MARKER}"`) expect(safeStringify(undefined)).toBe(`"__next_tagged_undefined"`)
}) })
it('should handle objects with circular references', () => { it('should handle objects with circular references', () => {
...@@ -108,7 +104,7 @@ describe('forward-logs serialization', () => { ...@@ -108,7 +104,7 @@ describe('forward-logs serialization', () => {
} }
const result = safeStringify(problematicData) const result = safeStringify(problematicData)
expect(result).toBe(`"${UNAVAILABLE_MARKER}"`) expect(result).toBe(`"[Unable to view]"`)
}) })
}) })
}) })
import { configure } from 'next/dist/compiled/safe-stable-stringify'
import { import {
getOwnerStack, getOwnerStack,
setOwnerStackIfAvailable, setOwnerStackIfAvailable,
} from './errors/stitched-error' } from './errors/stitched-error'
import { getErrorSource } from '../../../shared/lib/error-source' import { getErrorSource } from '../../../shared/lib/error-source'
import { import { getIsTerminalLoggingEnabled } from './terminal-logging-config'
getTerminalLoggingConfig,
getIsTerminalLoggingEnabled,
} from './terminal-logging-config'
import { import {
type ConsoleEntry, type ConsoleEntry,
type ConsoleErrorEntry, type ConsoleErrorEntry,
...@@ -15,28 +11,10 @@ import { ...@@ -15,28 +11,10 @@ import {
type ClientLogEntry, type ClientLogEntry,
type LogMethod, type LogMethod,
patchConsoleMethod, patchConsoleMethod,
UNDEFINED_MARKER,
} from '../../shared/forward-logs-shared' } from '../../shared/forward-logs-shared'
import { preLogSerializationClone, logStringify } from './forward-logs-utils'
const terminalLoggingConfig = getTerminalLoggingConfig() const isTerminalLoggingEnabled = getIsTerminalLoggingEnabled()
export const PROMISE_MARKER = 'Promise {}'
export const UNAVAILABLE_MARKER = '[Unable to view]'
const maximumDepth =
typeof terminalLoggingConfig === 'object' && terminalLoggingConfig.depthLimit
? terminalLoggingConfig.depthLimit
: 5
const maximumBreadth =
typeof terminalLoggingConfig === 'object' && terminalLoggingConfig.edgeLimit
? terminalLoggingConfig.edgeLimit
: 100
const stringify = configure({
maximumDepth,
maximumBreadth,
})
export const isTerminalLoggingEnabled = getIsTerminalLoggingEnabled()
const methods: Array<LogMethod> = [ const methods: Array<LogMethod> = [
'log', 'log',
...@@ -52,71 +30,6 @@ const methods: Array<LogMethod> = [ ...@@ -52,71 +30,6 @@ const methods: Array<LogMethod> = [
'groupEnd', 'groupEnd',
'trace', 'trace',
] ]
/**
* allows us to:
* - revive the undefined log in the server as it would look in the browser
* - not read/attempt to serialize promises (next will console error if you do that, and will cause this program to infinitely recurse)
* - if we read a proxy that throws (no way to detect if something is a proxy), explain to the user we can't read this data
*/
export function preLogSerializationClone<T>(
value: T,
seen = new WeakMap()
): any {
if (value === undefined) return UNDEFINED_MARKER
if (value === null || typeof value !== 'object') return value
if (seen.has(value as object)) return seen.get(value as object)
try {
Object.keys(value as object)
} catch {
return UNAVAILABLE_MARKER
}
try {
if (typeof (value as any).then === 'function') return PROMISE_MARKER
} catch {
return UNAVAILABLE_MARKER
}
if (Array.isArray(value)) {
const out: any[] = []
seen.set(value, out)
for (const item of value) {
try {
out.push(preLogSerializationClone(item, seen))
} catch {
out.push(UNAVAILABLE_MARKER)
}
}
return out
}
const proto = Object.getPrototypeOf(value)
if (proto === Object.prototype || proto === null) {
const out: Record<string, unknown> = {}
seen.set(value as object, out)
for (const key of Object.keys(value as object)) {
try {
out[key] = preLogSerializationClone((value as any)[key], seen)
} catch {
out[key] = UNAVAILABLE_MARKER
}
}
return out
}
return Object.prototype.toString.call(value)
}
// only safe if passed safeClone data
export const logStringify = (data: unknown): string => {
try {
const result = stringify(data)
return result ?? `"${UNAVAILABLE_MARKER}"`
} catch {
return `"${UNAVAILABLE_MARKER}"`
}
}
const afterThisFrame = (cb: () => void) => { const afterThisFrame = (cb: () => void) => {
let timeout: ReturnType<typeof setTimeout> | undefined let timeout: ReturnType<typeof setTimeout> | undefined
...@@ -154,6 +67,7 @@ const serializeEntries = (entries: Array<ClientLogEntry>) => ...@@ -154,6 +67,7 @@ const serializeEntries = (entries: Array<ClientLogEntry>) =>
} }
}) })
// Combined state and public API
export const logQueue: { export const logQueue: {
entries: Array<ClientLogEntry> entries: Array<ClientLogEntry>
onSocketReady: (socket: WebSocket) => void onSocketReady: (socket: WebSocket) => void
...@@ -208,6 +122,10 @@ export const logQueue: { ...@@ -208,6 +122,10 @@ export const logQueue: {
}) })
}, },
onSocketReady: (socket: WebSocket) => { onSocketReady: (socket: WebSocket) => {
if (!isTerminalLoggingEnabled) {
return
}
if (socket.readyState !== WebSocket.OPEN) { if (socket.readyState !== WebSocket.OPEN) {
// invariant // invariant
return return
...@@ -286,6 +204,10 @@ const createLogEntry = (level: LogMethod, args: any[]) => { ...@@ -286,6 +204,10 @@ const createLogEntry = (level: LogMethod, args: any[]) => {
} }
export const forwardErrorLog = (args: any[]) => { export const forwardErrorLog = (args: any[]) => {
if (!isTerminalLoggingEnabled) {
return
}
const errorObjects = args.filter((arg) => arg instanceof Error) const errorObjects = args.filter((arg) => arg instanceof Error)
const first = errorObjects.at(0) const first = errorObjects.at(0)
if (first) { if (first) {
...@@ -345,6 +267,10 @@ const stackWithOwners = (error: Error) => { ...@@ -345,6 +267,10 @@ const stackWithOwners = (error: Error) => {
} }
export function logUnhandledRejection(reason: unknown) { export function logUnhandledRejection(reason: unknown) {
if (!isTerminalLoggingEnabled) {
return
}
if (reason instanceof Error) { if (reason instanceof Error) {
createUnhandledRejectionErrorEntry(reason, stackWithOwners(reason)) createUnhandledRejectionErrorEntry(reason, stackWithOwners(reason))
return return
...@@ -429,11 +355,19 @@ const isIgnoredLog = (args: any[]) => { ...@@ -429,11 +355,19 @@ const isIgnoredLog = (args: any[]) => {
} }
export function forwardUnhandledError(error: Error) { export function forwardUnhandledError(error: Error) {
if (!isTerminalLoggingEnabled) {
return
}
createUncaughtErrorEntry(error.name, error.message, stackWithOwners(error)) createUncaughtErrorEntry(error.name, error.message, stackWithOwners(error))
} }
// TODO: this router check is brittle, we need to update based on the current router the user is using // TODO: this router check is brittle, we need to update based on the current router the user is using
export const initializeDebugLogForwarding = (router: 'app' | 'pages'): void => { export const initializeDebugLogForwarding = (router: 'app' | 'pages'): void => {
if (!isTerminalLoggingEnabled) {
return
}
// probably don't need this // probably don't need this
if (isPatched) { if (isPatched) {
return return
......
...@@ -15,7 +15,6 @@ import { ...@@ -15,7 +15,6 @@ import {
forwardUnhandledError, forwardUnhandledError,
logUnhandledRejection, logUnhandledRejection,
forwardErrorLog, forwardErrorLog,
isTerminalLoggingEnabled,
} from '../app/forward-logs' } from '../app/forward-logs'
const usePagesDevOverlayBridge = () => { const usePagesDevOverlayBridge = () => {
...@@ -82,9 +81,7 @@ function nextJsHandleConsoleError(...args: any[]) { ...@@ -82,9 +81,7 @@ function nextJsHandleConsoleError(...args: any[]) {
storeHydrationErrorStateFromConsoleArgs(...args) storeHydrationErrorStateFromConsoleArgs(...args)
// TODO: Surfaces non-errors logged via `console.error`. // TODO: Surfaces non-errors logged via `console.error`.
handleError(maybeError) handleError(maybeError)
if (isTerminalLoggingEnabled) { forwardErrorLog(args)
forwardErrorLog(args)
}
origConsoleError.apply(window.console, args) origConsoleError.apply(window.console, args)
} }
...@@ -92,7 +89,7 @@ function onUnhandledError(event: ErrorEvent) { ...@@ -92,7 +89,7 @@ function onUnhandledError(event: ErrorEvent) {
const error = event?.error const error = event?.error
handleError(error) handleError(error)
if (error && isTerminalLoggingEnabled) { if (error) {
forwardUnhandledError(error as Error) forwardUnhandledError(error as Error)
} }
} }
...@@ -109,9 +106,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) { ...@@ -109,9 +106,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) {
} }
dispatcher.onUnhandledRejection(reason) dispatcher.onUnhandledRejection(reason)
if (isTerminalLoggingEnabled) { logUnhandledRejection(reason)
logUnhandledRejection(reason)
}
} }
export function register() { export function register() {
...@@ -124,9 +119,7 @@ export function register() { ...@@ -124,9 +119,7 @@ export function register() {
Error.stackTraceLimit = 50 Error.stackTraceLimit = 50
} catch {} } catch {}
if (isTerminalLoggingEnabled) { initializeDebugLogForwarding('pages')
initializeDebugLogForwarding('pages')
}
window.addEventListener('error', onUnhandledError) window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection) window.addEventListener('unhandledrejection', onUnhandledRejection)
window.console.error = nextJsHandleConsoleError window.console.error = nextJsHandleConsoleError
......
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