Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 26x 14x 11x 37x 62x 62x 62x 3x 62x 53x 53x 21x 32x 32x 32x 32x 3x 62x 62x 2x 62x 1x 74x 74x 2x 72x 2x 2x 2x 1x 2x 70x 1x 2x 1x 69x 69x 69x 74x 8x 8x 61x 61x 488x 488x 23x 488x 488x 5x 5x 5x 1x 5x 18x 18x 3x 61x 54x 61x 13x 10x 10x 10x 12x 10x 10x 10x 3x 22x 21x 21x 21x 37x 37x 2x 35x 1x 1x 1x 37x 37x 37x 21x 2x 2x 2x 1x 1x 1x 1x | /**
* Mismatch detection for Coherent.js hydration
*
* Compares server-rendered DOM against client virtual DOM to detect
* hydration mismatches in development mode.
*/
import {
isElementVNode,
readElement,
getRenderedChildren,
getSignificantDOMChildren,
alignChildren,
resolveAttributeValue,
renderedAttributes,
} from './vnode.js';
/**
* Format path segments into readable string
* @param {Array} segments - Path segments
* @returns {string} - Formatted path
*/
export function formatPath(segments) {
if (!segments || segments.length === 0) return 'root';
return segments.join('.');
}
/** Attributes compared between the virtual node and the DOM. */
const ATTRIBUTE_CHECKS = [
{ virtual: 'className', dom: 'class' },
{ virtual: 'id', dom: 'id' },
{ virtual: 'type', dom: 'type' },
{ virtual: 'value', dom: 'value' },
{ virtual: 'checked', dom: 'checked' },
{ virtual: 'disabled', dom: 'disabled' },
{ virtual: 'href', dom: 'href' },
{ virtual: 'src', dom: 'src' }
];
function textOf(node) {
return (node?.textContent ?? '').trim();
}
/**
* Compare a list of rendered children (see getRenderedChildren) with the
* significant DOM children of `parent`.
* @private
*/
function compareChildren(parent, vList, path, mismatches, childSegment) {
const dList = getSignificantDOMChildren(parent);
const { pairs, exact } = alignChildren(vList, dList);
if (exact && vList.length !== dList.length) {
mismatches.push({
path: formatPath([...path, 'children']),
type: 'children_count',
expected: vList.length,
actual: dList.length,
domPath: getDOMPath(parent)
});
}
for (const [item, node, index] of pairs) {
const childPath = [...path, childSegment(index)];
if (item.type === 'element') {
mismatches.push(...detectMismatch(node, item.vNode, childPath));
} else Eif (item.type === 'text') {
const expected = item.text.trim();
Iif (node.nodeType !== 3) {
mismatches.push({
path: formatPath(childPath),
type: 'text',
expected,
actual: describeNode(node),
domPath: getDOMPath(parent)
});
} else if (textOf(node) !== expected) {
mismatches.push({
path: formatPath(childPath),
type: 'text',
expected,
actual: textOf(node),
domPath: getDOMPath(parent)
});
}
}
}
Iif (!exact) return;
for (let i = dList.length; i < vList.length; i++) {
mismatches.push({
path: formatPath([...path, childSegment(i)]),
type: 'missing_dom_child',
expected: describeRendered(vList[i]),
actual: null,
domPath: getDOMPath(parent)
});
}
for (let i = vList.length; i < dList.length; i++) {
mismatches.push({
path: formatPath([...path, childSegment(i)]),
type: 'extra_dom_child',
expected: null,
actual: describeNode(dList[i]),
domPath: getDOMPath(parent)
});
}
}
/**
* Detect mismatches between DOM and virtual DOM
*
* Children are compared as the server rendered them: null, undefined and
* booleans produce nothing, nested arrays are flattened, adjacent strings form
* one text node and whitespace-only text is ignored on both sides.
*
* @param {Element} domElement - Real DOM element
* @param {Object|string|number|Array} virtualNode - Virtual DOM node; an array
* is compared against the children of `domElement`
* @param {Array} path - Current path for error reporting
* @returns {Array} - Array of mismatch objects
*/
export function detectMismatch(domElement, virtualNode, path = []) {
const mismatches = [];
if (virtualNode === null || virtualNode === undefined || typeof virtualNode === 'boolean') {
return mismatches;
}
// Handle text nodes (string or number in virtual DOM)
if (typeof virtualNode === 'string' || typeof virtualNode === 'number') {
const expectedText = String(virtualNode).trim();
const actualText = textOf(domElement);
if (actualText !== expectedText) {
mismatches.push({
path: formatPath(path),
type: 'text',
expected: expectedText,
actual: actualText,
domPath: getDOMPath(domElement)
});
}
return mismatches;
}
// A fragment (array or function component): compare against the children
if (Array.isArray(virtualNode) || typeof virtualNode === 'function') {
const vList = getRenderedChildren('fragment', { children: virtualNode });
compareChildren(domElement, vList, path, mismatches, (i) => `[${i}]`);
return mismatches;
}
Iif (!isElementVNode(virtualNode)) {
return mismatches;
}
const { tagName, props } = readElement(virtualNode);
// Check tag name
const domTagName = domElement.tagName?.toLowerCase();
if (domTagName !== tagName.toLowerCase()) {
mismatches.push({
path: formatPath(path),
type: 'tagName',
expected: tagName,
actual: domTagName,
domPath: getDOMPath(domElement)
});
// Can't continue comparing if tag is different
return mismatches;
}
// Check critical attributes, evaluated the way core renders them
const attributes = renderedAttributes(props);
for (const { virtual, dom } of ATTRIBUTE_CHECKS) {
const isClass = dom === 'class';
if (props[virtual] === undefined && !(isClass && props.class !== undefined)) continue;
// class comes from className, class or both, arrays and objects joined
const expectedValue = isClass
? attributes.get('class') ?? null
: resolveAttributeValue(props[virtual]);
const actualValue = domElement.getAttribute(dom);
// true renders a bare attribute; false and null render none
if (typeof expectedValue === 'boolean' || expectedValue === null || expectedValue === undefined) {
const expectedPresent = expectedValue === true;
const actualPresent = actualValue !== null && actualValue !== undefined;
if (expectedPresent !== actualPresent) {
mismatches.push({
path: formatPath([...path, `@${dom}`]),
type: 'attribute',
expected: expectedPresent,
actual: actualPresent,
domPath: getDOMPath(domElement)
});
}
continue;
}
const expectedStr = String(expectedValue);
if (expectedStr !== actualValue) {
mismatches.push({
path: formatPath([...path, `@${dom}`]),
type: 'attribute',
expected: expectedStr,
actual: actualValue,
domPath: getDOMPath(domElement)
});
}
}
// Recursively check children
compareChildren(
domElement,
getRenderedChildren(tagName, props),
path,
mismatches,
(i) => `children[${i}]`
);
return mismatches;
}
/**
* Report mismatches to console with detailed information
*
* @param {Array} mismatches - Array of mismatch objects
* @param {Object} options - Reporting options
*/
export function reportMismatches(mismatches, options = {}) {
if (!mismatches || mismatches.length === 0) return;
const { componentName = 'Unknown', strict = false } = options;
const header = `[Coherent.js] Hydration mismatch detected in "${componentName}"!\n` +
`Found ${mismatches.length} difference(s) between server and client:\n`;
const details = mismatches.map((m, i) => {
return `\n${i + 1}. ${m.type} at ${m.path}\n` +
` DOM path: ${m.domPath}\n` +
` Expected: ${JSON.stringify(m.expected)}\n` +
` Actual: ${JSON.stringify(m.actual)}`;
}).join('');
const advice = '\n\nThis usually happens when:\n' +
' - Server renders with different data than client\n' +
' - Using Date.now(), Math.random(), or browser-only APIs during render\n' +
' - Component is not pure (has side effects during render)\n';
console.warn(header + details + advice);
if (strict) {
throw new Error(`Hydration failed: ${mismatches.length} mismatch(es) found. See console for details.`);
}
}
/**
* Get a readable DOM path for debugging
* @private
*/
function getDOMPath(element) {
if (!element || !element.tagName) return '(unknown)';
const parts = [];
let current = element;
while (current && current.tagName) {
let selector = current.tagName.toLowerCase();
if (current.id) {
selector += `#${current.id}`;
} else if (current.className && typeof current.className === 'string') {
const classes = current.className.trim().split(/\s+/).slice(0, 2);
Eif (classes.length > 0 && classes[0]) {
selector += `.${classes.join('.')}`;
}
}
parts.unshift(selector);
current = current.parentElement;
// Limit depth
Iif (parts.length > 5) {
parts.unshift('...');
break;
}
}
return parts.join(' > ');
}
/**
* Describe a rendered child (see getRenderedChildren) for error messages
* @private
*/
function describeRendered(item) {
Iif (item.type === 'text') {
return `text: "${item.text.trim().substring(0, 50)}"`;
}
Eif (item.type === 'element') {
return `<${Object.keys(item.vNode)[0]}>`;
}
return 'raw content';
}
/**
* Describe a DOM node for error messages
* @private
*/
function describeNode(node) {
Iif (!node) return '(null)';
Iif (node.nodeType === 3) { // Text node
return `text: "${(node.textContent || '').substring(0, 50)}"`;
}
Eif (node.nodeType === 1) { // Element
return `<${node.tagName.toLowerCase()}>`;
}
return `node(type=${node.nodeType})`;
}
|