Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(workers): derive shared constructor option dictionaries
ldm08eb108a2f6fe
diff --git a/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs b/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rsindex 7942b1a18..c6eac2700 100644--- a/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs+++ b/moli-renderer-v8/src/context_bootstrap/shared_worker_host.rs@@ -1,4 +1,5 @@use crate::content_security_policy::ContentSecurityPolicy;+use crate::webidl;use super::{CHILD_BROWSING_CONTEXT_HANDLE_SLOT, MessagePortRealmBinding,@@ -36,7 +37,7 @@ use crate::{types::SubresourcePolicyContext,util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value,- throw_type_error, v8_string, v8str,+ throw_type_error, v8str,},worker::{WorkerNetworkPolicy, WorkerScriptKind, worker_secure_context_for_script_url},};@@ -564,108 +565,78 @@ fn child_context_handle_from_global<'s>(}}-fn parse_shared_worker_options(- scope: &mut v8::PinScope<'_, '_>,- args: &v8::FunctionCallbackArguments<'_>,+#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "SharedWorkerOptions")]+struct SharedWorkerOptionsMembers {+ #[webidl(inherit)]+ worker: super::worker_host::WorkerOptionsMembers,+ #[webidl(default = false)]+ extended_lifetime: bool,+ #[webidl(converter = "enum")]+ same_site_cookies: Option<SameSiteCookies>,+}++#[derive(webidl::WebIdlEnum)]+#[webidl(name = "SharedWorkerSameSiteCookies")]+enum SameSiteCookies {+ #[webidl(token = "all")]+ All,+ #[webidl(token = "none")]+ None,+}++fn parse_shared_worker_options<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,) -> Option<SharedWorkerOptions> {- if args.length() < 2 {- return Some(SharedWorkerOptions::default());- }let value = args.get(1);- if value.is_undefined() || value.is_null() {- return Some(SharedWorkerOptions::default());- }- if value.is_string() {- return Some(SharedWorkerOptions {- name: value.to_string(scope)?.to_rust_string_lossy(scope),- ..SharedWorkerOptions::default()- });- }- if !value.is_object() {- return Some(SharedWorkerOptions {- name: value.to_string(scope)?.to_rust_string_lossy(scope),- ..SharedWorkerOptions::default()- });- }- let Ok(object) = v8::Local::<v8::Object>::try_from(value) else {- throw_type_error(+ // The legacy DOMString-or-dictionary union chooses strings for primitives.+ // Nullish values choose an empty dictionary, whose defaults come from derive.+ if !value.is_object() && !value.is_null_or_undefined() {+ return match webidl::convert::<webidl::DomString>(scope,- "Failed to construct 'SharedWorker': options must be a string or object.",- );- return None;- };- let name = optional_string_property(scope, object, "name")?.unwrap_or_default();- let script_kind = match optional_string_property(scope, object, "type")? {- Some(value) if value == "classic" => WorkerScriptKind::Classic,- Some(value) if value == "module" => WorkerScriptKind::Module,- Some(_) => {- throw_type_error(- scope,- "Failed to construct 'SharedWorker': the provided worker type is invalid.",- );- return None;- }- None => WorkerScriptKind::Classic,- };- let credentials_mode = match optional_string_property(scope, object, "credentials")? {- Some(value) if value == "omit" => SharedWorkerCredentialsMode::Omit,- Some(value) if value == "same-origin" => SharedWorkerCredentialsMode::SameOrigin,- Some(value) if value == "include" => SharedWorkerCredentialsMode::Include,- Some(_) => {- throw_type_error(- scope,- "Failed to construct 'SharedWorker': the provided credentials mode is invalid.",- );- return None;- }- None => SharedWorkerCredentialsMode::SameOrigin,- };- let extended_lifetime = boolean_property(scope, object, "extendedLifetime")?;- let same_site_cookies = match optional_string_property(scope, object, "sameSiteCookies")? {- Some(value) if value == "all" => Some(SharedWorkerSameSiteCookies::All),- Some(value) if value == "none" => Some(SharedWorkerSameSiteCookies::None),- Some(_) => {- throw_type_error(- scope,- "Failed to construct 'SharedWorker': the provided sameSiteCookies mode is invalid.",- );+ value,+ webidl::Context::argument("SharedWorker", 2),+ ) {+ Ok(name) => Some(SharedWorkerOptions {+ name: name.0,+ ..Default::default()+ }),+ Err(error) => {+ webidl::throw_error(scope, &error);+ None+ }+ };+ }+ let options = match webidl::convert::<webidl::Dictionary<SharedWorkerOptionsMembers>>(+ scope,+ value,+ webidl::Context::argument("SharedWorker", 2),+ ) {+ Ok(options) => options.0,+ Err(error) => {+ webidl::throw_error(scope, &error);return None;}- None => None,};Some(SharedWorkerOptions {- name,- script_kind,- credentials_mode,- extended_lifetime,- same_site_cookies,+ name: options.worker.name,+ script_kind: options.worker.worker_type,+ credentials_mode: match options.worker.credentials_mode.0 {+ moli_fetch::RequestCredentialsMode::Omit => SharedWorkerCredentialsMode::Omit,+ moli_fetch::RequestCredentialsMode::SameOrigin => {+ SharedWorkerCredentialsMode::SameOrigin+ }+ moli_fetch::RequestCredentialsMode::Include => SharedWorkerCredentialsMode::Include,+ },+ extended_lifetime: options.extended_lifetime,+ same_site_cookies: options.same_site_cookies.map(|value| match value {+ SameSiteCookies::All => SharedWorkerSameSiteCookies::All,+ SameSiteCookies::None => SharedWorkerSameSiteCookies::None,+ }),})}-fn boolean_property(- scope: &mut v8::PinScope<'_, '_>,- object: v8::Local<'_, v8::Object>,- key: &str,-) -> Option<bool> {- let key = v8_string(scope, key)?;- object- .get(scope, key.into())- .map(|value| value.boolean_value(scope))-}--fn optional_string_property(- scope: &mut v8::PinScope<'_, '_>,- object: v8::Local<'_, v8::Object>,- key: &str,-) -> Option<Option<String>> {- let key = v8_string(scope, key)?;- let value = object.get(scope, key.into())?;- if value.is_undefined() {- return Some(None);- }- Some(Some(value.to_string(scope)?.to_rust_string_lossy(scope)))-}-fn prepare_shared_worker_script_load(request_client: ResourceRequestClient,resource_task_runner: crate::network::RendererResourceTaskRunner,diff --git a/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs b/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rsindex ec0f21a51..7b76abf07 100644--- a/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs+++ b/moli-renderer-v8/src/context_bootstrap/worker_host/constructor.rs@@ -1,10 +1,25 @@use super::*;use crate::web_api_interfaces;-struct WorkerOptionsMembers {- worker_type: WorkerScriptKind,- name: String,- credentials_mode: moli_fetch::RequestCredentialsMode,+#[derive(webidl::WebIdlDictionary)]+#[webidl(prefix = "WorkerOptions")]+pub(in crate::context_bootstrap) struct WorkerOptionsMembers {+ #[webidl(name = "type", default = WorkerScriptKind::Classic, converter = "enum")]+ pub(in crate::context_bootstrap) worker_type: WorkerScriptKind,+ #[webidl(default = "")]+ pub(in crate::context_bootstrap) name: String,+ #[webidl(name = "credentials", default = WorkerCredentials(moli_fetch::RequestCredentialsMode::SameOrigin), converter = "enum")]+ pub(in crate::context_bootstrap) credentials_mode: WorkerCredentials,+}++#[derive(webidl::WebIdlEnum)]+#[webidl(name = "RequestCredentials", parse_with = parse_credentials)]+pub(in crate::context_bootstrap) struct WorkerCredentials(+ pub(in crate::context_bootstrap) moli_fetch::RequestCredentialsMode,+);++fn parse_credentials(value: &str) -> Option<WorkerCredentials> {+ value.parse().ok().map(WorkerCredentials)}use crate::context_bootstrap::navigation_serialize::{@@ -16,7 +31,6 @@ use crate::types::DedicatedWorkerId;use crate::webidl;use crate::worker::{NestedWorkerContext, WorkerScriptKind};use moli_encoding::{encode_url_query_for_legacy_web, form_output_encoding_for_label};-use moli_v8_util::v8_string;use moli_webapi_declare::WebApiObject;use url::Url;@@ -126,7 +140,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(let worker_options = match parse_worker_options(scope, &args) {Ok(worker_options) => worker_options,Err(error) => {- throw_type_error(scope, &error);+ webidl::throw_error(scope, &error);return;}};@@ -235,7 +249,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(creator_top_level_site,creator_storage_key,worker_options.name.clone(),- worker_options.credentials_mode,+ worker_options.credentials_mode.0,None,outside_settings_load,execution_context_owner,@@ -318,7 +332,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(creator_request_client.clone(),).with_script_kind(worker_options.worker_type)- .with_module_credentials_mode(worker_options.credentials_mode)+ .with_module_credentials_mode(worker_options.credentials_mode.0).with_module_static_import_initiator_url(base_url.clone()).with_module_static_import_content_security_policies(document_content_security_policies).with_network_policy(network_policy)@@ -396,7 +410,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(creator_top_level_site,creator_storage_key,worker_options.name.clone(),- worker_options.credentials_mode,+ worker_options.credentials_mode.0,reserved_service_worker_client_id,outside_settings_load,execution_context_owner,@@ -425,7 +439,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(network_partition_key,creator_policy_context,worker_options.worker_type,- worker_options.credentials_mode,+ worker_options.credentials_mode.0,document_referrer_policy,document_content_security_policies,worker_options.name.clone(),@@ -519,7 +533,7 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(nested_context.loader.request_client().clone(),).with_script_kind(worker_options.worker_type)- .with_module_credentials_mode(worker_options.credentials_mode)+ .with_module_credentials_mode(worker_options.credentials_mode.0).with_module_static_import_initiator_url(nested_context.base_url.clone()).with_module_static_import_content_security_policies(nested_context.module_static_import_content_security_policies,@@ -707,74 +721,13 @@ fn worker_event_handler_setter<'s>(fn parse_worker_options<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,-) -> Result<WorkerOptionsMembers, String> {- let options = webidl::dictionary_arg(args, 1, webidl::Context::argument("WorkerOptions", 2))- .map_err(|_| {- "Failed to construct 'Worker': the provided options are invalid.".to_owned()- })?;- let Some(options) = options else {- return Ok(WorkerOptionsMembers {- worker_type: WorkerScriptKind::Classic,- name: String::new(),- credentials_mode: moli_fetch::RequestCredentialsMode::SameOrigin,- });- };- let worker_type = webidl::optional_member_or::<webidl::EnumValue<WorkerScriptKind>>(+) -> Result<WorkerOptionsMembers, webidl::WebIdlError> {+ webidl::convert::<webidl::Dictionary<WorkerOptionsMembers>>(scope,- options,- "type",- webidl::Context::member("WorkerOptions", "type"),- webidl::EnumValue(WorkerScriptKind::Classic),+ args.get(1),+ webidl::Context::argument("Worker", 2),).map(|value| value.0)- .map_err(|_| "Failed to construct 'Worker': the provided worker type is invalid.".to_owned())?;- let name = webidl::optional_member_or::<webidl::DomString>(- scope,- options,- "name",- webidl::Context::member("WorkerOptions", "name"),- webidl::DomString(String::new()),- )- .map(|value| value.0)- .map_err(|_| {- "Failed to construct 'Worker': the provided worker options are invalid.".to_owned()- })?;- let credentials_mode = worker_options_credentials_mode(scope, options)?;- Ok(WorkerOptionsMembers {- worker_type,- name,- credentials_mode,- })-}--fn worker_options_credentials_mode(- scope: &mut v8::PinScope<'_, '_>,- options: v8::Local<'_, v8::Object>,-) -> Result<moli_fetch::RequestCredentialsMode, String> {- let key = v8_string(scope, "credentials").ok_or_else(|| {- "Failed to construct 'Worker': the provided worker options are invalid.".to_owned()- })?;- let Some(value) = options.get(scope, key.into()) else {- return Err(- "Failed to construct 'Worker': the provided worker options are invalid.".to_owned(),- );- };- if value.is_undefined() {- return Ok(moli_fetch::RequestCredentialsMode::SameOrigin);- }- let Some(value) = value.to_string(scope) else {- return Err(- "Failed to construct 'Worker': the provided worker options are invalid.".to_owned(),- );- };- match value.to_rust_string_lossy(scope).as_str() {- "omit" => Ok(moli_fetch::RequestCredentialsMode::Omit),- "same-origin" => Ok(moli_fetch::RequestCredentialsMode::SameOrigin),- "include" => Ok(moli_fetch::RequestCredentialsMode::Include),- _ => Err(- "Failed to construct 'Worker': the provided credentials mode is invalid.".to_owned(),- ),- }}pub(in crate::context_bootstrap) fn resolve_worker_script_url(diff --git a/moli-renderer-v8/src/context_bootstrap/worker_host/mod.rs b/moli-renderer-v8/src/context_bootstrap/worker_host/mod.rsindex e6c82e56a..e33503b94 100644--- a/moli-renderer-v8/src/context_bootstrap/worker_host/mod.rs+++ b/moli-renderer-v8/src/context_bootstrap/worker_host/mod.rs@@ -26,7 +26,7 @@ mod dispatch;mod methods;pub(in crate::context_bootstrap) use constructor::{- document_query_encoding_override, is_cross_origin_http_worker_script,+ WorkerOptionsMembers, document_query_encoding_override, is_cross_origin_http_worker_script,materialize_worker_script_source, resolve_worker_script_url, throw_worker_dom_exception,trusted_worker_script_url_string_or_throw, worker_constructor_base_url,worker_script_resource_url, worker_script_scheme_can_load,diff --git a/moli-renderer-v8/src/context_bootstrap/worker_host/tests.rs b/moli-renderer-v8/src/context_bootstrap/worker_host/tests.rsindex 29c06f834..5841f678d 100644--- a/moli-renderer-v8/src/context_bootstrap/worker_host/tests.rs+++ b/moli-renderer-v8/src/context_bootstrap/worker_host/tests.rs@@ -403,7 +403,7 @@ fn constructor_rejects_invalid_worker_type_option() {r#"new Worker("postMessage('hi')", { type: "potato" })"#,);assert!(- err.contains("worker type is invalid"),+ err.contains("type is not a valid enum value of type WorkerType"),"expected invalid worker type error, got: {err}");}@@ -418,7 +418,7 @@ fn constructor_rejects_null_worker_type_option_member() {r#"new Worker("postMessage('hi')", { type: null })"#,);assert!(- err.contains("worker type is invalid"),+ err.contains("type is not a valid enum value of type WorkerType"),"expected invalid worker type error, got: {err}");}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex 034af2ff9..b10678926 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -77,6 +77,7 @@ mod webrtc;mod webrtc_events;mod window_legacy_objects;mod worker_listener_invocation;+mod worker_options;mod document_domain_lifetime;mod document_domain_setter;diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/worker_options.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/worker_options.rsnew file mode 100644index 000000000..549d727e8--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/worker_options.rs@@ -0,0 +1,28 @@+use super::*;++#[test]+fn worker_constructors_convert_inherited_options_before_launch() {+ let mut vm = new_storage_html_test_vm("https://worker-options.test/");+ assert_eq!(+ vm.eval(include_str!(+ "../../../../tests/fixtures/worker-options-dictionary.js"+ ))+ .unwrap(),+ "true"+ );+ assert_eq!(+ vm.eval(+ r#"(() => {+ const trace = [], sentinel = {};+ let caught;+ try { new SharedWorker('http://[', new Proxy({}, {get(_target, key) {+ trace.push(key);+ if (key === 'extendedLifetime') throw sentinel;+ }})); } catch (error) { caught = error; }+ return caught === sentinel && trace.join() === 'credentials,name,type,extendedLifetime';+ })()"#,+ )+ .unwrap(),+ "true"+ );+}diff --git a/moli-renderer-v8/tests/fixtures/worker-options-dictionary.js b/moli-renderer-v8/tests/fixtures/worker-options-dictionary.jsnew file mode 100644index 000000000..2d54a408e--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/worker-options-dictionary.js@@ -0,0 +1,53 @@+(() => {+ const assert = (ok, label) => { if (!ok) throw Error(label); };+ const base = ['credentials', 'name', 'type'];+ const invalidUrl = 'http://[';+ for (const Constructor of [Worker, SharedWorker]) {+ const members = Constructor === Worker ? base : [...base, 'sameSiteCookies'];+ const trace = [];+ const options = {};+ for (const key of members) Object.defineProperty(options, key, {+ configurable: true, get() { trace.push(key); }+ });+ let error;+ try { new Constructor(invalidUrl, options); } catch (caught) { error = caught; }+ assert(error instanceof DOMException && error.name === 'SyntaxError', Constructor.name + ' URL validation');+ assert(trace.join() === members.join(), Constructor.name + ' inheritance order: ' + trace);+ for (const stop of members) for (const sentinel of [undefined, null, false, 0, 'sentinel', {}, new Error('sentinel')]) {+ trace.length = 0;+ const bad = Object.create(options);+ Object.defineProperty(bad, stop, {get() { trace.push(stop); throw sentinel; }});+ let error, threw = false;+ try { new Constructor(invalidUrl, bad); } catch (caught) { error = caught; threw = true; }+ assert(threw && Object.is(error, sentinel), Constructor.name + '/' + stop + ' original exception');+ assert(trace.join() === members.slice(0, members.indexOf(stop) + 1).join(), Constructor.name + '/' + stop + ' short circuit');+ }+ for (const member of ['credentials', 'type', ...(Constructor === SharedWorker ? ['sameSiteCookies'] : [])]) {+ for (const value of [null, 'invalid', Symbol('enum')]) {+ let error;+ try { new Constructor(invalidUrl, {[member]: value}); } catch (caught) { error = caught; }+ assert(error instanceof TypeError, Constructor.name + '/' + member + ' enum conversion');+ }+ }+ const ignored = new Proxy({}, {has() { throw Error('unexpected has'); }, get(_target, key) {+ if (!['credentials', 'name', 'type', 'sameSiteCookies', 'extendedLifetime'].includes(key)) throw Error('unknown member ' + String(key));+ }});+ error = undefined;+ try { new Constructor(invalidUrl, ignored); } catch (caught) { error = caught; }+ assert(error && error.name === 'SyntaxError', Constructor.name + ' only reads dictionary members with Get');+ }+ for (const value of [undefined, null, {}, new String('boxed')]) for (const Constructor of [Worker, SharedWorker]) {+ let error;+ try { new Constructor(invalidUrl, value); } catch (caught) { error = caught; }+ assert(error && error.name === 'SyntaxError', Constructor.name + ' nullish / object dictionary');+ }+ for (const value of [1, true, 'name', 1n, Symbol('name')]) {+ let error;+ try { new Worker(invalidUrl, value); } catch (caught) { error = caught; }+ assert(error instanceof TypeError, 'Worker primitive dictionary rejected');+ error = undefined;+ try { new SharedWorker(invalidUrl, value); } catch (caught) { error = caught; }+ assert(error && (typeof value === 'symbol' ? error instanceof TypeError : error.name === 'SyntaxError'), 'SharedWorker string-or-options discrimination');+ }+ return true;+})()