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 {
processMessage,
type StaticIndicatorState,
} from './hot-reloader-app'
import {
isTerminalLoggingEnabled,
logQueue,
} from '../../../../next-devtools/userspace/app/forward-logs'
import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs'
import { InvariantError } from '../../../../shared/lib/invariant-error'
import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants'
......@@ -57,9 +54,7 @@ export function createWebSocket(
newWebSocket.binaryType = 'arraybuffer'
function handleOnline() {
if (isTerminalLoggingEnabled) {
logQueue.onSocketReady(newWebSocket)
}
logQueue.onSocketReady(newWebSocket)
reconnections = 0
window.console.log('[HMR] connected')
......
import {
isTerminalLoggingEnabled,
logQueue,
} from '../../../../next-devtools/userspace/app/forward-logs'
import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
type HmrMessageSentToBrowser,
......@@ -35,9 +32,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
if (source) source.close()
function handleOnline() {
if (isTerminalLoggingEnabled) {
logQueue.onSocketReady(source)
}
logQueue.onSocketReady(source)
reconnections = 0
window.console.log('[HMR] connected')
}
......
import { patchConsoleError } from './errors/intercept-console-error'
import { handleGlobalErrors } from './errors/use-error-handler'
import {
initializeDebugLogForwarding,
isTerminalLoggingEnabled,
} from './forward-logs'
import { initializeDebugLogForwarding } from './forward-logs'
handleGlobalErrors()
patchConsoleError()
if (isTerminalLoggingEnabled) {
initializeDebugLogForwarding('app')
}
initializeDebugLogForwarding('app')
......@@ -2,7 +2,7 @@ import isError from '../../../../lib/is-error'
import { isNextRouterError } from '../../../../client/components/is-next-router-error'
import { handleConsoleError } from './use-error-handler'
import { parseConsoleArgs } from '../../../../client/lib/console'
import { forwardErrorLog, isTerminalLoggingEnabled } from '../forward-logs'
import { forwardErrorLog } from '../forward-logs'
export const originConsoleError = globalThis.console.error
......@@ -37,9 +37,7 @@ export function patchConsoleError() {
args
)
}
if (isTerminalLoggingEnabled) {
forwardErrorLog(args)
}
forwardErrorLog(args)
originConsoleError.apply(window.console, args)
}
......
......@@ -7,11 +7,7 @@ import {
import isError from '../../../../lib/is-error'
import { createConsoleError } from '../../../shared/console-error'
import { coerceError, setOwnerStackIfAvailable } from './stitched-error'
import {
forwardUnhandledError,
isTerminalLoggingEnabled,
logUnhandledRejection,
} from '../forward-logs'
import { forwardUnhandledError, logUnhandledRejection } from '../forward-logs'
const queueMicroTask =
globalThis.queueMicrotask || ((cb: () => void) => Promise.resolve().then(cb))
......@@ -100,9 +96,7 @@ function onUnhandledError(event: WindowEventMap['error']): void | boolean {
const error = coerceError(thrownValue)
setOwnerStackIfAvailable(error)
handleClientError(error)
if (isTerminalLoggingEnabled) {
forwardUnhandledError(error)
}
forwardUnhandledError(error)
}
}
......@@ -121,9 +115,7 @@ function onUnhandledRejection(ev: WindowEventMap['unhandledrejection']): void {
handler(error)
}
if (isTerminalLoggingEnabled) {
logUnhandledRejection(reason)
}
logUnhandledRejection(reason)
}
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,
PROMISE_MARKER,
UNAVAILABLE_MARKER,
logStringify,
} from './forward-logs'
import { preLogSerializationClone, logStringify } from './forward-logs-utils'
const safeStringify = (data: unknown) =>
logStringify(preLogSerializationClone(data))
......@@ -16,7 +10,9 @@ describe('forward-logs serialization', () => {
expect(preLogSerializationClone('hello')).toBe('hello')
expect(preLogSerializationClone(true)).toBe(true)
expect(preLogSerializationClone(null)).toBe(null)
expect(preLogSerializationClone(undefined)).toBe(UNDEFINED_MARKER)
expect(preLogSerializationClone(undefined)).toBe(
'__next_tagged_undefined'
)
})
it('should handle circular references', () => {
......@@ -29,19 +25,19 @@ describe('forward-logs serialization', () => {
it('should handle promises', () => {
const promise = Promise.resolve(42)
expect(preLogSerializationClone(promise)).toBe(PROMISE_MARKER)
expect(preLogSerializationClone(promise)).toBe('Promise {}')
})
it('should handle arrays', () => {
const arr = [1, 'test', undefined, null]
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', () => {
const obj = { a: 1, b: undefined, c: 'test' }
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', () => {
......@@ -54,7 +50,7 @@ describe('forward-logs serialization', () => {
const cloned = preLogSerializationClone(obj)
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', () => {
......@@ -80,7 +76,7 @@ describe('forward-logs serialization', () => {
const arr = [1, throwingProxy, 'normal']
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', () => {
expect(safeStringify(42)).toBe('42')
expect(safeStringify('hello')).toBe('"hello"')
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', () => {
......@@ -108,7 +104,7 @@ describe('forward-logs serialization', () => {
}
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 {
getOwnerStack,
setOwnerStackIfAvailable,
} from './errors/stitched-error'
import { getErrorSource } from '../../../shared/lib/error-source'
import {
getTerminalLoggingConfig,
getIsTerminalLoggingEnabled,
} from './terminal-logging-config'
import { getIsTerminalLoggingEnabled } from './terminal-logging-config'
import {
type ConsoleEntry,
type ConsoleErrorEntry,
......@@ -15,28 +11,10 @@ import {
type ClientLogEntry,
type LogMethod,
patchConsoleMethod,
UNDEFINED_MARKER,
} from '../../shared/forward-logs-shared'
import { preLogSerializationClone, logStringify } from './forward-logs-utils'
const terminalLoggingConfig = getTerminalLoggingConfig()
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 isTerminalLoggingEnabled = getIsTerminalLoggingEnabled()
const methods: Array<LogMethod> = [
'log',
......@@ -52,71 +30,6 @@ const methods: Array<LogMethod> = [
'groupEnd',
'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) => {
let timeout: ReturnType<typeof setTimeout> | undefined
......@@ -154,6 +67,7 @@ const serializeEntries = (entries: Array<ClientLogEntry>) =>
}
})
// Combined state and public API
export const logQueue: {
entries: Array<ClientLogEntry>
onSocketReady: (socket: WebSocket) => void
......@@ -208,6 +122,10 @@ export const logQueue: {
})
},
onSocketReady: (socket: WebSocket) => {
if (!isTerminalLoggingEnabled) {
return
}
if (socket.readyState !== WebSocket.OPEN) {
// invariant
return
......@@ -286,6 +204,10 @@ const createLogEntry = (level: LogMethod, args: any[]) => {
}
export const forwardErrorLog = (args: any[]) => {
if (!isTerminalLoggingEnabled) {
return
}
const errorObjects = args.filter((arg) => arg instanceof Error)
const first = errorObjects.at(0)
if (first) {
......@@ -345,6 +267,10 @@ const stackWithOwners = (error: Error) => {
}
export function logUnhandledRejection(reason: unknown) {
if (!isTerminalLoggingEnabled) {
return
}
if (reason instanceof Error) {
createUnhandledRejectionErrorEntry(reason, stackWithOwners(reason))
return
......@@ -429,11 +355,19 @@ const isIgnoredLog = (args: any[]) => {
}
export function forwardUnhandledError(error: Error) {
if (!isTerminalLoggingEnabled) {
return
}
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
export const initializeDebugLogForwarding = (router: 'app' | 'pages'): void => {
if (!isTerminalLoggingEnabled) {
return
}
// probably don't need this
if (isPatched) {
return
......
......@@ -15,7 +15,6 @@ import {
forwardUnhandledError,
logUnhandledRejection,
forwardErrorLog,
isTerminalLoggingEnabled,
} from '../app/forward-logs'
const usePagesDevOverlayBridge = () => {
......@@ -82,9 +81,7 @@ function nextJsHandleConsoleError(...args: any[]) {
storeHydrationErrorStateFromConsoleArgs(...args)
// TODO: Surfaces non-errors logged via `console.error`.
handleError(maybeError)
if (isTerminalLoggingEnabled) {
forwardErrorLog(args)
}
forwardErrorLog(args)
origConsoleError.apply(window.console, args)
}
......@@ -92,7 +89,7 @@ function onUnhandledError(event: ErrorEvent) {
const error = event?.error
handleError(error)
if (error && isTerminalLoggingEnabled) {
if (error) {
forwardUnhandledError(error as Error)
}
}
......@@ -109,9 +106,7 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) {
}
dispatcher.onUnhandledRejection(reason)
if (isTerminalLoggingEnabled) {
logUnhandledRejection(reason)
}
logUnhandledRejection(reason)
}
export function register() {
......@@ -124,9 +119,7 @@ export function register() {
Error.stackTraceLimit = 50
} catch {}
if (isTerminalLoggingEnabled) {
initializeDebugLogForwarding('pages')
}
initializeDebugLogForwarding('pages')
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
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