The headless browser for AI agents and web scraping
Batch rendering observers and browser tasks
SGavrl02ee089132e9
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 03cef9ca..2da8ef89 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -51,6 +51,7 @@'Text', 'Comment', 'CDATASection', 'ProcessingInstruction', 'CharacterData','CSSStyleDeclaration', 'DOMTokenList', 'NamedNodeMap', 'Screen', 'NetworkInformation','MessageChannel', 'MessagePort', 'BroadcastChannel', 'CustomElementRegistry',+ 'Scheduler','XMLHttpRequestEventTarget', 'HTMLMediaElement', 'HTMLVideoElement','HTMLAudioElement', 'WebGL2RenderingContext','SVGElement', 'SVGGraphicsElement', 'SVGGeometryElement', 'SVGPathElement',@@ -867,6 +868,206 @@ globalThis.cancelAnimationFrame = (id) => {};globalThis.queueMicrotask = globalThis.queueMicrotask || ((fn) => Promise.resolve().then(fn));+// Prioritized Task Scheduling. A scheduler task is a real event-loop task,+// ordered strictly by effective priority and FIFO within one priority. Yield+// continuations rank immediately above ordinary tasks of the same priority.+// This keeps background prefetch work behind visible hydration while still+// giving every callback its own microtask checkpoint.+const _schedulerConstructionKey = {};+const _schedulerInstances = new WeakSet();+const _schedulerPriorityRank = {+ "background": 0,+ "user-visible": 1,+ "user-blocking": 2,+};+const _schedulerTaskQueues = Array.from({ length: 6 }, () => []);+let _schedulerPumpScheduled = false;+let _schedulerCurrentState = null;++function _schedulerRemoveAbort(task) {+ if (task.signal && task.abortHandler) {+ task.signal.removeEventListener("abort", task.abortHandler);+ task.abortHandler = null;+ }+}++function _schedulerSchedulePump() {+ if (_schedulerPumpScheduled) return;+ _schedulerPumpScheduled = true;+ _scheduleAfter(0, _schedulerRunOneTask);+}++function _schedulerEnqueue(task, continuation) {+ if (task.canceled) return;+ const effectivePriority = _schedulerPriorityRank[task.priority] * 2+ + (continuation ? 1 : 0);+ _schedulerTaskQueues[effectivePriority].push(task);+ _schedulerSchedulePump();+}++function _schedulerRunOneTask() {+ _schedulerPumpScheduled = false;+ let task = null;+ for (let priority = _schedulerTaskQueues.length - 1; priority >= 0; priority--) {+ const queue = _schedulerTaskQueues[priority];+ while (queue.length) {+ const candidate = queue.shift();+ if (!candidate.canceled) {+ task = candidate;+ break;+ }+ }+ if (task) break;+ }+ if (!task) return;++ task.started = true;+ const previousState = _schedulerCurrentState;+ _schedulerCurrentState = task.state;+ try {+ if (task.callback === null) {+ task.resolve(undefined);+ } else {+ const callback = task.callback;+ task.resolve(callback());+ }+ } catch (error) {+ task.reject(error);+ } finally {+ _schedulerCurrentState = previousState;+ task.completed = true;+ _schedulerRemoveAbort(task);+ }++ // Queue only one native task at a time. This preserves a microtask+ // checkpoint between scheduler callbacks and lets newly posted high-priority+ // work overtake lower-priority work which is still waiting.+ if (_schedulerTaskQueues.some(queue => queue.length)) _schedulerSchedulePump();+}++function _schedulerNormalizeOptions(options) {+ const dictionary = options == null ? {} : Object(options);++ let delay = 0;+ const rawDelay = dictionary.delay;+ if (rawDelay !== undefined) {+ if (typeof rawDelay === "bigint") {+ throw new TypeError("Failed to read the 'delay' property from 'SchedulerPostTaskOptions': Value is not of type 'unsigned long long'.");+ }+ delay = Number(rawDelay);+ if (!Number.isFinite(delay) || delay < 0 || delay >= 18446744073709551616) {+ throw new TypeError("Failed to read the 'delay' property from 'SchedulerPostTaskOptions': Value is outside the 'unsigned long long' value range.");+ }+ delay = Math.trunc(delay);+ }++ let priority = "user-visible";+ const rawPriority = dictionary.priority;+ if (rawPriority !== undefined) {+ priority = String(rawPriority);+ if (!Object.prototype.hasOwnProperty.call(_schedulerPriorityRank, priority)) {+ throw new TypeError("The provided value '" + priority + "' is not a valid enum value of type TaskPriority.");+ }+ }++ const signal = dictionary.signal;+ if (signal !== undefined && !(signal instanceof globalThis.AbortSignal)) {+ throw new TypeError("Failed to read the 'signal' property from 'SchedulerPostTaskOptions': Failed to convert value to 'AbortSignal'.");+ }+ return { delay, priority, signal: signal === undefined ? null : signal };+}++function _schedulerCreateTask(callback, state, resolve, reject) {+ const task = {+ callback, state, resolve, reject,+ priority: state.priority,+ signal: state.signal,+ abortHandler: null,+ delayTimerId: null,+ canceled: false,+ started: false,+ completed: false,+ };+ if (task.signal) {+ task.abortHandler = () => {+ if (task.completed || task.canceled) return;+ task.canceled = true;+ if (task.delayTimerId !== null) clearTimeout(task.delayTimerId);+ _schedulerRemoveAbort(task);+ reject(task.signal.reason);+ };+ task.signal.addEventListener("abort", task.abortHandler);+ }+ return task;+}++globalThis.Scheduler = class Scheduler {+ constructor(key) {+ if (key !== _schedulerConstructionKey) {+ throw new TypeError("Failed to construct 'Scheduler': Illegal constructor");+ }+ _schedulerInstances.add(this);+ }++ postTask(callback, options = {}) {+ return new Promise((resolve, reject) => {+ if (!_schedulerInstances.has(this)) throw new TypeError("Illegal invocation");+ if (typeof callback !== "function") {+ throw new TypeError("Failed to execute 'postTask' on 'Scheduler': parameter 1 is not of type 'Function'.");+ }+ const normalized = _schedulerNormalizeOptions(options);+ if (normalized.signal && normalized.signal.aborted) {+ reject(normalized.signal.reason);+ return;+ }+ const state = { priority: normalized.priority, signal: normalized.signal };+ const task = _schedulerCreateTask(callback, state, resolve, reject);+ if (normalized.delay > 0) {+ task.delayTimerId = setTimeout(() => {+ task.delayTimerId = null;+ _schedulerEnqueue(task, false);+ }, normalized.delay);+ } else {+ _schedulerEnqueue(task, false);+ }+ });+ }++ yield() {+ return new Promise((resolve, reject) => {+ if (!_schedulerInstances.has(this)) throw new TypeError("Illegal invocation");+ const inherited = _schedulerCurrentState;+ const state = inherited+ ? { priority: inherited.priority, signal: inherited.signal }+ : { priority: "user-visible", signal: null };+ if (state.signal && state.signal.aborted) {+ reject(state.signal.reason);+ return;+ }+ _schedulerEnqueue(_schedulerCreateTask(null, state, resolve, reject), true);+ });+ }+};+Object.defineProperty(globalThis.Scheduler.prototype, Symbol.toStringTag, {+ value: "Scheduler",+ configurable: true,+});+_markNative(globalThis.Scheduler);+_markNative(globalThis.Scheduler.prototype.postTask);+_markNative(globalThis.Scheduler.prototype.yield);++const _defaultScheduler = new globalThis.Scheduler(_schedulerConstructionKey);+Object.defineProperty(globalThis, "scheduler", {+ get() { return _defaultScheduler; },+ set(value) {+ Object.defineProperty(globalThis, "scheduler", {+ value, writable: true, enumerable: true, configurable: true,+ });+ },+ enumerable: true,+ configurable: true,+});+// MessagePort is a task-backed EventTarget, not a pair of callback slots.// React currently uses `onmessage`, while Angular/Zone.js and worker-style// schedulers commonly use addEventListener + start and inspect the prototype.@@ -6500,7 +6701,12 @@ function _scheduleResizeRenderCheckpoint() {}if (_resizeRenderCheckpointPending) return;_resizeRenderCheckpointPending = true;- _scheduleAfter(0, () => {+ // Resize observations are gathered at a rendering opportunity, not once+ // for every zero-delay task which happens to mutate the DOM. A frame-sized+ // one-shot coalesces framework microtasks/timers without installing a+ // perpetual frame pump; the callback still runs promptly when the embedder+ // explicitly drives the event loop.+ _scheduleAfter(_RAF_FRAME_DELAY_MS, () => {_resizeRenderCheckpointPending = false;_resizeRenderCheckpointRunning = true;let depth = 0;@@ -6510,11 +6716,20 @@ function _scheduleResizeRenderCheckpoint() {// that manufacture an ever-deeper subtree during one delivery cycle.for (let iteration = 0; iteration < 64; iteration++) {_resizeRenderCheckpointRerun = false;- const measurements = new Map();+ const observers = [...globalThis.__resizeObservers];+ const targets = [];+ const seenTargets = new Set();+ for (const observer of observers) {+ for (const target of observer._targets.keys()) {+ if (seenTargets.has(target)) continue;+ seenTargets.add(target);+ targets.push(target);+ }+ }+ const measurements = _roMeasurements(targets);let shallowest = Infinity;let active = false;skipped = false;- const observers = [...globalThis.__resizeObservers];// Gather every observer before invoking any callback. A callback from an// earlier observer must not change the geometry gathered for a later one.for (const observer of observers) {@@ -6558,10 +6773,10 @@ function _roNodeDepth(target) {while (node && (node = node.parentNode || node.host || null)) depth++;return depth;}-function _roMeasurement(target) {- let geometry = null;+function _roMeasurement(target, suppliedGeometry, suppliedByBatch = false) {+ let geometry = suppliedGeometry ?? null;const hasRenderer = typeof Deno.core.ops.op_layout_geometry === "function";- if (hasRenderer && target?._nid != null) {+ if (!suppliedByBatch && hasRenderer && target?._nid != null) {try {const raw = Deno.core.ops.op_layout_geometry(String(target._nid | 0));geometry = raw ? JSON.parse(raw) : null;@@ -6571,7 +6786,7 @@ function _roMeasurement(target) {// Preserve deterministic geometry in non-render builds. This path has no// native layout cache, but lifecycle behavior (initial delivery and// change-only rechecks) should remain useful to automation consumers.- if (!hasRenderer && target?.getBoundingClientRect) {+ if (!suppliedByBatch && !hasRenderer && target?.getBoundingClientRect) {const rect = target.getBoundingClientRect();geometry = {x: rect.x, y: rect.y,@@ -6592,7 +6807,18 @@ function _roMeasurement(target) {};}- const style = getComputedStyle(target);+ // The bulk native measurement includes this small style subset from the+ // same PreparedRender as geometry. Non-render builds retain the CSSOM+ // fallback, and a missing/invalid bulk result falls back above.+ const style = suppliedByBatch+ ? {+ ...geometry,+ // `writing-mode` is not yet part of the renderer's compact computed+ // snapshot. Preserve the existing CSSOM fallback for an authored+ // inline value so batching does not silently swap inline/block axes.+ writingMode: geometry.writingMode || target?.style?.writingMode || "",+ }+ : getComputedStyle(target);const paddingTop = _roNumber(style.paddingTop);const paddingRight = _roNumber(style.paddingRight);const paddingBottom = _roNumber(style.paddingBottom);@@ -6647,6 +6873,32 @@ function _roMeasurement(target) {};}+function _roMeasurements(targets) {+ const measurements = new Map();+ if (!targets.length) return measurements;+ const bulk = Deno.core.ops.op_resize_observer_measurements;+ if (typeof bulk === "function"+ && targets.every(target => target?._nid != null)) {+ try {+ const raw = bulk(JSON.stringify(targets.map(target => target._nid | 0)));+ const geometries = raw ? JSON.parse(raw) : null;+ if (Array.isArray(geometries) && geometries.length === targets.length) {+ for (let index = 0; index < targets.length; index++) {+ measurements.set(+ targets[index],+ _roMeasurement(targets[index], geometries[index], true),+ );+ }+ return measurements;+ }+ } catch (_error) {}+ }+ for (const target of targets) {+ measurements.set(target, _roMeasurement(target));+ }+ return measurements;+}+const _roConstructionKey = {};const _roSizeValues = new WeakMap();globalThis.ResizeObserverSize = class ResizeObserverSize {@@ -7575,9 +7827,8 @@ globalThis.NodeFilter = {// ResizeObserver is defined earlier with real per-target firing; the stub// that previously lived here was a no-op that clobbered the real class.//-// Viewport IntersectionObserver. Render builds provide real, scroll-relative-// target boxes through getBoundingClientRect. Element scroll-container roots-// remain intentionally unsupported until their offsets participate in layout.+// IntersectionObserver. Render builds provide real, scroll-relative target,+// element-root, and overflow-ancestor boxes from one prepared layout snapshot.globalThis.__intersectionObservers = [];let _intersectionRenderCheckpointPending = false;function _scheduleIntersectionRenderCheckpoint() {@@ -7585,13 +7836,41 @@ function _scheduleIntersectionRenderCheckpoint() {_intersectionRenderCheckpointPending = true;// Intersection observation is part of the browser's rendering update, not// a synchronous side effect of observe() or a DOM mutation. One queued task- // coalesces every observer/target and therefore performs at most one layout- // flush for the checkpoint.- _scheduleAfter(0, () => {+ // coalesces every observer/target and therefore performs one bulk layout+ // read for the checkpoint without installing a perpetual frame pump.+ _scheduleAfter(_RAF_FRAME_DELAY_MS, () => {_intersectionRenderCheckpointPending = false;- for (const observer of globalThis.__intersectionObservers) {+ const observers = globalThis.__intersectionObservers.filter(+ observer => observer._connected && observer._targets.size,+ );+ const elements = [];+ const seen = new Set();+ const addElement = element => {+ if (!(element instanceof Element) || seen.has(element)) return;+ seen.add(element);+ elements.push(element);+ };++ // Gather the complete clip graph before entering native code. DOM/shadow+ // ancestry stays in JS, while every geometry/style value comes from the+ // same animation sample and PreparedRender snapshot.+ for (const observer of observers) {+ for (const target of observer._targets) addElement(target);+ }+ for (const observer of observers) {+ if (observer._root instanceof Element) addElement(observer._root);+ for (const target of observer._targets) {+ let ancestor = target.parentNode || target.host || null;+ while (ancestor && ancestor !== observer._root && ancestor.nodeType !== 9) {+ addElement(ancestor);+ ancestor = ancestor.parentNode || ancestor.host || null;+ }+ }+ }+ const measurements = _ioMeasurements(elements);+ for (const observer of observers) {if (observer._connected && observer._targets.size) {- observer._check([...observer._targets], false);+ observer._check([...observer._targets], false, measurements);}}});@@ -7619,15 +7898,53 @@ function _ioMargins(value) {function _ioClipsOverflow(value) {return /^(?:auto|clip|hidden|overlay|scroll)$/.test(String(value || ""));}-function _ioElementPaddingBox(element, style) {- const geometry = element._renderBoxGeometry();- const rect = geometry- ? element._rectFromRenderGeometry(geometry)- : element.getBoundingClientRect();+function _ioMeasurements(elements) {+ const measurements = new Map();+ if (!elements.length) return measurements;+ const bulk = Deno.core.ops.op_intersection_observer_measurements;+ const nativeElements = elements.filter(element => element?._nid != null);+ if (typeof bulk !== "function" || !nativeElements.length) return measurements;+ try {+ const raw = bulk(JSON.stringify(nativeElements.map(element => element._nid | 0)));+ const geometries = raw ? JSON.parse(raw) : null;+ if (Array.isArray(geometries) && geometries.length === nativeElements.length) {+ for (let index = 0; index < nativeElements.length; index++) {+ measurements.set(nativeElements[index], geometries[index]);+ }+ }+ } catch (_error) {}+ return measurements;+}+function _ioElementRect(element, measurements) {+ if (measurements.has(element)) {+ const geometry = measurements.get(element);+ return geometry+ ? _ioRect(+ _roNumber(geometry.x), _roNumber(geometry.y),+ _roNumber(geometry.width), _roNumber(geometry.height),+ )+ : _ioRect(0, 0, 0, 0);+ }+ const rect = element.getBoundingClientRect();+ return _ioRect(rect.x, rect.y, rect.width, rect.height);+}+function _ioElementStyle(element, measurements) {+ return measurements.has(element)+ ? (measurements.get(element) || {})+ : getComputedStyle(element);+}+function _ioElementPaddingBox(element, style, measurements) {+ const hasMeasurement = measurements.has(element);+ const geometry = measurements.get(element);+ const rect = _ioElementRect(element, measurements);const borderLeft = _roNumber(style.borderLeftWidth);const borderTop = _roNumber(style.borderTopWidth);- const width = geometry ? geometry.clientWidth : element.clientWidth;- const height = geometry ? geometry.clientHeight : element.clientHeight;+ const width = hasMeasurement+ ? (geometry ? _roNumber(geometry.clientWidth) : 0)+ : element.clientWidth;+ const height = hasMeasurement+ ? (geometry ? _roNumber(geometry.clientHeight) : 0)+ : element.clientHeight;return _ioRect(rect.left + borderLeft, rect.top + borderTop, width, height);}globalThis.IntersectionObserver = class IntersectionObserver {@@ -7659,16 +7976,16 @@ globalThis.IntersectionObserver = class IntersectionObserver {this._deliveryPending = false;globalThis.__intersectionObservers.push(this);}- _rootBounds() {+ _rootBounds(measurements) {let x = 0, y = 0;let width = globalThis.innerWidth || 1280;let height = globalThis.innerHeight || 720;if (this._root instanceof Element) {- const style = getComputedStyle(this._root);+ const style = _ioElementStyle(this._root, measurements);const clips = _ioClipsOverflow(style.overflowX) ||_ioClipsOverflow(style.overflowY);if (clips) {- const paddingBox = _ioElementPaddingBox(this._root, style);+ const paddingBox = _ioElementPaddingBox(this._root, style, measurements);x = paddingBox.left;y = paddingBox.top;// The intersection root for a content-clipping element is its padding@@ -7676,7 +7993,7 @@ globalThis.IntersectionObserver = class IntersectionObserver {width = paddingBox.width;height = paddingBox.height;} else {- const rect = this._root.getBoundingClientRect();+ const rect = _ioElementRect(this._root, measurements);x = rect.left;y = rect.top;width = rect.width;@@ -7693,9 +8010,15 @@ globalThis.IntersectionObserver = class IntersectionObserver {const left = resolve(this._margins[3], width);return _ioRect(x - left, y - top, width + left + right, height + top + bottom);}- _entry(target, root) {- const rect = target.getBoundingClientRect();- let inRootTree = !(this._root instanceof Element) || this._root.contains(target);+ _entry(target, root, measurements) {+ const rect = _ioElementRect(target, measurements);+ // A connected zero-area box may intersect when its edges touch the root,+ // but a detached or non-generated box must never become intersecting just+ // because its synthetic zero rectangle happens to sit at the origin.+ const hasGeneratedBox = !measurements.has(target) ||+ measurements.get(target) !== null;+ let inRootTree = hasGeneratedBox && target.isConnected &&+ (!(this._root instanceof Element) || this._root.contains(target));let left = Math.max(rect.left, root.left);let top = Math.max(rect.top, root.top);let right = Math.min(rect.right, root.right);@@ -7709,11 +8032,11 @@ globalThis.IntersectionObserver = class IntersectionObserver {let ancestor = target.parentNode || target.host || null;while (inRootTree && ancestor && ancestor !== this._root && ancestor.nodeType !== 9) {if (ancestor instanceof Element) {- const style = getComputedStyle(ancestor);+ const style = _ioElementStyle(ancestor, measurements);const clipX = _ioClipsOverflow(style.overflowX);const clipY = _ioClipsOverflow(style.overflowY);if (clipX || clipY) {- const clip = _ioElementPaddingBox(ancestor, style);+ const clip = _ioElementPaddingBox(ancestor, style, measurements);if (clipX) {left = Math.max(left, clip.left);right = Math.min(right, clip.right);@@ -7749,8 +8072,8 @@ globalThis.IntersectionObserver = class IntersectionObserver {while (index < this._thresholds.length && this._thresholds[index] <= ratio) index++;return index;}- _queueChanged(target, forceInitial, root) {- const entry = this._entry(target, root);+ _queueChanged(target, forceInitial, root, measurements) {+ const entry = this._entry(target, root, measurements);const previous = this._previous.get(target);const changed = forceInitial || !previous ||previous.isIntersecting !== entry.isIntersecting ||@@ -7762,11 +8085,13 @@ globalThis.IntersectionObserver = class IntersectionObserver {});if (changed) this._records.push(entry);}- _check(targets, forceInitial) {+ _check(targets, forceInitial, measurements = new Map()) {if (!this._connected) return;- const root = this._rootBounds();+ const root = this._rootBounds(measurements);for (const target of targets) {- if (this._targets.has(target)) this._queueChanged(target, !!forceInitial, root);+ if (this._targets.has(target)) {+ this._queueChanged(target, !!forceInitial, root, measurements);+ }}if (!this._records.length || this._deliveryPending) return;this._deliveryPending = true;@@ -11190,6 +11515,8 @@ globalThis.Worker = class Worker {setInterval: globalThis.setInterval,clearTimeout: globalThis.clearTimeout,clearInterval: globalThis.clearInterval,+ scheduler: globalThis.scheduler,+ Scheduler: globalThis.Scheduler,fetch: globalThis.fetch,console: globalThis.console,performance: globalThis.performance,diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 55d1c762..a6f6d78e 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -3470,6 +3470,8 @@ pub fn build_extension() -> Extension {ops.push(op_image_metadata());ops.push(op_load_image_metadata());ops.push(op_layout_geometry());+ ops.push(op_resize_observer_measurements());+ ops.push(op_intersection_observer_measurements());ops.push(op_computed_style());ops.push(op_css_supports());ops.push(op_layout_metrics());@@ -4277,6 +4279,137 @@ fn op_layout_geometry(state: &OpState, #[string] nid_str: String) -> String {String::new()}+/// Measure every target in one ResizeObserver rendering opportunity.+///+/// ResizeObserver gathers all observations before it invokes any callback.+/// Crossing the JS/native boundary once per target defeated that batching:+/// each read sampled the document timeline and could rebuild the retained+/// cascade/layout independently. Accept the complete target list, freeze the+/// animation sample once, prepare/resolve layout once, and return the small+/// computed-style subset needed to derive content/border/device-pixel boxes.+/// The result is index-aligned with the input and contains `null` for targets+/// which currently generate no box (detached, `display:none`, and stale ids).+#[cfg(feature = "render")]+#[op2]+#[string]+fn op_resize_observer_measurements(state: &OpState, #[string] nids_json: String) -> String {+ let nids = serde_json::from_str::<Vec<u32>>(&nids_json).unwrap_or_default();+ if nids.is_empty() {+ return "[]".to_string();+ }++ let shared = state.borrow::<SharedState>().clone();+ let mut gs = shared.borrow_mut();+ sample_live_document_animations(&mut gs);+ if ensure_resolved_scroll(&mut gs).is_none() {+ return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()])+ .unwrap_or_else(|_| "[]".to_string());+ }+ let Some((_, scroll)) = gs.resolved_scroll.as_ref() else {+ return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()])+ .unwrap_or_else(|_| "[]".to_string());+ };+ let Some(prepared) = gs.prepared_render.as_ref() else {+ return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()])+ .unwrap_or_else(|_| "[]".to_string());+ };++ let style_value =+ |snapshot: &std::collections::HashMap<&'static str, String>, name: &'static str| {+ snapshot.get(name).cloned().unwrap_or_default()+ };+ let measurements = nids+ .into_iter()+ .map(|nid| {+ let nid = obscura_dom::tree::NodeId::new(nid);+ let rect = prepared.viewport_rect_with_scroll(nid, scroll)?;+ let (client_width, client_height) = prepared.client_size(nid)?;+ let snapshot = prepared.computed_style(nid)?;+ Some(serde_json::json!({+ "x": rect.x,+ "y": rect.y,+ "clientWidth": client_width,+ "clientHeight": client_height,+ "paddingTop": style_value(&snapshot, "padding-top"),+ "paddingRight": style_value(&snapshot, "padding-right"),+ "paddingBottom": style_value(&snapshot, "padding-bottom"),+ "paddingLeft": style_value(&snapshot, "padding-left"),+ "borderTopWidth": style_value(&snapshot, "border-top-width"),+ "borderRightWidth": style_value(&snapshot, "border-right-width"),+ "borderBottomWidth": style_value(&snapshot, "border-bottom-width"),+ "borderLeftWidth": style_value(&snapshot, "border-left-width"),+ "writingMode": style_value(&snapshot, "writing-mode"),+ "display": style_value(&snapshot, "display"),+ }))+ })+ .collect::<Vec<_>>();+ serde_json::to_string(&measurements).unwrap_or_else(|_| "[]".to_string())+}++/// Measure the complete IntersectionObserver clip graph in one rendering+/// opportunity. The JS side supplies the unique observed targets, element+/// roots, and intervening element ancestors. Sampling animations and preparing+/// layout once here avoids turning each target/ancestor box and style read into+/// a separate retained-layout rebuild.+///+/// Results are index-aligned with the input. A `null` entry means that the node+/// currently generates no layout box (for example, it is detached or hidden).+#[cfg(feature = "render")]+#[op2]+#[string]+fn op_intersection_observer_measurements(+ state: &OpState,+ #[string] nids_json: String,+) -> String {+ let nids = serde_json::from_str::<Vec<u32>>(&nids_json).unwrap_or_default();+ if nids.is_empty() {+ return "[]".to_string();+ }++ let shared = state.borrow::<SharedState>().clone();+ let mut gs = shared.borrow_mut();+ sample_live_document_animations(&mut gs);+ if ensure_resolved_scroll(&mut gs).is_none() {+ return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()])+ .unwrap_or_else(|_| "[]".to_string());+ }+ let Some((_, scroll)) = gs.resolved_scroll.as_ref() else {+ return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()])+ .unwrap_or_else(|_| "[]".to_string());+ };+ let Some(prepared) = gs.prepared_render.as_ref() else {+ return serde_json::to_string(&vec![serde_json::Value::Null; nids.len()])+ .unwrap_or_else(|_| "[]".to_string());+ };++ let style_value =+ |snapshot: &std::collections::HashMap<&'static str, String>, name: &'static str| {+ snapshot.get(name).cloned().unwrap_or_default()+ };+ let measurements = nids+ .into_iter()+ .map(|nid| {+ let nid = obscura_dom::tree::NodeId::new(nid);+ let rect = prepared.viewport_rect_with_scroll(nid, scroll)?;+ let (client_width, client_height) = prepared.client_size(nid)?;+ let snapshot = prepared.computed_style(nid)?;+ Some(serde_json::json!({+ "x": rect.x,+ "y": rect.y,+ "width": rect.width,+ "height": rect.height,+ "clientWidth": client_width,+ "clientHeight": client_height,+ "borderTopWidth": style_value(&snapshot, "border-top-width"),+ "borderLeftWidth": style_value(&snapshot, "border-left-width"),+ "overflowX": style_value(&snapshot, "overflow-x"),+ "overflowY": style_value(&snapshot, "overflow-y"),+ }))+ })+ .collect::<Vec<_>>();+ serde_json::to_string(&measurements).unwrap_or_else(|_| "[]".to_string())+}+/// One renderer-computed CSS snapshot for `getComputedStyle()`. Returning all/// supported properties together keeps a single JS style object to one native/// call and one use of the retained prepared layout.diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 70c84e2e..a1f695cb 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -183,6 +183,12 @@ impl WatchdogToken {}}+// Observation deadlines are checked between browser tasks. A task which has+// already started receives this bounded completion allowance, matching the+// fixed-wait path while retaining an absolute backstop for infinite script.+const SYNCHRONOUS_TASK_FLOOR_MS: u64 = 5_000;+const WATCHDOG_SCHEDULING_MARGIN_MS: u64 = 500;+impl ObscuraJsRuntime {/// Freeze the document timeline for one JavaScript task. Browser timelines/// update at task/rendering boundaries, not on each forced style or layout@@ -1742,7 +1748,6 @@ impl ObscuraJsRuntime {// task boundary. Keep a separate long-task floor so short compositor// slices and explicit waits do not kill legitimate framework work,// while an actually unyielding task remains bounded.- const SYNCHRONOUS_TASK_FLOOR_MS: u64 = 5_000;// One watchdog for the complete pump avoids spawning a native thread// per cooperative task. Adding the floor after the observation budget// guarantees that even a task beginning just before `deadline` gets@@ -1750,7 +1755,8 @@ impl ObscuraJsRuntime {let synchronous_budget = budget.saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS));let token =- self.arm_watchdog(synchronous_budget + std::time::Duration::from_millis(500));+ self.arm_watchdog(synchronous_budget+ + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS));let result = loop {if tokio::time::Instant::now() >= deadline {break Ok(());@@ -1872,7 +1878,11 @@ impl ObscuraJsRuntime {let external_work_deadline = started + external_work_grace;let activity_tail = std::time::Duration::from_millis(OBSERVABLE_ACTIVITY_TAIL_MS);let mut activity_deadline = deadline.min(started + activity_tail);- let token = self.arm_watchdog(budget + std::time::Duration::from_millis(500));+ let token = self.arm_watchdog(+ budget+ .saturating_add(std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS))+ + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),+ );let mut generation = self.activity_generation();let mut quiet_since: Option<tokio::time::Instant> = None;let result = loop {@@ -1927,14 +1937,14 @@ impl ObscuraJsRuntime {// iteration may synchronously drain an arbitrarily long chain of// nextTick/macrotask/microtask callbacks before returning. Tokio's// deadline cannot preempt that native V8 call. Bound the individual- // turn to the readiness horizon plus the same 500ms synchronous- // safety margin used by fixed waits. Reaching this bound means the- // adaptive observation window is exhausted; clear V8 termination- // and capture the current stable frame instead of starting another- // unbounded turn.+ // turn beyond the readiness horizon by the same bounded task+ // allowance as fixed waits. The observation window may expire+ // while valid framework/layout work is running; browser capture+ // waits for that task boundary instead of terminating it midway.let tick_watchdog = self.arm_watchdog(policy_deadline.saturating_duration_since(now)- + std::time::Duration::from_millis(500),+ + std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS)+ + std::time::Duration::from_millis(WATCHDOG_SCHEDULING_MARGIN_MS),);let tick = tokio::time::timeout_at(policy_deadline,@@ -2579,6 +2589,134 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn scheduler_post_task_observes_priority_fifo_and_task_boundaries() {+ let mut rt = setup_runtime("<html><body></body></html>");+ rt.execute_script(+ "scheduler-priority-order",+ r#"+ globalThis.__schedulerOrder = ["sync"];+ const schedule = (name, priority) => scheduler.postTask(() => {+ __schedulerOrder.push(name);+ Promise.resolve().then(() => __schedulerOrder.push(name + "-microtask"));+ return name + "-result";+ }, { priority });+ globalThis.__schedulerResults = Promise.all([+ schedule("background-1", "background"),+ schedule("background-2", "background"),+ schedule("visible", "user-visible"),+ schedule("blocking-1", "user-blocking"),+ schedule("blocking-2", "user-blocking"),+ ]).then(values => { globalThis.__schedulerValues = values; });+ Promise.resolve().then(() => __schedulerOrder.push("initial-microtask"));+ "#,+ )+ .unwrap();++ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("__schedulerOrder").unwrap(),+ serde_json::json!([+ "sync",+ "initial-microtask",+ "blocking-1",+ "blocking-1-microtask",+ "blocking-2",+ "blocking-2-microtask",+ "visible",+ "visible-microtask",+ "background-1",+ "background-1-microtask",+ "background-2",+ "background-2-microtask",+ ])+ );+ assert_eq!(+ rt.evaluate("__schedulerValues").unwrap(),+ serde_json::json!([+ "background-1-result",+ "background-2-result",+ "visible-result",+ "blocking-1-result",+ "blocking-2-result",+ ])+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn scheduler_abort_delay_and_yield_follow_task_state() {+ let mut rt = setup_runtime("<html><body></body></html>");+ rt.execute_script(+ "scheduler-abort-delay-yield",+ r#"+ globalThis.__schedulerState = {+ order: [],+ canceledCallbackRan: false,+ exactAbortReason: false,+ selfAbortCallbackRan: false,+ exactSelfAbortReason: false,+ };+ const abortReason = { reason: "stop" };+ const canceled = new AbortController();+ scheduler.postTask(() => {+ __schedulerState.canceledCallbackRan = true;+ }, { signal: canceled.signal, delay: 20 }).catch(error => {+ __schedulerState.exactAbortReason = error === abortReason;+ });+ canceled.abort(abortReason);++ const selfAbortReason = { reason: "inside callback" };+ const selfCanceled = new AbortController();+ scheduler.postTask(() => {+ __schedulerState.selfAbortCallbackRan = true;+ selfCanceled.abort(selfAbortReason);+ return "ignored result";+ }, { signal: selfCanceled.signal }).catch(error => {+ __schedulerState.exactSelfAbortReason = error === selfAbortReason;+ });++ scheduler.postTask(async () => {+ __schedulerState.order.push("blocking-start");+ await scheduler.yield();+ __schedulerState.order.push("blocking-continuation");+ }, { priority: "user-blocking" });+ scheduler.postTask(() => {+ __schedulerState.order.push("background");+ }, { priority: "background" });+ "#,+ )+ .unwrap();++ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate(+ r#"[+ __schedulerState.order,+ __schedulerState.canceledCallbackRan,+ __schedulerState.exactAbortReason,+ __schedulerState.selfAbortCallbackRan,+ __schedulerState.exactSelfAbortReason,+ scheduler instanceof Scheduler,+ Object.prototype.toString.call(scheduler),+ Scheduler.prototype.postTask.length,+ Scheduler.prototype.yield.length,+ ]"#,+ )+ .unwrap(),+ serde_json::json!([+ ["blocking-start", "blocking-continuation", "background"],+ false,+ true,+ true,+ true,+ true,+ "[object Scheduler]",+ 1,+ 0,+ ])+ );+ }+#[tokio::test(flavor = "current_thread")]async fn self_requeueing_message_channel_yields_to_timers() {let mut rt = setup_runtime("<html><body></body></html>");@@ -4810,6 +4948,37 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn adaptive_observation_deadline_does_not_terminate_the_active_task() {+ let mut rt = setup_runtime("<html><body></body></html>");+ rt.execute_script(+ "adaptive-task-crossing-observation-deadline",+ "globalThis.__adaptiveLongTaskCompleted = false;\+ setTimeout(() => {\+ const end = performance.now() + 600;\+ while (performance.now() < end) {}\+ __adaptiveLongTaskCompleted = true;\+ }, 0);",+ )+ .unwrap();++ let started = std::time::Instant::now();+ rt.run_event_loop_until_quiescent(20, 10).await.unwrap();+ let elapsed = started.elapsed();++ assert!(+ elapsed >= std::time::Duration::from_millis(500)+ && elapsed < std::time::Duration::from_millis(1_500),+ "adaptive settle must wait for the active task boundary: {elapsed:?}",+ );+ assert_eq!(+ rt.evaluate("globalThis.__adaptiveLongTaskCompleted")+ .unwrap(),+ serde_json::json!(true),+ "adaptive readiness must not terminate valid page work",+ );+ }+#[tokio::test(flavor = "current_thread")]async fn quiescent_event_loop_yields_from_continuously_ready_non_visual_work() {let mut rt = setup_runtime("<html><body></body></html>");@@ -4856,8 +5025,12 @@ mod tests {let elapsed = started.elapsed();assert!(- elapsed < std::time::Duration::from_millis(1_200),- "one synchronous callback drain consumed the adaptive budget: {elapsed:?}"+ elapsed >= std::time::Duration::from_millis(SYNCHRONOUS_TASK_FLOOR_MS)+ && elapsed+ < std::time::Duration::from_millis(+ SYNCHRONOUS_TASK_FLOOR_MS + 1_500,+ ),+ "one synchronous callback drain escaped the bounded task allowance: {elapsed:?}");assert_eq!(rt.evaluate(@@ -8455,6 +8628,107 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn resize_observer_batches_unique_targets_into_one_native_layout_read() {+ let dom = parse_html(+ r#"<html style="margin:0"><body style="margin:0">+ <div id="a" style="box-sizing:border-box;width:100px;height:30px;padding:2px 3px;border:1px solid"></div>+ <div id="b" style="box-sizing:border-box;width:110px;height:30px;padding:2px 3px;border:1px solid"></div>+ <div id="c" style="box-sizing:border-box;width:120px;height:30px;padding:2px 3px;border:1px solid"></div>+ <div id="d" style="box-sizing:border-box;width:130px;height:30px;padding:2px 3px;border:1px solid"></div>+ <div id="vertical" style="box-sizing:border-box;width:140px;height:30px;padding:2px 3px;border:1px solid;writing-mode:vertical-rl"></div>+ <div id="hidden" style="display:none;width:50px;height:20px"></div>+ </body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.set_viewport(400.0, 300.0);+ rt.run_page_init();+ rt.execute_script(+ "batch-resize-observer-targets",+ r#"+ globalThis.__resizeBulkCalls = 0;+ globalThis.__resizeBulkSizes = [];+ globalThis.__resizeLegacyGeometryCalls = 0;+ globalThis.__resizeComputedStyleCalls = 0;+ const nativeBulk = Deno.core.ops.op_resize_observer_measurements;+ const nativeGeometry = Deno.core.ops.op_layout_geometry;+ const nativeComputedStyle = Deno.core.ops.op_computed_style;+ Deno.core.ops.op_resize_observer_measurements = input => {+ __resizeBulkCalls++;+ __resizeBulkSizes.push(JSON.parse(input).length);+ return nativeBulk(input);+ };+ Deno.core.ops.op_layout_geometry = (...args) => {+ __resizeLegacyGeometryCalls++;+ return nativeGeometry(...args);+ };+ Deno.core.ops.op_computed_style = (...args) => {+ __resizeComputedStyleCalls++;+ return nativeComputedStyle(...args);+ };++ globalThis.__resizeBatchRecords = [];+ const detached = document.createElement("div");+ detached.id = "detached";+ detached.style.cssText = "width:60px;height:20px";+ const targets = ["a", "b", "c", "d", "vertical", "hidden"]+ .map(id => document.getElementById(id));+ targets.push(detached);+ const observer = new ResizeObserver(entries => {+ __resizeBatchRecords.push(entries.map(entry => [+ entry.target.id,+ entry.contentBoxSize[0].inlineSize,+ entry.contentBoxSize[0].blockSize,+ entry.borderBoxSize[0].inlineSize,+ entry.borderBoxSize[0].blockSize,+ ]));+ });+ for (const target of targets) observer.observe(target);+ // A second observer of an existing target must share the same+ // native measurement rather than adding it to the batch twice.+ globalThis.__duplicateResizeRecords = 0;+ const duplicate = new ResizeObserver(entries => {+ __duplicateResizeRecords += entries.length;+ });+ duplicate.observe(targets[2], { box: "border-box" });+ "#,+ )+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();++ assert_eq!(+ rt.evaluate(+ r#"[+ __resizeBulkCalls,+ __resizeBulkSizes,+ __resizeLegacyGeometryCalls,+ __resizeComputedStyleCalls,+ __duplicateResizeRecords,+ __resizeBatchRecords,+ ]"#,+ )+ .unwrap(),+ serde_json::json!([+ 1,+ [7],+ 0,+ 0,+ 1,+ [[+ ["a", 92, 24, 100, 30],+ ["b", 102, 24, 110, 30],+ ["c", 112, 24, 120, 30],+ ["d", 122, 24, 130, 30],+ ["vertical", 24, 132, 30, 140],+ ["hidden", 0, 0, 0, 0],+ ["detached", 0, 0, 0, 0],+ ]],+ ])+ );+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn resize_observer_selected_box_and_viewport_lifecycle_match_chromium() {@@ -8704,9 +8978,9 @@ mod tests {}}, { threshold: [0, 0.5, 1] });observer.observe(target);- setTimeout(() => window.scrollTo(0, 100), 5);- setTimeout(() => window.scrollTo(0, 260), 15);- setTimeout(() => resolve(records), 30);+ setTimeout(() => window.scrollTo(0, 100), 25);+ setTimeout(() => window.scrollTo(0, 260), 50);+ setTimeout(() => resolve(records), 80);})"#,true,@@ -8720,6 +8994,108 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn intersection_observer_batches_unique_clip_graph_into_one_native_layout_read() {+ let dom = parse_html(+ r#"<html style="margin:0"><body style="margin:0">+ <div id="root" style="width:200px;height:100px;overflow:hidden">+ <div id="clip" style="width:150px;height:80px;overflow:auto">+ <div id="a" style="width:30px;height:20px"></div>+ <div id="b" style="width:40px;height:20px"></div>+ <div id="hidden" style="display:none"></div>+ </div>+ </div>+ </body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.set_viewport(300.0, 200.0);+ rt.run_page_init();+ rt.execute_script(+ "batch-intersection-observer-clip-graph",+ r#"+ globalThis.__intersectionBulkCalls = 0;+ globalThis.__intersectionBulkSizes = [];+ globalThis.__intersectionLegacyGeometryCalls = 0;+ globalThis.__intersectionComputedStyleCalls = 0;+ const nativeBulk = Deno.core.ops.op_intersection_observer_measurements;+ const nativeGeometry = Deno.core.ops.op_layout_geometry;+ const nativeComputedStyle = Deno.core.ops.op_computed_style;+ Deno.core.ops.op_intersection_observer_measurements = input => {+ __intersectionBulkCalls++;+ __intersectionBulkSizes.push(JSON.parse(input).length);+ return nativeBulk(input);+ };+ Deno.core.ops.op_layout_geometry = (...args) => {+ __intersectionLegacyGeometryCalls++;+ return nativeGeometry(...args);+ };+ Deno.core.ops.op_computed_style = (...args) => {+ __intersectionComputedStyleCalls++;+ return nativeComputedStyle(...args);+ };++ const root = document.getElementById("root");+ const a = document.getElementById("a");+ const b = document.getElementById("b");+ const hidden = document.getElementById("hidden");+ const detached = document.createElement("div");+ detached.id = "detached";+ globalThis.__intersectionBatchRecords = [];+ const first = new IntersectionObserver(entries => {+ __intersectionBatchRecords.push(entries.map(entry => [+ entry.target.id,+ entry.isIntersecting,+ ]));+ }, { root });+ const second = new IntersectionObserver(entries => {+ __intersectionBatchRecords.push(entries.map(entry => [+ entry.target.id,+ entry.isIntersecting,+ ]));+ }, { root });+ first.observe(a);+ first.observe(b);+ first.observe(hidden);+ first.observe(detached);+ // The second observer shares its target, root, and clip ancestor+ // with the first and must not duplicate any native measurements.+ second.observe(b);+ "#,+ )+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();++ assert_eq!(+ rt.evaluate(+ r#"[+ __intersectionBulkCalls,+ __intersectionBulkSizes,+ __intersectionLegacyGeometryCalls,+ __intersectionComputedStyleCalls,+ __intersectionBatchRecords,+ ]"#,+ )+ .unwrap(),+ serde_json::json!([+ 1,+ [6],+ 0,+ 0,+ [+ [+ ["a", true],+ ["b", true],+ ["hidden", false],+ ["detached", false],+ ],+ [["b", true]],+ ],+ ])+ );+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn intersection_observer_element_root_uses_live_padding_box_and_scroll() {@@ -8758,8 +9134,8 @@ mod tests {})));}, { root, threshold: [0, 1] });observer.observe(document.getElementById("target"));- setTimeout(() => { root.scrollTop = 999; }, 5);- setTimeout(() => resolve(records), 30);+ setTimeout(() => { root.scrollTop = 999; }, 25);+ setTimeout(() => resolve(records), 60);})"#,true,@@ -8827,8 +9203,8 @@ mod tests {threshold: [0, 1],});observer.observe(document.getElementById("target"));- setTimeout(() => { clip.scrollTop = 999; }, 5);- setTimeout(() => resolve(records), 30);+ setTimeout(() => { clip.scrollTop = 999; }, 25);+ setTimeout(() => resolve(records), 60);})"#,true,@@ -8883,9 +9259,16 @@ mod tests {serde_json::json!([["sync", "after-observe-0", "microtask"], 0]));rt.run_event_loop_bounded(100).await.unwrap();+ #[cfg(feature = "render")]+ let expected_geometry_reads = 0;+ #[cfg(not(feature = "render"))]+ let expected_geometry_reads = 2;assert_eq!(rt.evaluate("[__ioOrder, __ioReads]").unwrap(),- serde_json::json!([["sync", "after-observe-0", "microtask", "observer"], 2])+ serde_json::json!([+ ["sync", "after-observe-0", "microtask", "observer"],+ expected_geometry_reads,+ ]));}@@ -9084,18 +9467,18 @@ mod tests {"#,).unwrap();- rt.run_event_loop_bounded(10).await.unwrap();+ rt.run_event_loop_bounded(40).await.unwrap();rt.evaluate(r#"document.getElementById("spacer").setAttribute("style", "height:120px")"#).unwrap();- rt.run_event_loop_bounded(10).await.unwrap();+ rt.run_event_loop_bounded(40).await.unwrap();assert_eq!(rt.evaluate("__ioRecords").unwrap(),serde_json::json!([[false, 150]]));rt.set_viewport(200.0, 160.0);- rt.run_event_loop_bounded(20).await.unwrap();+ rt.run_event_loop_bounded(40).await.unwrap();assert_eq!(rt.evaluate("__ioRecords").unwrap(),serde_json::json!([[false, 150], [true, 120]])