Skip to content

The headless browser for AI agents and web scraping

Precompile common browser methods in startup snapshot

SGavrl98653ad99c92
diff --git a/crates/obscura-js/build.rs b/crates/obscura-js/build.rs
index ad216827..099d0787 100644
--- a/crates/obscura-js/build.rs
+++ b/crates/obscura-js/build.rs
@@ -160,6 +160,37 @@ fn main() {
/// Generate a snapshot using the host V8 (for native builds or as fallback).
fn generate_host_snapshot(bootstrap_js: &str, snapshot_path: &PathBuf) {
assert!(bootstrap_js.is_ascii(), "bootstrap source must be ASCII; use Unicode escapes in literals");
+ // Compiler intrinsics are confined to this build process and an unretained hook.
+ deno_core::v8::V8::set_flags_from_string("--allow-natives-syntax");
+ let compiler = r#""use strict";
+Object.defineProperty(globalThis, '__obscura_snapshot_compile', {
+ configurable: true,
+ value(helpers) {
+ const functions = new Set(helpers);
+ const targets = [
+ [Node, ['nodeType', 'textContent', 'parentNode', 'isConnected', 'getRootNode', 'appendChild', 'insertBefore']],
+ [Element, ['tagName', 'innerHTML', 'getAttribute', 'setAttribute', 'querySelector', 'querySelectorAll', 'id']],
+ [Document, ['documentElement', 'getElementById', 'querySelector', 'querySelectorAll', 'createElement', 'createTextNode']],
+ [HTMLImageElement, ['src']],
+ [Response, ['text', 'json']],
+ [Headers, ['get', 'set']],
+ [URL, ['href', 'toString']],
+ ];
+ for (const [constructor, names] of targets) {
+ functions.add(constructor);
+ for (const name of names) {
+ const descriptor = Object.getOwnPropertyDescriptor(constructor.prototype, name);
+ if (!descriptor) throw Error('Missing snapshot member: ' + constructor.name + '.' + name);
+ for (const fn of [descriptor.value, descriptor.get, descriptor.set]) {
+ if (typeof fn === 'function') functions.add(fn);
+ }
+ }
+ }
+ for (const fn of functions) %EnsureFeedbackVectorForFunction(fn);
+ },
+});
+"#;
+ let bootstrap_js = format!("{compiler}{bootstrap_js}");
let output = deno_core::snapshot::create_snapshot(
deno_core::snapshot::CreateSnapshotOptions {
cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"),
@@ -174,7 +205,11 @@ fn generate_host_snapshot(bootstrap_js: &str, snapshot_path: &PathBuf) {
..Default::default()
}],
extension_transpiler: None,
- with_runtime_cb: None,
+ with_runtime_cb: Some(Box::new(|runtime| {
+ runtime.execute_script("<obscura:snapshot-check>",
+ "if ('__obscura_snapshot_compile' in globalThis) throw Error('Snapshot compiler hook was retained');")
+ .expect("snapshot compiler hook must not reach page realms");
+ })),
},
None,
)
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 71f8a138..c77d5201 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -18435,7 +18435,8 @@ globalThis.__obscura_init = (function() {
// and leave them out of the hide list (and thus visible to the reflection-API
// filter and to fingerprinting scripts). getOwnPropertyNames captures them.
globalThis.__obscura_hide_list = Object.getOwnPropertyNames(globalThis).filter(k =>
- k.startsWith('_') || k.includes('obscura') || k.includes('Obscura')
+ k !== '__obscura_snapshot_compile' &&
+ (k.startsWith('_') || k.includes('obscura') || k.includes('Obscura'))
);
/* ===== WPT conformance shims: batch 2 ===== */
@@ -19069,4 +19070,20 @@ if (typeof Response !== 'undefined' && Response.prototype && !Response.prototype
}
})();
+// Compile common bodies at snapshot build time without invoking them.
+if (typeof globalThis.__obscura_snapshot_compile === 'function') {
+ const compile = globalThis.__obscura_snapshot_compile;
+ delete globalThis.__obscura_snapshot_compile;
+ compile([
+ _fpRand, _browserPostedTaskDiscardQueue, _eventTargetDispatch, _domEventDispatch,
+ _runPostConnectionSteps, __prepareInsertedSubtree, _relevantNodeList,
+ _ensureInsertionValidity, _preInsertConverted, _attributeOldValuesWanted,
+ _insertOneNode, _resolveUrl, _applyScreenSize, _bodyToUint8Array, _serializeBody,
+ _releaseLinkedStylesheetsIn, _detachStyleSheetsInSubtree,
+ _scheduleIntersectionRenderCheckpoint, _attachResponseAbort, _nodeList,
+ _ensureWindowNamedProperty, _windowNamedNamesInTree, _registerWindowNamedTree,
+ _reconcileWindowNamedProperties, _installFramingRelationships,
+ ]);
+}
+
})();
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 0752dd9b..e9398b19 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -4584,6 +4584,38 @@ impl Default for ObscuraJsRuntime {
#[cfg(test)]
mod tests {
+ #[cfg(obscura_external_bootstrap)]
+ #[test]
+ fn snapshot_core_methods_have_bytecode_before_first_use() {
+ crate::v8_flags::set_v8_flags("--allow-natives-syntax");
+ let mut rt = super::ObscuraJsRuntime::new();
+ assert_eq!(rt.evaluate(r#"(() => {
+ const methods = [Node, Element, Document, Response, Headers,
+ Node.prototype.appendChild, Document.prototype.createElement,
+ Object.getOwnPropertyDescriptor(Node.prototype, 'textContent').get,
+ Object.getOwnPropertyDescriptor(Node.prototype, 'textContent').set];
+ // V8's kInterpreted bit identifies shared bytecode, including
+ // restored closures whose entry point is still CompileLazy.
+ return methods.filter(fn => !(%GetOptimizationStatus(fn) & (1 << 6)))
+ .map(fn => fn.name);
+ })()"#).unwrap(), serde_json::json!([]),
+ "common browser operations must not recompile in each fresh document");
+ }
+
+ #[test]
+ fn snapshot_compiler_is_not_available_in_page_or_frame_realms() {
+ let mut rt = setup_runtime("<html><body><iframe id='frame'></iframe></body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const check = `(function() {
+ let denied = false;
+ try { Function('return %GetOptimizationStatus(function() {});')(); }
+ catch (error) { denied = error instanceof SyntaxError; }
+ return denied && !('__obscura_snapshot_compile' in globalThis);
+ })()`;
+ return [eval(check), document.getElementById('frame').contentWindow.eval(check)];
+ })()"#).unwrap(), serde_json::json!([true, true]));
+ }
+
#[test]
fn bootstrap_source_uses_ascii_snapshot_storage() {
let source = include_str!("../js/bootstrap.js")