Truly independent web browser
LibWeb: Implement CompressionStream and DecompressionStream in Rust
Shannon Boothb43e661e69a6
diff --git a/Cargo.lock b/Cargo.lockindex 49b60e31a04..7f32b7b0804 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -917,6 +917,7 @@ dependencies = ["encoding_rs","ladybird_allocator","libcompositing_rust",+ "libcompress_rust","libgfx_rust","libjs_rust","libtextcodec_rust",diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.tomlindex 8de8a27559c..6c5e2a38ae5 100644--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml@@ -22,6 +22,7 @@ ak = { path = "../../../../AK/Rust" }encoding_rs = "0.8.42"ladybird_allocator = { path = "../../../RustAllocator", optional = true }libcompositing_rust = { path = "../../../LibCompositing/Rust" }+libcompress_rust = { path = "../../../LibCompress/Rust" }libgfx_rust = { path = "../../../LibGfx/Rust", default-features = false }libjs_rust = { path = "../../../LibJS/Rust", default-features = false }libtextcodec_rust = { path = "../../../LibTextCodec/Rust" }diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex d93fea34dfd..cccec1b3a3a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -13,17 +13,18 @@ use std::borrow::Cow;use ak::{Utf16String, Utf16StringUnits, convert_valid_utf16_to_utf8, utf8_length_from_valid_utf16};use libjs_rust::api::{- Array, ArrayBuffer, ArrayBufferOrder, DataView, ErrorKind, ErrorType, FunctionObject, Gc, MarkedVec, Must, Object,- PrimitiveString, PropertyKey, Root, ThrowCompletionOr, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,- get_iterator_from_method_impl, get_view_byte_length, is_typed_array_out_of_bounds, is_view_out_of_bounds,- iterator_step_value, make_data_view_with_buffer_witness_record, make_typed_array_with_buffer_witness_record,- to_well_formed, typed_array_byte_length,+ Array, ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, DataView, ErrorKind, ErrorType, FunctionObject, Gc,+ MarkedVec, Must, Object, PrimitiveString, PropertyKey, Root, ThrowCompletionOr, Trace, TypedArrayBase,+ TypedArrayKind, Value, Vm, create_typed_array_on_buffer, get_iterator_from_method_impl, get_view_byte_length,+ is_typed_array_out_of_bounds, is_view_out_of_bounds, iterator_step_value,+ make_data_view_with_buffer_witness_record, make_typed_array_with_buffer_witness_record, to_well_formed,+ typed_array_byte_length,};use crate::ak_format::ak_formatted;-use crate::bindings::CallContext;use crate::bindings::interface::{Interface, Ref, create_dictionary_object, wrap};use crate::bindings::services::web_bindings_object_implements_interface;+use crate::bindings::{CallContext, Exception, WebIdlResult};/// A USVString, a string without lone surrogates. Its UTF-16 code units are always well-formed.#[derive(Clone, Eq, PartialEq)]@@ -646,6 +647,20 @@ unsafe fn borrowed_or_copied_bytes_of_buffer(buffer: &ArrayBuffer, bytes: Range<Some(Cow::Borrowed(unsafe { ak::slice_from_raw_parts(data, bytes.len()) }))}+/// https://webidl.spec.whatwg.org/#arraybufferview-create, for a Uint8Array in the realm of the call context.+pub(crate) fn create_uint8_array(cx: &CallContext, bytes: &[u8]) -> WebIdlResult<Gc<Object>> {+ let length = u32::try_from(bytes.len())+ .map_err(|_| Exception::RangeError(ErrorType::InvalidLength.message(&[&"typed array"])))?;+ let buffer =+ ArrayBuffer::try_create_written_by(cx.vm(), cx.realm(), bytes.len(), ArrayBufferShared::No, |output| {+ for (byte, value) in output.iter_mut().zip(bytes) {+ byte.write(*value);+ }+ bytes.len()+ })?;+ Ok(create_typed_array_on_buffer(cx.vm(), cx.realm(), TypedArrayKind::Uint8Array, length, buffer).upcast())+}+impl ArrayBufferView {/// # Safety///diff --git a/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rsnew file mode 100644index 00000000000..4b5952ec821--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs@@ -0,0 +1,154 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! CompressionStream, https://compression.spec.whatwg.org/#compressionstream++use core::cell::RefCell;+use std::io;++use ak::Utf16String;+use libcompress_rust::{Compressor, Format};+use libjs_rust::api::{EmbedderClass, EmbedderValue, Trace, Value};++use crate::bindings::conversions::{CppInterface, create_uint8_array};+use crate::bindings::interface::Wrappable;+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::compression::buffer_source_of_chunk;+use crate::streams::generic_transform_stream::{TransformSteps, TransformStream};++/// https://compression.spec.whatwg.org/#enumdef-compressionformat+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum CompressionFormat {+ Brotli,+ Deflate,+ DeflateRaw,+ Gzip,+}++impl From<CompressionFormat> for Format {+ fn from(format: CompressionFormat) -> Self {+ match format {+ CompressionFormat::Brotli => Format::Brotli,+ CompressionFormat::Deflate => Format::Zlib,+ CompressionFormat::DeflateRaw => Format::Deflate,+ CompressionFormat::Gzip => Format::Gzip,+ }+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CompressionStream {+ // https://streams.spec.whatwg.org/#generictransformstream-transform+ transform: TransformStream,+}++impl Wrappable for CompressionStream {}++impl CompressionStream {+ // https://compression.spec.whatwg.org/#dom-compressionstream-compressionstream+ pub(crate) fn construct(cx: &mut CallContext, format: CompressionFormat) -> WebIdlResult<Self> {+ // 1. If format is unsupported in CompressionStream, then throw a TypeError.+ // 2. Set this's format to format.+ let context = CompressionContext::new(format);++ // 3. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the compress and enqueue a chunk+ // algorithm with this and chunk.+ // 4. Let flushAlgorithm be an algorithm which takes no argument and runs the compress flush and enqueue algorithm with this.+ // 5. Set this's transform to a new TransformStream.+ // 6. Set up this's transform with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.+ Ok(Self {+ transform: TransformStream::create_and_set_up(cx, context),+ })+ }++ // https://streams.spec.whatwg.org/#dom-generictransformstream-readable+ pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // The readable getter steps are to return this's transform.[[readable]].+ Ok(self.transform.readable(cx))+ }++ // https://streams.spec.whatwg.org/#dom-generictransformstream-writable+ pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // The writable getter steps are to return this's transform.[[writable]].+ Ok(self.transform.writable(cx))+ }+}++/// https://compression.spec.whatwg.org/#compression-context, which the algorithms of the stream's transform run on.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct CompressionContext {+ #[gc(untraced)]+ compressor: RefCell<Compressor>,+}++static COMPRESSION_CONTEXT_CLASS: EmbedderClass<CompressionContext> = EmbedderClass::new("CompressionContext");++impl EmbedderValue for CompressionContext {+ const CLASS: &'static EmbedderClass<Self> = &COMPRESSION_CONTEXT_CLASS;+}++impl CompressionContext {+ fn new(format: CompressionFormat) -> Self {+ Self {+ compressor: RefCell::new(Compressor::new(format.into())),+ }+ }+}++fn compression_failed(step: &str, error: &io::Error) -> Exception {+ Exception::TypeError(Utf16String::from_utf8(&format!("Unable to compress {step}: {error}")))+}++impl TransformSteps for CompressionContext {+ // https://compression.spec.whatwg.org/#compress-and-enqueue-a-chunk+ fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()> {+ // 1. If chunk is not a BufferSource type, then throw a TypeError.+ let chunk = buffer_source_of_chunk(cx, chunk)?;++ // 2. Let buffer be the result of compressing chunk with cs's format and context.+ // SAFETY: Compressing neither runs script nor allocates a cell.+ let buffer = unsafe { chunk.with_bytes(|bytes| self.compressor.borrow_mut().compress(bytes)) }+ .map_err(|error| compression_failed("chunk", &error))?;++ // 3. If buffer is empty, return.+ if buffer.is_empty() {+ return Ok(());+ }++ // 4. Let arrays be the result of splitting buffer into one or more non-empty pieces and converting them into+ // Uint8Arrays.+ let array = create_uint8_array(cx, &buffer)?;++ // 5. For each Uint8Array array of arrays, enqueue array in cs's transform.+ transform.enqueue(Value::from_object(array));+ Ok(())+ }++ // https://compression.spec.whatwg.org/#compress-flush-and-enqueue+ fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()> {+ // 1. Let buffer be the result of compressing an empty input with cs's format and context, with the finish flag.+ let buffer = self+ .compressor+ .borrow_mut()+ .finish()+ .map_err(|error| compression_failed("flush", &error))?;++ // 2. If buffer is empty, return.+ if buffer.is_empty() {+ return Ok(());+ }++ // 3. Let arrays be the result of splitting buffer into one or more non-empty pieces and converting them into+ // Uint8Arrays.+ let array = create_uint8_array(cx, &buffer)?;++ // 4. For each Uint8Array array of arrays, enqueue array in cs's transform.+ transform.enqueue(Value::from_object(array));+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rsnew file mode 100644index 00000000000..f6bcb036a1c--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs@@ -0,0 +1,160 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! DecompressionStream, https://compression.spec.whatwg.org/#decompressionstream++use core::cell::RefCell;++use ak::Utf16String;+use libcompress_rust::{Decompressed, Decompressor};+use libjs_rust::api::{EmbedderClass, EmbedderValue, Trace, Value};++use crate::bindings::conversions::{CppInterface, create_uint8_array};+use crate::bindings::interface::Wrappable;+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::compression::buffer_source_of_chunk;+use crate::compression::compression_stream::CompressionFormat;+use crate::streams::generic_transform_stream::{TransformSteps, TransformStream};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DecompressionStream {+ // https://streams.spec.whatwg.org/#generictransformstream-transform+ transform: TransformStream,+}++impl Wrappable for DecompressionStream {}++impl DecompressionStream {+ // https://compression.spec.whatwg.org/#dom-decompressionstream-decompressionstream+ pub(crate) fn construct(cx: &mut CallContext, format: CompressionFormat) -> WebIdlResult<Self> {+ // 1. If format is unsupported in DecompressionStream, then throw a TypeError.+ // 2. Set this's format to format.+ let context = DecompressionContext::new(format);++ // 3. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the decompress and enqueue a chunk+ // algorithm with this and chunk.+ // 4. Let flushAlgorithm be an algorithm which takes no argument and runs the decompress flush and enqueue algorithm with this.+ // 5. Set this's transform to a new TransformStream.+ // 6. Set up this's transform with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.+ Ok(Self {+ transform: TransformStream::create_and_set_up(cx, context),+ })+ }++ // https://streams.spec.whatwg.org/#dom-generictransformstream-readable+ pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // The readable getter steps are to return this's transform.[[readable]].+ Ok(self.transform.readable(cx))+ }++ // https://streams.spec.whatwg.org/#dom-generictransformstream-writable+ pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ // The writable getter steps are to return this's transform.[[writable]].+ Ok(self.transform.writable(cx))+ }+}++/// https://compression.spec.whatwg.org/#compression-context, which the algorithms of the stream's transform run on.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct DecompressionContext {+ #[gc(untraced)]+ decompressor: RefCell<Decompressor>,+}++static DECOMPRESSION_CONTEXT_CLASS: EmbedderClass<DecompressionContext> = EmbedderClass::new("DecompressionContext");++impl EmbedderValue for DecompressionContext {+ const CLASS: &'static EmbedderClass<Self> = &DECOMPRESSION_CONTEXT_CLASS;+}++impl DecompressionContext {+ fn new(format: CompressionFormat) -> Self {+ Self {+ decompressor: RefCell::new(Decompressor::new(format.into())),+ }+ }++ fn decompress(&self, input: &[u8]) -> Result<Decompressed, String> {+ self.decompressor+ .borrow_mut()+ .decompress(input)+ .map_err(|error| error.to_string())+ }++ fn has_reached_end_of_compressed_input(&self) -> bool {+ self.decompressor.borrow().has_reached_end()+ }+}++fn decompression_failed(step: &str, error: &str) -> Exception {+ Exception::TypeError(Utf16String::from_utf8(&format!("Unable to decompress {step}: {error}")))+}++impl TransformSteps for DecompressionContext {+ // https://compression.spec.whatwg.org/#decompress-and-enqueue-a-chunk+ fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()> {+ // 1. If chunk is not a BufferSource type, then throw a TypeError.+ let chunk = buffer_source_of_chunk(cx, chunk)?;++ // 2. Let buffer be the result of decompressing chunk with ds's format and context. If this results in an error,+ // then throw a TypeError.+ // SAFETY: Decompressing neither runs script nor allocates a cell.+ let decompressed = unsafe { chunk.with_bytes(|bytes| self.decompress(bytes)) }+ .map_err(|error| decompression_failed("chunk", &error))?;+ let buffer = decompressed.output;++ // 3. If buffer is empty, return.+ // AD-HOC: Skip steps 4 and 5 instead, so that step 6 also rejects a chunk that gives no output.+ // See: https://github.com/whatwg/compression/issues/78+ if !buffer.is_empty() {+ // 4. Let arrays be the result of splitting buffer into one or more non-empty pieces and converting them+ // into Uint8Arrays.+ let array = create_uint8_array(cx, &buffer)?;++ // 5. For each Uint8Array array of arrays, enqueue array in ds's transform.+ transform.enqueue(Value::from_object(array));+ }++ // 6. If the end of the compressed input has been reached, and ds's context has not fully consumed chunk, then+ // throw a TypeError.+ if self.has_reached_end_of_compressed_input() && decompressed.unconsumed_input > 0 {+ return Err(decompression_failed(+ "chunk",+ "Data after the end of the compressed input",+ ));+ }+ Ok(())+ }++ // https://compression.spec.whatwg.org/#decompress-flush-and-enqueue+ fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()> {+ // 1. Let buffer be the result of decompressing an empty input with ds's format and context, with the finish+ // flag.+ // NB: Each chunk gave all the output that the decoder could make of it, so an empty input gives no more.+ let buffer = self+ .decompress(&[])+ .map_err(|error| decompression_failed("flush", &error))?+ .output;++ // 2. If buffer is not empty:+ if !buffer.is_empty() {+ // 1. Let arrays be the result of splitting buffer into one or more non-empty pieces and converting them+ // into Uint8Arrays.+ let array = create_uint8_array(cx, &buffer)?;++ // 2. For each Uint8Array array of arrays, enqueue array in ds's transform.+ transform.enqueue(Value::from_object(array));+ }++ // 3. If the end of the compressed input has not been reached, then throw a TypeError.+ if !self.has_reached_end_of_compressed_input() {+ return Err(decompression_failed("flush", "The compressed input ended early"));+ }+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/compression/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/compression/mod.rsnew file mode 100644index 00000000000..b029e693617--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/mod.rs@@ -0,0 +1,31 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Compression Standard, https://compression.spec.whatwg.org/++pub(crate) mod compression_stream;+pub(crate) mod decompression_stream;++use ak::Utf16String;+use libjs_rust::api::Value;++use crate::bindings::conversions::{BufferSource, BufferSourceRules, buffer_source_if};+use crate::bindings::{CallContext, Exception, WebIdlResult};++/// The chunk as a BufferSource, or the TypeError that compressing or decompressing a chunk throws when it is not a+/// BufferSource type.+fn buffer_source_of_chunk(cx: &CallContext, chunk: Value) -> WebIdlResult<BufferSource> {+ let rules = BufferSourceRules {+ allow_shared: false,+ allow_resizable: false,+ };+ let buffer_source = if chunk.is_object() {+ buffer_source_if(cx.vm(), chunk.as_object(), &rules)?+ } else {+ None+ };+ buffer_source.ok_or_else(|| Exception::TypeError(Utf16String::from_ascii(b"Chunk is not a BufferSource type")))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 29cdab44c2f..2b8d4c1ce6c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -39,6 +39,16 @@ pub(crate) mod bindings;reason = "the bindings call every attribute and operation as one that can throw")]pub(crate) mod canvas_2d;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]+pub(crate) mod compression;#[cfg_attr(not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces")diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rsnew file mode 100644index 00000000000..130362af303--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rs@@ -0,0 +1,153 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The TransformStream of an interface that includes GenericTransformStream,+//! https://streams.spec.whatwg.org/#generictransformstream, which LibWeb implements in C++.++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{+ EmbedderCell, EmbedderValue, ForeignCellSlot, Gc, Object, RawNativeFunctionResult, Trace, Value,+};++use crate::bindings::conversions::CppInterface;+use crate::bindings::interface::realm_arguments;+use crate::bindings::{CallContext, WebIdlResult};++/// The steps of the transformAlgorithm, with the chunk, and of the flushAlgorithm, without one.+type StepsEntry = unsafe extern "C" fn(+ vm: *mut c_void,+ realm: *mut c_void,+ steps: *mut c_void,+ transform: *mut c_void,+ chunk: *const u64,+) -> RawNativeFunctionResult;++/// Web::Streams::TransformStreamSide+#[repr(u8)]+enum Side {+ Readable,+ Writable,+}++unsafe extern "C" {+ /// A new TransformStream in the realm, set up with a transformAlgorithm and a flushAlgorithm that call the entry+ /// with the steps, a cell that the stream keeps alive.+ fn web_transform_stream_create(realm: *mut c_void, steps: *mut c_void, run_steps: StepsEntry) -> *mut c_void;++ fn web_transform_stream_enqueue(transform: *mut c_void, chunk: u64);++ /// The wrapper in the realm of the stream's [[readable]] or [[writable]].+ fn web_transform_stream_side(transform: *mut c_void, realm: *mut c_void, side: Side) -> *mut c_void;+}++/// The transformAlgorithm and flushAlgorithm that a TransformStream is set up with,+/// https://streams.spec.whatwg.org/#transformstream-set-up, which the stream holds in a cell of their own. They+/// resolve the promise that the algorithm returns, or reject it with what they throw.+pub(crate) trait TransformSteps: EmbedderValue {+ fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()>;++ fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()>;+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TransformStream(ForeignCellSlot);++impl TransformStream {+ /// # Safety+ ///+ /// `transform` must be a live TransformStream.+ unsafe fn from_raw(transform: *mut c_void) -> Self {+ let slot = ForeignCellSlot::empty();+ // SAFETY: The caller passes a live TransformStream, a cell of the heap.+ unsafe { slot.set(Some(NonNull::new(transform).expect("LibWeb passes a TransformStream"))) };+ Self(slot)+ }++ /// A new TransformStream, set up with the steps,+ /// https://streams.spec.whatwg.org/#transformstream-set-up+ pub(crate) fn create_and_set_up<T: TransformSteps>(cx: &CallContext, steps: T) -> Self {+ let steps = T::CLASS.allocate(cx.vm(), steps);+ // SAFETY: The realm and the cell are live, and the entry takes a cell of the class of the steps.+ unsafe {+ Self::from_raw(web_transform_stream_create(+ cx.realm().as_ptr().cast(),+ steps.as_ptr().cast(),+ run_steps::<T>,+ ))+ }+ }++ /// https://streams.spec.whatwg.org/#transformstream-enqueue+ pub(crate) fn enqueue(&self, chunk: Value) {+ // SAFETY: The slot keeps the stream alive.+ unsafe { web_transform_stream_enqueue(self.0.as_ptr(), chunk.0) };+ }++ /// The stream's [[readable]].+ pub(crate) fn readable(&self, cx: &CallContext) -> CppInterface {+ self.side(cx, Side::Readable)+ }++ /// The stream's [[writable]].+ pub(crate) fn writable(&self, cx: &CallContext) -> CppInterface {+ self.side(cx, Side::Writable)+ }++ fn side(&self, cx: &CallContext, side: Side) -> CppInterface {+ // SAFETY: The slot keeps the stream alive, and the realm is live.+ let wrapper = unsafe { web_transform_stream_side(self.0.as_ptr(), cx.realm().as_ptr().cast(), side) };+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns a wrapper");+ // SAFETY: LibWeb returns a live wrapper of the ReadableStream or the WritableStream that the side names.+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }+ }+}++/// The steps of the transformAlgorithm, given a chunk, or else of the flushAlgorithm, of a TransformStream that+/// create_and_set_up() set up.+///+/// # Safety+///+/// LibWeb passes the VM, the realm of the stream, the cell of the steps, which the stream keeps alive, the stream, and+/// a chunk that is live for the call or null.+unsafe extern "C" fn run_steps<T: TransformSteps>(+ vm: *mut c_void,+ realm: *mut c_void,+ steps: *mut c_void,+ transform: *mut c_void,+ chunk: *const u64,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the live VM, realm, cell and stream.+ let (cx, steps, transform) = unsafe { steps_arguments::<T>(vm, realm, steps, transform) };+ let _type_error_realm = cx.vm().type_error_realm_scope(cx.realm());+ // SAFETY: The caller passes a chunk that is live for the call, or null.+ let result = match unsafe { chunk.as_ref() } {+ Some(&chunk) => steps.transform(&cx, &transform, Value(chunk)),+ None => steps.flush(&cx, &transform),+ };+ RawNativeFunctionResult::from_completion(result.map(|()| Value::UNDEFINED).map_err(|error| error.throw(&cx)))+}++/// # Safety+///+/// The pointers must be the live VM, a live realm, a live cell of the class of the steps and a live TransformStream.+unsafe fn steps_arguments<'vm, T: TransformSteps>(+ vm: *mut c_void,+ realm: *mut c_void,+ steps: *mut c_void,+ transform: *mut c_void,+) -> (CallContext<'vm>, Gc<EmbedderCell<T>>, TransformStream) {+ // SAFETY: The caller passes the live VM and realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ let steps = NonNull::new(steps).expect("LibWeb passes the steps");+ // SAFETY: The caller passes a live cell of an embedder class.+ let steps = unsafe { T::CLASS.downcast(steps) }.expect("LibWeb passes the steps it was given");+ // SAFETY: The caller passes a live TransformStream.+ let transform = unsafe { TransformStream::from_raw(transform) };+ (CallContext::new(vm, realm), steps, transform)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rsindex e7302f49111..5553de84996 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rs@@ -10,4 +10,6 @@pub(crate) mod byte_length_queuing_strategy;#[cfg(not(test))]pub(crate) mod count_queuing_strategy;+#[cfg(not(test))]+pub(crate) mod generic_transform_stream;pub(crate) mod queuing_strategy_init;diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 4a6ab326b92..8f0cb725155 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -38,8 +38,6 @@ set(SOURCESCompositor/CompositorHost.cppCompositor/NavigablePresenter.cppCompositor/RenderClock.cpp- Compression/CompressionStream.cpp- Compression/DecompressionStream.cppContentSecurityPolicy/BlockingAlgorithms.cppContentSecurityPolicy/Directives/BaseUriDirective.cppContentSecurityPolicy/Directives/ChildSourceDirective.cpp@@ -1136,7 +1134,7 @@ target_sources(LibWeb PRIVATE $<TARGET_OBJECTS:LibJSObjects>)target_compile_definitions(LibWeb PRIVATE LibJS_EXPORTS)target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon LibJSHeaders)-target_link_libraries(LibWeb PRIVATE LibCore LibCompress LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasm LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)+target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasm LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)# LibWeb still includes ANGLE's GLES headers for WebGL constants and types, but# the actual GL entry points live in the Compositor. Copy only ANGLE's compilediff --git a/Libraries/LibWeb/Compression/CompressionStream.cpp b/Libraries/LibWeb/Compression/CompressionStream.cppdeleted file mode 100644index 48d1810e145..00000000000--- a/Libraries/LibWeb/Compression/CompressionStream.cpp+++ /dev/null@@ -1,177 +0,0 @@-/*- * Copyright (c) 2024, Tim Flynn <[email protected]>- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCompress/Brotli.h>-#include <LibCompress/Deflate.h>-#include <LibCompress/Gzip.h>-#include <LibCompress/Zlib.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Bindings/CompressionStream.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Compression/CompressionStream.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/TransformStreamOperations.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/WebIDL/AbstractOperations.h>--namespace Web::Compression {--GC_DEFINE_ALLOCATOR(CompressionStream);--static ErrorOr<Compressor> create_compressor(Bindings::CompressionFormat format, AllocatingMemoryStream& input_stream)-{- auto stream = MaybeOwned<Stream> { input_stream };- switch (format) {- case Bindings::CompressionFormat::Brotli:- return TRY(Compress::BrotliCompressor::create(move(stream)));- case Bindings::CompressionFormat::Deflate:- return TRY(Compress::ZlibCompressor::create(move(stream)));- case Bindings::CompressionFormat::DeflateRaw:- return TRY(Compress::DeflateCompressor::create(move(stream)));- case Bindings::CompressionFormat::Gzip:- return TRY(Compress::GzipCompressor::create(move(stream)));- }-- VERIFY_NOT_REACHED();-}--WebIDL::ExceptionOr<GC::Ref<CompressionStream>> CompressionStream::create_for_constructor(JS::Object& relevant_global_object, Bindings::CompressionFormat format)-{- // 1. If format is unsupported in CompressionStream, then throw a TypeError.- // 2. Set this's format to format.- auto input_stream = make<AllocatingMemoryStream>();- auto compressor = create_compressor(format, *input_stream);- if (compressor.is_error())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to create compressor: {}", compressor.error()) };-- return create(relevant_global_object, compressor.release_value(), move(input_stream));-}--// https://compression.spec.whatwg.org/#dom-compressionstream-compressionstream-WebIDL::ExceptionOr<GC::Ref<CompressionStream>> CompressionStream::create(JS::Object& relevant_global_object, Compressor compressor, NonnullOwnPtr<AllocatingMemoryStream> input_stream)-{- auto& realm = HTML::relevant_realm(relevant_global_object);-- // 5. Set this's transform to a new TransformStream.- // NOTE: We do this first so that we may store it as nonnull in the GenericTransformStream.- auto transform_stream = GC::Heap::the().allocate<Streams::TransformStream>();- auto stream = GC::Heap::the().allocate<CompressionStream>(transform_stream, move(compressor), move(input_stream));-- // 3. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the compress and enqueue a chunk- // algorithm with this and chunk.- auto transform_algorithm = GC::create_function(GC::Heap::the(), [stream, realm = GC::Ref(realm)](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {- if (auto result = stream->compress_and_enqueue_chunk(realm, chunk); result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());-- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 4. Let flushAlgorithm be an algorithm which takes no argument and runs the compress flush and enqueue algorithm with this.- auto flush_algorithm = GC::create_function(GC::Heap::the(), [stream, realm = GC::Ref(realm)]() -> GC::Ref<WebIDL::Promise> {- if (auto result = stream->compress_flush_and_enqueue(realm); result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());-- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 6. Set up this's transform with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.- stream->m_transform->set_up(realm, transform_algorithm, flush_algorithm);-- return stream;-}--CompressionStream::CompressionStream(GC::Ref<Streams::TransformStream> transform, Compressor compressor, NonnullOwnPtr<AllocatingMemoryStream> input_stream)- : Streams::GenericTransformStreamMixin(transform)- , m_compressor(move(compressor))- , m_output_stream(move(input_stream))-{-}--CompressionStream::~CompressionStream() = default;--void CompressionStream::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- Streams::GenericTransformStreamMixin::visit_edges(visitor);-}--// https://compression.spec.whatwg.org/#compress-and-enqueue-a-chunk-WebIDL::ExceptionOr<void> CompressionStream::compress_and_enqueue_chunk(JS::Realm& realm, JS::Value chunk)-{- // 1. If chunk is not a BufferSource type, then throw a TypeError.- if (!WebIDL::is_buffer_source_type(chunk))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Chunk is not a BufferSource type"_utf16 };-- // 2. Let buffer be the result of compressing chunk with cs's format and context.- auto maybe_buffer = [&]() -> ErrorOr<ByteBuffer> {- auto chunk_buffer = TRY(WebIDL::get_buffer_source_copy(chunk.as_object()));- return compress(chunk_buffer, Finish::No);- }();- if (maybe_buffer.is_error())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to compress chunk: {}", maybe_buffer.error()) };-- auto buffer = maybe_buffer.release_value();-- // 3. If buffer is empty, return.- if (buffer.is_empty())- return {};-- // 4. Split buffer into one or more non-empty pieces and convert them into Uint8Arrays.- auto array_buffer = JS::ArrayBuffer::create(realm, move(buffer));- auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);-- // 5. For each Uint8Array array, enqueue array in cs's transform.- TRY(Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), array));- return {};-}--// https://compression.spec.whatwg.org/#compress-flush-and-enqueue-WebIDL::ExceptionOr<void> CompressionStream::compress_flush_and_enqueue(JS::Realm& realm)-{- // 1. Let buffer be the result of compressing an empty input with cs's format and context, with the finish flag.- auto maybe_buffer = compress({}, Finish::Yes);- if (maybe_buffer.is_error())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to compress flush: {}", maybe_buffer.error()) };-- auto buffer = maybe_buffer.release_value();-- // 2. If buffer is empty, return.- if (buffer.is_empty())- return {};-- // 3. Split buffer into one or more non-empty pieces and convert them into Uint8Arrays.- auto array_buffer = JS::ArrayBuffer::create(realm, move(buffer));- auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);-- // 4. For each Uint8Array array, enqueue array in cs's transform.- TRY(Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), array));- return {};-}--ErrorOr<ByteBuffer> CompressionStream::compress(ReadonlyBytes bytes, Finish finish)-{- TRY(m_compressor.visit([&](auto const& compressor) {- return compressor->write_until_depleted(bytes);- }));-- if (finish == Finish::Yes) {- TRY(m_compressor.visit([](auto const& compressor) {- return compressor->finish();- }));- }-- auto buffer = TRY(ByteBuffer::create_uninitialized(m_output_stream->used_buffer_size()));- TRY(m_output_stream->read_until_filled(buffer.bytes()));-- return buffer;-}--}diff --git a/Libraries/LibWeb/Compression/CompressionStream.h b/Libraries/LibWeb/Compression/CompressionStream.hdeleted file mode 100644index b89c46d93ce..00000000000--- a/Libraries/LibWeb/Compression/CompressionStream.h+++ /dev/null@@ -1,63 +0,0 @@-/*- * Copyright (c) 2024, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/MemoryStream.h>-#include <AK/NonnullOwnPtr.h>-#include <AK/Variant.h>-#include <LibCompress/Forward.h>-#include <LibGC/Ptr.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Streams/GenericTransformStream.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Bindings {--enum class CompressionFormat : u8;--}--namespace Web::Compression {--using Compressor = Variant<- NonnullOwnPtr<Compress::BrotliCompressor>,- NonnullOwnPtr<Compress::ZlibCompressor>,- NonnullOwnPtr<Compress::DeflateCompressor>,- NonnullOwnPtr<Compress::GzipCompressor>>;--// https://compression.spec.whatwg.org/#compressionstream-class CompressionStream final- : public Bindings::GCAllocatedWrappable- , public Streams::GenericTransformStreamMixin {- WEB_WRAPPABLE(CompressionStream, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(CompressionStream);--public:- static WebIDL::ExceptionOr<GC::Ref<CompressionStream>> create(JS::Object& relevant_global_object, Compressor, NonnullOwnPtr<AllocatingMemoryStream>);- static WebIDL::ExceptionOr<GC::Ref<CompressionStream>> create_for_constructor(JS::Object&, Bindings::CompressionFormat);- virtual ~CompressionStream() override;--private:- CompressionStream(GC::Ref<Streams::TransformStream>, Compressor, NonnullOwnPtr<AllocatingMemoryStream>);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- WebIDL::ExceptionOr<void> compress_and_enqueue_chunk(JS::Realm&, JS::Value);- WebIDL::ExceptionOr<void> compress_flush_and_enqueue(JS::Realm&);-- enum class Finish {- No,- Yes,- };- ErrorOr<ByteBuffer> compress(ReadonlyBytes, Finish);-- Compressor m_compressor;- NonnullOwnPtr<AllocatingMemoryStream> m_output_stream;-};--}diff --git a/Libraries/LibWeb/Compression/CompressionStream.idl b/Libraries/LibWeb/Compression/CompressionStream.idlindex 45ef88b36f6..b909e3518c8 100644--- a/Libraries/LibWeb/Compression/CompressionStream.idl+++ b/Libraries/LibWeb/Compression/CompressionStream.idl@@ -7,7 +7,7 @@ enum CompressionFormat {};// https://compression.spec.whatwg.org/#compressionstream-[Exposed=*]+[Exposed=*, ImplementedIn=Rust]interface CompressionStream {constructor(CompressionFormat format);};diff --git a/Libraries/LibWeb/Compression/DecompressionStream.cpp b/Libraries/LibWeb/Compression/DecompressionStream.cppdeleted file mode 100644index 7952d6e9d64..00000000000--- a/Libraries/LibWeb/Compression/DecompressionStream.cpp+++ /dev/null@@ -1,171 +0,0 @@-/*- * Copyright (c) 2024, Tim Flynn <[email protected]>- * Copyright (c) 2025, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCompress/Brotli.h>-#include <LibCompress/Deflate.h>-#include <LibCompress/Gzip.h>-#include <LibCompress/Zlib.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Bindings/CompressionStream.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Compression/DecompressionStream.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/WebIDL/AbstractOperations.h>--namespace Web::Compression {--GC_DEFINE_ALLOCATOR(DecompressionStream);--static ErrorOr<Decompressor> create_decompressor(Bindings::CompressionFormat format, AllocatingMemoryStream& input_stream)-{- auto stream = MaybeOwned<Stream> { input_stream };- switch (format) {- case Bindings::CompressionFormat::Brotli:- return TRY(Compress::BrotliDecompressor::create(move(stream)));- case Bindings::CompressionFormat::Deflate:- return TRY(Compress::ZlibDecompressor::create(move(stream)));- case Bindings::CompressionFormat::DeflateRaw:- return TRY(Compress::DeflateDecompressor::create(move(stream)));- case Bindings::CompressionFormat::Gzip:- return TRY(Compress::GzipDecompressor::create(move(stream)));- }-- VERIFY_NOT_REACHED();-}--WebIDL::ExceptionOr<GC::Ref<DecompressionStream>> DecompressionStream::create_for_constructor(JS::Object& relevant_global_object, Bindings::CompressionFormat format)-{- // 1. If format is unsupported in DecompressionStream, then throw a TypeError.- // 2. Set this's format to format.- auto input_stream = make<AllocatingMemoryStream>();- auto decompressor = create_decompressor(format, *input_stream);- if (decompressor.is_error())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to create decompressor: {}", decompressor.error()) };-- return create(relevant_global_object, decompressor.release_value(), move(input_stream));-}--// https://compression.spec.whatwg.org/#dom-decompressionstream-decompressionstream-WebIDL::ExceptionOr<GC::Ref<DecompressionStream>> DecompressionStream::create(JS::Object& relevant_global_object, Decompressor decompressor, NonnullOwnPtr<AllocatingMemoryStream> input_stream)-{- auto& realm = HTML::relevant_realm(relevant_global_object);-- // 5. Set this's transform to a new TransformStream.- // NOTE: We do this first so that we may store it as nonnull in the GenericTransformStream.- auto transform_stream = GC::Heap::the().allocate<Streams::TransformStream>();- auto stream = GC::Heap::the().allocate<DecompressionStream>(transform_stream, move(decompressor), move(input_stream));-- // 3. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the decompress and enqueue a chunk- // algorithm with this and chunk.- auto transform_algorithm = GC::create_function(GC::Heap::the(), [stream, realm = GC::Ref(realm)](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {- if (auto result = stream->decompress_and_enqueue_chunk(realm, chunk); result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());-- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 4. Let flushAlgorithm be an algorithm which takes no argument and runs the decompress flush and enqueue algorithm with this.- auto flush_algorithm = GC::create_function(GC::Heap::the(), [stream, realm = GC::Ref(realm)]() -> GC::Ref<WebIDL::Promise> {- if (auto result = stream->decompress_flush_and_enqueue(realm); result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());-- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 6. Set up this's transform with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.- stream->m_transform->set_up(realm, transform_algorithm, flush_algorithm);-- return stream;-}--DecompressionStream::DecompressionStream(GC::Ref<Streams::TransformStream> transform, Decompressor decompressor, NonnullOwnPtr<AllocatingMemoryStream> input_stream)- : Streams::GenericTransformStreamMixin(transform)- , m_decompressor(move(decompressor))- , m_input_stream(move(input_stream))-{-}--DecompressionStream::~DecompressionStream() = default;--void DecompressionStream::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- Streams::GenericTransformStreamMixin::visit_edges(visitor);-}--// https://compression.spec.whatwg.org/#decompress-and-enqueue-a-chunk-WebIDL::ExceptionOr<void> DecompressionStream::decompress_and_enqueue_chunk(JS::Realm& realm, JS::Value chunk)-{- // 1. If chunk is not a BufferSource type, then throw a TypeError.- if (!WebIDL::is_buffer_source_type(chunk))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Chunk is not a BufferSource type"_utf16 };-- // 2. Let buffer be the result of decompressing chunk with ds's format and context. If this results in an error,- // then throw a TypeError.- auto maybe_buffer = [&]() -> ErrorOr<ByteBuffer> {- auto chunk_buffer = TRY(WebIDL::get_buffer_source_copy(chunk.as_object()));- TRY(m_input_stream->write_until_depleted(move(chunk_buffer)));-- auto decompressed = TRY(ByteBuffer::create_uninitialized(4096));- auto size = TRY(m_decompressor.visit([&](auto const& decompressor) -> ErrorOr<size_t> {- return TRY(decompressor->read_some(decompressed.bytes())).size();- }));- return decompressed.slice(0, size);- }();- if (maybe_buffer.is_error())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to decompress chunk: {}", maybe_buffer.error()) };-- auto buffer = maybe_buffer.release_value();-- // 3. If buffer is empty, return.- if (buffer.is_empty())- return {};-- // 4. Split buffer into one or more non-empty pieces and convert them into Uint8Arrays.- auto array_buffer = JS::ArrayBuffer::create(realm, move(buffer));- auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);-- // 5. For each Uint8Array array, enqueue array in ds's transform.- m_transform->enqueue(array);- return {};-}--// https://compression.spec.whatwg.org/#decompress-flush-and-enqueue-WebIDL::ExceptionOr<void> DecompressionStream::decompress_flush_and_enqueue(JS::Realm& realm)-{- // 1. Let buffer be the result of decompressing an empty input with ds's format and context, with the finish flag.- auto maybe_buffer = m_decompressor.visit([&](auto const& decompressor) -> ErrorOr<ByteBuffer> {- return TRY(decompressor->read_until_eof());- });- if (maybe_buffer.is_error())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to decompress flush: {}", maybe_buffer.error()) };-- auto buffer = maybe_buffer.release_value();-- // Note: LibCompress already throws an error if we call read_until_eof and no more progress can be made- // 2. If the end of the compressed input has not been reached, then throw a TypeError.- VERIFY(m_decompressor.visit([](auto const& decompressor) { return decompressor->is_eof(); }));-- // 3. If buffer is empty, return.- if (buffer.is_empty())- return {};-- // 4. Split buffer into one or more non-empty pieces and convert them into Uint8Arrays.- auto array_buffer = JS::ArrayBuffer::create(realm, move(buffer));- auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);-- // 5. For each Uint8Array array, enqueue array in ds's transform.- m_transform->enqueue(array);- return {};-}--}diff --git a/Libraries/LibWeb/Compression/DecompressionStream.h b/Libraries/LibWeb/Compression/DecompressionStream.hdeleted file mode 100644index 817bde3c62c..00000000000--- a/Libraries/LibWeb/Compression/DecompressionStream.h+++ /dev/null@@ -1,52 +0,0 @@-/*- * Copyright (c) 2024, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/MemoryStream.h>-#include <AK/NonnullOwnPtr.h>-#include <AK/Variant.h>-#include <LibCompress/Forward.h>-#include <LibGC/Ptr.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Compression/CompressionStream.h>-#include <LibWeb/Streams/GenericTransformStream.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Compression {--using Decompressor = Variant<- NonnullOwnPtr<Compress::BrotliDecompressor>,- NonnullOwnPtr<Compress::ZlibDecompressor>,- NonnullOwnPtr<Compress::DeflateDecompressor>,- NonnullOwnPtr<Compress::GzipDecompressor>>;--// https://compression.spec.whatwg.org/#decompressionstream-class DecompressionStream final- : public Bindings::GCAllocatedWrappable- , public Streams::GenericTransformStreamMixin {- WEB_WRAPPABLE(DecompressionStream, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DecompressionStream);--public:- static WebIDL::ExceptionOr<GC::Ref<DecompressionStream>> create(JS::Object& relevant_global_object, Decompressor, NonnullOwnPtr<AllocatingMemoryStream>);- static WebIDL::ExceptionOr<GC::Ref<DecompressionStream>> create_for_constructor(JS::Object&, Bindings::CompressionFormat);- virtual ~DecompressionStream() override;--private:- DecompressionStream(GC::Ref<Streams::TransformStream>, Decompressor, NonnullOwnPtr<AllocatingMemoryStream>);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- WebIDL::ExceptionOr<void> decompress_and_enqueue_chunk(JS::Realm&, JS::Value);- WebIDL::ExceptionOr<void> decompress_flush_and_enqueue(JS::Realm&);-- Decompressor m_decompressor;- NonnullOwnPtr<AllocatingMemoryStream> m_input_stream;-};--}diff --git a/Libraries/LibWeb/Compression/DecompressionStream.idl b/Libraries/LibWeb/Compression/DecompressionStream.idlindex 2e4ea8089e1..c4b5a9685eb 100644--- a/Libraries/LibWeb/Compression/DecompressionStream.idl+++ b/Libraries/LibWeb/Compression/DecompressionStream.idl@@ -1,5 +1,5 @@// https://compression.spec.whatwg.org/#decompressionstream-[Exposed=*]+[Exposed=*, ImplementedIn=Rust]interface DecompressionStream {constructor(CompressionFormat format);};diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex ba5a2c2f7d6..fb68338386b 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -156,13 +156,6 @@ class ClipboardItem;}-namespace Web::Compression {--class CompressionStream;-class DecompressionStream;--}-namespace Web::ContentSecurityPolicy {class Policy;diff --git a/Libraries/LibWeb/Streams/GenericTransformStream.cpp b/Libraries/LibWeb/Streams/GenericTransformStream.cppindex ed720eba3f0..6f10bfa4668 100644--- a/Libraries/LibWeb/Streams/GenericTransformStream.cpp+++ b/Libraries/LibWeb/Streams/GenericTransformStream.cpp@@ -4,13 +4,34 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Streams/GenericTransformStream.h>#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/Streams/TransformStream.h>#include <LibWeb/Streams/WritableStream.h>+#include <LibWeb/WebIDL/Promise.h>namespace Web::Streams {+// The transformAlgorithm and flushAlgorithm of a TransformStream that an implementation in Rust of an interface that+// includes GenericTransformStream sets up, which take the cell that holds them, and a chunk for the transformAlgorithm.+using RustTransformStreamSteps = JSCompletion (*)(JSVM*, JS::Realm*, GC::ForeignCell* steps, TransformStream*, JSValue const* chunk);++enum class TransformStreamSide : u8 {+ Readable,+ Writable,+};++extern "C" {+TransformStream* web_transform_stream_create(JS::Realm*, GC::ForeignCell* steps, RustTransformStreamSteps);+void web_transform_stream_enqueue(TransformStream*, JSValue chunk);+void* web_transform_stream_side(TransformStream*, JS::Realm*, TransformStreamSide);+}+GenericTransformStreamMixin::GenericTransformStreamMixin(GC::Ref<TransformStream> transform): m_transform(transform){@@ -37,4 +58,41 @@ GC::Ref<WritableStream> GenericTransformStreamMixin::writable()return m_transform->writable();}+static GC::Ref<WebIDL::Promise> promise_for(JS::Realm& realm, JSCompletion completion)+{+ auto result = JS::HostABI::completion_from_abi<JS::Value>(completion);+ if (result.is_error())+ return WebIDL::create_rejected_promise(realm, result.release_error().value());+ return WebIDL::create_resolved_promise(realm, JS::js_undefined());+}++TransformStream* web_transform_stream_create(JS::Realm* realm, GC::ForeignCell* steps, RustTransformStreamSteps run_steps)+{+ auto transform = GC::Heap::the().allocate<TransformStream>();++ auto transform_algorithm = GC::create_function(GC::Heap::the(), [realm = GC::Ref { *realm }, steps = GC::Ref { *steps }, transform, run_steps](JS::Value chunk) {+ auto abi_chunk = JS::HostABI::value_to_abi(chunk);+ return promise_for(realm, run_steps(JS::HostABI::vm_to_abi(realm->vm()), realm.ptr(), steps.ptr(), transform.ptr(), &abi_chunk));+ });+ auto flush_algorithm = GC::create_function(GC::Heap::the(), [realm = GC::Ref { *realm }, steps = GC::Ref { *steps }, transform, run_steps]() {+ return promise_for(realm, run_steps(JS::HostABI::vm_to_abi(realm->vm()), realm.ptr(), steps.ptr(), transform.ptr(), nullptr));+ });+ transform->set_up(*realm, transform_algorithm, flush_algorithm);++ return transform.ptr();+}++void web_transform_stream_enqueue(TransformStream* transform, JSValue chunk)+{+ transform->enqueue(JS::HostABI::value_from_abi(chunk));+}++void* web_transform_stream_side(TransformStream* transform, JS::Realm* realm, TransformStreamSide side)+{+ GC::Ref<Bindings::Wrappable> stream = side == TransformStreamSide::Readable+ ? GC::Ref<Bindings::Wrappable> { transform->readable() }+ : GC::Ref<Bindings::Wrappable> { transform->writable() };+ return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, stream).ptr();+}+}diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 9ebec065aa5..bad102459f7 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -38,7 +38,6 @@ ALLOWED_REALM_MENTIONS = {"Animations": (5, 14, "animation callbacks/events and CSS value materialization still pass spec-selected realms"),"CSS": (7, 19, "CSS Typed OM, parser-facing reification, and style-value JS materialization"),"Clipboard": (4, 16, "clipboard item/data callbacks still materialize JS values in caller-selected realms"),- "Compression": (4, 8, "compression streams still use realms for stream/chunk conversion plumbing"),"ContentSecurityPolicy": (4, 14, "CSP violation/report objects and callbacks still materialize JS-facing values"),"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),"Crypto": (8, 383, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),@@ -68,9 +67,10 @@ ALLOWED_REALM_MENTIONS = {"service worker jobs, caches, and container promises still materialize results in selected realms",),"Streams": (- 34,- 212,- "Streams algorithms still use realms for controller/read/write operations and chunk conversion",+ 35,+ 219,+ "Streams algorithms still use realms for controller/read/write operations and chunk conversion, and the "+ "TransformStreams that Rust implementations set up take the realm of their algorithms",),"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),"WebAssembly": (diff --git a/Tests/LibWeb/Text/expected/Compression/decompression-chunk-output.txt b/Tests/LibWeb/Text/expected/Compression/decompression-chunk-output.txtnew file mode 100644index 00000000000..0ec0eec6ec2--- /dev/null+++ b/Tests/LibWeb/Text/expected/Compression/decompression-chunk-output.txt@@ -0,0 +1,8 @@+deflate repetitive: 100000 of 100000+deflate random: 50000 of 50000+deflate-raw repetitive: 100000 of 100000+deflate-raw random: 50000 of 50000+gzip repetitive: 100000 of 100000+gzip random: 50000 of 50000+brotli repetitive: 100000 of 100000+brotli random: 50000 of 50000diff --git a/Tests/LibWeb/Text/expected/Compression/decompression-input-after-end.txt b/Tests/LibWeb/Text/expected/Compression/decompression-input-after-end.txtnew file mode 100644index 00000000000..f475cd14a6c--- /dev/null+++ b/Tests/LibWeb/Text/expected/Compression/decompression-input-after-end.txt@@ -0,0 +1,9 @@+deflate, no padding: 0 bytes+deflate, padding in the same chunk: TypeError+deflate, padding in another chunk: TypeError+deflate-raw, no padding: 0 bytes+deflate-raw, padding in the same chunk: TypeError+deflate-raw, padding in another chunk: TypeError+gzip, no padding: 0 bytes+gzip, padding in the same chunk: TypeError+gzip, padding in another chunk: TypeErrordiff --git a/Tests/LibWeb/Text/expected/wpt-import/compression/compression-bad-chunks.any.txt b/Tests/LibWeb/Text/expected/wpt-import/compression/compression-bad-chunks.any.txtindex 4ef3282132a..88c65020437 100644--- a/Tests/LibWeb/Text/expected/wpt-import/compression/compression-bad-chunks.any.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/compression/compression-bad-chunks.any.txt@@ -2,33 +2,32 @@ Harness status: OKFound 28 tests-20 Pass-8 Fail+28 PassPass chunk of type undefined should error the stream for deflatePass chunk of type null should error the stream for deflatePass chunk of type numeric should error the stream for deflatePass chunk of type object, not BufferSource should error the stream for deflatePass chunk of type array should error the stream for deflate-Fail chunk of type SharedArrayBuffer should error the stream for deflate-Fail chunk of type shared Uint8Array should error the stream for deflate+Pass chunk of type SharedArrayBuffer should error the stream for deflate+Pass chunk of type shared Uint8Array should error the stream for deflatePass chunk of type undefined should error the stream for deflate-rawPass chunk of type null should error the stream for deflate-rawPass chunk of type numeric should error the stream for deflate-rawPass chunk of type object, not BufferSource should error the stream for deflate-rawPass chunk of type array should error the stream for deflate-raw-Fail chunk of type SharedArrayBuffer should error the stream for deflate-raw-Fail chunk of type shared Uint8Array should error the stream for deflate-raw+Pass chunk of type SharedArrayBuffer should error the stream for deflate-raw+Pass chunk of type shared Uint8Array should error the stream for deflate-rawPass chunk of type undefined should error the stream for gzipPass chunk of type null should error the stream for gzipPass chunk of type numeric should error the stream for gzipPass chunk of type object, not BufferSource should error the stream for gzipPass chunk of type array should error the stream for gzip-Fail chunk of type SharedArrayBuffer should error the stream for gzip-Fail chunk of type shared Uint8Array should error the stream for gzip+Pass chunk of type SharedArrayBuffer should error the stream for gzip+Pass chunk of type shared Uint8Array should error the stream for gzipPass chunk of type undefined should error the stream for brotliPass chunk of type null should error the stream for brotliPass chunk of type numeric should error the stream for brotliPass chunk of type object, not BufferSource should error the stream for brotliPass chunk of type array should error the stream for brotli-Fail chunk of type SharedArrayBuffer should error the stream for brotli-Fail chunk of type shared Uint8Array should error the stream for brotli\ No newline at end of file+Pass chunk of type SharedArrayBuffer should error the stream for brotli+Pass chunk of type shared Uint8Array should error the stream for brotli\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/compression/decompression-extra-input.any.txt b/Tests/LibWeb/Text/expected/wpt-import/compression/decompression-extra-input.any.txtnew file mode 100644index 00000000000..a7312547d0e--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/compression/decompression-extra-input.any.txt@@ -0,0 +1,9 @@+Harness status: OK++Found 4 tests++4 Pass+Pass decompressing deflate input with extra pad should still give the output+Pass decompressing gzip input with extra pad should still give the output+Pass decompressing deflate-raw input with extra pad should still give the output+Pass decompressing brotli input with extra pad should still give the output\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/Compression/decompression-chunk-output.html b/Tests/LibWeb/Text/input/Compression/decompression-chunk-output.htmlnew file mode 100644index 00000000000..19a154da80a--- /dev/null+++ b/Tests/LibWeb/Text/input/Compression/decompression-chunk-output.html@@ -0,0 +1,45 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ async function compress(format, bytes) {+ const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream(format));+ return new Uint8Array(await new Response(stream).arrayBuffer());+ }++ async function decompressedBytesBeforeClose(format, compressed) {+ const decompressor = new DecompressionStream(format);+ const reader = decompressor.readable.getReader();+ const writer = decompressor.writable.getWriter();++ const notQueued = Symbol();+ const firstRead = reader.read();+ await writer.write(compressed);++ let total = (await firstRead).value.byteLength;+ while (true) {+ const result = await Promise.race([reader.read(), Promise.resolve(notQueued)]);+ if (result === notQueued)+ return total;+ total += result.value.byteLength;+ }+ }++ asyncTest(async done => {+ const repetitive = new TextEncoder().encode("a".repeat(100000));++ let seed = 1;+ const random = new Uint8Array(50000).map(() => {+ seed = (seed * 1103515245 + 12345) % 2147483648;+ return seed >> 16;+ });++ for (const format of ["deflate", "deflate-raw", "gzip", "brotli"]) {+ for (const [name, input] of [["repetitive", repetitive], ["random", random]]) {+ const compressed = await compress(format, input);+ const available = await decompressedBytesBeforeClose(format, compressed);+ println(`${format} ${name}: ${available} of ${input.byteLength}`);+ }+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/Compression/decompression-input-after-end.html b/Tests/LibWeb/Text/input/Compression/decompression-input-after-end.htmlnew file mode 100644index 00000000000..2dc6d5fd784--- /dev/null+++ b/Tests/LibWeb/Text/input/Compression/decompression-input-after-end.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // zlib, raw deflate and gzip compressions of the empty string.+ const compressedEmptyInput = {+ "deflate": [0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01],+ "deflate-raw": [0x03, 0x00],+ "gzip": [0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],+ };++ async function decompress(format, chunks) {+ const decompressor = new DecompressionStream(format);+ const writer = decompressor.writable.getWriter();+ for (const chunk of chunks)+ writer.write(new Uint8Array(chunk)).catch(() => {});+ writer.close().catch(() => {});+ try {+ const output = await new Response(decompressor.readable).arrayBuffer();+ return `${output.byteLength} bytes`;+ } catch (error) {+ return error.name;+ }+ }++ asyncTest(async done => {+ for (const [format, compressed] of Object.entries(compressedEmptyInput)) {+ println(`${format}, no padding: ${await decompress(format, [compressed])}`);+ println(`${format}, padding in the same chunk: ${await decompress(format, [[...compressed, 0]])}`);+ println(`${format}, padding in another chunk: ${await decompress(format, [compressed, [0]])}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/compression/decompression-extra-input.any.html b/Tests/LibWeb/Text/input/wpt-import/compression/decompression-extra-input.any.htmlnew file mode 100644index 00000000000..be8ae7f282e--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/compression/decompression-extra-input.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../resources/testharness.js"></script>+<script src="../resources/testharnessreport.js"></script>+<script src="resources/decompression-input.js"></script>+<div id=log></div>+<script src="../compression/decompression-extra-input.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/compression/decompression-extra-input.any.js b/Tests/LibWeb/Text/input/wpt-import/compression/decompression-extra-input.any.jsnew file mode 100644index 00000000000..24d0484c662--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/compression/decompression-extra-input.any.js@@ -0,0 +1,20 @@+// META: global=window,worker+// META: script=resources/decompression-input.js++'use strict';++const tests = compressedBytes.map(+ ([format, chunk]) => [format, new Uint8Array([...chunk, 0])]+);++for (const [format, chunk] of tests) {+ promise_test(async t => {+ const ds = new DecompressionStream(format);+ const reader = ds.readable.getReader();+ const writer = ds.writable.getWriter();+ writer.write(chunk).catch(() => { });+ const { done, value } = await reader.read();+ assert_array_equals(Array.from(value), expectedChunkValue, "value should match");+ await promise_rejects_js(t, TypeError, reader.read(), "Extra input should eventually throw");+ }, `decompressing ${format} input with extra pad should still give the output`);+}