// --- browser-bundle/15-snapshot.js --- // The page snapshot producer and the live-page IO the rules cannot do from // a snapshot. Pure measurement: what the probe in 10-probe.js reads on // demand, this reads once and serializes, so the WASM core can run where // the page's Content-Security-Policy keeps WebAssembly out (the extension's // offscreen document; see crates/core/src/browser/snapshot.rs for the // consumer and the field contract). Nothing in here decides anything about // a design: no thresholds, no rule names, no snippet strings. // // Exposed as `__impeccableSnapshot`: // capture(options) -> { json, elements, stats } | { error } // answer(needs, elements) -> facts for the core (`hitTests` -> `hits`) // idOf(el, elements) -> the element's snapshot id (0 when absent) // visualIO(elements) -> the IO half of the visual-contrast pass // (image loads, canvas pixel reads) over live // Elements, keyed by snapshot id // STYLE_PROPS / PSEUDO_PROPS / STATE_PSEUDOS (the capture contract) // Computed-style properties the rules read. Mirrors STYLE_PROPS in // crates/core/src/browser/snapshot.rs (cargo xtask bundle checks the two // lists agree). const __SNAP_STYLE_PROPS = [ "animationIterationCount", "animationName", "animationTimingFunction", "backdropFilter", "background", "backgroundClip", "backgroundColor", "backgroundImage", "backgroundPosition", "backgroundSize", "blockSize", "borderBottomColor", "borderBottomWidth", "borderBottomStyle", "borderLeftColor", "borderLeftWidth", "borderLeftStyle", "borderRadius", "borderRightColor", "borderRightWidth", "borderRightStyle", "borderTopColor", "borderTopWidth", "borderTopStyle", "bottom", "boxShadow", "clip", "clip-path", "clipPath", "color", "content", "contentVisibility", "cssFloat", "display", "filter", "float", "fontFamily", "fontSize", "fontStyle", "fontVariant", "fontVariantCaps", "fontWeight", "height", "hyphens", "inlineSize", "inset", "insetBlock", "insetBlockEnd", "insetBlockStart", "insetInline", "insetInlineEnd", "insetInlineStart", "left", "letterSpacing", "lineHeight", "marginBottom", "marginLeft", "marginRight", "marginTop", "maxHeight", "maxWidth", "minHeight", "minWidth", "mixBlendMode", "objectFit", "objectPosition", "opacity", "outline", "outlineColor", "outlineOffset", "outlineStyle", "outlineWidth", "overflow", "overflowX", "overflowY", "paddingBottom", "paddingLeft", "paddingRight", "paddingTop", "pointerEvents", "position", "right", "textAlign", "textDecoration", "textDecorationLine", "textIndent", "textOverflow", "textShadow", "textTransform", "top", "transform", "transitionDuration", "transitionProperty", "transitionTimingFunction", "verticalAlign", "visibility", "webkitBackgroundClip", "webkitClipPath", "webkitHyphens", "webkitTextFillColor", "whiteSpace", "width", "wordBreak", "zIndex", ]; // `::before` / `::after` properties, recorded where `content` is set. const __SNAP_PSEUDO_PROPS = [ "content", "position", "opacity", "display", "width", "height", "top", "right", "bottom", "left", "backgroundColor", "backgroundImage", "background", "borderRadius", "transform", "visibility", ]; // Pseudo-class states recorded per element (`el.matches(':name')`), so the // snapshot selector engine can answer `:checked` / `:disabled` / ... the way // the live DOM would. Mirrors STATE_PSEUDOS in crates/core/src/browser/selector.rs. const __SNAP_STATE_PSEUDOS = [ "hover", "active", "focus", "focus-within", "focus-visible", "target", "target-within", "checked", "indeterminate", "disabled", "required", "invalid", "user-invalid", "user-valid", "in-range", "out-of-range", "placeholder-shown", "default", "open", "autofill", "-webkit-autofill", "popover-open", "modal", "fullscreen", "-webkit-full-screen", "picture-in-picture", "playing", "buffering", "seeking", "muted", "volume-locked", ]; const __SNAP_NS = { "http://www.w3.org/1999/xhtml": 0, "http://www.w3.org/2000/svg": 1, "http://www.w3.org/1998/Math/MathML": 2 }; const __SNAP_DEFAULT_MAX_ELEMENTS = 30000; const __SNAP_DEFAULT_MAX_BYTES = 48 * 1024 * 1024; function __snapRect4(r) { return [r.x, r.y, r.width, r.height]; } function __snapNum(v) { return typeof v === 'number' ? v : null; } // getDirectTextRect(el): union of the client rects of the element's // non-blank direct text nodes (same measure as 10-probe.js). function __snapDirectTextRect(node) { const rects = []; for (const child of node.childNodes) { if (child.nodeType !== 3 || !(child.textContent || '').trim()) continue; const range = document.createRange(); range.selectNodeContents(child); for (const rect of range.getClientRects()) { if (rect.width >= 1 && rect.height >= 1) rects.push(rect); } range.detach?.(); } if (rects.length === 0) return null; const left = Math.min(...rects.map(r => r.left)); const top = Math.min(...rects.map(r => r.top)); const right = Math.max(...rects.map(r => r.right)); const bottom = Math.max(...rects.map(r => r.bottom)); return [left, top, right - left, bottom - top]; } // ─── Linked stylesheet corpus (JS: injected/index.mjs #709) ──────────────── // JS: injected/index.mjs#pseudoElementHostSelector function __snapPseudoElementHostSelector(selector) { const raw = String(selector || ''); const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']); const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || ''); const consumeFunction = (start) => { let depth = 0; let quote = ''; for (let i = start; i < raw.length; i += 1) { const char = raw[i]; if (char === '\\') { i += 1; continue; } if (quote) { if (char === quote) quote = ''; continue; } if (char === '"' || char === "'") { quote = char; continue; } if (char === '(') depth += 1; if (char === ')' && --depth === 0) return i + 1; } return raw.length; }; let output = ''; let found = false; for (let i = 0; i < raw.length;) { const char = raw[i]; if (char === '\\') { output += raw.slice(i, Math.min(raw.length, i + 2)); i += 2; continue; } if (char === '"' || char === "'") { const quote = char; const start = i; i += 1; while (i < raw.length) { if (raw[i] === '\\') { i += 2; continue; } const value = raw[i]; i += 1; if (value === quote) break; } output += raw.slice(start, i); continue; } if (char !== ':') { output += char; i += 1; continue; } let end = i + 1; let isPseudoElement = false; if (raw[end] === ':') { end += 1; const nameStart = end; while (isNameChar(raw[end])) end += 1; isPseudoElement = end > nameStart; } else { const nameStart = end; while (isNameChar(raw[end])) end += 1; isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase()); } if (!isPseudoElement) { output += char; i += 1; continue; } if (raw[end] === '(') end = consumeFunction(end); found = true; if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*'; i = end; } if (!found) return null; return output.trim().replace(/,\s*(?=,|$)/g, ''); } // JS: injected/index.mjs#selectorNodesForLiveDom function __snapSelectorNodesForLiveDom(root, selector) { const raw = String(selector || '').trim(); if (!raw) return null; const fallback = __snapPseudoElementHostSelector(raw); if (fallback == null) { // An empty result from a valid full selector is authoritative. In // particular, do not broaden inactive :hover/:focus/:not() rules to // their host element by stripping pseudo-classes. try { return Array.from(root.querySelectorAll(raw)); } catch { return null; } } // Resolve pseudo-elements to their originating live elements. An attached // pseudo-element (`.card::before`) belongs to the element before it, while // a hostless pseudo-element after a combinator (`main > ::before`) belongs // to a matching element at that position (`main > *`). if (!fallback || /^[,\s]*$/.test(fallback)) return null; try { return Array.from(root.querySelectorAll(fallback)); } catch { return null; } } let __snapContainerProbeSequence = 0; function __snapIsContainerCssRule(rule) { return rule?.constructor?.name === 'CSSContainerRule' || /^\s*@container\b/i.test(rule?.cssText || ''); } function __snapStyleRuleAppliesToLiveMatches(rule, matches) { const style = rule?.style; if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false; const sequence = ++__snapContainerProbeSequence; const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`; const value = `impeccable-container-active-${sequence}`; const previousValue = style.getPropertyValue(property); const previousPriority = style.getPropertyPriority(property); try { style.setProperty(property, value, 'important'); } catch { return false; } const pseudoElements = [...new Set( String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [], )]; try { return matches.some(el => [null, ...pseudoElements].some(pseudo => { try { const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el); return computed.getPropertyValue(property).trim() === value; } catch { return false; } })); } finally { if (previousValue) style.setProperty(property, previousValue, previousPriority); else style.removeProperty(property); } } function __snapConditionalCssRuleIsActive(rule) { const type = Number(rule?.type); const constructorName = rule?.constructor?.name || ''; if (constructorName === 'CSSMediaRule' || type === 4) { const condition = rule.conditionText || rule.media?.mediaText || ''; if (!condition || typeof window.matchMedia !== 'function') return true; try { return window.matchMedia(condition).matches; } catch { return true; } } if (constructorName === 'CSSSupportsRule' || type === 12) { const condition = rule.conditionText || ''; if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true; try { return CSS.supports(condition); } catch { return true; } } return true; } function __snapSplitCssCommaList(value) { const parts = []; let current = ''; let quote = ''; let escaped = false; for (const char of String(value || '')) { if (escaped) { current += char; escaped = false; continue; } if (char === '\\') { current += char; escaped = true; continue; } if (quote) { current += char; if (char === quote) quote = ''; continue; } if (char === '"' || char === "'") { quote = char; current += char; continue; } if (char === ',') { parts.push(current); current = ''; continue; } current += char; } parts.push(current); return parts; } function __snapNormalizeAnimationName(value) { const name = String(value || '').trim(); if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) { return name.slice(1, -1); } return name; } function __snapAnimationNamesDeclaredByRule(rule) { const style = rule?.style; if (!style) return []; let value = ''; try { value = style.animationName || style.getPropertyValue?.('animation-name') || style.webkitAnimationName || style.getPropertyValue?.('-webkit-animation-name') || ''; } catch { return []; } return __snapSplitCssCommaList(value) .map(__snapNormalizeAnimationName) .filter(name => name && name.toLowerCase() !== 'none'); } function __snapKeyframesRuleName(rule, cssText) { const constructorName = rule?.constructor?.name || ''; const type = Number(rule?.type); const isKeyframes = constructorName === 'CSSKeyframesRule' || constructorName === 'WebKitCSSKeyframesRule' || type === 7 || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText); if (!isKeyframes) return ''; const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i); return __snapNormalizeAnimationName(rule?.name || match?.[1] || ''); } function __snapCssPropertyName(property) { if (property.startsWith('--')) return property; return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`); } function __snapResolvedAnimationKeyframes(candidateNames) { if (typeof document.getAnimations !== 'function') return null; let animations; try { animations = document.getAnimations(); } catch { return null; } const resolved = new Map(); const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']); for (const animation of animations) { const name = __snapNormalizeAnimationName(animation?.animationName || ''); if (!name || !candidateNames.has(name) || resolved.has(name)) continue; let frames; try { frames = animation.effect?.getKeyframes?.() || []; } catch { continue; } const blocks = []; for (const frame of frames) { const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset; if (!Number.isFinite(rawOffset)) continue; const offset = Math.round(rawOffset * 1000000) / 10000; const declarations = Object.entries(frame) .filter(([property, value]) => !metadata.has(property) && value != null && value !== '') .map(([property, value]) => `${__snapCssPropertyName(property)}: ${value};`); const easing = String(frame.easing || '').trim(); if (easing && easing.toLowerCase() !== 'linear') { declarations.push(`animation-timing-function: ${easing};`); } if (declarations.length === 0) continue; blocks.push(`${offset}% { ${declarations.join(' ')} }`); } if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`); } return resolved; } // Read CSS that is absent from document.outerHTML. Inline