// Ported from jev-ultrafast (MIT): jev_ultrafast/snapshot.js. // Atomic single-evaluate observation of one frame's controls, viewport text, and a freshness fingerprint. // Adapted to fastbrowse's Control shape (role + operation set, not per-kind actions) and to traverse // open shadow roots. Runs once per frame session (main frame or an OOPIF); the Python side merges frames. // biome-ignore format: Python appends mode arguments to this parenthesized expression. ((mode, allowedOrigins = null) => { const granted = doc => { if (allowedOrigins === null) return true; const frame = doc.defaultView.frameElement; if (frame) { if (frame.hasAttribute('srcdoc') || !frame.getAttribute('src')) return false; const source = new URL(frame.src); if (!['http:', 'https:'].includes(source.protocol) || !allowedOrigins.includes(source.origin)) return false; } const url = new URL(doc.URL); return ['http:', 'https:'].includes(url.protocol) && allowedOrigins.includes(url.origin); }; // Form context is repeated for each submit-capable input in safety prompts. const FORM_TEXT_CHARS = 2000; // Freshness guards bound comparison work on large cards; this text is never sent to a model. const GUARD_TEXT_CHARS = 6000; // Twin controls repeat their card heading, so keep its excerpt shorter than the control itself. const CONTROL_CONTEXT_CHARS = 120; // A hover target can be a whole card whose text would crowd out the other controls. const HOVER_LABEL_CHARS = 200; // Each hover rule fans out to DOM queries, so bound stylesheet work per observation. const MAX_HOVER_RULES = 200; // Hover targets supplement the actionable controls rather than fill their observation budget. const MAX_HOVER_TARGETS = 40; // Each candidate checks hidden descendants, which can stall a dense page's observation. const MAX_HOVER_CHECKS = 400; const excerpt = (text, cap) => text.length <= cap ? text : `${text.slice(0, cap)} [${text.length - cap} characters omitted]`; // A transparent native checkbox is the one control TodoMVC shows, so only its own opacity is excused: a // transparent ancestor still hides it. Walked by style, not layout box, as a `display: contents` parent // generates no box yet hides nothing. const nativeChoice = e => e.tagName === 'INPUT' && ['checkbox', 'radio'].includes(e.type); const shownThrough = e => { for (let a = e.parentElement ?? e.getRootNode().host; a; a = a.parentElement ?? a.getRootNode().host) if (a.ownerDocument.defaultView.getComputedStyle(a).opacity === '0') return false; return true; }; const registry = (window.__fastbrowse ||= { ids: new WeakMap(), nodes: new Map(), next: 1 }); // Keep the page's own timer overrides from holding a browser-side frame wait open. registry.nativeSetTimeout ||= window.setTimeout.bind(window); registry.nativeClearTimeout ||= window.clearTimeout.bind(window); registry.nativeRequestAnimationFrame ||= window.requestAnimationFrame.bind(window); // What was offered to be acted on; `ids` also names hover targets and fingerprinted nodes. registry.controls ||= new WeakSet(); // A visible loading indicator means the page is still fetching what it will draw, which network idle and a // quiet DOM both report as settled: a spinner mutates nothing while it spins. Named classes are a heuristic // and deliberately so -- the wait on them is bounded and expires into proceeding, so a false match costs // time and never correctness. Hidden indicators are ignored because most pages keep one in the DOM always. const LOADING = '[aria-busy="true"],[role="progressbar"],progress:not([value]),' + ['spinner', 'loading', 'loader', 'skeleton', 'shimmer'] .flatMap(name => [`[class*="${name}" i]`, `[id*="${name}" i]`]) .join(','); // Only an indicator on screen is waited on. GitHub keeps an empty fixed progress bar and lazy skeletons below // the fold, which load only once scrolled to: waiting on them spent the full wait on every GitHub page. const showing = e => { if (!e.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) return false; const r = e.getBoundingClientRect(); const view = e.ownerDocument.defaultView || window; return ( r.width > 0 && r.height > 0 && r.bottom > 0 && r.right > 0 && r.top < view.innerHeight && r.left < view.innerWidth ); }; if (!registry.track) { const roots = new WeakSet(); const changed = () => { registry.lastMutation = performance.now(); }; const observer = new MutationObserver(changed); registry.track = root => { if (roots.has(root)) return; roots.add(root); observer.observe(root, { subtree: true, childList: true, characterData: true, attributes: true }); // Input handlers can defer a navigation or redraw without mutating yet. Start the quiet clock at the // event, so the reply's travel time counts toward settling even when the action changes nothing. for (const event of [ 'input', 'change', 'scroll', 'wheel', 'pointermove', 'pointerdown', 'pointerup', 'keydown', 'keyup', ]) root.addEventListener(event, changed, true); changed(); }; registry.track(document); } if (mode === 'fingerprint') { let hash = 2166136261; let loading = false; const hashText = text => { for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 16777619); }; const include = root => { registry.track(root); loading ||= [...root.querySelectorAll(LOADING)].some(showing); const text = root.body?.innerText ?? root.textContent ?? ''; hashText(text); // innerText omits shadow trees and child documents even when their content is visible. for (const e of root.querySelectorAll('*')) { // A filter can change only its checkmark, so text alone reported "Nonstop only" as a no-op. // Field values stay out: the run judges fills by the value it wrote, even when a popup changes. // Only rendered controls: a hidden carousel's aria-selected dots churn on their own and would read as // progress. if ( ('checked' in e || 'selected' in e || e.hasAttribute('aria-checked') || e.hasAttribute('aria-selected')) && e.checkVisibility({ checkOpacity: !nativeChoice(e), checkVisibilityCSS: true }) && (!nativeChoice(e) || shownThrough(e)) ) hashText( JSON.stringify([ e.checked ?? null, e.selected ?? null, e.getAttribute('aria-checked'), e.getAttribute('aria-selected'), ]), ); if (e.shadowRoot) include(e.shadowRoot); if (e.tagName === 'IFRAME' || e.tagName === 'FRAME') { let inner = null; try { inner = e.contentDocument; } catch { inner = null; } if (inner?.body && granted(inner)) include(inner); } } }; include(document); return { fingerprint: location.href + '|' + document.title + '|' + (hash >>> 0) + '|' + scrollY, ready: document.readyState === 'interactive' || document.readyState === 'complete', quietFor: performance.now() - registry.lastMutation, hidden: document.hidden, loading, }; } if (!document.body) return null; const identity = e => { if (!registry.ids.has(e)) registry.ids.set(e, registry.next++); const id = registry.ids.get(e); registry.nodes.set(id, e); return id; }; for (const [id, e] of registry.nodes) if (!e.isConnected) registry.nodes.delete(id); const safe = e => e.type !== 'hidden'; // Password and agent-typed secret values never leave the page: only their length is observed. const secret = e => e.type === 'password' || e.dataset?.fastbrowseSecret === '1'; const reveal = e => (typeof e.value !== 'string' ? null : secret(e) ? '•'.repeat(e.value.length) : e.value); const visible = e => { // Todo lists paint the checkmark beside a transparent native input without associating a label. // The input still receives clicks; opacity alone must not remove the only control for that row. // A transparent input with a visible label of its own keeps the label as its click target: TodoMVC's // "Mark all as complete" input is 1px and off screen, and only its label can be clicked. const choice = nativeChoice(e) && e.ownerDocument.defaultView.getComputedStyle(e).pointerEvents !== 'none' && ![...(e.labels || [])].some(l => l.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })); if ( e.closest('[aria-hidden="true"],[inert]') || !e.checkVisibility({ checkOpacity: !choice, checkVisibilityCSS: true }) || (choice && !shownThrough(e)) ) return false; if (!choice) return true; const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0 && !e.matches(':disabled') && !e.closest('[aria-disabled="true"]'); }; registry.visible = visible; // Styled checkboxes and radios often hide the native input. Its visible label is the click // target, but the input still owns the checked/disabled state and must participate in freshness. const sourceOf = e => (e.tagName === 'LABEL' && ['checkbox', 'radio', 'file'].includes(e.control?.type) ? e.control : e); // Their text is code, not a name: Amazon nests a