File size: 6,500 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import {
  getHydrationWarningType,
  isHydrationError as isReact18HydrationError,
  isHydrationWarning as isReact18HydrationWarning,
} from '../../shared/react-18-hydration-error'
import {
  isHydrationError as isReact19HydrationError,
  isErrorMessageWithComponentStackDiff as isReact19HydrationWarning,
} from '../../shared/react-19-hydration-error'
import type { HydrationErrorState } from '../../shared/hydration-error'

// We only need this for React 18 or hydration console errors in React 19.
// Once we surface console.error in the dev overlay in pages router, we should only
// use this for React 18.
let hydrationErrorState: HydrationErrorState = {}

const squashedHydrationErrorDetails = new WeakMap<Error, HydrationErrorState>()

export function getSquashedHydrationErrorDetails(
  error: Error
): HydrationErrorState | null {
  return squashedHydrationErrorDetails.has(error)
    ? squashedHydrationErrorDetails.get(error)!
    : null
}

export function attachHydrationErrorState(error: Error) {
  if (!isReact18HydrationError(error) && !isReact19HydrationError(error)) {
    return
  }

  let parsedHydrationErrorState: typeof hydrationErrorState = {}

  // If there's any extra information in the error message to display,
  // append it to the error message details property
  if (hydrationErrorState.warning) {
    // The patched console.error found hydration errors logged by React
    // Append the logged warning to the error message
    parsedHydrationErrorState = {
      // It contains the warning, component stack, server and client tag names
      ...hydrationErrorState,
    }

    // Consume the cached hydration diff.
    // This is only required for now when we still squashed the hydration diff log into hydration error.
    // Once the all error is logged to dev overlay in order, this will go away.
    if (hydrationErrorState.reactOutputComponentDiff) {
      parsedHydrationErrorState.reactOutputComponentDiff =
        hydrationErrorState.reactOutputComponentDiff
    }

    squashedHydrationErrorDetails.set(error, parsedHydrationErrorState)
  }
}

// TODO: Only handle React 18. Once we surface console.error in the dev overlay in pages router,
// we can use the same behavior as App Router.
export function storeHydrationErrorStateFromConsoleArgs(...args: any[]) {
  let [message, firstContent, secondContent, ...rest] = args
  if (isReact18HydrationWarning(message)) {
    // Some hydration warnings has 4 arguments, some has 3, fallback to the last argument
    // when the 3rd argument is not the component stack but an empty string
    // For some warnings, there's only 1 argument for template.
    // The second argument is the diff or component stack.
    if (args.length === 3) {
      secondContent = ''
    }

    const warning = message
      .replace(/Warning: /, '')
      .replace('%s', firstContent)
      .replace('%s', secondContent)
      // remove the last %s from the message
      .replace(/%s/g, '')

    const lastArg = (rest[rest.length - 1] || '').trim()

    hydrationErrorState.reactOutputComponentDiff = generateHydrationDiffReact18(
      message,
      firstContent,
      secondContent,
      lastArg
    )

    hydrationErrorState.warning = warning
  } else if (isReact19HydrationWarning(message)) {
    // Some hydration warnings has 4 arguments, some has 3, fallback to the last argument
    // when the 3rd argument is not the component stack but an empty string
    // For some warnings, there's only 1 argument for template.
    // The second argument is the diff or component stack.
    if (args.length === 3) {
      secondContent = ''
    }

    const warning = message
      .replace('%s', firstContent)
      .replace('%s', secondContent)
      // remove the last %s from the message
      .replace(/%s/g, '')

    const lastArg = (args[args.length - 1] || '').trim()

    hydrationErrorState.reactOutputComponentDiff = lastArg
    hydrationErrorState.warning = warning
  }
}

/*
 * Some hydration errors in React 18 does not have the diff in the error message.
 * Instead it has the error stack trace which is component stack that we can leverage.
 * Will parse the diff from the error stack trace
 *  e.g.
 *  Warning: Expected server HTML to contain a matching <div> in <p>.
 *    at div
 *    at p
 *    at div
 *    at div
 *    at Page
 *  output:
 *    <Page>
 *      <div>
 *        <p>
 *  >       <div>
 *
 */
function generateHydrationDiffReact18(
  message: string,
  firstContent: string,
  secondContent: string,
  lastArg: string
) {
  const componentStack = lastArg
  let firstIndex = -1
  let secondIndex = -1
  const hydrationWarningType = getHydrationWarningType(message)

  // at div\n at Foo\n at Bar (....)\n -> [div, Foo]
  const components = componentStack
    .split('\n')
    // .reverse()
    .map((line: string, index: number) => {
      // `<space>at <component> (<location>)` -> `at <component> (<location>)`
      line = line.trim()
      // extract `<space>at <component>` to `<<component>>`
      // e.g. `  at Foo` -> `<Foo>`
      const [, component, location] = /at (\w+)( \((.*)\))?/.exec(line) || []
      // If there's no location then it's user-land stack frame
      if (!location) {
        if (component === firstContent && firstIndex === -1) {
          firstIndex = index
        } else if (component === secondContent && secondIndex === -1) {
          secondIndex = index
        }
      }
      return location ? '' : component
    })
    .filter(Boolean)
    .reverse()

  let diff = ''
  for (let i = 0; i < components.length; i++) {
    const component = components[i]
    const matchFirstContent =
      hydrationWarningType === 'tag' && i === components.length - firstIndex - 1
    const matchSecondContent =
      hydrationWarningType === 'tag' &&
      i === components.length - secondIndex - 1
    if (matchFirstContent || matchSecondContent) {
      const spaces = ' '.repeat(Math.max(i * 2 - 2, 0) + 2)
      diff += `> ${spaces}<${component}>\n`
    } else {
      const spaces = ' '.repeat(i * 2 + 2)
      diff += `${spaces}<${component}>\n`
    }
  }
  if (hydrationWarningType === 'text') {
    const spaces = ' '.repeat(components.length * 2)
    diff += `+ ${spaces}"${firstContent}"\n`
    diff += `- ${spaces}"${secondContent}"\n`
  } else if (hydrationWarningType === 'text-in-tag') {
    const spaces = ' '.repeat(components.length * 2)
    diff += `> ${spaces}<${secondContent}>\n`
    diff += `>   ${spaces}"${firstContent}"\n`
  }
  return diff
}