Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(file-api): convert constructor inputs before processing Blob parts
ldm0785d6da55155
diff --git a/moli-renderer-v8/src/blob.rs b/moli-renderer-v8/src/blob.rsindex f55a9e400..9fe5acf2e 100644--- a/moli-renderer-v8/src/blob.rs+++ b/moli-renderer-v8/src/blob.rs@@ -1,7 +1,6 @@use crate::web_api_interfaces;use moli_file_api::{- BlobId, BlobLineEndings, BlobStore, blob_slice_relative_index, clamp_blob_long_long,- normalize_blob_line_endings_with_native_ending, normalize_blob_mime_type,+ BlobId, BlobStore, blob_slice_relative_index, clamp_blob_long_long, normalize_blob_mime_type,};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};use std::sync::{Arc, OnceLock};@@ -15,6 +14,18 @@ use super::{const BLOB_ID_SLOT: &str = "__lmBlobId";+mod parts;+pub(crate) use parts::{BlobParts, BlobPropertyBag, required_blob_parts_argument};++#[derive(webidl::WebIdlArgs)]+#[webidl(prefix = "Blob")]+struct BlobConstructorArgs<'s> {+ #[webidl(with = parts::optional_blob_parts_argument)]+ parts: BlobParts<'s>,+ #[webidl(dictionary)]+ options: BlobPropertyBag,+}+fn native_blob_line_ending() -> &'static str {if moli_browser_profile::DEFAULT_WINDOW_SURFACE_PROFILE.platform@@ -83,10 +94,20 @@ pub(super) fn blob_constructor_callback<'s>(return;}- let Some((bytes, mime_type)) = collect_blob_bytes_and_type(scope, args.get(0), args.get(1))- else {+ let Some(parsed) = webidl::parse_args::<BlobConstructorArgs>(scope, &args) else {return;};+ let bytes = match parsed+ .parts+ .into_bytes(scope, parsed.options.line_endings())+ {+ Ok(bytes) => bytes,+ Err(error) => {+ webidl::throw_error(scope, &error);+ return;+ }+ };+ let mime_type = normalize_blob_mime_type(&parsed.options.r#type);init_blob_object(scope, args.this(), bytes, mime_type);rv.set(args.this().into());@@ -385,95 +406,6 @@ pub(super) fn object_url_bytes_and_type(url: &str) -> Option<(Vec<u8>, String)>blob_store().object_url_bytes_and_type(url)}-pub(super) fn collect_blob_bytes_and_type<'s>(- scope: &mut v8::PinScope<'s, '_>,- parts_value: v8::Local<'s, v8::Value>,- options_value: v8::Local<'s, v8::Value>,-) -> Option<(Vec<u8>, String)> {- collect_blob_bytes_and_type_with_options_context(- scope,- parts_value,- options_value,- "BlobPropertyBag",- 2,- )-}--pub(super) fn collect_blob_bytes_and_type_with_options_context<'s>(- scope: &mut v8::PinScope<'s, '_>,- parts_value: v8::Local<'s, v8::Value>,- options_value: v8::Local<'s, v8::Value>,- options_context: &'static str,- options_argument_index: usize,-) -> Option<(Vec<u8>, String)> {- collect_blob_bytes_and_type_with_parts_mode(- scope,- parts_value,- options_value,- options_context,- options_argument_index,- BlobPartsMode::Optional,- )-}--pub(crate) fn collect_required_blob_bytes_and_type_with_options_context<'s>(- scope: &mut v8::PinScope<'s, '_>,- parts_value: v8::Local<'s, v8::Value>,- options_value: v8::Local<'s, v8::Value>,- options_context: &'static str,- options_argument_index: usize,-) -> Option<(Vec<u8>, String)> {- collect_blob_bytes_and_type_with_parts_mode(- scope,- parts_value,- options_value,- options_context,- options_argument_index,- BlobPartsMode::Required,- )-}--fn collect_blob_bytes_and_type_with_parts_mode<'s>(- scope: &mut v8::PinScope<'s, '_>,- parts_value: v8::Local<'s, v8::Value>,- options_value: v8::Local<'s, v8::Value>,- options_context: &'static str,- options_argument_index: usize,- parts_mode: BlobPartsMode,-) -> Option<(Vec<u8>, String)> {- let endings = match blob_property_bag_endings(- scope,- options_value,- webidl::Context::argument(options_context, options_argument_index),- ) {- Ok(endings) => endings,- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- };- let bytes = match blob_part_sequence_bytes(scope, parts_value, parts_mode, endings) {- Ok(bytes) => bytes,- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- };- let mime_type = match blob_property_bag_type(- scope,- options_value,- webidl::Context::argument(options_context, options_argument_index),- ) {- Ok(mime_type) => mime_type,- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- };-- Some((bytes, mime_type))-}-fn blob_bytes(blob_id: BlobId) -> Option<Vec<u8>> {blob_store().blob_bytes(blob_id)}@@ -502,350 +434,6 @@ fn track_blob_ref_lifetime(crate::v8_finalizer::track_context_owned_v8_finalizer(scope, object, finalizer);}-fn blob_property_bag_endings<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,- context: webidl::Context,-) -> Result<BlobLineEndings, webidl::WebIdlError> {- let Some(object) = webidl::dictionary_value(value, context)? else {- return Ok(BlobLineEndings::Transparent);- };- let Some(value) = webidl::property_result(- scope,- object,- "endings",- webidl::Context::member("BlobPropertyBag", "endings"),- )?- else {- return Ok(BlobLineEndings::Transparent);- };- if value.is_undefined() {- return Ok(BlobLineEndings::Transparent);- }- webidl::convert::<webidl::EnumValue<BlobLineEndingsWebIdl>>(- scope,- value,- webidl::Context::member("BlobPropertyBag", "endings"),- )- .map(|value| value.0.into())-}--fn blob_property_bag_type<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,- context: webidl::Context,-) -> Result<String, webidl::WebIdlError> {- let Some(object) = webidl::dictionary_value(value, context)? else {- return Ok(String::new());- };- let Some(value) = webidl::property_result(- scope,- object,- "type",- webidl::Context::member("BlobPropertyBag", "type"),- )?- else {- return Ok(String::new());- };- if value.is_undefined() {- return Ok(String::new());- }- let value = webidl::convert::<webidl::DomString>(- scope,- value,- webidl::Context::member("BlobPropertyBag", "type"),- )?;- Ok(normalize_blob_mime_type(&value.0))-}--fn bytes_from_blob_part<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,- endings: BlobLineEndings,-) -> Result<Vec<u8>, webidl::WebIdlError> {- if let Ok(object) = v8::Local::<v8::Object>::try_from(value)- && let Some(bytes) = blob_bytes_from_object(scope, object)- {- return Ok(bytes);- }- if let Some(bytes) = buffer_source_bytes_from_value(scope, value) {- return Ok(bytes);- }- let text = webidl::convert::<webidl::UsvString>(- scope,- value,- webidl::Context::member("BlobPart", "value"),- )?- .0;- Ok(- normalize_blob_line_endings_with_native_ending(&text, endings, native_blob_line_ending())- .into_bytes(),- )-}--#[derive(Clone, Copy)]-enum BlobPartsMode {- Optional,- Required,-}--fn blob_part_sequence_bytes<'s>(- scope: &mut v8::PinScope<'s, '_>,- value: v8::Local<'s, v8::Value>,- mode: BlobPartsMode,- endings: BlobLineEndings,-) -> Result<Vec<u8>, webidl::WebIdlError> {- if matches!(mode, BlobPartsMode::Optional) && value.is_undefined() {- return Ok(Vec::new());- }- let Ok(object) = v8::Local::<v8::Object>::try_from(value) else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts must be an iterable object.",- ));- };- if is_platform_indexed_blob_parts_object(scope, object)? {- return blob_part_array_like_bytes(scope, object, endings);- }- let iterator_key = v8::Symbol::get_iterator(scope);- let Some(iterator_value) = webidl::symbol_property_result(- scope,- object,- iterator_key,- webidl::Context::member("BlobPart", "@@iterator"),- )?- else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts must be an iterable object.",- ));- };- if iterator_value.is_null_or_undefined() {- return Err(webidl::WebIdlError::custom_message(- "Blob parts must be an iterable object.",- ));- }- let Ok(iterator_method) = v8::Local::<v8::Function>::try_from(iterator_value) else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts @@iterator must be callable.",- ));- };- let Some(iterator_value) = call_function_result(- scope,- iterator_method,- value,- &[],- webidl::Context::member("BlobPart", "@@iterator"),- )?- else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts @@iterator must return an iterator.",- ));- };- let Ok(iterator) = v8::Local::<v8::Object>::try_from(iterator_value) else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts @@iterator must return an iterator.",- ));- };- let Some(next_method) = webidl::property_result(- scope,- iterator,- "next",- webidl::Context::member("BlobPart", "next"),- )?- else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts iterator must have next().",- ));- };- let Ok(next_method) = v8::Local::<v8::Function>::try_from(next_method) else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts iterator next must be callable.",- ));- };-- let mut bytes = Vec::new();- loop {- let Some(step_value) = call_function_result(- scope,- next_method,- iterator.into(),- &[],- webidl::Context::member("BlobPart", "next"),- )?- else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts iterator next() must return an object.",- ));- };- let Ok(step) = v8::Local::<v8::Object>::try_from(step_value) else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts iterator next() must return an object.",- ));- };- let done = webidl::property_result(- scope,- step,- "done",- webidl::Context::member("BlobPart", "done"),- )?- .is_some_and(|value| value.boolean_value(scope));- if done {- break;- }- let Some(part) = webidl::property_result(- scope,- step,- "value",- webidl::Context::member("BlobPart", "value"),- )?- else {- return Err(webidl::WebIdlError::custom_message(- "Blob parts iterator result is missing value.",- ));- };- bytes.extend(bytes_from_blob_part(scope, part, endings)?);- }- Ok(bytes)-}--fn blob_part_array_like_bytes<'s>(- scope: &mut v8::PinScope<'s, '_>,- mut object: v8::Local<'s, v8::Object>,- endings: BlobLineEndings,-) -> Result<Vec<u8>, webidl::WebIdlError> {- if blob_platform_indexed_object_kind(scope, object)- == Some(BlobPlatformIndexedObjectKind::HtmlSelectElement)- {- if let Some(options) = webidl::property_result(- scope,- object,- "options",- webidl::Context::member("BlobPart", "options"),- )?- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- {- object = options;- } else if let Some(children) = webidl::property_result(- scope,- object,- "children",- webidl::Context::member("BlobPart", "children"),- )?- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- {- object = children;- }- }- let mut bytes = Vec::new();- let length_value = webidl::property_result(- scope,- object,- "length",- webidl::Context::member("BlobPart", "length"),- )?- .ok_or_else(|| webidl::WebIdlError::custom_message("Blob parts array-like missing length."))?;- let length = webidl::convert::<webidl::UnsignedLong>(- scope,- length_value,- webidl::Context::member("BlobPart", "length"),- )?- .0;- for index in 0..length {- let Some(part) = get_index_result(scope, object, index)? else {- continue;- };- bytes.extend(bytes_from_blob_part(scope, part, endings)?);- }- Ok(bytes)-}--fn is_platform_indexed_blob_parts_object<'s>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,-) -> Result<bool, webidl::WebIdlError> {- Ok(blob_platform_indexed_object_kind(scope, object).is_some())-}--#[derive(Clone, Copy, PartialEq, Eq)]-enum BlobPlatformIndexedObjectKind {- Collection,- HtmlSelectElement,- NamedNodeMap,- FileList,- DomStringList,-}--fn blob_platform_indexed_object_kind<'s>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,-) -> Option<BlobPlatformIndexedObjectKind> {- match moli_webapi_declare::web_api_object_type(scope, object)?.name() {- "NamedNodeMap" => Some(BlobPlatformIndexedObjectKind::NamedNodeMap),- "FileList" => Some(BlobPlatformIndexedObjectKind::FileList),- "DOMStringList" => Some(BlobPlatformIndexedObjectKind::DomStringList),- "HTMLCollection"- | "HTMLFormControlsCollection"- | "HTMLOptionsCollection"- | "NodeList"- | "RadioNodeList" => Some(BlobPlatformIndexedObjectKind::Collection),- "HTMLSelectElement" => Some(BlobPlatformIndexedObjectKind::HtmlSelectElement),- _ => None,- }-}--fn get_index_result<'s>(- scope: &mut v8::PinScope<'s, '_>,- object: v8::Local<'s, v8::Object>,- index: u32,-) -> Result<Option<v8::Local<'s, v8::Value>>, webidl::WebIdlError> {- let try_catch = std::pin::pin!(v8::TryCatch::new(scope));- let mut scope = try_catch.init();- match object.get_index(&scope, index) {- Some(value) => Ok(Some(value)),- None if scope.has_caught() => {- let _ = scope.rethrow();- Err(webidl::WebIdlError::pending_exception(- webidl::Context::member("BlobPart", "sequence item"),- ))- }- None => Ok(None),- }-}--fn call_function_result<'s>(- scope: &mut v8::PinScope<'s, '_>,- function: v8::Local<'s, v8::Function>,- receiver: v8::Local<'s, v8::Value>,- args: &[v8::Local<'s, v8::Value>],- context: webidl::Context,-) -> Result<Option<v8::Local<'s, v8::Value>>, webidl::WebIdlError> {- let try_catch = std::pin::pin!(v8::TryCatch::new(scope));- let mut scope = try_catch.init();- match function.call(&scope, receiver, args) {- Some(value) => Ok(Some(value)),- None if scope.has_caught() => {- let _ = scope.rethrow();- Err(webidl::WebIdlError::pending_exception(context))- }- None => Ok(None),- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, webidl::WebIdlEnum)]-#[webidl(name = "EndingType")]-enum BlobLineEndingsWebIdl {- Transparent,- Native,-}--impl From<BlobLineEndingsWebIdl> for BlobLineEndings {- fn from(value: BlobLineEndingsWebIdl) -> Self {- match value {- BlobLineEndingsWebIdl::Transparent => Self::Transparent,- BlobLineEndingsWebIdl::Native => Self::Native,- }- }-}-fn clamped_long_long_arg(scope: &mut v8::PinScope<'_, '_>,args: &v8::FunctionCallbackArguments<'_>,diff --git a/moli-renderer-v8/src/blob/parts.rs b/moli-renderer-v8/src/blob/parts.rsnew file mode 100644index 000000000..416c4395c--- /dev/null+++ b/moli-renderer-v8/src/blob/parts.rs@@ -0,0 +1,125 @@+use super::native_blob_line_ending;+use crate::{web_api_interfaces, webidl};+use moli_file_api::{BlobLineEndings, normalize_blob_line_endings_with_native_ending};++pub(crate) struct BlobParts<'s>(Vec<BlobPart<'s>>);++enum BlobPart<'s> {+ Blob(v8::Local<'s, v8::Object>),+ Buffer(webidl::NonSharedBufferSource<'s>),+ Text(String),+}++impl<'s> webidl::WebIdlConverter<'s> for BlobPart<'s> {+ type Options = ();++ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: webidl::Context,+ _options: &Self::Options,+ ) -> Result<Self, webidl::WebIdlError> {+ if let Ok(object) = v8::Local::<v8::Object>::try_from(value)+ && web_api_interfaces::Blob::is_instance(scope, object)+ {+ let target = moli_webapi_declare::web_api_object_target(scope, object)+ .expect("converted Blob part");+ return Ok(Self::Blob(target));+ }+ if value.is_array_buffer() || value.is_shared_array_buffer() || value.is_array_buffer_view()+ {+ return webidl::convert::<webidl::NonSharedBufferSource>(scope, value, context)+ .map(Self::Buffer);+ }+ webidl::convert::<webidl::UsvString>(scope, value, context).map(|text| Self::Text(text.0))+ }+}++impl<'s> BlobParts<'s> {+ pub(crate) fn into_bytes(+ self,+ scope: &mut v8::PinScope<'s, '_>,+ endings: BlobLineEndings,+ ) -> Result<Vec<u8>, webidl::WebIdlError> {+ let mut bytes = Vec::new();+ for part in self.0 {+ match part {+ BlobPart::Blob(object) => {+ let data = super::blob_bytes_from_object(scope, object).ok_or_else(|| {+ webidl::WebIdlError::cannot_convert(+ webidl::Context::member("BlobPart", "value"),+ "Blob",+ )+ })?;+ bytes.extend(data);+ }+ BlobPart::Buffer(source) => bytes.extend(source.to_vec(scope)),+ BlobPart::Text(text) => bytes.extend(+ normalize_blob_line_endings_with_native_ending(+ &text,+ endings,+ native_blob_line_ending(),+ )+ .into_bytes(),+ ),+ }+ }+ Ok(bytes)+ }+}++pub(crate) fn optional_blob_parts_argument<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,+ index: i32,+) -> Result<BlobParts<'s>, webidl::WebIdlError> {+ let value = args.get(index);+ if value.is_undefined() {+ return Ok(BlobParts(Vec::new()));+ }+ let parts = webidl::convert::<webidl::Sequence<BlobPart>>(+ scope,+ value,+ webidl::Context::argument("Blob", index as usize + 1),+ )?;+ Ok(BlobParts(parts.0))+}++pub(crate) fn required_blob_parts_argument<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: &v8::FunctionCallbackArguments<'s>,+ index: i32,+) -> Result<BlobParts<'s>, webidl::WebIdlError> {+ let parts = webidl::convert::<webidl::Sequence<BlobPart>>(+ scope,+ args.get(index),+ webidl::Context::argument("File", index as usize + 1),+ )?;+ Ok(BlobParts(parts.0))+}++#[derive(Default, webidl::WebIdlDictionary)]+#[webidl(prefix = "BlobPropertyBag")]+pub(crate) struct BlobPropertyBag {+ #[webidl(converter = "enum", default = BlobLineEndingsWebIdl::Transparent)]+ endings: BlobLineEndingsWebIdl,+ #[webidl(default = String::new())]+ pub(crate) r#type: String,+}++impl BlobPropertyBag {+ pub(crate) fn line_endings(&self) -> BlobLineEndings {+ match self.endings {+ BlobLineEndingsWebIdl::Transparent => BlobLineEndings::Transparent,+ BlobLineEndingsWebIdl::Native => BlobLineEndings::Native,+ }+ }+}++#[derive(Clone, Copy, Default, webidl::WebIdlEnum)]+#[webidl(name = "EndingType")]+enum BlobLineEndingsWebIdl {+ #[default]+ Transparent,+ Native,+}diff --git a/moli-renderer-v8/src/context_bootstrap/file_api/file.rs b/moli-renderer-v8/src/context_bootstrap/file_api/file.rsindex e502439c7..1d8be4320 100644--- a/moli-renderer-v8/src/context_bootstrap/file_api/file.rs+++ b/moli-renderer-v8/src/context_bootstrap/file_api/file.rs@@ -52,10 +52,10 @@ struct FileConstructorArgs<'s> {#[webidl(required,name = "fileBits",- converter = "raw",+ with = blob::required_blob_parts_argument,missing_message = "Failed to construct 'File': fileBits argument is required.")]- file_bits: v8::Local<'s, v8::Value>,+ file_bits: blob::BlobParts<'s>,#[webidl(required,name = "fileName",@@ -63,8 +63,16 @@ struct FileConstructorArgs<'s> {missing_message = "Failed to construct 'File': fileName argument is required.")]name: String,- #[webidl(index = 2, converter = "raw")]- options: Option<v8::Local<'s, v8::Value>>,+ #[webidl(dictionary)]+ options: FilePropertyBag,+}++#[derive(Default, webidl::WebIdlDictionary)]+#[webidl(prefix = "FilePropertyBag")]+struct FilePropertyBag {+ #[webidl(inherit)]+ base: blob::BlobPropertyBag,+ last_modified: Option<i64>,}pub(super) fn install_file_template_bindings<'s>(@@ -164,69 +172,28 @@ pub(in crate::context_bootstrap) fn file_constructor_callback<'s>(let Some(parsed) = webidl::parse_args::<FileConstructorArgs<'s>>(scope, &args) else {return;};- let options = parsed- .options- .unwrap_or_else(|| v8::undefined(scope).into());- let Some((bytes, mime_type)) = blob::collect_required_blob_bytes_and_type_with_options_context(- scope,- parsed.file_bits,- options,- "FilePropertyBag",- 3,- ) else {- return;+ let bytes = match parsed+ .file_bits+ .into_bytes(scope, parsed.options.base.line_endings())+ {+ Ok(bytes) => bytes,+ Err(error) => {+ webidl::throw_error(scope, &error);+ return;+ }};+ let mime_type = moli_file_api::normalize_blob_mime_type(&parsed.options.base.r#type);blob::init_blob_object(scope, args.this(), bytes, mime_type);- let Some(last_modified) = file_last_modified_from_options(scope, options) else {- return;- };- let last_modified = last_modified.unwrap_or_else(unix_epoch_millis);+ let last_modified = parsed+ .options+ .last_modified+ .map(|value| value as f64)+ .unwrap_or_else(unix_epoch_millis);initialize_file_metadata(scope, args.this(), &parsed.name, last_modified);rv.set(args.this().into());}-fn file_last_modified_from_options<'s>(- scope: &mut v8::PinScope<'s, '_>,- options_value: v8::Local<'s, v8::Value>,-) -> Option<Option<f64>> {- if options_value.is_null_or_undefined() {- return Some(None);- }- let Ok(options) = v8::Local::<v8::Object>::try_from(options_value) else {- return Some(None);- };- let value = match webidl::property_result(- scope,- options,- "lastModified",- webidl::Context::member("FilePropertyBag", "lastModified"),- ) {- Ok(value) => value,- Err(error) => {- webidl::throw_error(scope, &error);- return None;- }- };- let Some(value) = value else {- return Some(None);- };- if value.is_undefined() {- return Some(None);- }- match webidl::convert::<webidl::UnrestrictedDouble>(- scope,- value,- webidl::Context::member("FilePropertyBag", "lastModified"),- ) {- Ok(value) => Some(Some(value.0)),- Err(error) => {- webidl::throw_error(scope, &error);- None- }- }-}-pub(crate) fn build_file_object<'s>(scope: &mut v8::PinScope<'s, '_>,file: &SelectedFile,diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/blob_constructor.rs b/moli-renderer-v8/src/runtime/page_vm/tests/blob_constructor.rsnew file mode 100644index 000000000..4dd06552c--- /dev/null+++ b/moli-renderer-v8/src/runtime/page_vm/tests/blob_constructor.rs@@ -0,0 +1,66 @@+use super::*;++#[tokio::test(flavor = "current_thread")]+async fn blob_and_file_constructors_convert_before_processing_bytes() {+ run_blob_constructor_fixture(+ include_str!("../../../../tests/fixtures/blob-constructor-conversion.js"),+ 184,+ )+ .await;+}++#[tokio::test(flavor = "current_thread")]+async fn blob_and_file_constructors_copy_buffers_after_later_detachment() {+ run_blob_constructor_fixture(+ include_str!("../../../../tests/fixtures/blob-constructor-detachment.js"),+ 72,+ )+ .await;+}++async fn run_blob_constructor_fixture(fixture: &'static str, expected_checks: usize) {+ run_page_vm_async_test(async move {+ let loader =+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");+ let (mut page, _resource_source, _owner_wake) =+ page_vm_with_bound_task_sources_and_owner_wake(+ &loader,+ Url::parse("https://blob-constructor-conversion.test/")?,+ );+ page.vm_mut().eval(fixture)?;+ let deadline = Instant::now() + Duration::from_secs(20);+ while page.vm_mut().eval("typeof __uiEventResults")? == "undefined" {+ let _ = page+ .run_next_child_frame_task_source_for_semantic_test()+ .await;+ for selector in [+ PageSelectedTaskTestSelector::ResourceCompletion,+ PageSelectedTaskTestSelector::WorkerHostBridge,+ PageSelectedTaskTestSelector::DedicatedWorkerClientEvent,+ ] {+ let _ = page+ .run_exact_selected_page_task_for_test(selector, &loader)+ .await?;+ }+ anyhow::ensure!(+ Instant::now() < deadline,+ "Blob constructor fixture did not finish: {}",+ page.vm_mut()+ .eval("JSON.stringify(__blobConstructorProgress)")?+ );+ tokio::time::sleep(Duration::from_millis(1)).await;+ }+ let facts: serde_json::Value =+ serde_json::from_str(&page.vm_mut().eval("JSON.stringify(__uiEventResults)")?)?;+ let checks = facts["checks"].as_array().unwrap();+ let failures = checks+ .iter()+ .filter(|check| check["passed"] != true)+ .collect::<Vec<_>>();+ assert!(failures.is_empty(), "{failures:#?}");+ assert_eq!(checks.len(), expected_checks);+ Ok::<_, anyhow::Error>(())+ })+ .await+ .expect("Blob/File conversion preserves argument order and deferred buffer copying");+}diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rsindex 3b3e7b26b..f92fd1886 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs@@ -2260,4 +2260,5 @@ pub(super) async fn drain_page_work_until_no_pending_subresources(}mod extracted;+mod blob_constructor;mod blob_text;diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rsindex ffc7c85a2..e98803e44 100644--- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs+++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs@@ -90,7 +90,6 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[DirectCallOwner::JavaScriptEntryPoint,),// Browser-created functions, Promise capabilities, and algorithm steps.- allowed("blob.rs", 1, DirectCallOwner::BrowserAlgorithm),allowed("context_bootstrap/animation_runtime.rs",1,diff --git a/moli-renderer-v8/tests/fixtures/blob-constructor-conversion.js b/moli-renderer-v8/tests/fixtures/blob-constructor-conversion.jsnew file mode 100644index 000000000..5279354fb--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/blob-constructor-conversion.js@@ -0,0 +1,141 @@+(async () => {+ const checks = [];+ globalThis.__blobConstructorProgress = {stage: 'setup', checks};+ async function runMatrix(owner, callee, prefix, checks) {+ const capture = action => {+ try {return {value: action()};} catch (error) {return {error};}+ };+ for (const kind of ['Blob', 'File']) {+ const label = `${prefix}/${kind}`;+ if (globalThis.__blobConstructorProgress) __blobConstructorProgress.stage = label;+ const C = callee[kind];+ const create = (parts, options, name = 'file.txt') => kind === 'Blob'+ ? new C(parts, options) : new C(parts, name, options);+ const check = (name, passed, detail) => checks.push({name: `${label}/${name}`, passed, detail});+ const events = [];+ const parts = {+ get [Symbol.iterator]() {+ events.push('iterator.get');+ return () => {+ events.push('iterator.call');+ let next = 0;+ return {next() {+ events.push('next');+ return next++ === 0 ? {value: {toString() {events.push('part.string'); return 'a';}}, done: false} : {done: true};+ }};+ };+ }+ };+ const result = create(parts, {+ get endings() {events.push('endings.get'); return {toString() {events.push('endings.string'); return 'transparent';}};},+ get type() {events.push('type.get'); return {toString() {events.push('type.string'); return 'TEXT/PLAIN';}};},+ get lastModified() {events.push('modified.get'); return {valueOf() {events.push('modified.number'); return 17;}};}+ }, {toString() {events.push('name.string'); return 'file.txt';}});+ const expected = ['iterator.get', 'iterator.call', 'next', 'part.string', 'next'];+ if (kind === 'File') expected.push('name.string');+ expected.push('endings.get', 'endings.string', 'type.get', 'type.string');+ if (kind === 'File') expected.push('modified.get', 'modified.number');+ check('argument and inherited dictionary order', events.join() === expected.join(), {events, expected});+ check('successful metadata and bytes', await result.text() === 'a' && result.type === 'text/plain' && (kind === 'Blob' || result.name === 'file.txt' && result.lastModified === 17));++ const partError = new callee.Error('part sentinel');+ const optionError = new callee.Error('option sentinel');+ let gets = 0;+ let outcome = capture(() => create([{toString() {throw partError;}}], {get endings() {gets++; throw optionError;}}));+ check('part exception precedes dictionary getters', outcome.error === partError && gets === 0, {error: outcome.error?.message, gets});+ outcome = capture(() => create([{toString() {throw partError;}}], 17));+ check('part conversion precedes invalid dictionary', outcome.error === partError, outcome.error?.name);+ let conversions = 0;+ outcome = capture(() => create([{toString() {conversions++; return 'a';}}], {endings: 'invalid'}));+ check('part conversion precedes enum validation', conversions === 1 && outcome.error instanceof callee.TypeError, {conversions, error: outcome.error?.name});++ const mutableParts = ['before'];+ const changed = create(mutableParts, {get endings() {mutableParts[0] = 'after'; return 'transparent';}});+ check('dictionary cannot replace already converted strings', await changed.text() === 'before');+ const appendParts = ['a'];+ const appended = create(appendParts, {get endings() {appendParts.push('extra'); return 'transparent';}});+ check('dictionary cannot append to converted sequence', await appended.text() === 'a');++ const data = new owner.Uint8Array([65]);+ const delayed = create([data], {get type() {data[0] = 66; return 'text/plain';}});+ check('buffer copying follows dictionary conversion', await delayed.text() === 'B');+ const earlier = new owner.Uint8Array([65]);+ const modified = create([earlier, {toString() {earlier[0] = 66; return 'S';}}]);+ check('buffer copying follows all part conversions', await modified.text() === 'BS');++ for (const [name, value] of [+ ['resizable buffer', new owner.ArrayBuffer(4, {maxByteLength: 8})],+ ['resizable view', new owner.Uint8Array(new owner.ArrayBuffer(4, {maxByteLength: 8}))]+ ]) {+ outcome = capture(() => create([value]));+ check(name + ' is rejected', outcome.error instanceof callee.TypeError, outcome.error?.name);+ }+ if (typeof owner.SharedArrayBuffer === 'function') {+ for (const [name, value] of [+ ['shared buffer', new owner.SharedArrayBuffer(4)],+ ['shared view', new owner.Uint8Array(new owner.SharedArrayBuffer(4))]+ ]) {+ outcome = capture(() => create([value]));+ check(name + ' is rejected', outcome.error instanceof callee.TypeError, outcome.error?.name);+ }+ }++ const item = new owner.Blob(['blob']);+ item.toString = () => {throw partError;};+ check('native Blob union ignores string coercion', await create([item]).text() === 'blob');+ const noClose = {count: 0};+ outcome = capture(() => create({[Symbol.iterator]() {+ return {next() {return {value: {toString() {throw partError;}}, done: false};}, return() {noClose.count++; return {done: true};}};+ }}));+ check('sequence failure propagates without IteratorClose', outcome.error === partError && noClose.count === 0);++ if (kind === 'File') {+ let names = 0;+ outcome = capture(() => create([{toString() {throw partError;}}], undefined, {toString() {names++; throw optionError;}}));+ check('fileBits precede fileName conversion', outcome.error === partError && names === 0, {names, error: outcome.error?.message});+ for (const [name, value, expected] of [+ ['NaN', NaN, 0], ['infinity', Infinity, 0], ['negative infinity', -Infinity, 0],+ ['signed wrap', 2 ** 63, -(2 ** 63)], ['unsigned wrap', 2 ** 64 + 8192, 8192]+ ]) {+ const file = create([], {lastModified: value});+ check('lastModified ' + name, file.lastModified === expected, {actual: file.lastModified, expected});+ }+ }+ }+ if (owner.document) {+ const list = owner.document.querySelectorAll('__missing');+ const iteratorEvents = [];+ Object.defineProperty(list, Symbol.iterator, {configurable: true, get() {+ iteratorEvents.push('get');+ return function* () {iteratorEvents.push('run'); yield 'custom';};+ }});+ const value = new callee.Blob(list);+ checks.push({name: `${prefix}/platform custom iterator`, passed: await value.text() === 'custom' && iteratorEvents.join() === 'get,run', detail: iteratorEvents});+ }+ }+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ const realms = [['top', window], ['child', frame.contentWindow]];+ for (const [ownerName, owner] of realms) for (const [calleeName, callee] of realms) {+ await runMatrix(owner, callee, `${ownerName}/${calleeName}`, checks);+ }+ __blobConstructorProgress.stage = 'worker constructors';+ const workerBody = async runMatrix => {+ const checks = [];+ await runMatrix(globalThis, globalThis, 'worker', checks);+ postMessage(checks); close();+ };+ const url = URL.createObjectURL(new Blob([`(${workerBody})(${runMatrix})`], {type: 'text/javascript'}));+ const worker = new Worker(url);+ try {+ checks.push(...await new Promise((resolve, reject) => {+ worker.onmessage = event => resolve(event.data);+ worker.onerror = event => reject(Error(event.message));+ }));+ } finally {worker.terminate(); URL.revokeObjectURL(url); frame.remove();}+ globalThis.__uiEventResults = {checks};+})().catch(error => {+ const checks = globalThis.__blobConstructorProgress.checks;+ checks.push({name: 'fixture completion', passed: false, detail: String(error.stack || error)});+ globalThis.__uiEventResults = {checks};+});diff --git a/moli-renderer-v8/tests/fixtures/blob-constructor-detachment.js b/moli-renderer-v8/tests/fixtures/blob-constructor-detachment.jsnew file mode 100644index 000000000..e7ccc0463--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/blob-constructor-detachment.js@@ -0,0 +1,32 @@+(async () => {+ const checks = [];+ globalThis.__blobConstructorProgress = {stage: 'detachment', checks};+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ try {+ const realms = [['top', window], ['child', frame.contentWindow]];+ for (const [sourceName, owner] of realms) for (const [calleeName, callee] of realms) {+ for (const kind of ['Blob', 'File']) for (const source of ['buffer', 'typed view', 'DataView']) {+ for (const phase of ['before conversion', 'dictionary conversion', 'later part conversion']) {+ const buffer = new owner.ArrayBuffer(4);+ new owner.Uint8Array(buffer).set([65, 66, 67, 68]);+ const value = source === 'buffer' ? buffer : source === 'typed view'+ ? new owner.Uint8Array(buffer, 1, 2) : new owner.DataView(buffer, 1, 2);+ const detach = () => buffer.transfer();+ if (phase === 'before conversion') detach();+ const parts = [value];+ if (phase === 'later part conversion') parts.push({toString() {detach(); return 'S';}});+ const options = phase === 'dictionary conversion' ? {get type() {detach(); return 'text/plain';}} : {};+ const expected = phase === 'later part conversion' ? 'S' : '';+ const name = `${sourceName}/${calleeName}/${kind}/${source}/${phase}`;+ try {+ const result = kind === 'Blob' ? new callee.Blob(parts, options) : new callee.File(parts, 'name', options);+ const actual = await result.text();+ checks.push({name, passed: actual === expected && buffer.byteLength === 0, detail: {actual, expected}});+ } catch (error) {checks.push({name, passed: false, detail: String(error.stack || error)});}+ }+ }+ }+ } finally {frame.remove();}+ globalThis.__uiEventResults = {checks};+})().catch(error => {globalThis.__uiEventResults = {checks: [{name: 'fixture completion', passed: false, detail: String(error.stack || error)}]};});