-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathdebug.js
408 lines (358 loc) · 11.4 KB
/
debug.js
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import { checkPropTypes } from './check-props';
import { options as rawOptions, Component } from 'preact';
import {
ELEMENT_NODE,
DOCUMENT_NODE,
DOCUMENT_FRAGMENT_NODE
} from './constants';
import {
getOwnerStack,
setupComponentStack,
getCurrentInternal,
getDisplayName
} from './component-stack';
import { IS_NON_DIMENSIONAL } from '../../compat/src/util';
import { validateTableMarkup } from './validateMarkup';
const options = /** @type {import('../../src/internal').Options} */ (rawOptions);
export function initDebug() {
setupComponentStack();
let hooksAllowed = false;
/* eslint-disable no-console */
let oldBeforeDiff = options._diff;
let oldDiffed = options.diffed;
let oldVnode = options.vnode;
let oldCatchError = options._catchError;
let oldRoot = options._root;
let oldHook = options._hook;
const warnedComponents = {
useEffect: new WeakMap(),
useLayoutEffect: new WeakMap(),
lazyPropTypes: new WeakMap()
};
const deprecations = [];
options._catchError = catchErrorHook;
options._root = rootHook;
options._diff = diffHook;
options._hook = hookHook;
options.vnode = vnodeHook;
options.diffed = diffedHook;
/** @type {typeof options["_catchError"]} */
function catchErrorHook(error, internal) {
let component = internal && internal._component;
if (component && typeof error.then == 'function') {
const promise = error;
error = new Error(
`Missing Suspense. The throwing component was: ${getDisplayName(
internal
)}`
);
let parent = internal;
for (; parent; parent = parent._parent) {
if (parent._component && parent._component._childDidSuspend) {
error = promise;
break;
}
}
// We haven't recovered and we know at this point that there is no
// Suspense component higher up in the tree
if (error instanceof Error) {
throw error;
}
}
try {
oldCatchError(error, internal);
// when an error was handled by an ErrorBoundary we will nontheless emit an error
// event on the window object. This is to make up for react compatibility in dev mode
// and thus make the Next.js dev overlay work.
if (typeof error.then != 'function') {
setTimeout(() => {
throw error;
});
}
} catch (e) {
throw e;
}
}
/** @type {typeof options["_root"]} */
function rootHook(vnode, parentNode) {
if (!parentNode) {
throw new Error(
'Undefined parent passed to render(), this is the second argument.\n' +
'Check if the element is available in the DOM/has the correct id.'
);
}
let isValid;
switch (parentNode.nodeType) {
case ELEMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
isValid = true;
break;
default:
isValid = false;
}
if (!isValid) {
let componentName = getDisplayName(vnode);
throw new Error(
`Expected a valid HTML node as a second argument to render. Received ${parentNode} instead: render(<${componentName} />, ${parentNode});`
);
}
if (oldRoot) oldRoot(vnode, parentNode);
}
/** @type {typeof options["_diff"]} */
function diffHook(internal, vnode) {
if (vnode === null || typeof vnode !== 'object') {
// TODO: This isn't correct. We need these checks to run on mount
oldBeforeDiff(internal, vnode);
return;
}
// Check if the user passed plain objects as children. Note that we cannot
// move this check into `options.vnode` because components can receive
// children in any shape they want (e.g.
// `<MyJSONFormatter>{{ foo: 123, bar: "abc" }}</MyJSONFormatter>`).
if (vnode.constructor !== undefined) {
const keys = Object.keys(vnode).join(',');
throw new Error(
`Objects are not valid as a child. Encountered an object with the keys {${keys}}.` +
`\n\n${getOwnerStack(internal)}`
);
}
let { type } = internal;
if (type === undefined) {
throw new Error(
'Undefined component passed to createElement()\n\n' +
'You likely forgot to export your component or might have mixed up default and named imports' +
serializeVNode(vnode) +
`\n\n${getOwnerStack(internal)}`
);
} else if (type != null && typeof type == 'object') {
if (type.constructor === undefined) {
throw new Error(
`Invalid type passed to createElement(): ${type}\n\n` +
'Did you accidentally pass a JSX literal as JSX twice?\n\n' +
` let My${getDisplayName(internal)} = ${serializeVNode(type)};\n` +
` let vnode = <My${getDisplayName(internal)} />;\n\n` +
'This usually happens when you export a JSX literal and not the component.' +
`\n\n${getOwnerStack(internal)}`
);
}
throw new Error(
'Invalid type passed to createElement(): ' +
(Array.isArray(type) ? 'array' : type)
);
}
hooksAllowed = true;
let isCompatNode = '$$typeof' in vnode;
if (
internal.ref !== undefined &&
typeof internal.ref != 'function' &&
typeof internal.ref != 'object' &&
!isCompatNode // allow string refs when preact-compat is installed
) {
throw new Error(
`Component's "ref" property should be a function, or an object created ` +
`by createRef(), but got [${typeof internal.ref}] instead\n` +
serializeVNode(internal) +
`\n\n${getOwnerStack(internal)}`
);
}
if (typeof internal.type == 'string') {
validateTableMarkup(internal);
for (const key in vnode.props) {
if (
key[0] === 'o' &&
key[1] === 'n' &&
typeof vnode.props[key] != 'function' &&
vnode.props[key] != null
) {
throw new Error(
`Component's "${key}" property should be a function, ` +
`but got [${typeof vnode.props[key]}] instead\n` +
serializeVNode(vnode) +
`\n\n${getOwnerStack(internal)}`
);
} else if (
!isCompatNode &&
key === 'style' &&
vnode.props[key] !== null &&
typeof vnode.props[key] === 'object'
) {
const style = vnode.props[key];
for (let i in style) {
if (typeof style[i] === 'number' && !IS_NON_DIMENSIONAL.test(i)) {
console.warn(
`Numeric CSS property value is missing a "px" unit: ${i}: ${style[i]}"\n` +
serializeVNode(vnode) +
`\n\n${getOwnerStack(vnode)}`
);
}
}
}
}
}
// Check prop-types if available
if (typeof internal.type == 'function' && internal.type.propTypes) {
if (
internal.type.displayName === 'Lazy' &&
!warnedComponents.lazyPropTypes.has(internal.type)
) {
const m =
'PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ';
try {
const lazyVNode = internal.type();
warnedComponents.lazyPropTypes.set(internal.type, true);
console.warn(
m + `Component wrapped in lazy() is ${getDisplayName(lazyVNode)}`
);
} catch (promise) {
console.warn(
m + "We will log the wrapped component's name once it is loaded."
);
}
}
// If vnode is not present we're mounting
let values = vnode ? vnode.props : internal.props;
if (internal.type._forwarded) {
values = Object.assign({}, values);
delete values.ref;
}
checkPropTypes(
internal.type.propTypes,
values,
'prop',
getDisplayName(internal),
() => getOwnerStack(internal)
);
}
if (oldBeforeDiff) oldBeforeDiff(internal, vnode);
}
/** @type {typeof options["_hook"]} */
function hookHook(internal, index, type) {
if (!internal || !hooksAllowed) {
throw new Error('Hook can only be invoked from render methods.');
}
if (oldHook) oldHook(internal, index, type);
}
// Ideally we'd want to print a warning once per component, but we
// don't have access to the vnode that triggered it here. As a
// compromise and to avoid flooding the console with warnings we
// print each deprecation warning only once.
const warn = (property, message) => ({
get() {
const key = 'get' + property + message;
if (deprecations && deprecations.indexOf(key) < 0) {
deprecations.push(key);
console.warn(`getting vnode.${property} is deprecated, ${message}`);
}
},
set() {
const key = 'set' + property + message;
if (deprecations && deprecations.indexOf(key) < 0) {
deprecations.push(key);
console.warn(`setting vnode.${property} is not allowed, ${message}`);
}
}
});
const deprecatedAttributes = {
nodeName: warn('nodeName', 'use vnode.type'),
attributes: warn('attributes', 'use vnode.props'),
children: warn('children', 'use vnode.props.children')
};
// Property descriptor: preserve a property's value but make it non-enumerable:
const debugProps = {
__source: { enumerable: false },
__self: { enumerable: false }
};
// If it's acceptable to inject debug properties onto the
// prototype, __proto__ is faster than defineProperties():
// https://esbench.com/bench/6021ebd7d9c27600a7bfdba3
const deprecatedProto = Object.create({}, deprecatedAttributes);
/** @type {typeof options["vnode"]} */
function vnodeHook(vnode) {
const props = vnode.props;
if (props != null && ('__source' in props || '__self' in props)) {
Object.defineProperties(props, debugProps);
vnode.__source = props.__source;
vnode.__self = props.__self;
}
// eslint-disable-next-line
vnode.__proto__ = deprecatedProto;
if (oldVnode) oldVnode(vnode);
}
/** @type {typeof options["diffed"]} */
function diffedHook(internal) {
hooksAllowed = false;
if (oldDiffed) oldDiffed(internal);
if (internal._child != null) {
let child = internal._child;
const keys = [];
if (child.key != null) {
keys.push(child.key);
}
while ((child = child._next) != null) {
if (child.key == null) continue;
const key = child.key;
if (keys.indexOf(key) !== -1) {
console.error(
'Following component has two or more children with the ' +
`same key attribute: "${key}". This may cause glitches and misbehavior ` +
'in rendering process. Component: \n\n' +
serializeVNode(internal) +
`\n\n${getOwnerStack(internal)}`
);
// Break early to not spam the console
break;
}
keys.push(key);
}
}
}
}
const setState = Component.prototype.setState;
/** @this {import('../../src/internal').Component} */
Component.prototype.setState = function(update, callback) {
if (this._internal == null) {
// `this._internal` will be `null` during componentWillMount. But it
// is perfectly valid to call `setState` during cWM. So we
// need an additional check to verify that we are dealing with a
// call inside constructor.
if (this.state == null) {
console.warn(
`Calling "this.setState" inside the constructor of a component is a ` +
`no-op and might be a bug in your application. Instead, set ` +
`"this.state = {}" directly.\n\n${getOwnerStack(
getCurrentInternal()
)}`
);
}
}
return setState.call(this, update, callback);
};
/**
* Serialize a vnode tree to a string
* @param {import('./internal').VNode} vnode
* @returns {string}
*/
export function serializeVNode(vnode) {
let { props } = vnode;
let name = getDisplayName(vnode);
let attrs = '';
for (let prop in props) {
if (props.hasOwnProperty(prop) && prop !== 'children') {
let value = props[prop];
// If it is an object but doesn't have toString(), use Object.toString
if (typeof value == 'function') {
value = `function ${value.displayName || value.name}() {}`;
}
value =
Object(value) === value && !value.toString
? Object.prototype.toString.call(value)
: value + '';
attrs += ` ${prop}=${JSON.stringify(value)}`;
}
}
let children = props.children;
return `<${name}${attrs}${
children && children.length ? '>..</' + name + '>' : ' />'
}`;
}