Truly independent web browser
LibWeb: Implement Streams in Rust
Shannon Booth1cf0a312ac9b
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex 70fa6e557a5..f01b2cf64a0 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -55,6 +55,18 @@ pub(crate) trait Wrappable {fn external_memory_size(&self) -> usize {0}++ /// Whether LibGC finalizes the object before it destroys it, which it does through finalize(), as it does a C+++ /// implementation object that overrides Cell::finalize().+ const FINALIZES: bool = false;++ /// What the object does when LibGC finalizes it, while every cell that dies in the collection is still intact.+ /// It must not allocate.+ fn finalize(_object: Ref<Self>)+ where+ Self: Trace + Sized,+ {+ }}/// The value of the cell of an object of an interface: its implementation, and its wrapper in the main world.@@ -113,13 +125,29 @@ impl<T: Wrappable + Trace> ExternalMemorySize for Wrapped<T> {/// The class of the cells of the objects of an interface, which the generated bindings of the interface define once.pub(crate) const fn cell_class<T: Wrappable + Trace + 'static>(name: &'static str) -> EmbedderClass<Wrapped<T>> {- if T::OWNS_EXTERNAL_MEMORY {+ let class = if T::OWNS_EXTERNAL_MEMORY {EmbedderClass::new_with_external_memory_size(name)} else {EmbedderClass::new(name)+ };+ if T::FINALIZES {+ class.with_finalize(finalize_object::<T>)+ } else {+ class}}+/// The finalize entry of the class of the cells of an interface whose implementation finalizes its objects.+///+/// # Safety+///+/// Only LibGC calls it, with a dead cell of the class.+unsafe extern "C" fn finalize_object<T: Wrappable + Trace + 'static>(cell: *mut c_void) {+ let cell = NonNull::new(cell.cast::<EmbedderCell<Wrapped<T>>>()).expect("LibGC passes a cell");+ // SAFETY: LibGC passes a dead cell of the class, which stays intact while it finalizes.+ T::finalize(unsafe { Gc::from_non_null(cell) });+}+/// Without the generated bindings, which a build of the crate on its own leaves out, nothing creates or wraps an/// object, but the implementations still name each other's objects. This stands in for the bindings of every/// interface so that they compile.diff --git a/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rsindex 4b5952ec821..dd2a7ae5866 100644--- a/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/compression_stream.rs@@ -13,11 +13,15 @@ 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::conversions::create_uint8_array;+use crate::bindings::interface::Ref;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};+use crate::streams::generic_transform_stream::{TransformSteps, create_and_set_up};+use crate::streams::readable_stream::ReadableStream;+use crate::streams::transform_stream::TransformStream;+use crate::streams::writable_stream::WritableStream;/// https://compression.spec.whatwg.org/#enumdef-compressionformat#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -43,7 +47,7 @@ impl From<CompressionFormat> for Format {#[gc(crate = libjs_rust)]pub(crate) struct CompressionStream {// https://streams.spec.whatwg.org/#generictransformstream-transform- transform: TransformStream,+ transform: Ref<TransformStream>,}impl Wrappable for CompressionStream {}@@ -61,20 +65,20 @@ impl CompressionStream {// 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),+ transform: create_and_set_up(cx, context),})}// https://streams.spec.whatwg.org/#dom-generictransformstream-readable- pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn readable(&self, _: &mut CallContext) -> WebIdlResult<Ref<ReadableStream>> {// The readable getter steps are to return this's transform.[[readable]].- Ok(self.transform.readable(cx))+ Ok(self.transform.readable_stream())}// https://streams.spec.whatwg.org/#dom-generictransformstream-writable- pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn writable(&self, _: &mut CallContext) -> WebIdlResult<Ref<WritableStream>> {// The writable getter steps are to return this's transform.[[writable]].- Ok(self.transform.writable(cx))+ Ok(self.transform.writable_stream())}}@@ -106,7 +110,7 @@ fn compression_failed(step: &str, error: &io::Error) -> Exception {impl TransformSteps for CompressionContext {// https://compression.spec.whatwg.org/#compress-and-enqueue-a-chunk- fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()> {+ fn transform(&self, cx: &CallContext, transform: Ref<TransformStream>, chunk: Value) -> WebIdlResult<()> {// 1. If chunk is not a BufferSource type, then throw a TypeError.let chunk = buffer_source_of_chunk(cx, chunk)?;@@ -125,12 +129,12 @@ impl TransformSteps for CompressionContext {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));+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(array));Ok(())}// https://compression.spec.whatwg.org/#compress-flush-and-enqueue- fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()> {+ fn flush(&self, cx: &CallContext, transform: Ref<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@@ -148,7 +152,7 @@ impl TransformSteps for CompressionContext {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));+ TransformStream::enqueue(transform, cx.vm(), 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.rsindex f6bcb036a1c..d6a02fdb066 100644--- a/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/compression/decompression_stream.rs@@ -12,18 +12,22 @@ 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::conversions::create_uint8_array;+use crate::bindings::interface::Ref;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};+use crate::streams::generic_transform_stream::{TransformSteps, create_and_set_up};+use crate::streams::readable_stream::ReadableStream;+use crate::streams::transform_stream::TransformStream;+use crate::streams::writable_stream::WritableStream;#[derive(Trace)]#[gc(crate = libjs_rust)]pub(crate) struct DecompressionStream {// https://streams.spec.whatwg.org/#generictransformstream-transform- transform: TransformStream,+ transform: Ref<TransformStream>,}impl Wrappable for DecompressionStream {}@@ -41,20 +45,20 @@ impl DecompressionStream {// 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),+ transform: create_and_set_up(cx, context),})}// https://streams.spec.whatwg.org/#dom-generictransformstream-readable- pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn readable(&self, _: &mut CallContext) -> WebIdlResult<Ref<ReadableStream>> {// The readable getter steps are to return this's transform.[[readable]].- Ok(self.transform.readable(cx))+ Ok(self.transform.readable_stream())}// https://streams.spec.whatwg.org/#dom-generictransformstream-writable- pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn writable(&self, _: &mut CallContext) -> WebIdlResult<Ref<WritableStream>> {// The writable getter steps are to return this's transform.[[writable]].- Ok(self.transform.writable(cx))+ Ok(self.transform.writable_stream())}}@@ -97,7 +101,7 @@ fn decompression_failed(step: &str, error: &str) -> Exception {impl TransformSteps for DecompressionContext {// https://compression.spec.whatwg.org/#decompress-and-enqueue-a-chunk- fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()> {+ fn transform(&self, cx: &CallContext, transform: Ref<TransformStream>, chunk: Value) -> WebIdlResult<()> {// 1. If chunk is not a BufferSource type, then throw a TypeError.let chunk = buffer_source_of_chunk(cx, chunk)?;@@ -117,7 +121,7 @@ impl TransformSteps for DecompressionContext {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));+ TransformStream::enqueue(transform, cx.vm(), 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@@ -132,7 +136,7 @@ impl TransformSteps for DecompressionContext {}// https://compression.spec.whatwg.org/#decompress-flush-and-enqueue- fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()> {+ fn flush(&self, cx: &CallContext, transform: Ref<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.@@ -148,7 +152,7 @@ impl TransformSteps for DecompressionContext {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));+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(array));}// 3. If the end of the compressed input has not been reached, then throw a TypeError.diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rsindex faa2d339570..145f7a5f2c5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs@@ -13,11 +13,15 @@ use encoding_rs::Encoding;use libjs_rust::api::{EmbedderClass, EmbedderValue, PrimitiveString, Trace, Value};use libtextcodec_rust::{DecodingFailed, StreamingDecoder, encoding_for_label};-use crate::bindings::conversions::{CppInterface, UsvString, buffer_source_type_of};+use crate::bindings::conversions::{UsvString, buffer_source_type_of};+use crate::bindings::interface::Ref;use crate::bindings::interface::Wrappable;use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::encoding::text_decoder::TextDecoderOptions;-use crate::streams::generic_transform_stream::{TransformSteps, TransformStream};+use crate::streams::generic_transform_stream::{TransformSteps, create_and_set_up};+use crate::streams::readable_stream::ReadableStream;+use crate::streams::transform_stream::TransformStream;+use crate::streams::writable_stream::WritableStream;#[derive(Trace)]#[gc(crate = libjs_rust)]@@ -30,7 +34,7 @@ pub(crate) struct TextDecoderStream {// https://encoding.spec.whatwg.org/#textdecoder-ignore-bom-flagignore_bom: bool,// https://streams.spec.whatwg.org/#generictransformstream-transform- transform: TransformStream,+ transform: Ref<TransformStream>,}impl Wrappable for TextDecoderStream {}@@ -87,7 +91,7 @@ impl TextDecoderStream {encoding,fatal,ignore_bom,- transform: TransformStream::create_and_set_up(cx, decoder),+ transform: create_and_set_up(cx, decoder),}}@@ -111,15 +115,15 @@ impl TextDecoderStream {}// https://streams.spec.whatwg.org/#dom-generictransformstream-readable- pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn readable(&self, _: &mut CallContext) -> WebIdlResult<Ref<ReadableStream>> {// The readable getter steps are to return this's transform.[[readable]].- Ok(self.transform.readable(cx))+ Ok(self.transform.readable_stream())}// https://streams.spec.whatwg.org/#dom-generictransformstream-writable- pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn writable(&self, _: &mut CallContext) -> WebIdlResult<Ref<WritableStream>> {// The writable getter steps are to return this's transform.[[writable]].- Ok(self.transform.writable(cx))+ Ok(self.transform.writable_stream())}}@@ -138,10 +142,14 @@ impl EmbedderValue for Decoder {}/// Enqueues the output of the decoder in the transform as a string, unless it is the empty string.-fn enqueue_output_chunk(cx: &CallContext, transform: &TransformStream, output: &[u16]) {+fn enqueue_output_chunk(cx: &CallContext, transform: Ref<TransformStream>, output: &[u16]) {let output_chunk = UsvString::from_utf16_replacing_lone_surrogates(output).into_utf16_string();if !output_chunk.is_empty() {- transform.enqueue(Value::from_string(PrimitiveString::create(cx.vm(), output_chunk)));+ TransformStream::enqueue(+ transform,+ cx.vm(),+ Value::from_string(PrimitiveString::create(cx.vm(), output_chunk)),+ );}}@@ -151,7 +159,7 @@ fn decoding_failed(_: DecodingFailed) -> Exception {impl TransformSteps for Decoder {// https://encoding.spec.whatwg.org/#decode-and-enqueue-a-chunk- fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()> {+ fn transform(&self, cx: &CallContext, transform: Ref<TransformStream>, chunk: Value) -> WebIdlResult<()> {// 1. Let bufferSource be the result of converting chunk to an AllowSharedBufferSource.let Some(buffer_source) = buffer_source_type_of(chunk) else {return Err(Exception::TypeError(Utf16String::from_ascii(@@ -181,7 +189,7 @@ impl TransformSteps for Decoder {}// https://encoding.spec.whatwg.org/#flush-and-enqueue- fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()> {+ fn flush(&self, cx: &CallContext, transform: Ref<TransformStream>) -> WebIdlResult<()> {// 1. Let output be the I/O queue of scalar values « end-of-queue ».// 2. While true:// 1. Let item be the result of reading from decoder's I/O queue.diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rsindex 08309d0eaf6..203972a5dc9 100644--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs@@ -11,16 +11,20 @@ use core::cell::Cell;use ak::Utf16String;use libjs_rust::api::{EmbedderClass, EmbedderValue, Trace, Value};-use crate::bindings::conversions::{CppInterface, create_uint8_array, to_dom_string};+use crate::bindings::conversions::{create_uint8_array, to_dom_string};+use crate::bindings::interface::Ref;use crate::bindings::interface::{Wrappable, with_temporary_execution_context};use crate::bindings::{CallContext, WebIdlResult};-use crate::streams::generic_transform_stream::{TransformSteps, TransformStream};+use crate::streams::generic_transform_stream::{TransformSteps, create_and_set_up};+use crate::streams::readable_stream::ReadableStream;+use crate::streams::transform_stream::TransformStream;+use crate::streams::writable_stream::WritableStream;#[derive(Trace)]#[gc(crate = libjs_rust)]pub(crate) struct TextEncoderStream {// https://streams.spec.whatwg.org/#generictransformstream-transform- transform: TransformStream,+ transform: Ref<TransformStream>,}impl Wrappable for TextEncoderStream {}@@ -45,7 +49,7 @@ impl TextEncoderStream {// flushAlgorithm.// 6. Set this's transform to transformStream.Ok(Self {- transform: TransformStream::create_and_set_up(cx, encoder),+ transform: create_and_set_up(cx, encoder),})}@@ -56,15 +60,15 @@ impl TextEncoderStream {}// https://streams.spec.whatwg.org/#dom-generictransformstream-readable- pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn readable(&self, _: &mut CallContext) -> WebIdlResult<Ref<ReadableStream>> {// The readable getter steps are to return this's transform.[[readable]].- Ok(self.transform.readable(cx))+ Ok(self.transform.readable_stream())}// https://streams.spec.whatwg.org/#dom-generictransformstream-writable- pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn writable(&self, _: &mut CallContext) -> WebIdlResult<Ref<WritableStream>> {// The writable getter steps are to return this's transform.[[writable]].- Ok(self.transform.writable(cx))+ Ok(self.transform.writable_stream())}}@@ -142,7 +146,7 @@ fn scalar_value_from_surrogates(leading: u16, trailing: u16) -> char {impl TransformSteps for Encoder {// https://encoding.spec.whatwg.org/#encode-and-enqueue-a-chunk- fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()> {+ fn transform(&self, cx: &CallContext, transform: Ref<TransformStream>, chunk: Value) -> WebIdlResult<()> {// 1. Let input be the result of converting chunk to a DOMString.let input = with_temporary_execution_context(cx.realm(), || to_dom_string(cx.vm(), chunk))?;@@ -166,7 +170,7 @@ impl TransformSteps for Encoder {let chunk = create_uint8_array(cx, &output)?;// 2. Enqueue chunk into encoder's transform.- transform.enqueue(Value::from_object(chunk));+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(chunk));}// 3. Return.@@ -186,7 +190,7 @@ impl TransformSteps for Encoder {}// https://encoding.spec.whatwg.org/#encode-and-flush- fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()> {+ fn flush(&self, cx: &CallContext, transform: Ref<TransformStream>) -> WebIdlResult<()> {// 1. If encoder's leading surrogate is non-null:if self.leading_surrogate.get().is_some() {// 1. Let chunk be the result of creating a Uint8Array object given « 0xEF, 0xBF, 0xBD » and encoder's@@ -195,7 +199,7 @@ impl TransformSteps for Encoder {let chunk = create_uint8_array(cx, &REPLACEMENT_CHARACTER_UTF8_BYTES)?;// 2. Enqueue chunk into encoder's transform.- transform.enqueue(Value::from_object(chunk));+ TransformStream::enqueue(transform, cx.vm(), Value::from_object(chunk));}Ok(())}diff --git a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rsindex 48c16adeb8e..db2530650aa 100644--- a/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/file_api/blob.rs@@ -12,15 +12,16 @@ use core::ops::Deref;use core::ptr::NonNull;use ak::{Utf16String, Utf16StringUnits};-use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, Trace};+use libjs_rust::api::{MarkedVec, RawNativeFunctionResult, Trace};use libwebcommon_rust::mime_sniff::mime_type::MimeType;use super::file::File;-use crate::bindings::conversions::{BufferSource, CppInterface, UsvString};-use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};+use crate::bindings::conversions::{BufferSource, UsvString};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_from_abi, cell_into_abi};use crate::bindings::promise::{WebIdlPromise, promise_from_abi};use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};use crate::bindings::{CallContext, WebIdlResult};+use crate::streams::readable_stream::ReadableStream;unsafe extern "C" {fn web_blob_bytes_destroy(owner: *mut c_void);@@ -468,11 +469,11 @@ impl Blob {}// https://w3c.github.io/FileAPI/#dom-blob-stream- pub(crate) fn stream(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {- // SAFETY: The realm is live, LibWeb copies the bytes, and it returns the wrapper of a new ReadableStream.+ pub(crate) fn stream(&self, cx: &mut CallContext) -> WebIdlResult<Ref<ReadableStream>> {+ // SAFETY: The realm is live, LibWeb copies the bytes, and it returns a new ReadableStream.unsafe {let stream = web_blob_get_stream(cx.realm().as_ptr().cast(), ak::Span::new(&self.raw_bytes()));- Ok(CppInterface::from_wrapper(object_from_abi(stream)))+ Ok(cell_from_abi(stream))}}@@ -541,17 +542,6 @@ impl Blob {}}-/// The object that LibWeb returns.-///-/// # Safety-///-/// `object` must be a live object.-unsafe fn object_from_abi(object: *mut c_void) -> Gc<Object> {- let object = NonNull::new(object.cast::<Object>()).expect("LibWeb returns an object");- // SAFETY: The caller passes a live object.- unsafe { Gc::from_non_null(object) }-}-impl Serializable for Blob {fn serialization_steps(&self,diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 2b8d4c1ce6c..4f28ab32ea4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -99,6 +99,10 @@ pub(crate) mod speech;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 streams;#[cfg_attr(not(web_idl_bindings),diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/abstract_operations.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/abstract_operations.rsnew file mode 100644index 00000000000..62e662b37b7--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/abstract_operations.rs@@ -0,0 +1,154 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Miscellaneous abstract operations, https://streams.spec.whatwg.org/#misc-abstract-ops++use core::ffi::c_void;++use libjs_rust::api::{+ ArrayBuffer, Gc, Must, RawNativeFunctionResult, Value, clone_array_buffer, construct, same_value,+};++use crate::bindings::conversions::{ArrayBufferView, BufferSource};+use crate::bindings::{CallContext, WebIdlResult};++unsafe extern "C" {+ /// StructuredDeserialize(? StructuredSerialize(value), realm).+ fn web_streams_structured_clone(realm: *mut c_void, value: u64) -> RawNativeFunctionResult;+}++// https://streams.spec.whatwg.org/#can-transfer-array-buffer+pub(crate) fn can_transfer_array_buffer(array_buffer: &ArrayBuffer) -> bool {+ // 1. Assert: O is an Object.+ // 2. Assert: O has an [[ArrayBufferData]] internal slot.++ // 3. If ! IsDetachedBuffer(O) is true, return false.+ if array_buffer.is_detached() {+ return false;+ }++ // 4. If SameValue(O.[[ArrayBufferDetachKey]], undefined) is false, return false.+ if !same_value(array_buffer.detach_key(), Value::UNDEFINED) {+ return false;+ }++ // 5. Return true.+ true+}++// https://streams.spec.whatwg.org/#is-non-negative-number+pub(crate) fn is_non_negative_number(value: Value) -> bool {+ // 1. If v is not a Number, return false.+ if !value.is_number() {+ return false;+ }++ // 2. If v is NaN, return false.+ if value.is_nan() {+ return false;+ }++ // 3. If v < 0, return false.+ if value.as_f64() < 0.0 {+ return false;+ }++ // 4. Return true.+ true+}++// https://streams.spec.whatwg.org/#transfer-array-buffer+pub(crate) fn transfer_array_buffer(cx: &CallContext, buffer: Gc<ArrayBuffer>) -> WebIdlResult<Gc<ArrayBuffer>> {+ // 1. Assert: ! IsDetachedBuffer(O) is false.+ assert!(!buffer.is_detached());++ // 2. Let arrayBufferData be O.[[ArrayBufferData]].+ // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].+ // 4. Perform ? DetachArrayBuffer(O).+ // NB: The data block is taken from the buffer as it is detached, so the transfer copies nothing.+ let block = buffer.detach_and_take_data_block(cx.vm())?;++ // 5. Return a new ArrayBuffer object, created in the current Realm, whose [[ArrayBufferData]] internal slot value+ // is arrayBufferData and whose [[ArrayBufferByteLength]] internal slot value is arrayBufferByteLength.+ Ok(ArrayBuffer::create_from_data_block(cx.vm(), cx.realm(), block))+}++// https://streams.spec.whatwg.org/#abstract-opdef-cloneasuint8array+pub(crate) fn clone_as_uint8_array(cx: &CallContext, view: ArrayBufferView) -> WebIdlResult<Value> {+ let vm = cx.vm();+ let extent = BufferSource::from(view).extent();++ // 1. Assert: O is an Object.+ // 2. Assert: O has an [[ViewedArrayBuffer]] internal slot.++ // 3. Assert: ! IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false.+ assert!(!extent.buffer.is_detached());++ // 4. Let buffer be ? CloneArrayBuffer(O.[[ViewedArrayBuffer]], O.[[ByteOffset]], O.[[ByteLength]], %ArrayBuffer%).+ let buffer = clone_array_buffer(vm, extent.buffer, extent.byte_offset, extent.byte_length)?;++ // 5. Let array be ! Construct(%Uint8Array%, « buffer »).+ let array = construct(+ vm,+ cx.realm().intrinsics().uint8_array_constructor(vm),+ &[Value::from_object(buffer)],+ None,+ )+ .must();++ // 6. Return array.+ Ok(Value::from_object(array))+}++// https://streams.spec.whatwg.org/#abstract-opdef-structuredclone+pub(crate) fn structured_clone(cx: &CallContext, value: Value) -> WebIdlResult<Value> {+ // 1. Let serialized be ? StructuredSerialize(v).+ // 2. Return ? StructuredDeserialize(serialized, the current Realm).+ // SAFETY: The realm and the value are live.+ Ok(unsafe { web_streams_structured_clone(cx.realm().as_ptr().cast(), value.0) }.into_completion()?)+}++// https://streams.spec.whatwg.org/#abstract-opdef-cancopydatablockbytes+pub(crate) fn can_copy_data_block_bytes_buffer(+ to_buffer: Gc<ArrayBuffer>,+ to_index: u64,+ from_buffer: Gc<ArrayBuffer>,+ from_index: u64,+ count: u64,+) -> bool {+ // 1. Assert: toBuffer is an Object.+ // 2. Assert: toBuffer has an [[ArrayBufferData]] internal slot.+ // 3. Assert: fromBuffer is an Object.+ // 4. Assert: fromBuffer has an [[ArrayBufferData]] internal slot.++ // 5. If toBuffer is fromBuffer, return false.+ if to_buffer == from_buffer {+ return false;+ }++ // 6. If ! IsDetachedBuffer(toBuffer) is true, return false.+ if to_buffer.is_detached() {+ return false;+ }++ // 7. If ! IsDetachedBuffer(fromBuffer) is true, return false.+ if from_buffer.is_detached() {+ return false;+ }++ // 8. If toIndex + count > toBuffer.[[ArrayBufferByteLength]], return false.+ if to_index + count > to_buffer.byte_length() as u64 {+ return false;+ }++ // 9. If fromIndex + count > fromBuffer.[[ArrayBufferByteLength]], return false.+ if from_index + count > from_buffer.byte_length() as u64 {+ return false;+ }++ // 10. Return true.+ true+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rsnew file mode 100644index 00000000000..f6c7d98411d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs@@ -0,0 +1,437 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The algorithms that streams and their controllers are set up with: one variant for each way the Streams Standard,+//! or a specification that sets a stream up, defines one, holding what its steps refer to. The steps of a variant are+//! next to the abstract operation that defines them.++use libjs_rust::api::{EmbedderCell, Gc, IteratorRecord, ThrowCompletionOr, Trace, Value};++use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};+use crate::bindings::conversions::to_unrestricted_double;+use crate::bindings::interface::{Ref, wrap};+use crate::bindings::promise::{WebIdlPromise, create_rejected_promise, create_resolved_promise};+use crate::bindings::{CallContext, WebIdlResult};+use crate::streams::cpp::{CppPromiseAlgorithm, CppPromiseAlgorithmWithArgument};+use crate::streams::cross_realm_transform::{CrossRealmTransformPort, CrossRealmWritableState};+use crate::streams::generic_transform_stream::RustTransformSteps;+use crate::streams::readable_stream::{+ ReadableStream, readable_stream_from_iterable_cancel_algorithm, readable_stream_from_iterable_pull_algorithm,+};+use crate::streams::readable_stream_tee::{ByteTeeState, DefaultTeeState};+use crate::streams::transform_stream::{+ TransformStream, transform_stream_default_sink_abort_algorithm, transform_stream_default_sink_close_algorithm,+ transform_stream_default_sink_write_algorithm, transform_stream_default_source_cancel_algorithm,+ transform_stream_default_source_pull_algorithm,+};+use crate::streams::transform_stream_default_controller::{+ TransformStreamDefaultController, transform_stream_default_controller_enqueue,+};+use crate::streams::underlying_source::ReadableStreamController;+use crate::streams::writable_stream_default_controller::WritableStreamDefaultController;++/// A promise resolved with undefined in the realm of the context.+fn resolved_with_undefined(cx: &CallContext) -> WebIdlPromise {+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+}++/// The startAlgorithm of a stream, which its set-up runs once.+pub(crate) enum StartAlgorithm {+ /// An algorithm that returns undefined.+ ReturnsUndefined,+ /// An algorithm that returns the result of invoking `start` with argument list « controller » and callback this+ /// value `this_value`.+ Callback {+ start: CallbackFunction,+ this_value: Value,+ controller: Value,+ },+ /// An algorithm that returns the promise.+ ReturnsPromise(WebIdlPromise),+}++impl StartAlgorithm {+ pub(crate) fn run(self) -> WebIdlResult<Value> {+ match self {+ Self::ReturnsUndefined => Ok(Value::UNDEFINED),+ Self::Callback {+ start,+ this_value,+ controller,+ } => Ok(start.invoke(Some(this_value), &[controller])?),+ Self::ReturnsPromise(promise) => Ok(Value::from_object(promise.promise())),+ }+ }+}++/// The pullAlgorithm of a readable stream's controller, https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullalgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum PullAlgorithm {+ /// An algorithm that returns a promise resolved with undefined.+ ReturnsResolvedUndefined,+ /// An algorithm that returns the result of invoking `pull` with argument list « controller » and callback this+ /// value `underlying_source`.+ Callback {+ pull: PromiseCallbackFunction,+ underlying_source: Value,+ controller: ReadableStreamController,+ },+ /// The pullAlgorithm of ReadableStreamFromIterable.+ FromIterable {+ stream: Ref<ReadableStream>,+ iterator_record: Gc<IteratorRecord>,+ },+ /// The pullAlgorithm of ReadableStreamDefaultTee.+ DefaultTee(Gc<EmbedderCell<DefaultTeeState>>),+ /// The pull1Algorithm or the pull2Algorithm of ReadableByteStreamTee.+ ByteTee {+ state: Gc<EmbedderCell<ByteTeeState>>,+ for_branch2: bool,+ },+ /// The pullAlgorithm of InitializeTransformStream.+ TransformStream(Ref<TransformStream>),+ /// The pullAlgorithm of SetUpCrossRealmTransformReadable.+ CrossRealm(CrossRealmTransformPort),+ /// The pullAlgorithmWrapper of setting up a ReadableStream with byte reading support, given the pullAlgorithm that+ /// C++ set the stream up with, if any.+ WithByteReadingSupport(Option<CppPromiseAlgorithm>),+}++impl PullAlgorithm {+ /// Performs the algorithm, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext) -> WebIdlPromise {+ match self {+ Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),+ Self::Callback {+ pull,+ underlying_source,+ controller,+ } => pull.invoke(Some(*underlying_source), &[controller.to_js(cx)]),+ Self::FromIterable {+ stream,+ iterator_record,+ } => readable_stream_from_iterable_pull_algorithm(cx, *stream, *iterator_record),+ Self::DefaultTee(state) => DefaultTeeState::pull_algorithm(*state, cx),+ Self::ByteTee { state, for_branch2 } => {+ if *for_branch2 {+ ByteTeeState::pull2_algorithm(*state, cx)+ } else {+ ByteTeeState::pull1_algorithm(*state, cx)+ }+ }+ Self::TransformStream(stream) => transform_stream_default_source_pull_algorithm(cx, *stream),+ Self::CrossRealm(port) => port.pull_algorithm(cx),+ Self::WithByteReadingSupport(pull_algorithm) => {+ // 1. Let result be the result of running pullAlgorithm, if pullAlgorithm was given, or null otherwise.+ // If this throws an exception e, return a promise rejected with e.+ // 2. If result is a Promise, then return result.+ if let Some(pull_algorithm) = pull_algorithm {+ return pull_algorithm.call();+ }++ // 3. Return a promise resolved with undefined.+ resolved_with_undefined(cx)+ }+ }+ }+}++/// The cancelAlgorithm of a readable stream's controller or of a TransformStreamDefaultController,+/// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-cancelalgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum CancelAlgorithm {+ /// An algorithm that returns a promise resolved with undefined.+ ReturnsResolvedUndefined,+ /// An algorithm that takes an argument reason and returns the result of invoking `cancel` with argument list+ /// « reason » and callback this value `this_value`.+ Callback {+ cancel: PromiseCallbackFunction,+ this_value: Value,+ },+ /// The cancelAlgorithm of ReadableStreamFromIterable.+ FromIterable { iterator_record: Gc<IteratorRecord> },+ /// The cancel1Algorithm or the cancel2Algorithm of ReadableStreamDefaultTee.+ DefaultTee {+ state: Gc<EmbedderCell<DefaultTeeState>>,+ for_branch2: bool,+ },+ /// The cancel1Algorithm or the cancel2Algorithm of ReadableByteStreamTee.+ ByteTee {+ state: Gc<EmbedderCell<ByteTeeState>>,+ for_branch2: bool,+ },+ /// The cancelAlgorithm of InitializeTransformStream.+ TransformStream(Ref<TransformStream>),+ /// The cancelAlgorithm of SetUpCrossRealmTransformReadable.+ CrossRealm(CrossRealmTransformPort),+ /// The cancelAlgorithmWrapper of setting up a ReadableStream with byte reading support or a TransformStream, given+ /// the cancelAlgorithm that C++ set the stream up with, if any.+ Wrapper(Option<CppPromiseAlgorithmWithArgument>),+}++impl CancelAlgorithm {+ /// Performs the algorithm given the reason, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext, reason: Value) -> WebIdlPromise {+ match self {+ Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),+ Self::Callback { cancel, this_value } => cancel.invoke(Some(*this_value), &[reason]),+ Self::FromIterable { iterator_record } => {+ readable_stream_from_iterable_cancel_algorithm(cx, *iterator_record, reason)+ }+ Self::DefaultTee { state, for_branch2 } => {+ if *for_branch2 {+ DefaultTeeState::cancel2_algorithm(*state, cx, reason)+ } else {+ DefaultTeeState::cancel1_algorithm(*state, cx, reason)+ }+ }+ Self::ByteTee { state, for_branch2 } => {+ if *for_branch2 {+ ByteTeeState::cancel2_algorithm(*state, cx, reason)+ } else {+ ByteTeeState::cancel1_algorithm(*state, cx, reason)+ }+ }+ Self::TransformStream(stream) => transform_stream_default_source_cancel_algorithm(cx, *stream, reason),+ Self::CrossRealm(port) => port.cancel_algorithm(cx, reason),+ Self::Wrapper(cancel_algorithm) => {+ // 1. Let result be the result of running cancelAlgorithm given reason, if cancelAlgorithm was given,+ // or null otherwise. If this throws an exception e, return a promise rejected with e.+ // 2. If result is a Promise, then return result.+ if let Some(cancel_algorithm) = cancel_algorithm {+ return cancel_algorithm.call(reason);+ }++ // 3. Return a promise resolved with undefined.+ resolved_with_undefined(cx)+ }+ }+ }+}++/// The strategySizeAlgorithm of a controller, https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-strategysizealgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum SizeAlgorithm {+ /// An algorithm that returns 1.+ ReturnsOne,+ /// An algorithm that returns the result of invoking strategy["size"] with argument list « chunk ».+ Strategy(CallbackFunction),+}++impl SizeAlgorithm {+ pub(crate) fn run(&self, cx: &CallContext, chunk: Value) -> ThrowCompletionOr<Value> {+ match self {+ Self::ReturnsOne => Ok(Value::from_i32(1)),+ Self::Strategy(size) => {+ let size = size.invoke(None, &[chunk])?;+ Ok(Value::from_f64(to_unrestricted_double(cx.vm(), size)?))+ }+ }+ }+}++/// The writeAlgorithm of a WritableStreamDefaultController, https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-writealgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum WriteAlgorithm {+ /// An algorithm that returns a promise resolved with undefined.+ ReturnsResolvedUndefined,+ /// An algorithm that takes an argument chunk and returns the result of invoking `write` with argument list+ /// « chunk, controller » and callback this value `underlying_sink`.+ Callback {+ write: PromiseCallbackFunction,+ underlying_sink: Value,+ controller: Ref<WritableStreamDefaultController>,+ },+ /// The writeAlgorithm of InitializeTransformStream.+ TransformStream(Ref<TransformStream>),+ /// The writeAlgorithm of SetUpCrossRealmTransformWritable.+ CrossRealm(Gc<EmbedderCell<CrossRealmWritableState>>),+}++impl WriteAlgorithm {+ /// Performs the algorithm given the chunk, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext, chunk: Value) -> WebIdlPromise {+ match self {+ Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),+ Self::Callback {+ write,+ underlying_sink,+ controller,+ } => {+ let controller = Value::from_object(wrap(cx, *controller));+ write.invoke(Some(*underlying_sink), &[chunk, controller])+ }+ Self::TransformStream(stream) => transform_stream_default_sink_write_algorithm(cx, *stream, chunk),+ Self::CrossRealm(state) => CrossRealmWritableState::write_algorithm(*state, cx, chunk),+ }+ }+}++/// The closeAlgorithm of a WritableStreamDefaultController, https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-closealgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum CloseAlgorithm {+ /// An algorithm that returns a promise resolved with undefined.+ ReturnsResolvedUndefined,+ /// An algorithm that returns the result of invoking `close` with argument list « » and callback this value+ /// `underlying_sink`.+ Callback {+ close: PromiseCallbackFunction,+ underlying_sink: Value,+ },+ /// The closeAlgorithm of InitializeTransformStream.+ TransformStream(Ref<TransformStream>),+ /// The closeAlgorithm of SetUpCrossRealmTransformWritable.+ CrossRealm(CrossRealmTransformPort),+}++impl CloseAlgorithm {+ /// Performs the algorithm, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext) -> WebIdlPromise {+ match self {+ Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),+ Self::Callback { close, underlying_sink } => close.invoke(Some(*underlying_sink), &[]),+ Self::TransformStream(stream) => transform_stream_default_sink_close_algorithm(cx, *stream),+ Self::CrossRealm(port) => port.close_algorithm(cx),+ }+ }+}++/// The abortAlgorithm of a WritableStreamDefaultController, https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-abortalgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum AbortAlgorithm {+ /// An algorithm that returns a promise resolved with undefined.+ ReturnsResolvedUndefined,+ /// An algorithm that takes an argument reason and returns the result of invoking `abort` with argument list+ /// « reason » and callback this value `underlying_sink`.+ Callback {+ abort: PromiseCallbackFunction,+ underlying_sink: Value,+ },+ /// The abortAlgorithm of InitializeTransformStream.+ TransformStream(Ref<TransformStream>),+ /// The abortAlgorithm of SetUpCrossRealmTransformWritable.+ CrossRealm(CrossRealmTransformPort),+}++impl AbortAlgorithm {+ /// Performs the algorithm given the reason, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext, reason: Value) -> WebIdlPromise {+ match self {+ Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),+ Self::Callback { abort, underlying_sink } => abort.invoke(Some(*underlying_sink), &[reason]),+ Self::TransformStream(stream) => transform_stream_default_sink_abort_algorithm(cx, *stream, reason),+ Self::CrossRealm(port) => port.abort_algorithm(cx, reason),+ }+ }+}++/// The transformAlgorithm of a TransformStreamDefaultController, https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-transformalgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum TransformAlgorithm {+ /// An algorithm that takes an argument chunk and returns the result of invoking `transform` with argument list+ /// « chunk, controller » and callback this value `transformer`.+ Callback {+ transform: PromiseCallbackFunction,+ transformer: Value,+ controller: Ref<TransformStreamDefaultController>,+ },+ /// The transformAlgorithm of SetUpTransformStreamDefaultControllerFromTransformer for a transformer without a+ /// transform member, which enqueues the chunk.+ Enqueue(Ref<TransformStreamDefaultController>),+ /// The transformAlgorithmWrapper of setting up a TransformStream, given the transformAlgorithm that C++ set the+ /// stream up with.+ CppWrapper(CppPromiseAlgorithmWithArgument),+ /// The transformAlgorithmWrapper of setting up a TransformStream, given steps of an implementation in Rust.+ RustWrapper(RustTransformSteps),+}++impl TransformAlgorithm {+ /// Performs the algorithm given the chunk, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext, chunk: Value) -> WebIdlPromise {+ match self {+ Self::Callback {+ transform,+ transformer,+ controller,+ } => {+ let controller = Value::from_object(wrap(cx, *controller));+ transform.invoke(Some(*transformer), &[chunk, controller])+ }+ Self::Enqueue(controller) => {+ // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).+ // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].+ if let Err(exception) = transform_stream_default_controller_enqueue(cx, *controller, chunk) {+ let reason = crate::bindings::promise::exception_value(cx.vm(), cx.realm(), exception);+ return create_rejected_promise(cx.vm(), cx.realm(), reason);+ }++ // 3. Otherwise, return a promise resolved with undefined.+ resolved_with_undefined(cx)+ }+ // 1. Let result be the result of running transformAlgorithm given chunk. If this throws an exception e,+ // return a promise rejected with e.+ // 2. If result is a Promise, then return result.+ Self::CppWrapper(transform_algorithm) => transform_algorithm.call(chunk),+ Self::RustWrapper(steps) => steps.transform(cx, chunk),+ }+ }+}++/// The flushAlgorithm of a TransformStreamDefaultController, https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-flushalgorithm+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum FlushAlgorithm {+ /// An algorithm that returns a promise resolved with undefined.+ ReturnsResolvedUndefined,+ /// An algorithm that returns the result of invoking `flush` with argument list « controller » and callback this+ /// value `transformer`.+ Callback {+ flush: PromiseCallbackFunction,+ transformer: Value,+ controller: Ref<TransformStreamDefaultController>,+ },+ /// The flushAlgorithmWrapper of setting up a TransformStream, given the flushAlgorithm that C++ set the stream up+ /// with, if any.+ CppWrapper(Option<CppPromiseAlgorithm>),+ /// The flushAlgorithmWrapper of setting up a TransformStream, given steps of an implementation in Rust.+ RustWrapper(RustTransformSteps),+}++impl FlushAlgorithm {+ /// Performs the algorithm, with the context of the realm of the stream.+ pub(crate) fn run(&self, cx: &CallContext) -> WebIdlPromise {+ match self {+ Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),+ Self::Callback {+ flush,+ transformer,+ controller,+ } => {+ let controller = Value::from_object(wrap(cx, *controller));+ flush.invoke(Some(*transformer), &[controller])+ }+ Self::CppWrapper(flush_algorithm) => {+ // 1. Let result be the result of running flushAlgorithm, if flushAlgorithm was given, or null+ // otherwise. If this throws an exception e, return a promise rejected with e.+ // 2. If result is a Promise, then return result.+ if let Some(flush_algorithm) = flush_algorithm {+ return flush_algorithm.call();+ }++ // 3. Return a promise resolved with undefined.+ resolved_with_undefined(cx)+ }+ Self::RustWrapper(steps) => steps.flush(cx),+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/cpp.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/cpp.rsnew file mode 100644index 00000000000..3678fbf9043--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/cpp.rs@@ -0,0 +1,227 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The cells of LibWeb's C++ code that streams hold: the algorithms that C++ sets a stream up with, and the read+//! requests that C++ reads a stream with, which are defined in Streams/ReadableStream.cpp.++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{ForeignCellSlot, Gc, Trace, Value};++use crate::bindings::promise::{WebIdlPromise, promise_from_abi};++unsafe extern "C" {+ /// Calls a GC::Function<GC::Ref<WebIDL::Promise>()>.+ fn web_streams_call_promise_algorithm(function: *mut c_void) -> *mut c_void;++ /// Calls a GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>.+ fn web_streams_call_promise_algorithm_with_argument(function: *mut c_void, argument: u64) -> *mut c_void;++ /// Performs the chunk steps of a Streams::ReadRequest.+ fn web_streams_read_request_chunk_steps(read_request: *mut c_void, chunk: u64);++ /// Performs the close steps of a Streams::ReadRequest.+ fn web_streams_read_request_close_steps(read_request: *mut c_void);++ /// Performs the error steps of a Streams::ReadRequest.+ fn web_streams_read_request_error_steps(read_request: *mut c_void, error: u64);++ /// Calls a GC::Function<void(ByteBuffer)> with a copy of the bytes.+ fn web_streams_call_bytes_steps(function: *mut c_void, bytes: ak::Span<'_, u8>);++ /// Calls a GC::Function<void(JS::Value)>.+ fn web_streams_call_value_steps(function: *mut c_void, value: u64);+}++/// A cell of LibWeb's C++ code, which this keeps alive.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppCell(ForeignCellSlot);++impl Clone for CppCell {+ fn clone(&self) -> Self {+ // SAFETY: The slot keeps the cell alive.+ unsafe { Self::from_raw(self.0.as_ptr()) }+ }+}++impl CppCell {+ /// # Safety+ ///+ /// `cell` must be a live cell of LibWeb's C++ code.+ pub(crate) unsafe fn from_raw(cell: *mut c_void) -> Self {+ let slot = ForeignCellSlot::empty();+ // SAFETY: The caller passes a live cell.+ unsafe { slot.set(Some(NonNull::new(cell).expect("C++ passes a cell"))) };+ Self(slot)+ }++ pub(crate) fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }+}++/// A promise-returning algorithm with no arguments that C++ set a stream up with, a pullAlgorithm or a flushAlgorithm.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppPromiseAlgorithm(pub(crate) CppCell);++impl CppPromiseAlgorithm {+ pub(crate) fn call(&self) -> WebIdlPromise {+ // SAFETY: The cell is a live GC::Function<GC::Ref<WebIDL::Promise>()>, which returns a live promise.+ unsafe { promise_from_abi(web_streams_call_promise_algorithm(self.0.as_ptr())) }+ }+}++/// A promise-returning algorithm with an argument that C++ set a stream up with, a cancelAlgorithm or a+/// transformAlgorithm.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppPromiseAlgorithmWithArgument(pub(crate) CppCell);++impl CppPromiseAlgorithmWithArgument {+ pub(crate) fn call(&self, argument: Value) -> WebIdlPromise {+ // SAFETY: The cell is a live GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>, which returns a live promise.+ unsafe {+ promise_from_abi(web_streams_call_promise_algorithm_with_argument(+ self.0.as_ptr(),+ argument.0,+ ))+ }+ }+}++/// A read request of LibWeb's C++ code, https://streams.spec.whatwg.org/#read-request+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppReadRequest(pub(crate) CppCell);++impl CppReadRequest {+ pub(crate) fn chunk_steps(&self, chunk: Value) {+ // SAFETY: The cell is a live Streams::ReadRequest.+ unsafe { web_streams_read_request_chunk_steps(self.0.as_ptr(), chunk.0) };+ }++ pub(crate) fn close_steps(&self) {+ // SAFETY: The cell is a live Streams::ReadRequest.+ unsafe { web_streams_read_request_close_steps(self.0.as_ptr()) };+ }++ pub(crate) fn error_steps(&self, error: Value) {+ // SAFETY: The cell is a live Streams::ReadRequest.+ unsafe { web_streams_read_request_error_steps(self.0.as_ptr(), error.0) };+ }+}++/// Steps of LibWeb's C++ code that take a byte sequence.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppBytesSteps(pub(crate) CppCell);++impl CppBytesSteps {+ pub(crate) fn call(&self, bytes: &[u8]) {+ // SAFETY: The cell is a live GC::Function<void(ByteBuffer)>, which copies the bytes.+ unsafe { web_streams_call_bytes_steps(self.0.as_ptr(), ak::Span::new(bytes)) };+ }+}++/// Steps of LibWeb's C++ code that take a JS value.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CppValueSteps(pub(crate) CppCell);++impl CppValueSteps {+ pub(crate) fn call(&self, value: Value) {+ // SAFETY: The cell is a live GC::Function<void(JS::Value)>.+ unsafe { web_streams_call_value_steps(self.0.as_ptr(), value.0) };+ }+}++unsafe extern "C" {+ /// The DOM::AbortSignal that a wrapper wraps.+ fn web_streams_abort_signal_from_wrapper(wrapper: *mut c_void) -> *mut c_void;++ /// The wrapper of a DOM::AbortSignal in the realm.+ fn web_streams_abort_signal_wrapper(realm: *mut c_void, signal: *mut c_void) -> *mut c_void;++ /// A new DOM::AbortSignal.+ fn web_streams_create_abort_signal() -> *mut c_void;++ fn web_streams_abort_signal_aborted(signal: *mut c_void) -> bool;++ fn web_streams_abort_signal_reason(signal: *mut c_void) -> u64;++ /// Adds an abort algorithm that calls the function, a native function with no arguments, to the signal, and+ /// returns whether it did, with its identifier in `id`: a signal that is aborted takes no algorithms.+ fn web_streams_abort_signal_add_algorithm(signal: *mut c_void, function: *mut c_void, id: &mut u64) -> bool;++ fn web_streams_abort_signal_remove_algorithm(signal: *mut c_void, id: u64);++ /// Signals abort on the signal with the reason, https://dom.spec.whatwg.org/#abortsignal-signal-abort, given the+ /// global object of the realm.+ fn web_streams_abort_signal_signal_abort(signal: *mut c_void, reason: u64, realm: *mut c_void);+}++/// A DOM::AbortSignal, https://dom.spec.whatwg.org/#abortsignal+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct AbortSignal(CppCell);++impl AbortSignal {+ /// The signal that a wrapper of an AbortSignal wraps.+ pub(crate) fn from_wrapper(wrapper: crate::bindings::conversions::CppInterface) -> Self {+ // SAFETY: The wrapper is a live wrapper of an AbortSignal, and LibWeb returns the signal it wraps.+ Self(unsafe { CppCell::from_raw(web_streams_abort_signal_from_wrapper(wrapper.wrapper().as_ptr().cast())) })+ }++ pub(crate) fn create() -> Self {+ // SAFETY: LibWeb returns a live signal.+ Self(unsafe { CppCell::from_raw(web_streams_create_abort_signal()) })+ }++ /// The wrapper of the signal in the realm.+ pub(crate) fn wrapper(&self, realm: Gc<libjs_rust::api::Realm>) -> crate::bindings::conversions::CppInterface {+ // SAFETY: The realm and the signal are live, and LibWeb returns the wrapper of the signal.+ let wrapper = unsafe { web_streams_abort_signal_wrapper(realm.as_ptr().cast(), self.0.as_ptr()) };+ let wrapper = NonNull::new(wrapper.cast::<libjs_rust::api::Object>()).expect("LibWeb returns a wrapper");+ // SAFETY: LibWeb returns a live wrapper of an AbortSignal.+ unsafe { crate::bindings::conversions::CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }+ }++ // https://dom.spec.whatwg.org/#abortsignal-aborted+ pub(crate) fn aborted(&self) -> bool {+ // SAFETY: The signal is live.+ unsafe { web_streams_abort_signal_aborted(self.0.as_ptr()) }+ }++ // https://dom.spec.whatwg.org/#abortsignal-abort-reason+ pub(crate) fn reason(&self) -> Value {+ // SAFETY: The signal is live.+ Value(unsafe { web_streams_abort_signal_reason(self.0.as_ptr()) })+ }++ /// Adds the abort algorithm, a native function with no arguments, to the signal,+ /// https://dom.spec.whatwg.org/#abortsignal-add, returning its identifier, or None if the signal is aborted.+ pub(crate) fn add_algorithm(&self, algorithm: Gc<libjs_rust::api::NativeFunction>) -> Option<u64> {+ let mut id = 0;+ // SAFETY: The signal and the function are live.+ unsafe { web_streams_abort_signal_add_algorithm(self.0.as_ptr(), algorithm.as_ptr().cast(), &mut id) }+ .then_some(id)+ }++ // https://dom.spec.whatwg.org/#abortsignal-remove+ pub(crate) fn remove_algorithm(&self, id: u64) {+ // SAFETY: The signal is live.+ unsafe { web_streams_abort_signal_remove_algorithm(self.0.as_ptr(), id) };+ }++ // https://dom.spec.whatwg.org/#abortsignal-signal-abort+ pub(crate) fn signal_abort(&self, reason: Value, realm: Gc<libjs_rust::api::Realm>) {+ // SAFETY: The signal, the reason and the realm are live.+ unsafe { web_streams_abort_signal_signal_abort(self.0.as_ptr(), reason.0, realm.as_ptr().cast()) };+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rsnew file mode 100644index 00000000000..74de910fe5b--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs@@ -0,0 +1,653 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Transferable streams, https://streams.spec.whatwg.org/#transferrable-streams, which LibWeb's C++ MessagePort+//! carries.++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{+ EmbedderCell, EmbedderClass, EmbedderValue, Gc, Must, NativeFunction, Object, PrimitiveString, PropertyKey,+ RawNativeFunctionResult, Realm, Trace, Value, Vm,+};++use crate::bindings::interface::{Ref, allocate};+use crate::bindings::promise::{+ NativeSteps, WebIdlPromise, create_promise, create_rejected_promise_from_exception, create_resolved_promise,+ exception_value, reject_promise_with_exception, resolve_promise, upon_fulfillment,+};+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::streams::algorithms::{+ AbortAlgorithm, CancelAlgorithm, CloseAlgorithm, PullAlgorithm, SizeAlgorithm, StartAlgorithm, WriteAlgorithm,+};+use crate::streams::cpp::CppCell;+use crate::streams::readable_stream::{ReadableStream, initialize_readable_stream};+use crate::streams::readable_stream_default_controller::{+ ReadableStreamDefaultController, readable_stream_default_controller_close,+ readable_stream_default_controller_enqueue, readable_stream_default_controller_error,+ set_up_readable_stream_default_controller,+};+use crate::streams::writable_stream::{WritableStream, initialize_writable_stream};+use crate::streams::writable_stream_default_controller::{+ WritableStreamDefaultController, set_up_writable_stream_default_controller,+ writable_stream_default_controller_error_if_needed,+};++unsafe extern "C" {+ /// Two new MessagePorts in the realm, entangled with each other.+ fn web_streams_create_entangled_ports(realm: *mut c_void, port1: &mut *mut c_void, port2: &mut *mut c_void);++ /// Adds handlers for the port's message and messageerror events that call the functions, native functions of the+ /// realm, with the event.+ fn web_streams_message_port_add_handlers(+ realm: *mut c_void,+ port: *mut c_void,+ on_message: *mut c_void,+ on_message_error: *mut c_void,+ );++ /// The data of a MessageEvent, whose wrapper the handlers of a port are called with.+ fn web_streams_message_event_data(event: u64) -> u64;++ /// Runs the message port post message steps providing the port with which the port is entangled, if any, the+ /// message and «[ "transfer" → « » ]».+ fn web_streams_message_port_post_message(+ realm: *mut c_void,+ port: *mut c_void,+ message: u64,+ ) -> RawNativeFunctionResult;++ /// Disentangles the port.+ fn web_streams_message_port_disentangle(port: *mut c_void);++ /// Enables the port's port message queue.+ fn web_streams_message_port_enable(port: *mut c_void);++ /// The MessagePort that a wrapper wraps.+ fn web_streams_message_port_from_object(object: *mut c_void) -> *mut c_void;++ /// The wrapper of the MessagePort in the realm.+ fn web_streams_message_port_wrapper(realm: *mut c_void, port: *mut c_void) -> *mut c_void;++ /// Sets the data holder to ! StructuredSerializeWithTransfer(value, « value »).+ fn web_streams_serialize_with_transfer(data_holder: *mut c_void, value: u64);++ /// ! StructuredDeserializeWithTransfer(dataHolder, the current Realm).[[Deserialized]], for the next value that the+ /// data holder holds.+ fn web_streams_deserialize_with_transfer(data_holder: *mut c_void) -> u64;+}++/// The steps of a port's message event handler, given the state of the transform and the data of the message.+type MessageSteps<C> = fn(&CallContext, C, Value);++/// The steps of a port's messageerror event handler, given the state of the transform.+type MessageErrorSteps<C> = fn(&CallContext, C);++/// A MessagePort that a cross-realm transform posts its messages to.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CrossRealmTransformPort(CppCell);++impl CrossRealmTransformPort {+ fn as_ptr(&self) -> *mut c_void {+ self.0.as_ptr()+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#disentangle+ fn disentangle(&self) {+ // SAFETY: The port is live.+ unsafe { web_streams_message_port_disentangle(self.as_ptr()) };+ }++ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-start+ fn enable(&self) {+ // SAFETY: The port is live.+ unsafe { web_streams_message_port_enable(self.as_ptr()) };+ }++ /// Adds the handlers for the port's message and messageerror events, which are given the state.+ fn add_handlers<C: Trace + Copy + 'static>(+ &self,+ cx: &CallContext,+ state: C,+ on_message: MessageSteps<C>,+ on_message_error: MessageErrorSteps<C>,+ ) {+ let realm = cx.realm();+ let on_message = NativeFunction::create(+ cx.vm(),+ NativeSteps {+ captures: (state, realm),+ steps: on_message,+ },+ |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageSteps<C>>| {+ let (state, realm) = function.captures;+ // SAFETY: The port's message event handler is called with a MessageEvent.+ let data = Value(unsafe { web_streams_message_event_data(vm.argument(0).0) });+ (function.steps)(&CallContext::new(vm, realm), state, data);+ Ok(Value::UNDEFINED)+ },+ 1,+ &PropertyKey::from_utf8(""),+ Some(realm),+ None,+ None,+ );+ let on_message_error = NativeFunction::create(+ cx.vm(),+ NativeSteps {+ captures: (state, realm),+ steps: on_message_error,+ },+ |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageErrorSteps<C>>| {+ let (state, realm) = function.captures;+ (function.steps)(&CallContext::new(vm, realm), state);+ Ok(Value::UNDEFINED)+ },+ 1,+ &PropertyKey::from_utf8(""),+ Some(realm),+ None,+ None,+ );+ // SAFETY: The realm, the port and the functions are live.+ unsafe {+ web_streams_message_port_add_handlers(+ realm.as_ptr().cast(),+ self.as_ptr(),+ on_message.as_ptr().cast(),+ on_message_error.as_ptr().cast(),+ );+ }+ }++ // https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessage+ fn pack_and_post_message(&self, cx: &CallContext, r#type: &str, value: Value) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let message be OrdinaryObjectCreate(null).+ let message = Object::create(vm, cx.realm(), None);++ // 2. Perform ! CreateDataProperty(message, "type", type).+ let r#type = Value::from_string(PrimitiveString::create_from_ascii(vm, r#type.as_bytes()));+ message+ .create_data_property(vm, &vm.names.type_, r#type, None, None)+ .must();++ // 3. Perform ! CreateDataProperty(message, "value", value).+ message+ .create_data_property(vm, &vm.names.value, value, None, None)+ .must();++ // 4. Let targetPort be the port with which port is entangled, if any; otherwise let it be null.+ // 5. Let options be «[ "transfer" → « » ]».+ // 6. Run the message port post message steps providing targetPort, message, and options.+ // SAFETY: The realm, the port and the message are live.+ unsafe {+ web_streams_message_port_post_message(+ cx.realm().as_ptr().cast(),+ self.as_ptr(),+ Value::from_object(message).0,+ )+ }+ .into_completion()?;+ Ok(())+ }++ // https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessagehandlingerror+ fn pack_and_post_message_handling_error(&self, cx: &CallContext, r#type: &str, value: Value) -> WebIdlResult<()> {+ // 1. Let result be PackAndPostMessage(port, type, value).+ let result = self.pack_and_post_message(cx, r#type, value);++ // 2. If result is an abrupt completion,+ let Err(exception) = result else {+ // 3. Return result as a completion record.+ return Ok(());+ };+ let error = exception_value(cx.vm(), cx.realm(), exception);++ // 1. Perform ! CrossRealmTransformSendError(port, result.[[Value]]).+ self.cross_realm_transform_send_error(cx, error);++ // 3. Return result as a completion record.+ Err(Exception::Thrown(libjs_rust::api::Throw::new(error)))+ }++ // https://streams.spec.whatwg.org/#abstract-opdef-crossrealmtransformsenderror+ fn cross_realm_transform_send_error(&self, cx: &CallContext, error: Value) {+ // 1. Perform PackAndPostMessage(port, "error", error), discarding the result.+ let _ = self.pack_and_post_message(cx, "error", error);+ }++ /// The pullAlgorithm of SetUpCrossRealmTransformReadable.+ pub(crate) fn pull_algorithm(&self, cx: &CallContext) -> WebIdlPromise {+ // 1. Perform ! PackAndPostMessage(port, "pull", undefined).+ self.pack_and_post_message(cx, "pull", Value::UNDEFINED).must();++ // 2. Return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }++ /// The cancelAlgorithm of SetUpCrossRealmTransformReadable, and the abortAlgorithm of+ /// SetUpCrossRealmTransformWritable.+ pub(crate) fn cancel_algorithm(&self, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).+ let result = self.pack_and_post_message_handling_error(cx, "error", reason);++ // 2. Disentangle port.+ self.disentangle();++ // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].+ if let Err(exception) = result {+ return create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception);+ }++ // 4. Otherwise, return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }++ /// The closeAlgorithm of SetUpCrossRealmTransformWritable.+ pub(crate) fn close_algorithm(&self, cx: &CallContext) -> WebIdlPromise {+ // 1. Perform ! PackAndPostMessage(port, "close", undefined).+ self.pack_and_post_message(cx, "close", Value::UNDEFINED).must();++ // 2. Disentangle port.+ self.disentangle();++ // 3. Return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }++ /// The abortAlgorithm of SetUpCrossRealmTransformWritable.+ pub(crate) fn abort_algorithm(&self, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).+ // 2. Disentangle port.+ // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].+ // 4. Otherwise, return a promise resolved with undefined.+ self.cancel_algorithm(cx, reason)+ }+}++/// The type and the value of a message that a cross-realm transform received, ! Get(data, "type") and+/// ! Get(data, "value").+fn type_and_value_of_message(vm: &Vm, data: Value) -> (Gc<PrimitiveString>, Value) {+ // 2. Assert: data is an Object.+ assert!(data.is_object());+ let data = data.as_object();++ // 3. Let type be ! Get(data, "type").+ let r#type = data.get(vm, &vm.names.type_).must();++ // 4. Let value be ! Get(data, "value").+ let value = data.get(vm, &vm.names.value).must();++ // 5. Assert: type is a String.+ assert!(r#type.is_string());+ (r#type.as_string(), value)+}++/// A new "DataCloneError" DOMException, which a cross-realm transform errors with when a message cannot be received.+fn data_clone_error(cx: &CallContext) -> Value {+ exception_value(+ cx.vm(),+ cx.realm(),+ Exception::Dom(+ "DataCloneError",+ ak::Utf16String::from_ascii(b"Unable to transfer stream"),+ ),+ )+}++/// The state that the handlers and the algorithms of a cross-realm transform share.+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+struct ReadableHandlerState {+ port: Gc<EmbedderCell<PortCell>>,+ controller: Ref<ReadableStreamDefaultController>,+}++/// A cell that holds a MessagePort, which the handlers of its events capture.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+struct PortCell(CrossRealmTransformPort);++static PORT_CELL_CLASS: EmbedderClass<PortCell> = EmbedderClass::new("CrossRealmTransformPort");++impl EmbedderValue for PortCell {+ const CLASS: &'static EmbedderClass<Self> = &PORT_CELL_CLASS;+}++// https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable+pub(crate) fn set_up_cross_realm_transform_readable(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ port: CrossRealmTransformPort,+) {+ stream.set_realm(cx.realm());++ // 1. Perform ! InitializeReadableStream(stream).+ initialize_readable_stream(stream);++ // 2. Let controller be a new ReadableStreamDefaultController.+ let controller = allocate(cx.vm(), ReadableStreamDefaultController::new());+ let state = ReadableHandlerState {+ port: PORT_CELL_CLASS.allocate(cx.vm(), PortCell(port.clone())),+ controller,+ };++ // 3. Add a handler for port’s message event with the following steps:+ fn on_message(cx: &CallContext, state: ReadableHandlerState, data: Value) {+ let port = &state.port.0;+ let controller = state.controller;++ // 1. Let data be the data of the message.+ // 2. Assert: data is an Object.+ // 3. Let type be ! Get(data, "type").+ // 4. Let value be ! Get(data, "value").+ // 5. Assert: type is a String.+ let (r#type, value) = type_and_value_of_message(cx.vm(), data);+ let r#type = r#type.to_utf8();++ // 6. If type is "chunk",+ if r#type == "chunk" {+ // 1. Perform ! ReadableStreamDefaultControllerEnqueue(controller, value).+ readable_stream_default_controller_enqueue(cx, controller, value).must();+ }+ // 7. Otherwise, if type is "close",+ else if r#type == "close" {+ // 1. Perform ! ReadableStreamDefaultControllerClose(controller).+ readable_stream_default_controller_close(cx, controller);++ // 2. Disentangle port.+ port.disentangle();+ }+ // 8. Otherwise, if type is "error",+ else if r#type == "error" {+ // 1. Perform ! ReadableStreamDefaultControllerError(controller, value).+ readable_stream_default_controller_error(cx, controller, value);++ // 2. Disentangle port.+ port.disentangle();+ }+ }++ // 4. Add a handler for port’s messageerror event with the following steps:+ fn on_message_error(cx: &CallContext, state: ReadableHandlerState) {+ let port = &state.port.0;++ // 1. Let error be a new "DataCloneError" DOMException.+ let error = data_clone_error(cx);++ // 2. Perform ! CrossRealmTransformSendError(port, error).+ port.cross_realm_transform_send_error(cx, error);++ // 3. Perform ! ReadableStreamDefaultControllerError(controller, error).+ readable_stream_default_controller_error(cx, state.controller, error);++ // 4. Disentangle port.+ port.disentangle();+ }+ port.add_handlers(cx, state, on_message, on_message_error);++ // 5. Enable port’s port message queue.+ port.enable();++ // 6. Let startAlgorithm be an algorithm that returns undefined.+ let start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 7. Let pullAlgorithm be the following steps:+ let pull_algorithm = PullAlgorithm::CrossRealm(port.clone());++ // 8. Let cancelAlgorithm be the following steps, taking a reason argument:+ let cancel_algorithm = CancelAlgorithm::CrossRealm(port);++ // 9. Let sizeAlgorithm be an algorithm that returns 1.+ let size_algorithm = SizeAlgorithm::ReturnsOne;++ // 10. Perform ! SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm,+ // cancelAlgorithm, 0, sizeAlgorithm).+ set_up_readable_stream_default_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ 0.0,+ size_algorithm,+ )+ .must();+}++/// The state that the handlers and the writeAlgorithm of SetUpCrossRealmTransformWritable share.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CrossRealmWritableState {+ port: CrossRealmTransformPort,+ controller: Ref<WritableStreamDefaultController>,+ // backpressurePromise+ backpressure_promise: Cell<Option<WebIdlPromise>>,+}++static CROSS_REALM_WRITABLE_STATE_CLASS: EmbedderClass<CrossRealmWritableState> =+ EmbedderClass::new("CrossRealmTransformWritable");++impl EmbedderValue for CrossRealmWritableState {+ const CLASS: &'static EmbedderClass<Self> = &CROSS_REALM_WRITABLE_STATE_CLASS;+}++impl CrossRealmWritableState {+ /// The writeAlgorithm of SetUpCrossRealmTransformWritable.+ pub(crate) fn write_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext, chunk: Value) -> WebIdlPromise {+ // 1. If backpressurePromise is undefined, set backpressurePromise to a promise resolved with undefined.+ let backpressure_promise = match this.backpressure_promise.get() {+ Some(backpressure_promise) => backpressure_promise,+ None => {+ let backpressure_promise = create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED);+ this.backpressure_promise.set(Some(backpressure_promise));+ backpressure_promise+ }+ };++ // AD-HOC: The steps below return a promise that they create when they run, but the error of+ // PackAndPostMessageHandlingError has to reach the original ReadableStream, which WPT tests: the+ // promise that reacting to backpressurePromise returns is the one that they reject or resolve.+ let reaction_promise = create_promise(cx.vm(), cx.realm());++ // 2. Return the result of reacting to backpressurePromise with the following fulfillment steps:+ upon_fulfillment(+ cx.vm(),+ backpressure_promise,+ (this, reaction_promise, chunk),+ |cx, (this, reaction_promise, chunk), _| {+ // 1. Set backpressurePromise to a new promise.+ this.backpressure_promise.set(Some(create_promise(cx.vm(), cx.realm())));++ // 2. Let result be PackAndPostMessageHandlingError(port, "chunk", chunk).+ let result = this.port.pack_and_post_message_handling_error(cx, "chunk", chunk);++ match result {+ // 3. If result is an abrupt completion,+ Err(exception) => {+ // 1. Disentangle port.+ this.port.disentangle();++ // 2. Return a promise rejected with result.[[Value]].+ reject_promise_with_exception(cx.vm(), reaction_promise, exception);+ }+ // 4. Otherwise, return a promise resolved with undefined.+ Ok(()) => resolve_promise(cx.vm(), reaction_promise, Value::UNDEFINED),+ }+ Ok(Value::UNDEFINED)+ },+ );+ reaction_promise+ }++ /// Resolves backpressurePromise with undefined and sets it to undefined, if it is not undefined.+ fn resolve_backpressure_promise(&self, vm: &Vm) {+ // 1. If backpressurePromise is not undefined,+ if let Some(backpressure_promise) = self.backpressure_promise.take() {+ // 1. Resolve backpressurePromise with undefined.+ // 2. Set backpressurePromise to undefined.+ resolve_promise(vm, backpressure_promise, Value::UNDEFINED);+ }+ }+}++// https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable+pub(crate) fn set_up_cross_realm_transform_writable(+ cx: &CallContext,+ stream: Ref<WritableStream>,+ port: CrossRealmTransformPort,+) {+ // 1. Perform ! InitializeWritableStream(stream).+ initialize_writable_stream(stream);++ // 2. Let controller be a new WritableStreamDefaultController.+ let controller = allocate(cx.vm(), WritableStreamDefaultController::new());++ // 3. Let backpressurePromise be a new promise.+ let state = CROSS_REALM_WRITABLE_STATE_CLASS.allocate(+ cx.vm(),+ CrossRealmWritableState {+ port: port.clone(),+ controller,+ backpressure_promise: Cell::new(Some(create_promise(cx.vm(), cx.realm()))),+ },+ );++ // 4. Add a handler for port’s message event with the following steps:+ fn on_message(cx: &CallContext, state: Gc<EmbedderCell<CrossRealmWritableState>>, data: Value) {+ // 1. Let data be the data of the message.+ // 2. Assert: data is an Object.+ // 3. Let type be ! Get(data, "type").+ // 4. Let value be ! Get(data, "value").+ // 5. Assert: type is a String.+ let (r#type, value) = type_and_value_of_message(cx.vm(), data);+ let r#type = r#type.to_utf8();++ // 6. If type is "pull",+ if r#type == "pull" {+ // 1. If backpressurePromise is not undefined,+ state.resolve_backpressure_promise(cx.vm());+ }+ // 7. Otherwise, if type is "error",+ else if r#type == "error" {+ // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, value).+ writable_stream_default_controller_error_if_needed(cx, state.controller, value);++ // 2. If backpressurePromise is not undefined,+ state.resolve_backpressure_promise(cx.vm());+ }+ }++ // 5. Add a handler for port’s messageerror event with the following steps:+ fn on_message_error(cx: &CallContext, state: Gc<EmbedderCell<CrossRealmWritableState>>) {+ // 1. Let error be a new "DataCloneError" DOMException.+ let error = data_clone_error(cx);++ // 2. Perform ! CrossRealmTransformSendError(port, error).+ state.port.cross_realm_transform_send_error(cx, error);++ // 3. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, error).+ writable_stream_default_controller_error_if_needed(cx, state.controller, error);++ // 4. Disentangle port.+ state.port.disentangle();+ }+ port.add_handlers(cx, state, on_message, on_message_error);++ // 6. Enable port’s port message queue.+ port.enable();++ // 7. Let startAlgorithm be an algorithm that returns undefined.+ let start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 8. Let writeAlgorithm be the following steps, taking a chunk argument:+ let write_algorithm = WriteAlgorithm::CrossRealm(state);++ // 9. Let closeAlgorithm be the following steps:+ let close_algorithm = CloseAlgorithm::CrossRealm(port.clone());++ // 10. Let abortAlgorithm be the following steps, taking a reason argument:+ let abort_algorithm = AbortAlgorithm::CrossRealm(port);++ // 11. Let sizeAlgorithm be an algorithm that returns 1.+ let size_algorithm = SizeAlgorithm::ReturnsOne;++ // 12. Perform ! SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm,+ // closeAlgorithm, abortAlgorithm, 1, sizeAlgorithm).+ set_up_writable_stream_default_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ write_algorithm,+ close_algorithm,+ abort_algorithm,+ 1.0,+ size_algorithm,+ )+ .must();+}++/// Two new MessagePorts in the current realm, entangled with each other.+pub(crate) fn create_entangled_ports(cx: &CallContext) -> (CrossRealmTransformPort, CrossRealmTransformPort) {+ let mut port1 = core::ptr::null_mut();+ let mut port2 = core::ptr::null_mut();+ // SAFETY: The realm is live, and LibWeb returns two live ports.+ unsafe {+ web_streams_create_entangled_ports(cx.realm().as_ptr().cast(), &mut port1, &mut port2);+ (+ CrossRealmTransformPort(CppCell::from_raw(port1)),+ CrossRealmTransformPort(CppCell::from_raw(port2)),+ )+ }+}++/// Sets the data holder to ! StructuredSerializeWithTransfer(port, « port »).+pub(crate) fn serialize_message_port(+ cx: &CallContext,+ data_holder: &mut TransferDataWriter,+ port: &CrossRealmTransformPort,+) {+ // SAFETY: The realm and the port are live, and LibWeb returns the wrapper of the port.+ let wrapper = unsafe { web_streams_message_port_wrapper(cx.realm().as_ptr().cast(), port.as_ptr()) };+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns a wrapper");+ // SAFETY: LibWeb returns a live wrapper.+ let wrapper = unsafe { Gc::from_non_null(wrapper) };+ serialize_with_transfer(data_holder, Value::from_object(wrapper));+}++/// The MessagePort of ! StructuredDeserializeWithTransfer(dataHolder.[[port]], the current Realm).+pub(crate) fn deserialize_message_port(+ _: &CallContext,+ data_holder: &mut TransferDataReader,+) -> CrossRealmTransformPort {+ let deserialized = deserialize_with_transfer(data_holder);+ assert!(deserialized.is_object());+ // SAFETY: The object is live, and LibWeb returns the MessagePort that it wraps.+ unsafe {+ let port = web_streams_message_port_from_object(deserialized.as_object().as_ptr().cast());+ CrossRealmTransformPort(CppCell::from_raw(port))+ }+}++/// Sets the data holder to ! StructuredSerializeWithTransfer(value, « value »).+pub(crate) fn serialize_with_transfer(data_holder: &mut TransferDataWriter, value: Value) {+ // SAFETY: The data holder is lent for the transfer steps, and the value is live.+ unsafe { web_streams_serialize_with_transfer(data_holder.as_raw(), value.0) };+}++/// ! StructuredDeserializeWithTransfer(dataHolder, the current Realm).[[Deserialized]]+pub(crate) fn deserialize_with_transfer(data_holder: &mut TransferDataReader) -> Value {+ // SAFETY: The data holder is lent for the transfer-receiving steps.+ Value(unsafe { web_streams_deserialize_with_transfer(data_holder.as_raw()) })+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rsnew file mode 100644index 00000000000..3d6bb8c4174--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/exports.rs@@ -0,0 +1,512 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The C ABI through which the C++ classes of Streams/ReadableStream.h and Streams/TransformStream.h set streams up+//! and read them, for the specifications that LibWeb implements in C++.++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{RawNativeFunctionResult, Realm, ThrowCompletionOr, Value, Vm};++use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_into_abi, realm_arguments};+use crate::bindings::promise::WebIdlPromise;+use crate::bindings::{CallContext, MustNotThrow, WebIdlResult};+use crate::streams::algorithms::{CancelAlgorithm, FlushAlgorithm, TransformAlgorithm};+use crate::streams::cpp::{+ CppBytesSteps, CppCell, CppPromiseAlgorithm, CppPromiseAlgorithmWithArgument, CppReadRequest, CppValueSteps,+};+use crate::streams::readable_byte_stream_controller::readable_byte_stream_controller_enqueue_native_bytes;+use crate::streams::readable_stream::ReadableStreamReader;+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamState, is_readable_stream_locked, readable_stream_cancel,+};+use crate::streams::readable_stream_default_reader::ReadableStreamDefaultReader;+use crate::streams::readable_stream_generic_reader::ReadableStreamGenericReader;+use crate::streams::readable_stream_tee::readable_stream_tee;+use crate::streams::transform_stream::TransformStream;+use crate::streams::transform_stream_default_controller::transform_stream_default_controller_enqueue;+use crate::streams::underlying_source::ReadableStreamController;++/// # Safety+///+/// `vm` must be the live VM.+unsafe fn vm_argument<'vm>(vm: *mut c_void) -> &'vm Vm {+ // SAFETY: The caller passes the live VM.+ unsafe { &*vm.cast::<Vm>() }+}++/// # Safety+///+/// `cell` must be null or a live cell of LibWeb's C++ code.+unsafe fn optional_cpp_cell(cell: *mut c_void) -> Option<CppCell> {+ // SAFETY: The caller passes null or a live cell.+ NonNull::new(cell).map(|cell| unsafe { CppCell::from_raw(cell.as_ptr()) })+}++fn completion(cx: &CallContext, result: WebIdlResult<()>) -> RawNativeFunctionResult {+ let result: ThrowCompletionOr<Value> = result+ .map(|()| Value::UNDEFINED)+ .map_err(|exception| exception.throw(cx));+ RawNativeFunctionResult::from_completion(result)+}++fn promise_into_abi(promise: WebIdlPromise) -> *mut c_void {+ promise.as_ptr().cast()+}++/// A new ReadableStream in the realm.+///+/// # Safety+///+/// The pointers must be the VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_create(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(allocate(vm, ReadableStream::new(realm)))+}++/// Sets the stream up with byte reading support, https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support,+/// given the pullAlgorithm and the cancelAlgorithm that C++ gives, if any.+///+/// # Safety+///+/// The pointers must be the VM, a live realm, a live ReadableStream, and null or the live GC::Functions of the+/// algorithms.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_set_up_with_byte_reading_support(+ vm: *mut c_void,+ realm: *mut c_void,+ stream: *mut c_void,+ pull_algorithm: *mut c_void,+ cancel_algorithm: *mut c_void,+ high_water_mark: f64,+) {+ // SAFETY: The caller passes the VM, a live realm, a live stream, and null or live algorithms.+ let ((vm, realm), stream, pull_algorithm, cancel_algorithm) = unsafe {+ (+ realm_arguments(vm, realm),+ cell_from_abi::<ReadableStream>(stream),+ optional_cpp_cell(pull_algorithm).map(CppPromiseAlgorithm),+ optional_cpp_cell(cancel_algorithm).map(CppPromiseAlgorithmWithArgument),+ )+ };+ let cx = CallContext::new(vm, realm);+ ReadableStream::set_up_with_byte_reading_support(stream, &cx, pull_algorithm, cancel_algorithm, high_water_mark);+}++/// The [[state]] of the stream: 0 for "readable", 1 for "closed", and 2 for "errored".+///+/// # Safety+///+/// `stream` must be a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_state(stream: *mut c_void) -> u8 {+ // SAFETY: The caller passes a live ReadableStream.+ let stream = unsafe { cell_from_abi::<ReadableStream>(stream) };+ match stream.state() {+ ReadableStreamState::Readable => 0,+ ReadableStreamState::Closed => 1,+ ReadableStreamState::Errored => 2,+ }+}++/// https://streams.spec.whatwg.org/#readablestream-locked+///+/// # Safety+///+/// `stream` must be a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_is_locked(stream: *mut c_void) -> bool {+ // SAFETY: The caller passes a live ReadableStream.+ let stream = unsafe { cell_from_abi::<ReadableStream>(stream) };+ // A ReadableStream stream is locked if ! IsReadableStreamLocked(stream) returns true.+ is_readable_stream_locked(stream)+}++/// https://streams.spec.whatwg.org/#is-readable-stream-disturbed+///+/// # Safety+///+/// `stream` must be a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_is_disturbed(stream: *mut c_void) -> bool {+ // SAFETY: The caller passes a live ReadableStream.+ let stream = unsafe { cell_from_abi::<ReadableStream>(stream) };+ // A ReadableStream stream is disturbed if stream.[[disturbed]] is true.+ stream.disturbed()+}++/// Whether the [[closeRequested]] of the stream's controller is true.+///+/// # Safety+///+/// `stream` must be a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_close_requested(stream: *mut c_void) -> bool {+ // SAFETY: The caller passes a live ReadableStream.+ let stream = unsafe { cell_from_abi::<ReadableStream>(stream) };+ match stream.controller() {+ Some(ReadableStreamController::ReadableStreamDefaultController(controller)) => controller.close_requested(),+ Some(ReadableStreamController::ReadableByteStreamController(controller)) => controller.close_requested(),+ None => false,+ }+}++/// https://streams.spec.whatwg.org/#readablestream-enqueue+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_enqueue(+ vm: *mut c_void,+ stream: *mut c_void,+ chunk: u64,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ let result = ReadableStream::enqueue(stream, vm, Value(chunk));+ completion(&stream.context(vm), result)+}++/// ReadableByteStreamControllerEnqueue on the controller of the stream, a ReadableByteStreamController, with a chunk of+/// the bytes, https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream, and the bytes must be lent for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_enqueue_native_bytes(+ vm: *mut c_void,+ stream: *mut c_void,+ bytes: ak::Span<'_, u8>,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ let cx = stream.context(vm);+ let Some(ReadableStreamController::ReadableByteStreamController(controller)) = stream.controller() else {+ panic!("C++ enqueues bytes into a stream with a ReadableByteStreamController");+ };+ let result = readable_byte_stream_controller_enqueue_native_bytes(&cx, controller, bytes.as_slice());+ completion(&cx, result)+}++/// https://streams.spec.whatwg.org/#readablestream-close+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_close(vm: *mut c_void, stream: *mut c_void) {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ ReadableStream::close(stream, vm);+}++/// https://streams.spec.whatwg.org/#readablestream-error+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_error(vm: *mut c_void, stream: *mut c_void, error: u64) {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ ReadableStream::error(stream, vm, Value(error));+}++/// ! ReadableStreamCancel(stream, reason), https://streams.spec.whatwg.org/#readable-stream-cancel+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_cancel(+ vm: *mut c_void,+ stream: *mut c_void,+ reason: u64,+) -> *mut c_void {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ promise_into_abi(readable_stream_cancel(&stream.context(vm), stream, Value(reason)))+}++/// To tee a ReadableStream stream, https://streams.spec.whatwg.org/#readablestream-tee, which sets the branches.+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_tee(+ vm: *mut c_void,+ stream: *mut c_void,+ branch1: &mut *mut c_void,+ branch2: &mut *mut c_void,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ let cx = stream.context(vm);++ // To tee a ReadableStream stream, return ? ReadableStreamTee(stream, true).+ let result = readable_stream_tee(&cx, stream, true).map(|(first, second)| {+ *branch1 = cell_into_abi(first);+ *branch2 = cell_into_abi(second);+ });+ completion(&cx, result)+}++/// To get a reader for a ReadableStream, https://streams.spec.whatwg.org/#readablestream-get-a-reader, which sets the+/// reader.+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_get_a_reader(+ vm: *mut c_void,+ stream: *mut c_void,+ reader: &mut *mut c_void,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the VM and a live ReadableStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStream>(stream)) };+ let result = ReadableStream::get_a_reader(stream, vm).map(|new_reader| *reader = cell_into_abi(new_reader));+ completion(&stream.context(vm), result)+}++/// The stream piped through the TransformStream, https://streams.spec.whatwg.org/#readablestream-pipe-through+///+/// # Safety+///+/// The pointers must be the VM, a live ReadableStream and a live TransformStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_piped_through(+ vm: *mut c_void,+ stream: *mut c_void,+ transform: *mut c_void,+ prevent_close: bool,+ prevent_abort: bool,+ prevent_cancel: bool,+) -> *mut c_void {+ // SAFETY: The caller passes the VM, a live ReadableStream and a live TransformStream.+ let (vm, stream, transform) = unsafe {+ (+ vm_argument(vm),+ cell_from_abi::<ReadableStream>(stream),+ cell_from_abi::<TransformStream>(transform),+ )+ };+ let readable = ReadableStream::piped_through(+ stream,+ vm,+ transform,+ prevent_close,+ prevent_abort,+ prevent_cancel,+ None,+ );+ cell_into_abi(readable)+}++/// The reader as a ReadableStreamReader.+fn default_reader(reader: Ref<ReadableStreamDefaultReader>) -> ReadableStreamReader {+ ReadableStreamReader::ReadableStreamDefaultReader(reader)+}++/// To read a chunk from a ReadableStreamDefaultReader, given a read request of C++,+/// https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-a-chunk+///+/// # Safety+///+/// The pointers must be the VM, a live ReadableStreamDefaultReader and a live Streams::ReadRequest.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_default_reader_read_a_chunk(+ vm: *mut c_void,+ reader: *mut c_void,+ read_request: *mut c_void,+) {+ // SAFETY: The caller passes the VM, a live reader and a live read request.+ let (vm, reader, read_request) = unsafe {+ (+ vm_argument(vm),+ cell_from_abi::<ReadableStreamDefaultReader>(reader),+ CppReadRequest(CppCell::from_raw(read_request)),+ )+ };+ ReadableStreamDefaultReader::read_a_chunk(vm, reader, read_request);+}++/// To read all bytes from a ReadableStreamDefaultReader, given the successSteps and the failureSteps of C++,+/// https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes+///+/// # Safety+///+/// The pointers must be the VM, a live ReadableStreamDefaultReader, a live GC::Function<void(ByteBuffer)> and a live+/// GC::Function<void(JS::Value)>.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_default_reader_read_all_bytes(+ vm: *mut c_void,+ reader: *mut c_void,+ success_steps: *mut c_void,+ failure_steps: *mut c_void,+) {+ // SAFETY: The caller passes the VM, a live reader and live steps.+ let (vm, reader, success_steps, failure_steps) = unsafe {+ (+ vm_argument(vm),+ cell_from_abi::<ReadableStreamDefaultReader>(reader),+ CppBytesSteps(CppCell::from_raw(success_steps)),+ CppValueSteps(CppCell::from_raw(failure_steps)),+ )+ };+ ReadableStreamDefaultReader::read_all_bytes(vm, reader, success_steps, failure_steps);+}++/// The steps of the reader's read(), https://streams.spec.whatwg.org/#default-reader-read+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStreamDefaultReader.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_default_reader_read(+ vm: *mut c_void,+ reader: *mut c_void,+) -> *mut c_void {+ // SAFETY: The caller passes the VM and a live reader.+ let (vm, reader) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStreamDefaultReader>(reader)) };+ let mut cx = reader.generic().context(vm);+ promise_into_abi(ReadableStreamDefaultReader::read(&reader, &mut cx).must())+}++/// The steps of the reader's cancel(), https://streams.spec.whatwg.org/#generic-reader-cancel+///+/// # Safety+///+/// The pointers must be the VM and a live ReadableStreamDefaultReader.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_default_reader_cancel(+ vm: *mut c_void,+ reader: *mut c_void,+ reason: u64,+) -> *mut c_void {+ // SAFETY: The caller passes the VM and a live reader.+ let (vm, reader) = unsafe { (vm_argument(vm), cell_from_abi::<ReadableStreamDefaultReader>(reader)) };+ promise_into_abi(ReadableStreamGenericReader::cancel(+ vm,+ default_reader(reader),+ Some(Value(reason)),+ ))+}++/// The realm of the reader's [[closedPromise]].+///+/// # Safety+///+/// `reader` must be a live ReadableStreamDefaultReader.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_readable_stream_default_reader_closed_promise_realm(+ reader: *mut c_void,+) -> *mut c_void {+ // SAFETY: The caller passes a live reader.+ let reader = unsafe { cell_from_abi::<ReadableStreamDefaultReader>(reader) };+ let realm: libjs_rust::api::Gc<Realm> = reader.generic().closed_promise_realm();+ realm.as_ptr().cast()+}++/// A new TransformStream in the realm.+///+/// # Safety+///+/// The pointers must be the VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_transform_stream_create(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(allocate(vm, TransformStream::new(realm)))+}++/// Sets the stream up with the algorithms that C++ gives, https://streams.spec.whatwg.org/#transformstream-set-up+///+/// # Safety+///+/// The pointers must be the VM, a live realm, a live TransformStream, the live GC::Function of the transformAlgorithm,+/// and null or the live GC::Functions of the flushAlgorithm and the cancelAlgorithm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_transform_stream_set_up(+ vm: *mut c_void,+ realm: *mut c_void,+ stream: *mut c_void,+ transform_algorithm: *mut c_void,+ flush_algorithm: *mut c_void,+ cancel_algorithm: *mut c_void,+) {+ // SAFETY: The caller passes the VM, a live realm, a live stream, a live transformAlgorithm and null or live+ // algorithms.+ let ((vm, realm), stream, transform_algorithm, flush_algorithm, cancel_algorithm) = unsafe {+ (+ realm_arguments(vm, realm),+ cell_from_abi::<TransformStream>(stream),+ CppPromiseAlgorithmWithArgument(CppCell::from_raw(transform_algorithm)),+ optional_cpp_cell(flush_algorithm).map(CppPromiseAlgorithm),+ optional_cpp_cell(cancel_algorithm).map(CppPromiseAlgorithmWithArgument),+ )+ };+ let cx = CallContext::new(vm, realm);+ TransformStream::set_up(+ stream,+ &cx,+ TransformAlgorithm::CppWrapper(transform_algorithm),+ FlushAlgorithm::CppWrapper(flush_algorithm),+ CancelAlgorithm::Wrapper(cancel_algorithm),+ );+}++/// TransformStreamDefaultControllerEnqueue(stream.[[controller]], chunk), as enqueuing the chunk into the stream does,+/// https://streams.spec.whatwg.org/#transformstream-enqueue+///+/// # Safety+///+/// The pointers must be the VM and a live TransformStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_transform_stream_enqueue(+ vm: *mut c_void,+ stream: *mut c_void,+ chunk: u64,+) -> RawNativeFunctionResult {+ // SAFETY: The caller passes the VM and a live TransformStream.+ let (vm, stream) = unsafe { (vm_argument(vm), cell_from_abi::<TransformStream>(stream)) };+ let cx = CallContext::new(vm, stream.backpressure_change_promise_realm());+ let controller = stream+ .controller()+ .expect("a TransformStream that is set up has a controller");+ let result = transform_stream_default_controller_enqueue(&cx, controller, Value(chunk));+ completion(&cx, result)+}++/// The stream's [[readable]].+///+/// # Safety+///+/// `stream` must be a live TransformStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_transform_stream_readable(stream: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live TransformStream.+ let stream = unsafe { cell_from_abi::<TransformStream>(stream) };+ cell_into_abi(stream.readable_stream())+}++/// The stream's [[writable]].+///+/// # Safety+///+/// `stream` must be a live TransformStream.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_transform_stream_writable(stream: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes a live TransformStream.+ let stream = unsafe { cell_from_abi::<TransformStream>(stream) };+ cell_into_abi(stream.writable_stream())+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rsindex 130362af303..b44d077285a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/generic_transform_stream.rs@@ -5,149 +5,152 @@*///! The TransformStream of an interface that includes GenericTransformStream,-//! https://streams.spec.whatwg.org/#generictransformstream, which LibWeb implements in C++.+//! https://streams.spec.whatwg.org/#generictransformstream, which the interface sets up with steps of its own.use core::ffi::c_void;use core::ptr::NonNull;-use libjs_rust::api::{- EmbedderCell, EmbedderValue, ForeignCellSlot, Gc, Object, RawNativeFunctionResult, Trace, Value,-};+use libjs_rust::api::{EmbedderCell, EmbedderValue, ForeignCellSlot, Gc, Trace, Value};-use crate::bindings::conversions::CppInterface;-use crate::bindings::interface::realm_arguments;+use crate::bindings::interface::{Ref, allocate, with_temporary_execution_context_and_callbacks};+use crate::bindings::promise::{WebIdlPromise, create_rejected_promise, create_resolved_promise, exception_value};use crate::bindings::{CallContext, WebIdlResult};+use crate::streams::algorithms::{CancelAlgorithm, FlushAlgorithm, TransformAlgorithm};+use crate::streams::transform_stream::TransformStream;-/// 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.+/// The transformAlgorithm and the flushAlgorithm that an interface sets its TransformStream up with,+/// https://streams.spec.whatwg.org/#transformstream-set-up, which live in a cell of their own. An exception that they+/// throw rejects the promise of the algorithm.pub(crate) trait TransformSteps: EmbedderValue {- fn transform(&self, cx: &CallContext, transform: &TransformStream, chunk: Value) -> WebIdlResult<()>;+ fn transform(&self, cx: &CallContext, transform: Ref<TransformStream>, chunk: Value) -> WebIdlResult<()>;- fn flush(&self, cx: &CallContext, transform: &TransformStream) -> WebIdlResult<()>;+ fn flush(&self, cx: &CallContext, transform: Ref<TransformStream>) -> WebIdlResult<()>;}+type TransformEntry = unsafe fn(&CallContext, NonNull<c_void>, Ref<TransformStream>, Value) -> WebIdlResult<()>;+type FlushEntry = unsafe fn(&CallContext, NonNull<c_void>, Ref<TransformStream>) -> WebIdlResult<()>;++/// The steps of an implementation of TransformSteps, with the stream that they were set up for. The steps run in the+/// realm of the stream, as the callbacks of a transformer run in their own realm, so what they enqueue is created there.#[derive(Trace)]#[gc(crate = libjs_rust)]-pub(crate) struct TransformStream(ForeignCellSlot);+pub(crate) struct RustTransformSteps {+ steps: ForeignCellSlot,+ stream: Ref<TransformStream>,+ #[gc(untraced)]+ transform: TransformEntry,+ #[gc(untraced)]+ flush: FlushEntry,+}-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)+impl Clone for RustTransformSteps {+ fn clone(&self) -> Self {+ let steps = ForeignCellSlot::empty();+ // SAFETY: The slot of `self` keeps the cell alive.+ unsafe { steps.set(Some(NonNull::new(self.steps.as_ptr()).expect("the steps are a cell"))) };+ Self {+ steps,+ stream: self.stream,+ transform: self.transform,+ flush: self.flush,+ }}+}- /// 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>,- ))+impl RustTransformSteps {+ fn new<T: TransformSteps>(steps: Gc<EmbedderCell<T>>, stream: Ref<TransformStream>) -> Self {+ let slot = ForeignCellSlot::empty();+ // SAFETY: The steps are a live cell.+ unsafe { slot.set(Some(steps.as_non_null().cast())) };+ Self {+ steps: slot,+ stream,+ transform: transform_entry::<T>,+ flush: flush_entry::<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) };+ fn steps(&self) -> NonNull<c_void> {+ NonNull::new(self.steps.as_ptr()).expect("the steps are a cell")}- /// The stream's [[readable]].- pub(crate) fn readable(&self, cx: &CallContext) -> CppInterface {- self.side(cx, Side::Readable)+ /// The transformAlgorithmWrapper of setting up the stream, given the chunk.+ pub(crate) fn transform(&self, cx: &CallContext, chunk: Value) -> WebIdlPromise {+ // 1. Let result be the result of running transformAlgorithm given chunk. If this throws an exception e, return+ // a promise rejected with e.+ let result = with_temporary_execution_context_and_callbacks(cx.realm(), || {+ // SAFETY: The entry is that of the class of the steps.+ unsafe { (self.transform)(cx, self.steps(), self.stream, chunk) }+ });+ promise_for(cx, result)}- /// The stream's [[writable]].- pub(crate) fn writable(&self, cx: &CallContext) -> CppInterface {- self.side(cx, Side::Writable)+ /// The flushAlgorithmWrapper of setting up the stream.+ pub(crate) fn flush(&self, cx: &CallContext) -> WebIdlPromise {+ // 1. Let result be the result of running flushAlgorithm, if flushAlgorithm was given, or null otherwise. If+ // this throws an exception e, return a promise rejected with e.+ let result = with_temporary_execution_context_and_callbacks(cx.realm(), || {+ // SAFETY: The entry is that of the class of the steps.+ unsafe { (self.flush)(cx, self.steps(), self.stream) }+ });+ promise_for(cx, result)}+}- 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)) }+/// A promise rejected with the exception that steps threw, or else, as their result is not a promise, a promise+/// resolved with undefined.+fn promise_for(cx: &CallContext, result: WebIdlResult<()>) -> WebIdlPromise {+ match result {+ Err(exception) => {+ let reason = exception_value(cx.vm(), cx.realm(), exception);+ create_rejected_promise(cx.vm(), cx.realm(), reason)+ }+ // 2. If result is a Promise, then return result.+ // 3. Return a promise resolved with undefined.+ Ok(()) => create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED),}}-/// 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) };+/// `steps` must be a live cell of the class of `T`.+unsafe fn transform_entry<T: TransformSteps>(+ cx: &CallContext,+ steps: NonNull<c_void>,+ stream: Ref<TransformStream>,+ chunk: Value,+) -> WebIdlResult<()> {+ // SAFETY: The caller passes a live cell of the class of T.+ let steps = unsafe { T::CLASS.downcast(steps) }.expect("the steps are of the class they were set up with");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)))+ steps.transform(cx, stream, chunk)}/// # 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)+/// `steps` must be a live cell of the class of `T`.+unsafe fn flush_entry<T: TransformSteps>(+ cx: &CallContext,+ steps: NonNull<c_void>,+ stream: Ref<TransformStream>,+) -> WebIdlResult<()> {+ // SAFETY: The caller passes a live cell of the class of T.+ let steps = unsafe { T::CLASS.downcast(steps) }.expect("the steps are of the class they were set up with");+ let _type_error_realm = cx.vm().type_error_realm_scope(cx.realm());+ steps.flush(cx, stream)+}++/// 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) -> Ref<TransformStream> {+ let steps = T::CLASS.allocate(cx.vm(), steps);+ let stream = allocate(cx.vm(), TransformStream::new(cx.realm()));+ let algorithms = RustTransformSteps::new(steps, stream);+ TransformStream::set_up(+ stream,+ cx,+ TransformAlgorithm::RustWrapper(algorithms.clone()),+ FlushAlgorithm::RustWrapper(algorithms),+ CancelAlgorithm::Wrapper(None),+ );+ stream}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rsindex 5553de84996..55ebf752aa5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/mod.rs@@ -6,10 +6,60 @@//! The Streams Standard, https://streams.spec.whatwg.org/+#[cfg(not(test))]+pub(crate) mod abstract_operations;+#[cfg(not(test))]+pub(crate) mod algorithms;#[cfg(not(test))]pub(crate) mod byte_length_queuing_strategy;#[cfg(not(test))]pub(crate) mod count_queuing_strategy;#[cfg(not(test))]+pub(crate) mod cpp;+#[cfg(not(test))]+pub(crate) mod cross_realm_transform;+#[cfg(not(test))]+pub(crate) mod exports;+#[cfg(not(test))]pub(crate) mod generic_transform_stream;+#[cfg(not(test))]+pub(crate) mod queue_with_sizes;+#[cfg(not(test))]+pub(crate) mod queuing_strategy;pub(crate) mod queuing_strategy_init;+#[cfg(not(test))]+pub(crate) mod read_request;+#[cfg(not(test))]+pub(crate) mod readable_byte_stream_controller;+#[cfg(not(test))]+pub(crate) mod readable_stream;+#[cfg(not(test))]+pub(crate) mod readable_stream_byob_reader;+#[cfg(not(test))]+pub(crate) mod readable_stream_byob_request;+#[cfg(not(test))]+pub(crate) mod readable_stream_default_controller;+#[cfg(not(test))]+pub(crate) mod readable_stream_default_reader;+#[cfg(not(test))]+pub(crate) mod readable_stream_generic_reader;+#[cfg(not(test))]+pub(crate) mod readable_stream_pipe_to;+#[cfg(not(test))]+pub(crate) mod readable_stream_tee;+#[cfg(not(test))]+pub(crate) mod transform_stream;+#[cfg(not(test))]+pub(crate) mod transform_stream_default_controller;+#[cfg(not(test))]+pub(crate) mod transformer;+#[cfg(not(test))]+pub(crate) mod underlying_sink;+#[cfg(not(test))]+pub(crate) mod underlying_source;+#[cfg(not(test))]+pub(crate) mod writable_stream;+#[cfg(not(test))]+pub(crate) mod writable_stream_default_controller;+#[cfg(not(test))]+pub(crate) mod writable_stream_default_writer;diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/queue_with_sizes.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/queue_with_sizes.rsnew file mode 100644index 00000000000..ec95c9cf80f--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/queue_with_sizes.rs@@ -0,0 +1,125 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Queue-with-sizes, https://streams.spec.whatwg.org/#queue-with-sizes++use std::collections::VecDeque;++use core::cell::Cell;++use libjs_rust::api::{GcRefCell, Trace, Value};++use crate::bindings::{Exception, WebIdlResult};+use crate::streams::abstract_operations::is_non_negative_number;++/// https://streams.spec.whatwg.org/#value-with-size+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ValueWithSize {+ pub(crate) value: Value,+ #[gc(untraced)]+ pub(crate) size: f64,+}++/// The [[queue]] and [[queueTotalSize]] internal slots of a container,+/// https://streams.spec.whatwg.org/#queue-with-sizes+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct QueueWithSizes {+ queue: GcRefCell<VecDeque<ValueWithSize>>,+ #[gc(untraced)]+ queue_total_size: Cell<f64>,+}++impl Default for QueueWithSizes {+ fn default() -> Self {+ Self {+ queue: GcRefCell::new(VecDeque::new()),+ queue_total_size: Cell::new(0.0),+ }+ }+}++impl QueueWithSizes {+ pub(crate) fn is_empty(&self) -> bool {+ self.queue.borrow().is_empty()+ }++ pub(crate) fn total_size(&self) -> f64 {+ self.queue_total_size.get()+ }++ // https://streams.spec.whatwg.org/#dequeue-value+ pub(crate) fn dequeue_value(&self) -> Value {+ // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.+ // 2. Assert: container.[[queue]] is not empty.+ // 3. Let valueWithSize be container.[[queue]][0].+ // 4. Remove valueWithSize from container.[[queue]].+ let value_with_size = self+ .queue+ .borrow_mut()+ .pop_front()+ .expect("a container dequeues from a queue that is not empty");++ // 5. Set container.[[queueTotalSize]] to container.[[queueTotalSize]] − valueWithSize’s size.+ self.queue_total_size+ .set(self.queue_total_size.get() - value_with_size.size);++ // 6. If container.[[queueTotalSize]] < 0, set container.[[queueTotalSize]] to 0. (This can occur due to+ // rounding errors.)+ if self.queue_total_size.get() < 0.0 {+ self.queue_total_size.set(0.0);+ }++ // 7. Return valueWithSize’s value.+ value_with_size.value+ }++ // https://streams.spec.whatwg.org/#enqueue-value-with-size+ pub(crate) fn enqueue_value_with_size(&self, value: Value, size: Value) -> WebIdlResult<()> {+ // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.+ // 2. If ! IsNonNegativeNumber(size) is false, throw a RangeError exception.+ if !is_non_negative_number(size) {+ return Err(Exception::range_error("Chunk has non-positive size"));+ }++ // 3. If size is +∞, throw a RangeError exception.+ let size = size.as_f64();+ if size == f64::INFINITY {+ return Err(Exception::range_error("Chunk has infinite size"));+ }++ // 4. Append a new value-with-size with value value and size size to container.[[queue]].+ self.queue.borrow_mut().push_back(ValueWithSize { value, size });++ // 5. Set container.[[queueTotalSize]] to container.[[queueTotalSize]] + size.+ self.queue_total_size.set(self.queue_total_size.get() + size);+ Ok(())+ }++ // https://streams.spec.whatwg.org/#peek-queue-value+ pub(crate) fn peek_queue_value(&self) -> Value {+ // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.+ // 2. Assert: container.[[queue]] is not empty.+ // 3. Let valueWithSize be container.[[queue]][0].+ // 4. Return valueWithSize’s value.+ self.queue+ .borrow()+ .front()+ .expect("a container peeks at a queue that is not empty")+ .value+ }++ // https://streams.spec.whatwg.org/#reset-queue+ pub(crate) fn reset_queue(&self) {+ // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.+ // 2. Set container.[[queue]] to a new empty list.+ self.queue.borrow_mut().clear();++ // 3. Set container.[[queueTotalSize]] to 0.+ self.queue_total_size.set(0.0);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/queuing_strategy.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/queuing_strategy.rsnew file mode 100644index 00000000000..5d7f1a64e1d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/queuing_strategy.rs@@ -0,0 +1,46 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! QueuingStrategy, https://streams.spec.whatwg.org/#qs-api, and the abstract operations that read it,+//! https://streams.spec.whatwg.org/#qs-abstract-ops++use crate::bindings::callback::CallbackFunction;+use crate::bindings::{Exception, WebIdlResult};+use crate::streams::algorithms::SizeAlgorithm;++/// The dictionary QueuingStrategy of Streams/QueuingStrategy.idl, whose members the bindings convert.+pub(crate) struct QueuingStrategy {+ pub(crate) high_water_mark: Option<f64>,+ pub(crate) size: Option<CallbackFunction>,+}++// https://streams.spec.whatwg.org/#validate-and-normalize-high-water-mark+pub(crate) fn extract_high_water_mark(strategy: &QueuingStrategy, default_hwm: f64) -> WebIdlResult<f64> {+ // 1. If strategy["highWaterMark"] does not exist, return defaultHWM.+ // 2. Let highWaterMark be strategy["highWaterMark"].+ let Some(high_water_mark) = strategy.high_water_mark else {+ return Ok(default_hwm);+ };++ // 3. If highWaterMark is NaN or highWaterMark < 0, throw a RangeError exception.+ if high_water_mark.is_nan() || high_water_mark < 0.0 {+ return Err(Exception::range_error("Invalid value for high water mark"));+ }++ // 4. Return highWaterMark.+ Ok(high_water_mark)+}++// https://streams.spec.whatwg.org/#make-size-algorithm-from-size-function+pub(crate) fn extract_size_algorithm(strategy: &QueuingStrategy) -> SizeAlgorithm {+ match &strategy.size {+ // 1. If strategy["size"] does not exist, return an algorithm that returns 1.+ None => SizeAlgorithm::ReturnsOne,+ // 2. Return an algorithm that performs the following steps, taking a chunk argument:+ // 1. Return the result of invoking strategy["size"] with argument list « chunk ».+ Some(size) => SizeAlgorithm::Strategy(size.clone()),+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/read_request.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/read_request.rsnew file mode 100644index 00000000000..e73a6e4cca7--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/read_request.rs@@ -0,0 +1,151 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Read requests, https://streams.spec.whatwg.org/#read-request, and read-into requests,+//! https://streams.spec.whatwg.org/#read-into-request: one variant for each place that defines one, holding what its+//! steps refer to. The steps of a variant are next to the algorithm that defines them.++use libjs_rust::api::{EmbedderCell, Gc, Realm, Trace, Value, Vm, create_iterator_result_object};++use crate::bindings::interface::Ref;+use crate::bindings::promise::{WebIdlPromise, reject_promise, resolve_promise};+use crate::streams::cpp::CppReadRequest;+use crate::streams::readable_stream::async_iterator_read_request_steps;+use crate::streams::readable_stream_default_reader::{ReadLoop, ReadableStreamDefaultReader};+use crate::streams::readable_stream_pipe_to::PipeTo;+use crate::streams::readable_stream_tee::{ByteTeeBYOBReadRequest, ByteTeeState, DefaultTeeState};++/// A read request, https://streams.spec.whatwg.org/#read-request+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum ReadRequest {+ /// The read request of ReadableStreamDefaultReader's read(), https://streams.spec.whatwg.org/#default-reader-read+ DefaultReaderRead(WebIdlPromise),+ /// The read request of a read-loop, https://streams.spec.whatwg.org/#read-loop+ ReadLoop(Gc<EmbedderCell<ReadLoop>>),+ /// The read request of getting the next iteration result of a ReadableStream's asynchronous iterator,+ /// https://streams.spec.whatwg.org/#ref-for-dfn-get-the-next-iteration-result+ AsyncIterator {+ reader: Ref<ReadableStreamDefaultReader>,+ promise: WebIdlPromise,+ },+ /// The read request of ReadableStreamDefaultTee's pullAlgorithm.+ DefaultTee(Gc<EmbedderCell<DefaultTeeState>>),+ /// The read request of ReadableByteStreamTee's pullWithDefaultReader.+ ByteTee(Gc<EmbedderCell<ByteTeeState>>),+ /// The read request through which ReadableStreamPipeTo reads chunks from its source.+ PipeTo(Gc<EmbedderCell<PipeTo>>),+ /// A read request of LibWeb's C++ code.+ Cpp(CppReadRequest),+}++impl ReadRequest {+ // chunk steps, given chunk+ pub(crate) fn chunk_steps(&self, vm: &Vm, chunk: Value) {+ match self {+ Self::DefaultReaderRead(promise) => {+ // Resolve promise with «[ "value" → chunk, "done" → false ]».+ let result = create_iterator_result_object(vm, current_realm(vm), chunk, false);+ resolve_promise(vm, *promise, Value::from_object(result));+ }+ Self::ReadLoop(read_loop) => ReadLoop::chunk_steps(*read_loop, vm, chunk),+ Self::AsyncIterator { reader, promise } => {+ async_iterator_read_request_steps::chunk_steps(vm, *reader, *promise, chunk);+ }+ Self::DefaultTee(state) => DefaultTeeState::read_request_chunk_steps(*state, vm, chunk),+ Self::ByteTee(state) => ByteTeeState::default_read_request_chunk_steps(*state, vm, chunk),+ Self::PipeTo(pipe_to) => PipeTo::read_request_chunk_steps(*pipe_to, vm, chunk),+ Self::Cpp(read_request) => read_request.chunk_steps(chunk),+ }+ }++ // close steps+ pub(crate) fn close_steps(&self, vm: &Vm) {+ match self {+ Self::DefaultReaderRead(promise) => {+ // Resolve promise with «[ "value" → undefined, "done" → true ]».+ let result = create_iterator_result_object(vm, current_realm(vm), Value::UNDEFINED, true);+ resolve_promise(vm, *promise, Value::from_object(result));+ }+ Self::ReadLoop(read_loop) => read_loop.close_steps(),+ Self::AsyncIterator { reader, promise } => {+ async_iterator_read_request_steps::close_steps(vm, *reader, *promise);+ }+ Self::DefaultTee(state) => DefaultTeeState::read_request_close_steps(*state, vm),+ Self::ByteTee(state) => ByteTeeState::default_read_request_close_steps(*state, vm),+ Self::PipeTo(pipe_to) => PipeTo::read_request_close_steps(*pipe_to, vm),+ Self::Cpp(read_request) => read_request.close_steps(),+ }+ }++ // error steps, given e+ pub(crate) fn error_steps(&self, vm: &Vm, error: Value) {+ match self {+ // Reject promise with e.+ Self::DefaultReaderRead(promise) => reject_promise(vm, *promise, error),+ Self::ReadLoop(read_loop) => read_loop.error_steps(error),+ Self::AsyncIterator { reader, promise } => {+ async_iterator_read_request_steps::error_steps(vm, *reader, *promise, error);+ }+ Self::DefaultTee(state) => DefaultTeeState::read_request_error_steps(*state, vm, error),+ Self::ByteTee(state) => ByteTeeState::default_read_request_error_steps(*state, vm, error),+ Self::PipeTo(pipe_to) => PipeTo::read_request_error_steps(*pipe_to, vm, error),+ Self::Cpp(read_request) => read_request.error_steps(error),+ }+ }+}++/// A read-into request, https://streams.spec.whatwg.org/#read-into-request+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum ReadIntoRequest {+ /// The read-into request of ReadableStreamBYOBReader's read(), https://streams.spec.whatwg.org/#byob-reader-read+ BYOBReaderRead(WebIdlPromise),+ /// The read-into request of ReadableByteStreamTee's pullWithBYOBReader.+ ByteTee(Gc<EmbedderCell<ByteTeeBYOBReadRequest>>),+}++impl ReadIntoRequest {+ // chunk steps, given chunk+ pub(crate) fn chunk_steps(&self, vm: &Vm, chunk: Value) {+ match self {+ Self::BYOBReaderRead(promise) => {+ // 1. Resolve promise with «[ "value" → chunk, "done" → false ]».+ let result = create_iterator_result_object(vm, current_realm(vm), chunk, false);+ resolve_promise(vm, *promise, Value::from_object(result));+ }+ Self::ByteTee(read_into_request) => read_into_request.chunk_steps(vm, chunk),+ }+ }++ // close steps, given chunk+ pub(crate) fn close_steps(&self, vm: &Vm, chunk: Value) {+ match self {+ Self::BYOBReaderRead(promise) => {+ // 1. Resolve promise with «[ "value" → chunk, "done" → true ]».+ let result = create_iterator_result_object(vm, current_realm(vm), chunk, true);+ resolve_promise(vm, *promise, Value::from_object(result));+ }+ Self::ByteTee(read_into_request) => read_into_request.close_steps(vm, chunk),+ }+ }++ // error steps, given e+ pub(crate) fn error_steps(&self, vm: &Vm, error: Value) {+ match self {+ // 1. Reject promise with e.+ Self::BYOBReaderRead(promise) => reject_promise(vm, *promise, error),+ Self::ByteTee(read_into_request) => read_into_request.error_steps(vm, error),+ }+ }+}++/// The current realm, which resolving a promise with the read result converts the result in: the realm of the function+/// that ran the request's steps, as https://webidl.spec.whatwg.org/#js-dictionary creates the object with its own+/// %Object.prototype%.+fn current_realm(vm: &Vm) -> Gc<Realm> {+ vm.current_realm().expect("a read request runs in a realm")+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rsnew file mode 100644index 00000000000..abe58e55ed1--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_byte_stream_controller.rs@@ -0,0 +1,1985 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableByteStreamController, https://streams.spec.whatwg.org/#rbs-controller-class, and its abstract operations,+//! https://streams.spec.whatwg.org/#rbs-controller-abstract-ops++use std::collections::VecDeque;++use core::cell::Cell;++use libjs_rust::api::{+ ArrayBuffer, ArrayBufferShared, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, FunctionObject,+ Gc, GcRefCell, MarkedVec, Must, Throw, Trace, TypedArrayBase, Value, Vm, clone_array_buffer, construct,+};++use crate::bindings::conversions::{ArrayBufferView, BufferSource};+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{WebIdlPromise, create_resolved_promise, exception_value, react_to_promise};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::streams::abstract_operations::{+ can_copy_data_block_bytes_buffer, can_transfer_array_buffer, transfer_array_buffer,+};+use crate::streams::algorithms::{CancelAlgorithm, PullAlgorithm, StartAlgorithm};+use crate::streams::read_request::{ReadIntoRequest, ReadRequest};+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamReader, ReadableStreamState, complete_rendering_pending_stream,+ is_readable_stream_locked, readable_stream_add_read_into_request, readable_stream_add_read_request,+ readable_stream_close, readable_stream_error, readable_stream_fulfill_read_into_request,+ readable_stream_fulfill_read_request, readable_stream_get_num_read_into_requests,+ readable_stream_get_num_read_requests, readable_stream_has_byob_reader, readable_stream_has_default_reader,+};+use crate::streams::readable_stream_byob_request::ReadableStreamBYOBRequest;+use crate::streams::underlying_source::{ReadableStreamController, UnderlyingSource};++// https://streams.spec.whatwg.org/#pull-into-descriptor-reader-type+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ReaderType {+ Default,+ Byob,+ None,+}++/// A pull-into descriptor, https://streams.spec.whatwg.org/#pull-into-descriptor, which a controller's+/// [[pendingPullIntos]] and the steps that fill it share.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct PullIntoDescriptor {+ // https://streams.spec.whatwg.org/#pull-into-descriptor-buffer+ pub(crate) buffer: Cell<Gc<ArrayBuffer>>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-buffer-byte-length+ #[gc(untraced)]+ pub(crate) buffer_byte_length: Cell<u64>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-byte-offset+ #[gc(untraced)]+ pub(crate) byte_offset: Cell<u64>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-byte-length+ #[gc(untraced)]+ pub(crate) byte_length: Cell<u64>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-bytes-filled+ #[gc(untraced)]+ pub(crate) bytes_filled: Cell<u64>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-minimum-fill+ #[gc(untraced)]+ pub(crate) minimum_fill: Cell<u64>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-element-size+ #[gc(untraced)]+ pub(crate) element_size: Cell<u64>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-view-constructor+ pub(crate) view_constructor: Gc<FunctionObject>,+ // https://streams.spec.whatwg.org/#pull-into-descriptor-reader-type+ #[gc(untraced)]+ pub(crate) reader_type: Cell<ReaderType>,+}++static PULL_INTO_DESCRIPTOR_CLASS: EmbedderClass<PullIntoDescriptor> = EmbedderClass::new("PullIntoDescriptor");++impl EmbedderValue for PullIntoDescriptor {+ const CLASS: &'static EmbedderClass<Self> = &PULL_INTO_DESCRIPTOR_CLASS;+}++pub(crate) type PullIntoDescriptorRef = Gc<EmbedderCell<PullIntoDescriptor>>;++/// A readable byte stream queue entry, https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableByteStreamQueueEntry {+ // https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-buffer+ pub(crate) buffer: Gc<ArrayBuffer>,+ // https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-byte-offset+ #[gc(untraced)]+ pub(crate) byte_offset: u64,+ // https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-byte-length+ #[gc(untraced)]+ pub(crate) byte_length: u64,+}++// https://streams.spec.whatwg.org/#readablebytestreamcontroller+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableByteStreamController {+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-autoallocatechunksize+ #[gc(untraced)]+ auto_allocate_chunk_size: Cell<Option<u64>>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-byobrequest+ byob_request: Cell<Option<Ref<ReadableStreamBYOBRequest>>>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-cancelalgorithm+ cancel_algorithm: GcRefCell<Option<CancelAlgorithm>>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-closerequested+ close_requested: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-pullagain+ pull_again: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-pullalgorithm+ pull_algorithm: GcRefCell<Option<PullAlgorithm>>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-pulling+ pulling: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-pendingpullintos+ pending_pull_intos: GcRefCell<VecDeque<PullIntoDescriptorRef>>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-queue+ queue: GcRefCell<VecDeque<ReadableByteStreamQueueEntry>>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-queuetotalsize+ #[gc(untraced)]+ queue_total_size: Cell<f64>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-started+ started: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-strategyhwm+ #[gc(untraced)]+ strategy_hwm: Cell<f64>,+ // https://streams.spec.whatwg.org/#readablebytestreamcontroller-stream+ stream: Cell<Option<Ref<ReadableStream>>>,+}++impl Wrappable for ReadableByteStreamController {}++impl ReadableByteStreamController {+ pub(crate) fn new() -> Self {+ Self {+ auto_allocate_chunk_size: Cell::new(None),+ byob_request: Cell::new(None),+ cancel_algorithm: GcRefCell::new(None),+ close_requested: Cell::new(false),+ pull_again: Cell::new(false),+ pull_algorithm: GcRefCell::new(None),+ pulling: Cell::new(false),+ pending_pull_intos: GcRefCell::new(VecDeque::new()),+ queue: GcRefCell::new(VecDeque::new()),+ queue_total_size: Cell::new(0.0),+ started: Cell::new(false),+ strategy_hwm: Cell::new(0.0),+ stream: Cell::new(None),+ }+ }++ pub(crate) fn close_requested(&self) -> bool {+ self.close_requested.get()+ }++ /// The controller's [[stream]], which it has once it is set up.+ pub(crate) fn stream(&self) -> Ref<ReadableStream> {+ self.stream.get().expect("a controller that is set up has a stream")+ }++ pub(crate) fn pending_pull_intos_is_empty(&self) -> bool {+ self.pending_pull_intos.borrow().is_empty()+ }++ /// The controller's [[pendingPullIntos]][0], if [[pendingPullIntos]] is not empty.+ fn first_pending_pull_into(&self) -> Option<PullIntoDescriptorRef> {+ self.pending_pull_intos.borrow().front().copied()+ }++ // https://streams.spec.whatwg.org/#reset-queue+ fn reset_queue(&self) {+ // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.++ // 2. Set container.[[queue]] to a new empty list.+ self.queue.borrow_mut().clear();++ // 3. Set container.[[queueTotalSize]] to 0.+ self.queue_total_size.set(0.0);+ }++ // https://streams.spec.whatwg.org/#rbs-controller-byob-request+ pub(crate) fn byob_request(+ this: &Ref<Self>,+ cx: &mut CallContext,+ ) -> WebIdlResult<Option<Ref<ReadableStreamBYOBRequest>>> {+ // 1. Return ! ReadableByteStreamControllerGetBYOBRequest(this).+ Ok(readable_byte_stream_controller_get_byob_request(cx, *this))+ }++ // https://streams.spec.whatwg.org/#rbs-controller-desired-size+ pub(crate) fn desired_size(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<Option<f64>> {+ // 1. Return ! ReadableByteStreamControllerGetDesiredSize(this).+ Ok(readable_byte_stream_controller_get_desired_size(*this))+ }++ // https://streams.spec.whatwg.org/#rbs-controller-close+ pub(crate) fn close(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. If this.[[closeRequested]] is true, throw a TypeError exception.+ if this.close_requested() {+ return Err(Exception::type_error("Controller is already closed"));+ }++ // 2. If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.+ let stream = this.stream();+ if stream.state() != ReadableStreamState::Readable {+ let message = if stream.state() == ReadableStreamState::Closed {+ "Cannot close a closed stream"+ } else {+ "Cannot close an errored stream"+ };+ return Err(Exception::type_error(message));+ }++ // 3. Perform ? ReadableByteStreamControllerClose(this).+ readable_byte_stream_controller_close(cx, *this)+ }++ // https://streams.spec.whatwg.org/#rbs-controller-error+ pub(crate) fn error(this: &Ref<Self>, cx: &mut CallContext, e: Option<Value>) -> WebIdlResult<()> {+ // 1. Perform ! ReadableByteStreamControllerError(this, e).+ readable_byte_stream_controller_error(cx, *this, e.unwrap_or(Value::UNDEFINED));+ Ok(())+ }++ // https://streams.spec.whatwg.org/#rbs-controller-enqueue+ pub(crate) fn enqueue(this: &Ref<Self>, cx: &mut CallContext, chunk: ArrayBufferView) -> WebIdlResult<()> {+ let chunk_extent = BufferSource::from(chunk).extent();++ // 1. If chunk.[[ByteLength]] is 0, throw a TypeError exception.+ // 2. If chunk.[[ViewedArrayBuffer]].[[ByteLength]] is 0, throw a TypeError exception.+ if chunk_extent.byte_length == 0 || chunk_extent.buffer.byte_length() == 0 {+ return Err(Exception::type_error("Cannot enqueue chunk with byte length of zero"));+ }++ // 3. If this.[[closeRequested]] is true, throw a TypeError exception.+ if this.close_requested() {+ return Err(Exception::type_error("Close is requested for controller"));+ }++ // 4. If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.+ if !this.stream().is_readable() {+ return Err(Exception::type_error("Stream is not readable"));+ }++ // 5. Return ? ReadableByteStreamControllerEnqueue(this, chunk).+ readable_byte_stream_controller_enqueue(cx, *this, chunk)+ }++ // https://streams.spec.whatwg.org/#rbs-controller-private-cancel+ pub(crate) fn cancel_steps(this: Ref<Self>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Perform ! ReadableByteStreamControllerClearPendingPullIntos(this).+ readable_byte_stream_controller_clear_pending_pull_intos(this);++ // 2. Perform ! ResetQueue(this).+ this.reset_queue();++ // 3. Let result be the result of performing this.[[cancelAlgorithm]], passing in reason.+ let cancel_algorithm = this+ .cancel_algorithm+ .borrow()+ .clone()+ .expect("a controller that is canceled has a cancel algorithm");+ let result = cancel_algorithm.run(&this.stream().context(cx.vm()), reason);++ // 4. Perform ! ReadableByteStreamControllerClearAlgorithms(this).+ readable_byte_stream_controller_clear_algorithms(this);++ // 5. Return result.+ result+ }++ // https://streams.spec.whatwg.org/#rbs-controller-private-pull+ pub(crate) fn pull_steps(this: Ref<Self>, cx: &CallContext, read_request: ReadRequest) {+ let vm = cx.vm();++ // 1. Let stream be this.[[stream]].+ let stream = this.stream();++ // 2. Assert: ! ReadableStreamHasDefaultReader(stream) is true.+ assert!(readable_stream_has_default_reader(stream));++ // 3. If this.[[queueTotalSize]] > 0,+ if this.queue_total_size.get() > 0.0 {+ // 1. Assert: ! ReadableStreamGetNumReadRequests(stream) is 0.+ assert!(readable_stream_get_num_read_requests(stream) == 0);++ // 2. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest).+ readable_byte_stream_controller_fill_read_request_from_queue(cx, this, read_request);++ // 3. Return.+ return;+ }++ // 4. Let autoAllocateChunkSize be this.[[autoAllocateChunkSize]].+ let auto_allocate_chunk_size = this.auto_allocate_chunk_size.get();++ // 5. If autoAllocateChunkSize is not undefined,+ if let Some(auto_allocate_chunk_size) = auto_allocate_chunk_size {+ // 1. Let buffer be Construct(%ArrayBuffer%, « autoAllocateChunkSize »).+ let buffer = ArrayBuffer::create(vm, cx.realm(), auto_allocate_chunk_size as usize, ArrayBufferShared::No);++ // 2. If buffer is an abrupt completion,+ let buffer = match buffer {+ Ok(buffer) => buffer,+ Err(throw) => {+ // 1. Perform readRequest’s error steps, given buffer.[[Value]].+ read_request.error_steps(vm, throw.value());++ // 2. Return.+ return;+ }+ };++ // 3. Let pullIntoDescriptor be a new pull-into descriptor with+ //+ // buffer buffer.[[Value]]+ // buffer byte length autoAllocateChunkSize+ // byte offset 0+ // byte length autoAllocateChunkSize+ // bytes filled 0+ // minimum fill 1+ // element size 1+ // view constructor %Uint8Array%+ // reader type "default"+ let pull_into_descriptor = PULL_INTO_DESCRIPTOR_CLASS.allocate(+ vm,+ PullIntoDescriptor {+ buffer: Cell::new(buffer),+ buffer_byte_length: Cell::new(auto_allocate_chunk_size),+ byte_offset: Cell::new(0),+ byte_length: Cell::new(auto_allocate_chunk_size),+ bytes_filled: Cell::new(0),+ minimum_fill: Cell::new(1),+ element_size: Cell::new(1),+ view_constructor: cx.realm().intrinsics().uint8_array_constructor(vm),+ reader_type: Cell::new(ReaderType::Default),+ },+ );++ // 4. Append pullIntoDescriptor to this.[[pendingPullIntos]].+ this.pending_pull_intos.borrow_mut().push_back(pull_into_descriptor);+ }++ // 6. Perform ! ReadableStreamAddReadRequest(stream, readRequest).+ readable_stream_add_read_request(stream, read_request);++ // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(this).+ readable_byte_stream_controller_call_pull_if_needed(cx, this);+ }++ // https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontroller-releasesteps+ pub(crate) fn release_steps(this: Ref<Self>) {+ // 1. If this.[[pendingPullIntos]] is not empty,+ if let Some(first_pending_pull_into) = this.first_pending_pull_into() {+ // 1. Let firstPendingPullInto be this.[[pendingPullIntos]][0].++ // 2. Set firstPendingPullInto’s reader type to "none".+ first_pending_pull_into.reader_type.set(ReaderType::None);++ // 3. Set this.[[pendingPullIntos]] to the list « firstPendingPullInto ».+ let mut pending_pull_intos = this.pending_pull_intos.borrow_mut();+ pending_pull_intos.clear();+ pending_pull_intos.push_back(first_pending_pull_into);+ }+ }+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed+pub(crate) fn readable_byte_stream_controller_call_pull_if_needed(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+) {+ // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).+ let should_pull = readable_byte_stream_controller_should_call_pull(controller);++ // 2. If shouldPull is false, return.+ if !should_pull {+ return;+ }++ // 3. If controller.[[pulling]] is true,+ if controller.pulling.get() {+ // 1. Set controller.[[pullAgain]] to true.+ controller.pull_again.set(true);++ // 2. Return.+ return;+ }++ // 4. Assert: controller.[[pullAgain]] is false.+ assert!(!controller.pull_again.get());++ // 5. Set controller.[[pulling]] to true.+ controller.pulling.set(true);++ // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].+ let pull_algorithm = controller+ .pull_algorithm+ .borrow()+ .clone()+ .expect("a controller that should pull has a pull algorithm");+ let pull_promise = pull_algorithm.run(&controller.stream().context(cx.vm()));++ react_to_promise(+ cx.vm(),+ pull_promise,+ controller,+ // 7. Upon fulfillment of pullPromise,+ Some(|cx, controller, _| {+ // 1. Set controller.[[pulling]] to false.+ controller.pulling.set(false);++ // 2. If controller.[[pullAgain]] is true,+ if controller.pull_again.get() {+ // 1. Set controller.[[pullAgain]] to false.+ controller.pull_again.set(false);++ // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).+ readable_byte_stream_controller_call_pull_if_needed(cx, controller);+ }++ Ok(Value::UNDEFINED)+ }),+ // 8. Upon rejection of pullPromise with reason e,+ Some(|cx, controller, error| {+ // 1. Perform ! ReadableByteStreamControllerError(controller, e).+ readable_byte_stream_controller_error(cx, controller, error);++ Ok(Value::UNDEFINED)+ }),+ );+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms+pub(crate) fn readable_byte_stream_controller_clear_algorithms(controller: Ref<ReadableByteStreamController>) {+ // 1. Set controller.[[pullAlgorithm]] to undefined.+ *controller.pull_algorithm.borrow_mut() = None;++ // 2. Set controller.[[cancelAlgorithm]] to undefined.+ *controller.cancel_algorithm.borrow_mut() = None;+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos+pub(crate) fn readable_byte_stream_controller_clear_pending_pull_intos(controller: Ref<ReadableByteStreamController>) {+ // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).+ readable_byte_stream_controller_invalidate_byob_request(controller);++ // 2. Set controller.[[pendingPullIntos]] to a new empty list.+ controller.pending_pull_intos.borrow_mut().clear();+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-close+pub(crate) fn readable_byte_stream_controller_close(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+) -> WebIdlResult<()> {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.+ if controller.close_requested() || stream.state() != ReadableStreamState::Readable {+ return Ok(());+ }++ complete_rendering_pending_stream(stream);++ // 3. If controller.[[queueTotalSize]] > 0,+ if controller.queue_total_size.get() > 0.0 {+ // 1. Set controller.[[closeRequested]] to true.+ controller.close_requested.set(true);++ // 2. Return.+ return Ok(());+ }++ // 4. If controller.[[pendingPullIntos]] is not empty,+ if let Some(first_pending_pull_into) = controller.first_pending_pull_into() {+ // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].++ // 2. If the remainder after dividing firstPendingPullInto’s bytes filled by firstPendingPullInto’s element size+ // is not 0,+ if first_pending_pull_into.bytes_filled.get() % first_pending_pull_into.element_size.get() != 0 {+ // 1. Let e be a new TypeError exception.+ let error = exception_value(+ cx.vm(),+ cx.realm(),+ Exception::type_error("Cannot close controller in the middle of processing a write request"),+ );++ // 2. Perform ! ReadableByteStreamControllerError(controller, e).+ readable_byte_stream_controller_error(cx, controller, error);++ // 3. Throw e.+ return Err(Exception::Thrown(Throw::new(error)));+ }+ }++ // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).+ readable_byte_stream_controller_clear_algorithms(controller);++ // 6. Perform ! ReadableStreamClose(stream).+ readable_stream_close(cx.vm(), stream);+ Ok(())+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor+pub(crate) fn readable_byte_stream_controller_commit_pull_into_descriptor(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ pull_into_descriptor: PullIntoDescriptorRef,+) {+ // 1. Assert: stream.[[state]] is not "errored".+ assert!(stream.state() != ReadableStreamState::Errored);++ // 2. Assert: pullIntoDescriptor.reader type is not "none".+ assert!(pull_into_descriptor.reader_type.get() != ReaderType::None);++ // 3. Let done be false.+ let mut done = false;++ // 4. If stream.[[state]] is "closed",+ if stream.state() == ReadableStreamState::Closed {+ // 1. Assert: the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element+ // size is 0.+ assert!(+ pull_into_descriptor+ .bytes_filled+ .get()+ .is_multiple_of(pull_into_descriptor.element_size.get())+ );++ // 2. Set done to true.+ done = true;+ }++ // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).+ let filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(cx, pull_into_descriptor);++ // 6. If pullIntoDescriptor’s reader type is "default",+ if pull_into_descriptor.reader_type.get() == ReaderType::Default {+ // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).+ readable_stream_fulfill_read_request(cx.vm(), stream, filled_view, done);+ }+ // 7. Otherwise,+ else {+ // 1. Assert: pullIntoDescriptor’s reader type is "byob".+ assert!(pull_into_descriptor.reader_type.get() == ReaderType::Byob);++ // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).+ readable_stream_fulfill_read_into_request(cx.vm(), stream, filled_view, done);+ }+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor+pub(crate) fn readable_byte_stream_controller_convert_pull_into_descriptor(+ cx: &CallContext,+ pull_into_descriptor: PullIntoDescriptorRef,+) -> Value {+ let vm = cx.vm();++ // 1. Let bytesFilled be pullIntoDescriptor’s bytes filled.+ let bytes_filled = pull_into_descriptor.bytes_filled.get();++ // 2. Let elementSize be pullIntoDescriptor’s element size.+ let element_size = pull_into_descriptor.element_size.get();++ // 3. Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.+ assert!(bytes_filled <= pull_into_descriptor.byte_length.get());++ // 4. Assert: the remainder after dividing bytesFilled by elementSize is 0.+ assert!(bytes_filled.is_multiple_of(element_size));++ // 5. Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).+ let buffer = transfer_array_buffer(cx, pull_into_descriptor.buffer.get()).must();++ // 6. Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset,+ // bytesFilled ÷ elementSize »).+ let view = construct(+ vm,+ pull_into_descriptor.view_constructor,+ &[+ Value::from_object(buffer),+ Value::from_f64(pull_into_descriptor.byte_offset.get() as f64),+ Value::from_f64((bytes_filled / element_size) as f64),+ ],+ None,+ )+ .must();+ Value::from_object(view)+}++fn readable_byte_stream_controller_enqueue_transferred_buffer(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ transferred_buffer: Gc<ArrayBuffer>,+ byte_offset: u64,+ byte_length: u64,+) -> WebIdlResult<()> {+ let vm = cx.vm();+ let stream = controller.stream();++ // 8. If controller.[[pendingPullIntos]] is not empty,+ if let Some(first_pending_pull_into) = controller.first_pending_pull_into() {+ // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].++ // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.+ if first_pending_pull_into.buffer.get().is_detached() {+ return Err(Exception::type_error("Buffer is detached"));+ }++ // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).+ readable_byte_stream_controller_invalidate_byob_request(controller);++ // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).+ first_pending_pull_into+ .buffer+ .set(transfer_array_buffer(cx, first_pending_pull_into.buffer.get()).must());++ // 5. If firstPendingPullInto’s reader type is "none", perform+ // ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).+ if first_pending_pull_into.reader_type.get() == ReaderType::None {+ readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(+ cx,+ controller,+ first_pending_pull_into,+ )?;+ }+ }++ // 9. If ! ReadableStreamHasDefaultReader(stream) is true,+ if readable_stream_has_default_reader(stream) {+ // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).+ readable_byte_stream_controller_process_read_requests_using_queue(cx, controller);++ // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,+ if readable_stream_get_num_read_requests(stream) == 0 {+ // 1. Assert: controller.[[pendingPullIntos]] is empty.+ assert!(controller.pending_pull_intos_is_empty());++ // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset,+ // byteLength).+ readable_byte_stream_controller_enqueue_chunk_to_queue(+ controller,+ transferred_buffer,+ byte_offset,+ byte_length,+ );+ }+ // 3. Otherwise,+ else {+ // 1. Assert: controller.[[queue]] is empty.+ assert!(controller.queue.borrow().is_empty());++ // 2. If controller.[[pendingPullIntos]] is not empty,+ if let Some(first_pending_pull_into) = controller.first_pending_pull_into() {+ // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".+ assert!(first_pending_pull_into.reader_type.get() == ReaderType::Default);++ // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).+ readable_byte_stream_controller_shift_pending_pull_into(controller);+ }++ // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).+ let transferred_view = construct(+ vm,+ cx.realm().intrinsics().uint8_array_constructor(vm),+ &[+ Value::from_object(transferred_buffer),+ Value::from_f64(byte_offset as f64),+ Value::from_f64(byte_length as f64),+ ],+ None,+ )+ .must();++ // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).+ readable_stream_fulfill_read_request(vm, stream, Value::from_object(transferred_view), false);+ }+ }+ // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,+ else if readable_stream_has_byob_reader(stream) {+ // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset,+ // byteLength).+ readable_byte_stream_controller_enqueue_chunk_to_queue(+ controller,+ transferred_buffer,+ byte_offset,+ byte_length,+ );++ // 2. Let filledPullIntos be the result of performing+ // ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).+ let filled_pull_intos =+ readable_byte_stream_controller_process_pull_into_descriptors_using_queue(vm, controller);++ // 3. For each filledPullInto of filledPullIntos,+ for index in 0..filled_pull_intos.len() {+ // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, filledPullInto).+ let filled_pull_into = filled_pull_intos.get(index).expect("the index is in bounds");+ readable_byte_stream_controller_commit_pull_into_descriptor(cx, stream, filled_pull_into);+ }+ }+ // 11. Otherwise,+ else {+ // 1. Assert: ! IsReadableStreamLocked(stream) is false.+ assert!(!is_readable_stream_locked(stream));++ // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset,+ // byteLength).+ readable_byte_stream_controller_enqueue_chunk_to_queue(+ controller,+ transferred_buffer,+ byte_offset,+ byte_length,+ );+ }++ // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).+ readable_byte_stream_controller_call_pull_if_needed(cx, controller);+ Ok(())+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue+pub(crate) fn readable_byte_stream_controller_enqueue(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ chunk: ArrayBufferView,+) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.+ if controller.close_requested() || stream.state() != ReadableStreamState::Readable {+ return Ok(());+ }++ // 3. Let buffer be chunk.[[ViewedArrayBuffer]].+ // 4. Let byteOffset be chunk.[[ByteOffset]].+ let chunk_extent = BufferSource::from(chunk).extent();+ let buffer = chunk_extent.buffer;+ let byte_offset = chunk_extent.byte_offset as u64;++ // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.+ // FIXME: The streams spec has not been updated for resizable ArrayBuffer objects. We must perform step 6 before+ // invoking TypedArrayByteLength in step 5. We also must check if the array is out-of-bounds, rather than+ // just detached.+ if chunk_extent.is_out_of_bounds {+ let name = match chunk {+ ArrayBufferView::TypedArray(_) => "TypedArray",+ ArrayBufferView::DataView(_) => "DataView",+ };+ return Ok(vm.throw_completion(ErrorKind::TypeError, ErrorType::BufferOutOfBounds, &[&name])?);+ }++ // 5. Let byteLength be chunk.[[ByteLength]].+ let byte_length = chunk_extent.byte_length as u64;++ // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).+ let transferred_buffer = transfer_array_buffer(cx, buffer)?;++ readable_byte_stream_controller_enqueue_transferred_buffer(+ cx,+ controller,+ transferred_buffer,+ byte_offset,+ byte_length,+ )+}++/// ReadableByteStreamControllerEnqueue with a chunk of the bytes, for C++ that enqueues bytes it received,+/// https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue+pub(crate) fn readable_byte_stream_controller_enqueue_native_bytes(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ bytes: &[u8],+) -> WebIdlResult<()> {+ let stream = controller.stream();+ if controller.close_requested() || stream.state() != ReadableStreamState::Readable {+ return Ok(());+ }++ let byte_length = bytes.len() as u64;++ // OPTIMIZATION: Native byte producers have no observable chunk object to detach, so enter the enqueue algorithm+ // after the TransferArrayBuffer step with an already-owned ArrayBuffer.+ let transferred_buffer = ArrayBuffer::create_from_bytes(cx.vm(), cx.realm(), bytes, ArrayBufferShared::No);+ readable_byte_stream_controller_enqueue_transferred_buffer(cx, controller, transferred_buffer, 0, byte_length)+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue+pub(crate) fn readable_byte_stream_controller_enqueue_chunk_to_queue(+ controller: Ref<ReadableByteStreamController>,+ buffer: Gc<ArrayBuffer>,+ byte_offset: u64,+ byte_length: u64,+) {+ // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length+ // byteLength to controller.[[queue]].+ controller.queue.borrow_mut().push_back(ReadableByteStreamQueueEntry {+ buffer,+ byte_offset,+ byte_length,+ });++ // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.+ controller+ .queue_total_size+ .set(controller.queue_total_size.get() + byte_length as f64);+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue+pub(crate) fn readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ buffer: Gc<ArrayBuffer>,+ byte_offset: u64,+ byte_length: u64,+) -> WebIdlResult<()> {+ // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).+ let clone_result = clone_array_buffer(cx.vm(), buffer, byte_offset as usize, byte_length as usize);++ // 2. If cloneResult is an abrupt completion,+ let clone_result = match clone_result {+ Ok(clone_result) => clone_result,+ Err(throw_completion) => {+ // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).+ readable_byte_stream_controller_error(cx, controller, throw_completion.value());++ // 2. Return cloneResult.+ return Err(throw_completion.into());+ }+ };++ // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).+ readable_byte_stream_controller_enqueue_chunk_to_queue(controller, clone_result, 0, byte_length);+ Ok(())+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue+pub(crate) fn readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ pull_into_descriptor: PullIntoDescriptorRef,+) -> WebIdlResult<()> {+ // 1. Assert: pullIntoDescriptor’s reader type is "none".+ assert!(pull_into_descriptor.reader_type.get() == ReaderType::None);++ // 2. If pullIntoDescriptor’s bytes filled > 0, perform+ // ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer,+ // pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).+ if pull_into_descriptor.bytes_filled.get() > 0 {+ readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(+ cx,+ controller,+ pull_into_descriptor.buffer.get(),+ pull_into_descriptor.byte_offset.get(),+ pull_into_descriptor.bytes_filled.get(),+ )?;+ }++ // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).+ readable_byte_stream_controller_shift_pending_pull_into(controller);+ Ok(())+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-error+pub(crate) fn readable_byte_stream_controller_error(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ error: Value,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If stream.[[state]] is not "readable", return.+ if stream.state() != ReadableStreamState::Readable {+ return;+ }++ // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).+ readable_byte_stream_controller_clear_pending_pull_intos(controller);++ // 4. Perform ! ResetQueue(controller).+ controller.reset_queue();++ // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).+ readable_byte_stream_controller_clear_algorithms(controller);++ // 6. Perform ! ReadableStreamError(stream, e).+ readable_stream_error(cx.vm(), stream, error);+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-head-pull-into-descriptor+pub(crate) fn readable_byte_stream_controller_fill_head_pull_into_descriptor(+ controller: Ref<ReadableByteStreamController>,+ size: u64,+ pull_into_descriptor: PullIntoDescriptorRef,+) {+ // 1. Assert: either controller.[[pendingPullIntos]] is empty, or controller.[[pendingPullIntos]][0] is+ // pullIntoDescriptor.+ assert!(+ controller+ .first_pending_pull_into()+ .is_none_or(|first_pending_pull_into| first_pending_pull_into == pull_into_descriptor)+ );++ // 2. Assert: controller.[[byobRequest]] is null.+ assert!(controller.byob_request.get().is_none());++ // 3. Set pullIntoDescriptor’s bytes filled to bytes filled + size.+ pull_into_descriptor+ .bytes_filled+ .set(pull_into_descriptor.bytes_filled.get() + size);+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-pull-into-descriptor-from-queue+pub(crate) fn readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(+ controller: Ref<ReadableByteStreamController>,+ pull_into_descriptor: PullIntoDescriptorRef,+) -> bool {+ // 1. Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length −+ // pullIntoDescriptor’s bytes filled).+ let max_bytes_to_copy = (controller.queue_total_size.get() as u64)+ .min(pull_into_descriptor.byte_length.get() - pull_into_descriptor.bytes_filled.get());++ // 2. Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.+ let max_bytes_filled = pull_into_descriptor.bytes_filled.get() + max_bytes_to_copy;++ // 3. Let totalBytesToCopyRemaining be maxBytesToCopy.+ let mut total_bytes_to_copy_remaining = max_bytes_to_copy;++ // 4. Let ready be false.+ let mut ready = false;++ // 5. Assert: ! IsDetachedBuffer(pullIntoDescriptor’s buffer) is false.+ assert!(!pull_into_descriptor.buffer.get().is_detached());++ // 6. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill.+ assert!(pull_into_descriptor.bytes_filled.get() < pull_into_descriptor.minimum_fill.get());++ // 7. Let remainderBytes be the remainder after dividing maxBytesFilled by pullIntoDescriptor’s element size.+ let remainder_bytes = max_bytes_filled % pull_into_descriptor.element_size.get();++ // 8. Let maxAlignedBytes be maxBytesFilled − remainderBytes.+ let max_aligned_bytes = max_bytes_filled - remainder_bytes;++ // 9. If maxAlignedBytes ≥ pullIntoDescriptor’s minimum fill,+ if max_aligned_bytes >= pull_into_descriptor.minimum_fill.get() {+ // 1. Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.+ total_bytes_to_copy_remaining = max_aligned_bytes - pull_into_descriptor.bytes_filled.get();++ // 2. Set ready to true.+ ready = true;++ // NOTE: A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head+ // of the queue, so the underlying source can keep filling it.+ }++ // 10. Let queue be controller.[[queue]].+ let queue = &controller.queue;++ // 11. While totalBytesToCopyRemaining > 0,+ while total_bytes_to_copy_remaining > 0 {+ // 1. Let headOfQueue be queue[0].+ let head_of_queue = queue+ .borrow()+ .front()+ .cloned()+ .expect("the queue holds the bytes to copy");++ // 2. Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).+ let bytes_to_copy = total_bytes_to_copy_remaining.min(head_of_queue.byte_length);++ // 3. Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.+ let dest_start = pull_into_descriptor.byte_offset.get() + pull_into_descriptor.bytes_filled.get();++ // 4. Let descriptorBuffer be pullIntoDescriptor’s buffer.+ let descriptor_buffer = pull_into_descriptor.buffer.get();++ // 5. Let queueBuffer be headOfQueue’s buffer.+ let queue_buffer = head_of_queue.buffer;++ // 6. Let queueByteOffset be headOfQueue’s byte offset.+ let queue_byte_offset = head_of_queue.byte_offset;++ // 7. Assert: ! CanCopyDataBlockBytes(descriptorBuffer, destStart, queueBuffer, queueByteOffset, bytesToCopy) is+ // true.+ assert!(can_copy_data_block_bytes_buffer(+ descriptor_buffer,+ dest_start,+ queue_buffer,+ queue_byte_offset,+ bytes_to_copy+ ));++ // 8. Perform ! CopyDataBlockBytes(descriptorBuffer.[[ArrayBufferData]], destStart,+ // queueBuffer.[[ArrayBufferData]], queueByteOffset, bytesToCopy).+ head_of_queue.buffer.copy_data_to(+ &descriptor_buffer,+ head_of_queue.byte_offset as usize,+ dest_start as usize,+ bytes_to_copy as usize,+ );++ {+ let mut queue = queue.borrow_mut();++ // 9. If headOfQueue’s byte length is bytesToCopy,+ if head_of_queue.byte_length == bytes_to_copy {+ // 1. Remove queue[0].+ queue.pop_front();+ }+ // 10. Otherwise,+ else {+ let head_of_queue = queue.front_mut().expect("the queue holds the bytes to copy");++ // 1. Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.+ head_of_queue.byte_offset += bytes_to_copy;++ // 2. Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.+ head_of_queue.byte_length -= bytes_to_copy;+ }+ }++ // 11. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.+ controller+ .queue_total_size+ .set(controller.queue_total_size.get() - bytes_to_copy as f64);++ // 12. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy,+ // pullIntoDescriptor).+ readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_to_copy, pull_into_descriptor);++ // 13. Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.+ total_bytes_to_copy_remaining -= bytes_to_copy;+ }++ // 12. If ready is false,+ if !ready {+ // 1. Assert: controller.[[queueTotalSize]] is 0.+ assert!(controller.queue_total_size.get() == 0.0);++ // 2. Assert: pullIntoDescriptor’s bytes filled > 0.+ assert!(pull_into_descriptor.bytes_filled.get() > 0);++ // 3. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill.+ assert!(pull_into_descriptor.bytes_filled.get() < pull_into_descriptor.minimum_fill.get());+ }++ // 13. Return ready.+ ready+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue+pub(crate) fn readable_byte_stream_controller_fill_read_request_from_queue(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ read_request: ReadRequest,+) {+ let vm = cx.vm();++ // 1. Assert: controller.[[queueTotalSize]] > 0.+ assert!(controller.queue_total_size.get() > 0.0);++ // 2. Let entry be controller.[[queue]][0].+ // 3. Remove entry from controller.[[queue]].+ let entry = controller+ .queue+ .borrow_mut()+ .pop_front()+ .expect("a controller with bytes in its queue has a queue entry");++ // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.+ controller+ .queue_total_size+ .set(controller.queue_total_size.get() - entry.byte_length as f64);++ // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).+ readable_byte_stream_controller_handle_queue_drain(cx, controller);++ // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).+ let view = construct(+ vm,+ cx.realm().intrinsics().uint8_array_constructor(vm),+ &[+ Value::from_object(entry.buffer),+ Value::from_f64(entry.byte_offset as f64),+ Value::from_f64(entry.byte_length as f64),+ ],+ None,+ )+ .must();++ // 7. Perform readRequest’s chunk steps, given view.+ read_request.chunk_steps(vm, Value::from_object(view));+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollergetbyobrequest+pub(crate) fn readable_byte_stream_controller_get_byob_request(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+) -> Option<Ref<ReadableStreamBYOBRequest>> {+ let vm = cx.vm();++ // 1. If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,+ if controller.byob_request.get().is_none()+ && let Some(first_descriptor) = controller.first_pending_pull_into()+ {+ // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].++ // 2. Let view be ! Construct(%Uint8Array%, « firstDescriptor’s buffer, firstDescriptor’s byte offset ++ // firstDescriptor’s bytes filled, firstDescriptor’s byte length − firstDescriptor’s bytes filled »).+ let view_object = construct(+ vm,+ cx.realm().intrinsics().uint8_array_constructor(vm),+ &[+ Value::from_object(first_descriptor.buffer.get()),+ Value::from_f64((first_descriptor.byte_offset.get() + first_descriptor.bytes_filled.get()) as f64),+ Value::from_f64((first_descriptor.byte_length.get() - first_descriptor.bytes_filled.get()) as f64),+ ],+ None,+ )+ .must();+ let view = view_object+ .downcast::<TypedArrayBase>()+ .expect("a Uint8Array is a typed array");++ // 3. Let byobRequest be a new ReadableStreamBYOBRequest.+ let byob_request = allocate(vm, ReadableStreamBYOBRequest::new());++ // 4. Set byobRequest.[[controller]] to controller.+ byob_request.set_controller(Some(controller));++ // 5. Set byobRequest.[[view]] to view.+ byob_request.set_view(Some(view));++ // 6. Set controller.[[byobRequest]] to byobRequest.+ controller.byob_request.set(Some(byob_request));+ }++ // 2. Return controller.[[byobRequest]].+ controller.byob_request.get()+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size+pub(crate) fn readable_byte_stream_controller_get_desired_size(+ controller: Ref<ReadableByteStreamController>,+) -> Option<f64> {+ // 1. Let state be controller.[[stream]].[[state]].+ let state = controller.stream().state();++ // 2. If state is "errored", return null.+ if state == ReadableStreamState::Errored {+ return None;+ }++ // 3. If state is "closed", return 0.+ if state == ReadableStreamState::Closed {+ return Some(0.0);+ }++ // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].+ Some(controller.strategy_hwm.get() - controller.queue_total_size.get())+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain+pub(crate) fn readable_byte_stream_controller_handle_queue_drain(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+) {+ let stream = controller.stream();++ // 1. Assert: controller.[[stream]].[[state]] is "readable".+ assert!(stream.state() == ReadableStreamState::Readable);++ // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,+ if controller.queue_total_size.get() == 0.0 && controller.close_requested() {+ // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).+ readable_byte_stream_controller_clear_algorithms(controller);++ // 2. Perform ! ReadableStreamClose(controller.[[stream]]).+ readable_stream_close(cx.vm(), stream);+ }+ // 3. Otherwise,+ else {+ // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).+ readable_byte_stream_controller_call_pull_if_needed(cx, controller);+ }+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request+pub(crate) fn readable_byte_stream_controller_invalidate_byob_request(controller: Ref<ReadableByteStreamController>) {+ // 1. If controller.[[byobRequest]] is null, return.+ let Some(byob_request) = controller.byob_request.get() else {+ return;+ };++ // 2. Set controller.[[byobRequest]].[[controller]] to undefined.+ byob_request.set_controller(None);++ // 3. Set controller.[[byobRequest]].[[view]] to null.+ byob_request.set_view(None);++ // 4. Set controller.[[byobRequest]] to null.+ controller.byob_request.set(None);+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue+pub(crate) fn readable_byte_stream_controller_process_pull_into_descriptors_using_queue(+ vm: &Vm,+ controller: Ref<ReadableByteStreamController>,+) -> MarkedVec<'_, PullIntoDescriptorRef> {+ // 1. Assert: controller.[[closeRequested]] is false.+ assert!(!controller.close_requested());++ // 2. Let filledPullIntos be a new empty list.+ let filled_pull_intos = MarkedVec::new(vm);++ // 3. While controller.[[pendingPullIntos]] is not empty,+ while let Some(pull_into_descriptor) = controller.first_pending_pull_into() {+ // 1. If controller.[[queueTotalSize]] is 0, then break.+ if controller.queue_total_size.get() == 0.0 {+ break;+ }++ // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].++ // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,+ if readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor) {+ // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).+ readable_byte_stream_controller_shift_pending_pull_into(controller);++ // 2. Append pullIntoDescriptor to filledPullIntos.+ filled_pull_intos.push(pull_into_descriptor);+ }+ }++ // 4. Return filledPullIntos.+ filled_pull_intos+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue+pub(crate) fn readable_byte_stream_controller_process_read_requests_using_queue(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+) {+ // 1. Let reader be controller.[[stream]].[[reader]].+ // 2. Assert: reader implements ReadableStreamDefaultReader.+ let Some(ReadableStreamReader::ReadableStreamDefaultReader(reader)) = controller.stream().reader() else {+ panic!("the stream has a ReadableStreamDefaultReader");+ };++ // 3. While reader.[[readRequests]] is not empty,+ while !reader.read_requests_is_empty() {+ // 1. If controller.[[queueTotalSize]] is 0, return.+ if controller.queue_total_size.get() == 0.0 {+ return;+ }++ // 2. Let readRequest be reader.[[readRequests]][0].+ // 3. Remove readRequest from reader.[[readRequests]].+ let read_request = reader.take_first_read_request();++ // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).+ readable_byte_stream_controller_fill_read_request_from_queue(cx, controller, read_request);+ }+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into+pub(crate) fn readable_byte_stream_controller_pull_into(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ view: ArrayBufferView,+ min: u64,+ read_into_request: ReadIntoRequest,+) {+ let vm = cx.vm();++ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. Let elementSize be 1.+ let mut element_size = 1;++ // 3. Let ctor be %DataView%.+ let mut ctor = cx.realm().intrinsics().data_view_constructor(vm);++ // 4. If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),+ if let ArrayBufferView::TypedArray(typed_array) = view {+ // 1. Set elementSize to the element size specified in the typed array constructors table for+ // view.[[TypedArrayName]].+ element_size = u64::from(typed_array.element_size());++ // 2. Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].+ ctor = typed_array.intrinsic_constructor(vm, cx.realm());+ }++ let view_extent = BufferSource::from(view).extent();++ // 5. Let minimumFill be min × elementSize.+ let minimum_fill = min * element_size;++ // 6. Assert: minimumFill ≥ 0 and minimumFill ≤ view.[[ByteLength]].+ assert!(minimum_fill <= view_extent.byte_length as u64);++ // 7. Assert: the remainder after dividing minimumFill by elementSize is 0.+ assert!(minimum_fill.is_multiple_of(element_size));++ // 8. Let byteOffset be view.[[ByteOffset]].+ let byte_offset = view_extent.byte_offset as u64;++ // 9. Let byteLength be view.[[ByteLength]].+ let byte_length = view_extent.byte_length as u64;++ // 10. Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).+ let buffer_result = transfer_array_buffer(cx, view_extent.buffer);++ // 11. If bufferResult is an abrupt completion,+ let buffer = match buffer_result {+ Err(exception) => {+ // 1. Perform readIntoRequest’s error steps, given bufferResult.[[Value]].+ read_into_request.error_steps(vm, exception_value(vm, cx.realm(), exception));++ // 2. Return.+ return;+ }+ // 12. Let buffer be bufferResult.[[Value]].+ Ok(buffer) => buffer,+ };++ // 13. Let pullIntoDescriptor be a new pull-into descriptor with+ //+ // buffer buffer+ // buffer byte length buffer.[[ArrayBufferByteLength]]+ // byte offset byteOffset+ // byte length byteLength+ // bytes filled 0+ // minimum fill minimumFill+ // element size elementSize+ // view constructor ctor+ // reader type "byob"+ let pull_into_descriptor = PULL_INTO_DESCRIPTOR_CLASS.allocate(+ vm,+ PullIntoDescriptor {+ buffer: Cell::new(buffer),+ buffer_byte_length: Cell::new(buffer.byte_length() as u64),+ byte_offset: Cell::new(byte_offset),+ byte_length: Cell::new(byte_length),+ bytes_filled: Cell::new(0),+ minimum_fill: Cell::new(minimum_fill),+ element_size: Cell::new(element_size),+ view_constructor: ctor,+ reader_type: Cell::new(ReaderType::Byob),+ },+ );++ // 14. If controller.[[pendingPullIntos]] is not empty,+ if !controller.pending_pull_intos_is_empty() {+ // 1. Append pullIntoDescriptor to controller.[[pendingPullIntos]].+ controller+ .pending_pull_intos+ .borrow_mut()+ .push_back(pull_into_descriptor);++ // 2. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).+ readable_stream_add_read_into_request(stream, read_into_request);++ // 3. Return.+ return;+ }++ // 15. If stream.[[state]] is "closed",+ if stream.state() == ReadableStreamState::Closed {+ // 1. Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).+ let empty_view = construct(+ vm,+ ctor,+ &[+ Value::from_object(pull_into_descriptor.buffer.get()),+ Value::from_f64(pull_into_descriptor.byte_offset.get() as f64),+ Value::from_i32(0),+ ],+ None,+ )+ .must();++ // 2. Perform readIntoRequest’s close steps, given emptyView.+ read_into_request.close_steps(vm, Value::from_object(empty_view));++ // 3. Return.+ return;+ }++ // 16. If controller.[[queueTotalSize]] > 0,+ if controller.queue_total_size.get() > 0.0 {+ // 1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,+ if readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor) {+ // 1. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).+ let filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(cx, pull_into_descriptor);++ // 2. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).+ readable_byte_stream_controller_handle_queue_drain(cx, controller);++ // 3. Perform readIntoRequest’s chunk steps, given filledView.+ read_into_request.chunk_steps(vm, filled_view);++ // 4. Return.+ return;+ }++ // 2. If controller.[[closeRequested]] is true,+ if controller.close_requested() {+ // 1. Let e be a TypeError exception.+ let error = exception_value(vm, cx.realm(), Exception::type_error("Reader has been released"));++ // 2. Perform ! ReadableByteStreamControllerError(controller, e).+ readable_byte_stream_controller_error(cx, controller, error);++ // 3. Perform readIntoRequest’s error steps, given e.+ read_into_request.error_steps(vm, error);++ // 4. Return.+ return;+ }+ }++ // 17. Append pullIntoDescriptor to controller.[[pendingPullIntos]].+ controller+ .pending_pull_intos+ .borrow_mut()+ .push_back(pull_into_descriptor);++ // 18. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).+ readable_stream_add_read_into_request(stream, read_into_request);++ // 19. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).+ readable_byte_stream_controller_call_pull_if_needed(cx, controller);+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond+pub(crate) fn readable_byte_stream_controller_respond(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ bytes_written: u64,+) -> WebIdlResult<()> {+ // 1. Assert: controller.[[pendingPullIntos]] is not empty.+ // 2. Let firstDescriptor be controller.[[pendingPullIntos]][0].+ let first_descriptor = controller+ .first_pending_pull_into()+ .expect("a controller that is responded to has a pending pull-into");++ // 3. Let state be controller.[[stream]].[[state]].+ let state = controller.stream().state();++ // 4. If state is "closed",+ if state == ReadableStreamState::Closed {+ // 1. If bytesWritten is not 0, throw a TypeError exception.+ if bytes_written != 0 {+ return Err(Exception::type_error("Bytes written is not zero for closed stream"));+ }+ }+ // 5. Otherwise,+ else {+ // 1. Assert: state is "readable".+ assert!(state == ReadableStreamState::Readable);++ // 2. If bytesWritten is 0, throw a TypeError exception.+ if bytes_written == 0 {+ return Err(Exception::type_error(+ "Bytes written is zero for stream which is not closed",+ ));+ }++ // 3. If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length, throw a RangeError+ // exception.+ if first_descriptor.bytes_filled.get() + bytes_written > first_descriptor.byte_length.get() {+ return Err(Exception::range_error(+ "Bytes written is greater than the pull requests byte length",+ ));+ }+ }++ // 6. Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).+ first_descriptor+ .buffer+ .set(transfer_array_buffer(cx, first_descriptor.buffer.get()).must());++ // 7. Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).+ readable_byte_stream_controller_respond_internal(cx, controller, bytes_written)+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-closed-state+pub(crate) fn readable_byte_stream_controller_respond_in_closed_state(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ first_descriptor: PullIntoDescriptorRef,+) {+ // 1. Assert: the remainder after dividing firstDescriptor’s bytes filled by firstDescriptor’s element size is 0.+ assert!(+ first_descriptor+ .bytes_filled+ .get()+ .is_multiple_of(first_descriptor.element_size.get())+ );++ // 2. If firstDescriptor’s reader type is "none", perform+ // ! ReadableByteStreamControllerShiftPendingPullInto(controller).+ if first_descriptor.reader_type.get() == ReaderType::None {+ readable_byte_stream_controller_shift_pending_pull_into(controller);+ }++ // 3. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 4. If ! ReadableStreamHasBYOBReader(stream) is true,+ if readable_stream_has_byob_reader(stream) {+ // 1. Let filledPullIntos be a new empty list.+ let filled_pull_intos = MarkedVec::new(cx.vm());++ // 2. While filledPullIntos’s size < ! ReadableStreamGetNumReadIntoRequests(stream),+ while filled_pull_intos.len() < readable_stream_get_num_read_into_requests(stream) {+ // 1. Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).+ let pull_into_descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);++ // 2. Append pullIntoDescriptor to filledPullIntos.+ filled_pull_intos.push(pull_into_descriptor);+ }++ // 3. For each filledPullInto of filledPullIntos,+ for index in 0..filled_pull_intos.len() {+ // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, filledPullInto).+ let filled_pull_into = filled_pull_intos.get(index).expect("the index is in bounds");+ readable_byte_stream_controller_commit_pull_into_descriptor(cx, stream, filled_pull_into);+ }+ }+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-readable-state+pub(crate) fn readable_byte_stream_controller_respond_in_readable_state(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ bytes_written: u64,+ pull_into_descriptor: PullIntoDescriptorRef,+) -> WebIdlResult<()> {+ // 1. Assert: pullIntoDescriptor’s bytes filled + bytesWritten ≤ pullIntoDescriptor’s byte length.+ assert!(pull_into_descriptor.bytes_filled.get() + bytes_written <= pull_into_descriptor.byte_length.get());++ // 2. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten,+ // pullIntoDescriptor).+ readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_written, pull_into_descriptor);++ // 3. If pullIntoDescriptor’s reader type is "none",+ if pull_into_descriptor.reader_type.get() == ReaderType::None {+ // 1. Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).+ readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(cx, controller, pull_into_descriptor)?;++ // 2. Let filledPullIntos be the result of performing+ // ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).+ let filled_pulled_intos =+ readable_byte_stream_controller_process_pull_into_descriptors_using_queue(cx.vm(), controller);++ // 3. For each filledPullInto of filledPullIntos,+ for index in 0..filled_pulled_intos.len() {+ // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], filledPullInto).+ let filled_pull_into = filled_pulled_intos.get(index).expect("the index is in bounds");+ readable_byte_stream_controller_commit_pull_into_descriptor(cx, controller.stream(), filled_pull_into);+ }++ // 4. Return.+ return Ok(());+ }++ // 4. If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.+ if pull_into_descriptor.bytes_filled.get() < pull_into_descriptor.minimum_fill.get() {+ return Ok(());+ }++ // NOTE: A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head of+ // the queue, so the underlying source can keep filling it.++ // 5. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).+ readable_byte_stream_controller_shift_pending_pull_into(controller);++ // 6. Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s+ // element size.+ let remainder_size = pull_into_descriptor.bytes_filled.get() % pull_into_descriptor.element_size.get();++ // 7. If remainderSize > 0,+ if remainder_size > 0 {+ // 1. Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.+ let end = pull_into_descriptor.byte_offset.get() + pull_into_descriptor.bytes_filled.get();++ // 2. Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer,+ // end − remainderSize, remainderSize).+ readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(+ cx,+ controller,+ pull_into_descriptor.buffer.get(),+ end - remainder_size,+ remainder_size,+ )?;+ }++ // 8. Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.+ pull_into_descriptor+ .bytes_filled+ .set(pull_into_descriptor.bytes_filled.get() - remainder_size);++ // 9. Let filledPullIntos be the result of performing+ // ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).+ let filled_pulled_intos =+ readable_byte_stream_controller_process_pull_into_descriptors_using_queue(cx.vm(), controller);++ // 10. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).+ readable_byte_stream_controller_commit_pull_into_descriptor(cx, controller.stream(), pull_into_descriptor);++ // 11. For each filledPullInto of filledPullIntos,+ for index in 0..filled_pulled_intos.len() {+ // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], filledPullInto).+ let filled_pull_into = filled_pulled_intos.get(index).expect("the index is in bounds");+ readable_byte_stream_controller_commit_pull_into_descriptor(cx, controller.stream(), filled_pull_into);+ }+ Ok(())+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-internal+pub(crate) fn readable_byte_stream_controller_respond_internal(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ bytes_written: u64,+) -> WebIdlResult<()> {+ // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].+ let first_descriptor = controller+ .first_pending_pull_into()+ .expect("a controller that is responded to has a pending pull-into");++ // 2. Assert: ! CanTransferArrayBuffer(firstDescriptor’s buffer) is true.+ assert!(can_transfer_array_buffer(&first_descriptor.buffer.get()));++ // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).+ readable_byte_stream_controller_invalidate_byob_request(controller);++ // 4. Let state be controller.[[stream]].[[state]].+ let state = controller.stream().state();++ // 5. If state is "closed",+ if state == ReadableStreamState::Closed {+ // 1. Assert: bytesWritten is 0.+ assert!(bytes_written == 0);++ // 2. Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).+ readable_byte_stream_controller_respond_in_closed_state(cx, controller, first_descriptor);+ }+ // 6. Otherwise,+ else {+ // 1. Assert: state is "readable".+ assert!(state == ReadableStreamState::Readable);++ // 2. Assert: bytesWritten > 0.+ assert!(bytes_written > 0);++ // 3. Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).+ readable_byte_stream_controller_respond_in_readable_state(cx, controller, bytes_written, first_descriptor)?;+ }++ // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).+ readable_byte_stream_controller_call_pull_if_needed(cx, controller);+ Ok(())+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-with-new-view+pub(crate) fn readable_byte_stream_controller_respond_with_new_view(+ cx: &CallContext,+ controller: Ref<ReadableByteStreamController>,+ view: ArrayBufferView,+) -> WebIdlResult<()> {+ let view_extent = BufferSource::from(view).extent();++ // 1. Assert: controller.[[pendingPullIntos]] is not empty.+ assert!(!controller.pending_pull_intos_is_empty());++ // 2. Assert: ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is false.+ assert!(!view_extent.buffer.is_detached());++ // 3. Let firstDescriptor be controller.[[pendingPullIntos]][0].+ let first_descriptor = controller+ .first_pending_pull_into()+ .expect("a controller that is responded to has a pending pull-into");++ // 4. Let state be controller.[[stream]].[[state]].+ let state = controller.stream().state();++ // 5. If state is "closed",+ if state == ReadableStreamState::Closed {+ // 1. If view.[[ByteLength]] is not 0, throw a TypeError exception.+ if view_extent.byte_length != 0 {+ return Err(Exception::type_error("Byte length is not zero for closed stream"));+ }+ }+ // 6. Otherwise,+ else {+ // 1. Assert: state is "readable".+ assert!(state == ReadableStreamState::Readable);++ // 2. If view.[[ByteLength]] is 0, throw a TypeError exception.+ if view_extent.byte_length == 0 {+ return Err(Exception::type_error(+ "Byte length is zero for stream which is not closed",+ ));+ }+ }++ // 7. If firstDescriptor’s byte offset + firstDescriptor’ bytes filled is not view.[[ByteOffset]], throw a+ // RangeError exception.+ if first_descriptor.byte_offset.get() + first_descriptor.bytes_filled.get() != view_extent.byte_offset as u64 {+ return Err(Exception::range_error(+ "Byte offset is not aligned with the pull request's byte offset",+ ));+ }++ // 8. If firstDescriptor’s buffer byte length is not view.[[ViewedArrayBuffer]].[[ByteLength]], throw a RangeError+ // exception.+ if first_descriptor.buffer_byte_length.get() != view_extent.buffer.byte_length() as u64 {+ return Err(Exception::range_error(+ "Buffer byte length is not aligned with the pull request's byte length",+ ));+ }++ // 9. If firstDescriptor’s bytes filled + view.[[ByteLength]] > firstDescriptor’s byte length, throw a RangeError+ // exception.+ if first_descriptor.bytes_filled.get() + view_extent.byte_length as u64 > first_descriptor.byte_length.get() {+ return Err(Exception::range_error(+ "Byte length is greater than the pull request's byte length",+ ));+ }++ // 10. Let viewByteLength be view.[[ByteLength]].+ let view_byte_length = view_extent.byte_length as u64;++ // 11. Set firstDescriptor’s buffer to ? TransferArrayBuffer(view.[[ViewedArrayBuffer]]).+ first_descriptor+ .buffer+ .set(transfer_array_buffer(cx, view_extent.buffer)?);++ // 12. Perform ? ReadableByteStreamControllerRespondInternal(controller, viewByteLength).+ readable_byte_stream_controller_respond_internal(cx, controller, view_byte_length)+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into+pub(crate) fn readable_byte_stream_controller_shift_pending_pull_into(+ controller: Ref<ReadableByteStreamController>,+) -> PullIntoDescriptorRef {+ // 1. Assert: controller.[[byobRequest]] is null.+ assert!(controller.byob_request.get().is_none());++ // 2. Let descriptor be controller.[[pendingPullIntos]][0].+ // 3. Remove descriptor from controller.[[pendingPullIntos]].+ // 4. Return descriptor.+ controller+ .pending_pull_intos+ .borrow_mut()+ .pop_front()+ .expect("a controller shifts a pending pull-into it has")+}++// https://streams.spec.whatwg.org/#readable-byte-stream-controller-should-call-pull+pub(crate) fn readable_byte_stream_controller_should_call_pull(controller: Ref<ReadableByteStreamController>) -> bool {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If stream.[[state]] is not "readable", return false.+ if stream.state() != ReadableStreamState::Readable {+ return false;+ }++ // 3. If controller.[[closeRequested]] is true, return false.+ if controller.close_requested() {+ return false;+ }++ // 4. If controller.[[started]] is false, return false.+ if !controller.started.get() {+ return false;+ }++ // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return+ // true.+ if readable_stream_has_default_reader(stream) && readable_stream_get_num_read_requests(stream) > 0 {+ return true;+ }++ // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0,+ // return true.+ if readable_stream_has_byob_reader(stream) && readable_stream_get_num_read_into_requests(stream) > 0 {+ return true;+ }++ // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).+ // 8. Assert: desiredSize is not null.+ let desired_size = readable_byte_stream_controller_get_desired_size(controller)+ .expect("a readable stream's controller has a desired size");++ // 9. If desiredSize > 0, return true.+ if desired_size > 0.0 {+ return true;+ }++ // 10. Return false.+ false+}++// https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller+#[allow(clippy::too_many_arguments, reason = "the abstract operation takes these arguments")]+pub(crate) fn set_up_readable_byte_stream_controller(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ controller: Ref<ReadableByteStreamController>,+ start_algorithm: StartAlgorithm,+ pull_algorithm: PullAlgorithm,+ cancel_algorithm: CancelAlgorithm,+ high_water_mark: f64,+ auto_allocate_chunk_size: Option<u64>,+) -> WebIdlResult<()> {+ // 1. Assert: stream.[[controller]] is undefined.+ assert!(stream.controller().is_none());++ // 2. If autoAllocateChunkSize is not undefined,+ if let Some(auto_allocate_chunk_size) = auto_allocate_chunk_size {+ // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.+ // 2. Assert: autoAllocateChunkSize is positive.+ assert!(auto_allocate_chunk_size > 0);+ }++ // 3. Set controller.[[stream]] to stream.+ controller.stream.set(Some(stream));++ // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.+ controller.pull_again.set(false);+ controller.pulling.set(false);++ // 5. Set controller.[[byobRequest]] to null.+ controller.byob_request.set(None);++ // 6. Perform ! ResetQueue(controller).+ controller.reset_queue();++ // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.+ controller.close_requested.set(false);+ controller.started.set(false);++ // 8. Set controller.[[strategyHWM]] to highWaterMark.+ controller.strategy_hwm.set(high_water_mark);++ // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.+ *controller.pull_algorithm.borrow_mut() = Some(pull_algorithm);++ // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.+ *controller.cancel_algorithm.borrow_mut() = Some(cancel_algorithm);++ // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.+ controller.auto_allocate_chunk_size.set(auto_allocate_chunk_size);++ // 12. Set controller.[[pendingPullIntos]] to a new empty list.+ controller.pending_pull_intos.borrow_mut().clear();++ // 13. Set stream.[[controller]] to controller.+ stream.set_controller(Some(ReadableStreamController::ReadableByteStreamController(controller)));++ // 14. Let startResult be the result of performing startAlgorithm.+ let start_result = start_algorithm.run()?;++ // 15. Let startPromise be a promise resolved with startResult.+ let start_promise = create_resolved_promise(cx.vm(), cx.realm(), start_result);++ react_to_promise(+ cx.vm(),+ start_promise,+ controller,+ // 16. Upon fulfillment of startPromise,+ Some(|cx, controller, _| {+ // 1. Set controller.[[started]] to true.+ controller.started.set(true);++ // 2. Assert: controller.[[pulling]] is false.+ assert!(!controller.pulling.get());++ // 3. Assert: controller.[[pullAgain]] is false.+ assert!(!controller.pull_again.get());++ // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).+ readable_byte_stream_controller_call_pull_if_needed(cx, controller);++ Ok(Value::UNDEFINED)+ }),+ // 17. Upon rejection of startPromise with reason r,+ Some(|cx, controller, reason| {+ // 1. Perform ! ReadableByteStreamControllerError(controller, r).+ readable_byte_stream_controller_error(cx, controller, reason);++ Ok(Value::UNDEFINED)+ }),+ );+ Ok(())+}++// https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source+pub(crate) fn set_up_readable_byte_stream_controller_from_underlying_source(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ underlying_source: Value,+ underlying_source_dict: UnderlyingSource,+ high_water_mark: f64,+) -> WebIdlResult<()> {+ // 1. Let controller be a new ReadableByteStreamController.+ let controller = allocate(cx.vm(), ReadableByteStreamController::new());++ // 2. Let startAlgorithm be an algorithm that returns undefined.+ let mut start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut pull_algorithm = PullAlgorithm::ReturnsResolvedUndefined;++ // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut cancel_algorithm = CancelAlgorithm::ReturnsResolvedUndefined;++ // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of+ // invoking underlyingSourceDict["start"] with argument list « controller » and callback this value+ // underlyingSource.+ if let Some(start) = underlying_source_dict.start {+ start_algorithm = StartAlgorithm::Callback {+ start,+ this_value: underlying_source,+ controller: ReadableStreamController::ReadableByteStreamController(controller).to_js(cx),+ };+ }++ // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of+ // invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value+ // underlyingSource.+ if let Some(pull) = underlying_source_dict.pull {+ pull_algorithm = PullAlgorithm::Callback {+ pull,+ underlying_source,+ controller: ReadableStreamController::ReadableByteStreamController(controller),+ };+ }++ // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument+ // reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and+ // callback this value underlyingSource.+ if let Some(cancel) = underlying_source_dict.cancel {+ cancel_algorithm = CancelAlgorithm::Callback {+ cancel,+ this_value: underlying_source,+ };+ }++ // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined+ // otherwise.+ let auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size;++ // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.+ if auto_allocate_chunk_size == Some(0) {+ return Err(Exception::type_error("Cannot use an auto allocate chunk size of 0"));+ }++ // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm,+ // cancelAlgorithm, highWaterMark, autoAllocateChunkSize).+ set_up_readable_byte_stream_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ high_water_mark,+ auto_allocate_chunk_size,+ )+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rsnew file mode 100644index 00000000000..8d313696d11--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs@@ -0,0 +1,1369 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStream, https://streams.spec.whatwg.org/#rs-class, and the abstract operations that work with readable+//! streams, https://streams.spec.whatwg.org/#rs-abstract-ops++use core::cell::Cell;+use core::ffi::c_void;++use libjs_rust::api::{+ Array, Gc, IteratorHint, IteratorRecord, Object, Realm, Trace, Value, Vm, call, get_iterator, iterator_complete,+ iterator_next, iterator_value,+};++use crate::bindings::async_iterable::{AsyncIterable, END_OF_ITERATION};+use crate::bindings::conversions::{ArrayBufferView, BufferSource, CppInterface, FromJs};+use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context_and_callbacks};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_rejected_promise, create_rejected_promise_from_exception,+ create_resolved_promise, mark_promise_as_handled, reject_promise, resolve_promise, upon_fulfillment,+};+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::streams::algorithms::{CancelAlgorithm, PullAlgorithm, SizeAlgorithm, StartAlgorithm};+use crate::streams::cpp::{CppPromiseAlgorithm, CppPromiseAlgorithmWithArgument};+use crate::streams::cross_realm_transform::{+ create_entangled_ports, deserialize_message_port, serialize_message_port, set_up_cross_realm_transform_readable,+ set_up_cross_realm_transform_writable,+};+use crate::streams::queuing_strategy::{QueuingStrategy, extract_high_water_mark, extract_size_algorithm};+use crate::streams::read_request::{ReadIntoRequest, ReadRequest};+use crate::streams::readable_byte_stream_controller::{+ ReadableByteStreamController, readable_byte_stream_controller_close, readable_byte_stream_controller_enqueue,+ readable_byte_stream_controller_error, readable_byte_stream_controller_get_byob_request,+ readable_byte_stream_controller_respond, set_up_readable_byte_stream_controller,+ set_up_readable_byte_stream_controller_from_underlying_source,+};+use crate::streams::readable_stream_byob_reader::{ReadableStreamBYOBReader, set_up_readable_stream_byob_reader};+use crate::streams::readable_stream_default_controller::{+ ReadableStreamDefaultController, readable_stream_default_controller_close,+ readable_stream_default_controller_enqueue, readable_stream_default_controller_error,+ set_up_readable_stream_default_controller, set_up_readable_stream_default_controller_from_underlying_source,+};+use crate::streams::readable_stream_default_reader::{+ ReadableStreamDefaultReader, readable_stream_default_reader_read, readable_stream_default_reader_release,+ set_up_readable_stream_default_reader,+};+use crate::streams::readable_stream_generic_reader::{+ ReadableStreamGenericReader, readable_stream_reader_generic_cancel,+};+use crate::streams::readable_stream_pipe_to::readable_stream_pipe_to;+use crate::streams::readable_stream_tee::readable_stream_tee;+use crate::streams::transform_stream::TransformStream;+use crate::streams::underlying_source::{ReadableStreamController, ReadableStreamType, UnderlyingSource};+use crate::streams::writable_stream::{WritableStream, is_writable_stream_locked};++unsafe extern "C" {+ /// Tells Page::RenderingStats that the stream, a ReadableStream, no longer holds rendering back.+ fn web_streams_complete_rendering_pending_stream(stream: *mut c_void);+}++// https://streams.spec.whatwg.org/#readablestream-state+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ReadableStreamState {+ Readable,+ Closed,+ Errored,+}++// https://streams.spec.whatwg.org/#enumdef-readablestreamreadermode+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ReadableStreamReaderMode {+ Byob,+}++/// The dictionary ReadableStreamGetReaderOptions of Streams/ReadableStream.idl, whose members the bindings convert.+pub(crate) struct ReadableStreamGetReaderOptions {+ pub(crate) mode: Option<ReadableStreamReaderMode>,+}++/// The dictionary ReadableWritablePair of Streams/ReadableStream.idl, whose members the bindings convert.+pub(crate) struct ReadableWritablePair {+ pub(crate) readable: Ref<ReadableStream>,+ pub(crate) writable: Ref<WritableStream>,+}++/// The dictionary StreamPipeOptions of Streams/ReadableStream.idl, whose members the bindings convert.+pub(crate) struct StreamPipeOptions {+ pub(crate) prevent_abort: bool,+ pub(crate) prevent_cancel: bool,+ pub(crate) prevent_close: bool,+ pub(crate) signal: Option<CppInterface>,+}++/// The dictionary ReadableStreamIteratorOptions of Streams/ReadableStream.idl, whose members the bindings convert.+pub(crate) struct ReadableStreamIteratorOptions {+ pub(crate) prevent_cancel: bool,+}++/// https://streams.spec.whatwg.org/#typedefdef-readablestreamreader+#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum ReadableStreamReader {+ ReadableStreamDefaultReader(Ref<ReadableStreamDefaultReader>),+ ReadableStreamBYOBReader(Ref<ReadableStreamBYOBReader>),+}++impl ReadableStreamReader {+ /// What the reader is as a ReadableStreamGenericReader, https://streams.spec.whatwg.org/#readablestreamgenericreader+ pub(crate) fn generic(&self) -> &ReadableStreamGenericReader {+ match self {+ Self::ReadableStreamDefaultReader(reader) => reader.generic(),+ Self::ReadableStreamBYOBReader(reader) => reader.generic(),+ }+ }+}++// https://streams.spec.whatwg.org/#readablestream+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStream {+ /// The realm of the stream, which its promises and the results of its operations are created in.+ realm: Cell<Gc<Realm>>,+ // https://streams.spec.whatwg.org/#readablestream-controller+ controller: Cell<Option<ReadableStreamController>>,+ // https://streams.spec.whatwg.org/#readablestream-detached+ detached: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablestream-disturbed+ disturbed: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablestream-reader+ reader: Cell<Option<ReadableStreamReader>>,+ // https://streams.spec.whatwg.org/#readablestream-state+ #[gc(untraced)]+ state: Cell<ReadableStreamState>,+ // https://streams.spec.whatwg.org/#readablestream-storederror+ stored_error: Cell<Value>,+}++impl Wrappable for ReadableStream {+ const FINALIZES: bool = true;++ fn finalize(stream: Ref<Self>) {+ complete_rendering_pending_stream(stream);+ }+}++impl ReadableStream {+ /// A new ReadableStream in the realm, which InitializeReadableStream has initialized.+ pub(crate) fn new(realm: Gc<Realm>) -> Self {+ Self {+ realm: Cell::new(realm),+ controller: Cell::new(None),+ detached: Cell::new(false),+ disturbed: Cell::new(false),+ reader: Cell::new(None),+ state: Cell::new(ReadableStreamState::Readable),+ stored_error: Cell::new(Value::UNDEFINED),+ }+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm.get()+ }++ pub(crate) fn set_realm(&self, realm: Gc<Realm>) {+ self.realm.set(realm);+ }++ pub(crate) fn controller(&self) -> Option<ReadableStreamController> {+ self.controller.get()+ }++ pub(crate) fn set_controller(&self, controller: Option<ReadableStreamController>) {+ self.controller.set(controller);+ }++ pub(crate) fn disturbed(&self) -> bool {+ self.disturbed.get()+ }++ pub(crate) fn set_disturbed(&self, disturbed: bool) {+ self.disturbed.set(disturbed);+ }++ pub(crate) fn reader(&self) -> Option<ReadableStreamReader> {+ self.reader.get()+ }++ pub(crate) fn set_reader(&self, reader: Option<ReadableStreamReader>) {+ self.reader.set(reader);+ }++ pub(crate) fn state(&self) -> ReadableStreamState {+ self.state.get()+ }++ pub(crate) fn set_state(&self, state: ReadableStreamState) {+ self.state.set(state);+ }++ pub(crate) fn stored_error(&self) -> Value {+ self.stored_error.get()+ }++ pub(crate) fn set_stored_error(&self, error: Value) {+ self.stored_error.set(error);+ }++ /// The context of the realm of the stream.+ pub(crate) fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, self.realm())+ }++ // https://streams.spec.whatwg.org/#rs-constructor+ pub(crate) fn construct(+ cx: &mut CallContext,+ underlying_source: Option<Gc<Object>>,+ strategy: QueuingStrategy,+ ) -> WebIdlResult<Ref<Self>> {+ // 1. If underlyingSource is missing, set it to null.+ let underlying_source = underlying_source.map_or(Value::NULL, Value::from_object);++ // 2. Let underlyingSourceDict be underlyingSource, converted to an IDL value of type UnderlyingSource.+ let underlying_source_dict = UnderlyingSource::from_js(cx.vm(), underlying_source)?;++ // 3. Perform ! InitializeReadableStream(this).+ let this = allocate(cx.vm(), Self::new(cx.realm()));++ // 4. If underlyingSourceDict["type"] is "bytes":+ if underlying_source_dict.r#type == Some(ReadableStreamType::Bytes) {+ // 1. If strategy["size"] exists, throw a RangeError exception.+ if strategy.size.is_some() {+ return Err(Exception::range_error("Size strategy not allowed for byte stream"));+ }++ // 2. Let highWaterMark be ? ExtractHighWaterMark(strategy, 0).+ let high_water_mark = extract_high_water_mark(&strategy, 0.0)?;++ // 3. Perform ? SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource,+ // underlyingSourceDict, highWaterMark).+ set_up_readable_byte_stream_controller_from_underlying_source(+ cx,+ this,+ underlying_source,+ underlying_source_dict,+ high_water_mark,+ )?;+ }+ // 5. Otherwise,+ else {+ // 1. Assert: underlyingSourceDict["type"] does not exist.+ assert!(underlying_source_dict.r#type.is_none());++ // 2. Let sizeAlgorithm be ! ExtractSizeAlgorithm(strategy).+ let size_algorithm = extract_size_algorithm(&strategy);++ // 3. Let highWaterMark be ? ExtractHighWaterMark(strategy, 1).+ let high_water_mark = extract_high_water_mark(&strategy, 1.0)?;++ // 4. Perform ? SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource,+ // underlyingSourceDict, highWaterMark, sizeAlgorithm).+ set_up_readable_stream_default_controller_from_underlying_source(+ cx,+ this,+ underlying_source,+ underlying_source_dict,+ high_water_mark,+ size_algorithm,+ )?;+ }+ Ok(this)+ }++ // https://streams.spec.whatwg.org/#rs-from+ pub(crate) fn from(cx: &mut CallContext, async_iterable: Value) -> WebIdlResult<Ref<Self>> {+ // 1. Return ? ReadableStreamFromIterable(asyncIterable).+ readable_stream_from_iterable(cx, async_iterable)+ }++ // https://streams.spec.whatwg.org/#rs-locked+ pub(crate) fn locked(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<bool> {+ // 1. Return ! IsReadableStreamLocked(this).+ Ok(is_readable_stream_locked(*this))+ }++ // https://streams.spec.whatwg.org/#rs-cancel+ pub(crate) fn cancel(this: &Ref<Self>, cx: &mut CallContext, reason: Option<Value>) -> WebIdlResult<WebIdlPromise> {+ let cx = &this.context(cx.vm());++ // 1. If ! IsReadableStreamLocked(this) is true, return a promise rejected with a TypeError exception.+ if is_readable_stream_locked(*this) {+ let exception = Exception::type_error("Cannot cancel a locked stream");+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 2. Return ! ReadableStreamCancel(this, reason).+ Ok(readable_stream_cancel(cx, *this, reason.unwrap_or(Value::UNDEFINED)))+ }++ // https://streams.spec.whatwg.org/#rs-get-reader+ pub(crate) fn get_reader(+ this: &Ref<Self>,+ cx: &mut CallContext,+ options: ReadableStreamGetReaderOptions,+ ) -> WebIdlResult<ReadableStreamReader> {+ let cx = &this.context(cx.vm());++ // 1. If options["mode"] does not exist, return ? AcquireReadableStreamDefaultReader(this).+ let Some(mode) = options.mode else {+ return Ok(ReadableStreamReader::ReadableStreamDefaultReader(+ acquire_readable_stream_default_reader(cx, *this)?,+ ));+ };++ // 2. Assert: options["mode"] is "byob".+ assert!(mode == ReadableStreamReaderMode::Byob);++ // 3. Return ? AcquireReadableStreamBYOBReader(this).+ Ok(ReadableStreamReader::ReadableStreamBYOBReader(+ acquire_readable_stream_byob_reader(cx, *this)?,+ ))+ }++ // https://streams.spec.whatwg.org/#rs-pipe-through+ pub(crate) fn pipe_through(+ this: &Ref<Self>,+ cx: &mut CallContext,+ transform: ReadableWritablePair,+ options: StreamPipeOptions,+ ) -> WebIdlResult<Ref<Self>> {+ let cx = &this.context(cx.vm());++ // 1. If ! IsReadableStreamLocked(this) is true, throw a TypeError exception.+ if is_readable_stream_locked(*this) {+ return Err(Exception::type_error(+ "Failed to execute 'pipeThrough' on 'ReadableStream': Cannot pipe a locked stream",+ ));+ }++ // 2. If ! IsWritableStreamLocked(transform["writable"]) is true, throw a TypeError exception.+ if is_writable_stream_locked(transform.writable) {+ return Err(Exception::type_error(+ "Failed to execute 'pipeThrough' on 'ReadableStream': parameter 1's 'writable' is locked",+ ));+ }++ // 3. Let signal be options["signal"] if it exists, or undefined otherwise.+ let signal = options.signal;++ // 4. Let promise be ! ReadableStreamPipeTo(this, transform["writable"], options["preventClose"],+ // options["preventAbort"], options["preventCancel"], signal).+ let promise = readable_stream_pipe_to(+ cx,+ *this,+ transform.writable,+ options.prevent_close,+ options.prevent_abort,+ options.prevent_cancel,+ signal,+ );++ // 5. Set promise.[[PromiseIsHandled]] to true.+ mark_promise_as_handled(cx.vm(), promise);++ // 6. Return transform["readable"].+ Ok(transform.readable)+ }++ // https://streams.spec.whatwg.org/#rs-pipe-to+ pub(crate) fn pipe_to(+ this: &Ref<Self>,+ cx: &mut CallContext,+ destination: Ref<WritableStream>,+ options: StreamPipeOptions,+ ) -> WebIdlResult<WebIdlPromise> {+ let cx = &this.context(cx.vm());++ // 1. If ! IsReadableStreamLocked(this) is true, return a promise rejected with a TypeError exception.+ if is_readable_stream_locked(*this) {+ let exception =+ Exception::type_error("Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe a locked stream");+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 2. If ! IsWritableStreamLocked(destination) is true, return a promise rejected with a TypeError exception.+ if is_writable_stream_locked(destination) {+ let exception = Exception::type_error(+ "Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe to a locked stream",+ );+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 3. Let signal be options["signal"] if it exists, or undefined otherwise.+ let signal = options.signal;++ // 4. Return ! ReadableStreamPipeTo(this, destination, options["preventClose"], options["preventAbort"],+ // options["preventCancel"], signal).+ Ok(readable_stream_pipe_to(+ cx,+ *this,+ destination,+ options.prevent_close,+ options.prevent_abort,+ options.prevent_cancel,+ signal,+ ))+ }++ // https://streams.spec.whatwg.org/#rs-tee+ pub(crate) fn tee(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Vec<Ref<Self>>> {+ let cx = &this.context(cx.vm());++ // 1. Return ? ReadableStreamTee(this, false).+ let (branch1, branch2) = readable_stream_tee(cx, *this, false)?;+ Ok(vec![branch1, branch2])+ }++ // https://streams.spec.whatwg.org/#ref-for-asynchronous-iterator-initialization-steps+ pub(crate) fn asynchronous_iterator_initialization_steps(+ this: &Ref<Self>,+ cx: &mut CallContext,+ options: ReadableStreamIteratorOptions,+ ) -> WebIdlResult<ReadableStreamAsyncIteratorState> {+ let realm_cx = &this.context(cx.vm());++ // 1. Let reader be ? AcquireReadableStreamDefaultReader(stream).+ // 2. Set iterator’s reader to reader.+ let reader = acquire_readable_stream_default_reader(realm_cx, *this)?;++ // 3. Let preventCancel be args[0]["preventCancel"].+ // 4. Set iterator’s prevent cancel to preventCancel.+ Ok(ReadableStreamAsyncIteratorState {+ reader,+ prevent_cancel: options.prevent_cancel,+ })+ }+}++/// The state of an asynchronous iterator of a ReadableStream, https://streams.spec.whatwg.org/#rs-asynciterator+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStreamAsyncIteratorState {+ reader: Ref<ReadableStreamDefaultReader>,+ #[gc(untraced)]+ prevent_cancel: bool,+}++impl AsyncIterable for ReadableStream {+ type IteratorState = ReadableStreamAsyncIteratorState;++ // https://streams.spec.whatwg.org/#ref-for-dfn-get-the-next-iteration-result+ fn get_the_next_iteration_result(cx: &CallContext, iterator: &ReadableStreamAsyncIteratorState) -> WebIdlPromise {+ // 1. Let reader be iterator’s reader.+ let reader = iterator.reader;++ // 2. Assert: reader.[[stream]] is not undefined.+ assert!(reader.generic().stream().is_some());++ // 3. Let promise be a new promise.+ let promise = create_promise(cx.vm(), cx.realm());++ // 4. Let readRequest be a new read request with the following items:+ let read_request = ReadRequest::AsyncIterator { reader, promise };++ // 5. Perform ! ReadableStreamDefaultReaderRead(this, readRequest).+ readable_stream_default_reader_read(cx.vm(), reader, read_request);++ // 6. Return promise.+ promise+ }++ // https://streams.spec.whatwg.org/#ref-for-asynchronous-iterator-return+ fn asynchronous_iterator_return(+ cx: &CallContext,+ iterator: &ReadableStreamAsyncIteratorState,+ arg: Value,+ ) -> WebIdlPromise {+ // 1. Let reader be iterator’s reader.+ let reader = iterator.reader;++ // 2. Assert: reader.[[stream]] is not undefined.+ assert!(reader.generic().stream().is_some());++ // 3. Assert: reader.[[readRequests]] is empty, as the async iterator machinery guarantees that any previous+ // calls to next() have settled before this is called.+ assert!(reader.read_requests_is_empty());++ // 4. If iterator’s prevent cancel is false:+ if !iterator.prevent_cancel {+ // 1. Let result be ! ReadableStreamReaderGenericCancel(reader, arg).+ let result = readable_stream_reader_generic_cancel(+ cx.vm(),+ ReadableStreamReader::ReadableStreamDefaultReader(reader),+ arg,+ );++ // 2. Perform ! ReadableStreamDefaultReaderRelease(reader).+ readable_stream_default_reader_release(cx.vm(), reader);++ // 3. Return result.+ return result;+ }++ // 5. Perform ! ReadableStreamDefaultReaderRelease(reader).+ readable_stream_default_reader_release(cx.vm(), reader);++ // 6. Return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }+}++/// The steps of the read request of getting the next iteration result of a ReadableStream's asynchronous iterator,+/// https://streams.spec.whatwg.org/#ref-for-dfn-get-the-next-iteration-result+pub(crate) mod async_iterator_read_request_steps {+ use super::*;++ // chunk steps, given chunk+ pub(crate) fn chunk_steps(vm: &Vm, _: Ref<ReadableStreamDefaultReader>, promise: WebIdlPromise, chunk: Value) {+ // 1. Resolve promise with chunk.+ resolve_promise(vm, promise, chunk);+ }++ // close steps+ pub(crate) fn close_steps(vm: &Vm, reader: Ref<ReadableStreamDefaultReader>, promise: WebIdlPromise) {+ // 1. Perform ! ReadableStreamDefaultReaderRelease(reader).+ readable_stream_default_reader_release(vm, reader);++ // 2. Resolve promise with end of iteration.+ resolve_promise(vm, promise, END_OF_ITERATION);+ }++ // error steps, given e+ pub(crate) fn error_steps(vm: &Vm, reader: Ref<ReadableStreamDefaultReader>, promise: WebIdlPromise, error: Value) {+ // 1. Perform ! ReadableStreamDefaultReaderRelease(reader).+ readable_stream_default_reader_release(vm, reader);++ // 2. Reject promise with e.+ reject_promise(vm, promise, error);+ }+}++impl Transferable for ReadableStream {+ fn detached(&self) -> &Cell<bool> {+ &self.detached+ }++ // https://streams.spec.whatwg.org/#ref-for-transfer-steps+ fn transfer_steps(+ this: &Ref<Self>,+ cx: &mut CallContext,+ data_holder: &mut TransferDataWriter,+ ) -> WebIdlResult<()> {+ let this = *this;+ let cx = &*cx;+ with_temporary_execution_context_and_callbacks(cx.realm(), || {+ // 1. If ! IsReadableStreamLocked(value) is true, throw a "DataCloneError" DOMException.+ if is_readable_stream_locked(this) {+ return Err(Exception::Dom(+ "DataCloneError",+ ak::Utf16String::from_ascii(b"Cannot transfer locked ReadableStream"),+ ));+ }++ // 2. Let port1 be a new MessagePort in the current Realm.+ // 3. Let port2 be a new MessagePort in the current Realm.+ // 4. Entangle port1 and port2.+ let (port1, port2) = create_entangled_ports(cx);++ // 5. Let writable be a new WritableStream in the current Realm.+ let writable = allocate(cx.vm(), WritableStream::new(cx.realm()));++ // 6. Perform ! SetUpCrossRealmTransformWritable(writable, port1).+ set_up_cross_realm_transform_writable(cx, writable, port1);++ // 7. Let promise be ! ReadableStreamPipeTo(value, writable, false, false, false).+ let promise = readable_stream_pipe_to(cx, this, writable, false, false, false, None);++ // 8. Set promise.[[PromiseIsHandled]] to true.+ mark_promise_as_handled(cx.vm(), promise);++ // 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).+ serialize_message_port(cx, data_holder, &port2);+ Ok(())+ })+ }++ // https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps+ fn transfer_receiving_steps(cx: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Ref<Self>> {+ let cx = &*cx;+ with_temporary_execution_context_and_callbacks(cx.realm(), || {+ let value = allocate(cx.vm(), Self::new(cx.realm()));++ // 1. Let deserializedRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[port]], the current Realm).+ // 2. Let port be deserializedRecord.[[Deserialized]].+ let port = deserialize_message_port(cx, data_holder);++ // 3. Perform ! SetUpCrossRealmTransformReadable(value, port).+ set_up_cross_realm_transform_readable(cx, value, port);+ Ok(value)+ })+ }+}++/// What specifications that set up and read ReadableStreams use, https://streams.spec.whatwg.org/#other-specs-rs+impl ReadableStream {+ // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support+ pub(crate) fn set_up_with_byte_reading_support(+ stream: Ref<Self>,+ cx: &CallContext,+ pull_algorithm: Option<CppPromiseAlgorithm>,+ cancel_algorithm: Option<CppPromiseAlgorithmWithArgument>,+ high_water_mark: f64,+ ) {+ stream.set_realm(cx.realm());++ // 1. Let startAlgorithm be an algorithm that returns undefined.+ let start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:+ let pull_algorithm_wrapper = PullAlgorithm::WithByteReadingSupport(pull_algorithm);++ // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:+ let cancel_algorithm_wrapper = CancelAlgorithm::Wrapper(cancel_algorithm);++ // 4. Perform ! InitializeReadableStream(stream).+ // 5. Let controller be a new ReadableByteStreamController.+ let controller = allocate(cx.vm(), ReadableByteStreamController::new());++ // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper,+ // cancelAlgorithmWrapper, highWaterMark, undefined).+ set_up_readable_byte_stream_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ pull_algorithm_wrapper,+ cancel_algorithm_wrapper,+ high_water_mark,+ None,+ )+ .must();+ }++ // https://streams.spec.whatwg.org/#readablestream-close+ pub(crate) fn close(this: Ref<Self>, vm: &Vm) {+ let cx = &this.context(vm);+ match this.controller().expect("a stream that is set up has a controller") {+ // 1. If stream.[[controller]] implements ReadableByteStreamController,+ ReadableStreamController::ReadableByteStreamController(controller) => {+ // 1. Perform ! ReadableByteStreamControllerClose(stream.[[controller]]).+ readable_byte_stream_controller_close(cx, controller).must();++ // 2. If stream.[[controller]].[[pendingPullIntos]] is not empty, perform+ // ! ReadableByteStreamControllerRespond(stream.[[controller]], 0).+ if !controller.pending_pull_intos_is_empty() {+ readable_byte_stream_controller_respond(cx, controller, 0).must();+ }+ }+ // 2. Otherwise, perform ! ReadableStreamDefaultControllerClose(stream.[[controller]]).+ ReadableStreamController::ReadableStreamDefaultController(controller) => {+ readable_stream_default_controller_close(cx, controller);+ }+ }+ }++ // https://streams.spec.whatwg.org/#readablestream-error+ pub(crate) fn error(this: Ref<Self>, vm: &Vm, error: Value) {+ let cx = &this.context(vm);+ match this.controller().expect("a stream that is set up has a controller") {+ // 1. If stream.[[controller]] implements ReadableByteStreamController, then perform+ // ! ReadableByteStreamControllerError(stream.[[controller]], e).+ ReadableStreamController::ReadableByteStreamController(controller) => {+ readable_byte_stream_controller_error(cx, controller, error);+ }+ // 2. Otherwise, perform ! ReadableStreamDefaultControllerError(stream.[[controller]], e).+ ReadableStreamController::ReadableStreamDefaultController(controller) => {+ readable_stream_default_controller_error(cx, controller, error);+ }+ }+ }++ // https://streams.spec.whatwg.org/#readablestream-readable+ pub(crate) fn is_readable(&self) -> bool {+ // A ReadableStream stream is readable if stream.[[state]] is "readable".+ self.state() == ReadableStreamState::Readable+ }++ // https://streams.spec.whatwg.org/#readablestream-get-a-reader+ pub(crate) fn get_a_reader(this: Ref<Self>, vm: &Vm) -> WebIdlResult<Ref<ReadableStreamDefaultReader>> {+ // To get a reader for a ReadableStream stream, return ? AcquireReadableStreamDefaultReader(stream). The result+ // will be a ReadableStreamDefaultReader.+ acquire_readable_stream_default_reader(&this.context(vm), this)+ }++ // https://streams.spec.whatwg.org/#readablestream-current-byob-request-view+ pub(crate) fn current_byob_request_view(this: Ref<Self>, vm: &Vm) -> Option<ArrayBufferView> {+ // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.+ let Some(ReadableStreamController::ReadableByteStreamController(controller)) = this.controller() else {+ panic!("the stream has a ReadableByteStreamController");+ };++ // 2. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(stream.[[controller]]).+ // 3. If byobRequest is null, then return null.+ let byob_request = readable_byte_stream_controller_get_byob_request(&this.context(vm), controller)?;++ // 4. Return byobRequest.[[view]].+ Some(ArrayBufferView::TypedArray(+ byob_request+ .current_view()+ .expect("a BYOB request of a controller has a view"),+ ))+ }++ // https://streams.spec.whatwg.org/#readablestream-enqueue+ pub(crate) fn enqueue(this: Ref<Self>, vm: &Vm, chunk: Value) -> WebIdlResult<()> {+ let cx = &this.context(vm);+ match this.controller().expect("a stream that is set up has a controller") {+ // 1. If stream.[[controller]] implements ReadableStreamDefaultController,+ ReadableStreamController::ReadableStreamDefaultController(controller) => {+ // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).+ readable_stream_default_controller_enqueue(cx, controller, chunk).must();+ }+ // 2. Otherwise,+ ReadableStreamController::ReadableByteStreamController(controller) => {+ // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.+ // 2. Assert: chunk is an ArrayBufferView.+ let chunk_view = match crate::bindings::conversions::buffer_source_type_of(chunk) {+ Some(BufferSource::TypedArray(typed_array)) => ArrayBufferView::TypedArray(typed_array),+ Some(BufferSource::DataView(view)) => ArrayBufferView::DataView(view),+ _ => panic!("a chunk of a byte stream is an ArrayBufferView"),+ };+ let chunk_extent = BufferSource::from(chunk_view).extent();++ // 3. Let byobView be the current BYOB request view for stream.+ let byob_view = Self::current_byob_request_view(this, vm);++ // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:+ let byob_extent = byob_view.map(|byob_view| BufferSource::from(byob_view).extent());+ if let Some(byob_extent) = byob_extent+ && chunk_extent.buffer == byob_extent.buffer+ {+ // 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].+ assert!(chunk_extent.byte_offset == byob_extent.byte_offset);++ // 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].+ assert!(chunk_extent.byte_length <= byob_extent.byte_length);++ // 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).+ readable_byte_stream_controller_respond(cx, controller, chunk_extent.byte_length as u64)?;+ }+ // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).+ else {+ readable_byte_stream_controller_enqueue(cx, controller, chunk_view)?;+ }+ }+ }+ Ok(())+ }++ // https://streams.spec.whatwg.org/#readablestream-pipe-through+ pub(crate) fn piped_through(+ this: Ref<Self>,+ vm: &Vm,+ transform: Ref<TransformStream>,+ prevent_close: bool,+ prevent_abort: bool,+ prevent_cancel: bool,+ signal: Option<CppInterface>,+ ) -> Ref<Self> {+ let cx = &this.context(vm);++ // 1. Assert: ! IsReadableStreamLocked(readable) is false.+ assert!(!is_readable_stream_locked(this));++ // 2. Assert: ! IsWritableStreamLocked(transform.[[writable]]) is false.+ assert!(!is_writable_stream_locked(transform.writable_stream()));++ // 3. Let signalArg be signal if signal was given, or undefined otherwise.+ // 4. Let promise be ! ReadableStreamPipeTo(readable, transform.[[writable]], preventClose, preventAbort,+ // preventCancel, signalArg).+ let promise = readable_stream_pipe_to(+ cx,+ this,+ transform.writable_stream(),+ prevent_close,+ prevent_abort,+ prevent_cancel,+ signal,+ );++ // 5. Set promise.[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, promise);++ // 6. Return transform.[[readable]].+ transform.readable_stream()+ }+}++/// Tells Page::RenderingStats that the stream no longer holds rendering back, once it has closed or errored or its+/// controller has been asked to close.+pub(crate) fn complete_rendering_pending_stream(stream: Ref<ReadableStream>) {+ // SAFETY: The stream is a live ReadableStream.+ unsafe { web_streams_complete_rendering_pending_stream(stream.as_ptr().cast()) };+}++// https://streams.spec.whatwg.org/#acquire-readable-stream-byob-reader+pub(crate) fn acquire_readable_stream_byob_reader(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+) -> WebIdlResult<Ref<ReadableStreamBYOBReader>> {+ // 1. Let reader be a new ReadableStreamBYOBReader.+ let reader = allocate(cx.vm(), ReadableStreamBYOBReader::new());++ // 2. Perform ? SetUpReadableStreamBYOBReader(reader, stream).+ set_up_readable_stream_byob_reader(cx, reader, stream)?;++ // 3. Return reader.+ Ok(reader)+}++// https://streams.spec.whatwg.org/#acquire-readable-stream-reader+pub(crate) fn acquire_readable_stream_default_reader(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+) -> WebIdlResult<Ref<ReadableStreamDefaultReader>> {+ // 1. Let reader be a new ReadableStreamDefaultReader.+ let reader = allocate(cx.vm(), ReadableStreamDefaultReader::new());++ // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).+ set_up_readable_stream_default_reader(cx, reader, stream)?;++ // 3. Return reader.+ Ok(reader)+}++// https://streams.spec.whatwg.org/#create-readable-stream+pub(crate) fn create_readable_stream(+ cx: &CallContext,+ start_algorithm: StartAlgorithm,+ pull_algorithm: PullAlgorithm,+ cancel_algorithm: CancelAlgorithm,+ high_water_mark: Option<f64>,+ size_algorithm: Option<SizeAlgorithm>,+) -> WebIdlResult<Ref<ReadableStream>> {+ // 4. Let stream be a new ReadableStream.+ // 5. Perform ! InitializeReadableStream(stream).+ let stream = allocate(cx.vm(), ReadableStream::new(cx.realm()));+ create_readable_stream_with_existing_stream(+ cx,+ stream,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ high_water_mark,+ size_algorithm,+ )?;+ Ok(stream)+}++/// CreateReadableStream for a stream that the caller created, for algorithms that refer to the stream before it is+/// set up, https://streams.spec.whatwg.org/#create-readable-stream+pub(crate) fn create_readable_stream_with_existing_stream(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ start_algorithm: StartAlgorithm,+ pull_algorithm: PullAlgorithm,+ cancel_algorithm: CancelAlgorithm,+ high_water_mark: Option<f64>,+ size_algorithm: Option<SizeAlgorithm>,+) -> WebIdlResult<()> {+ // 1. If highWaterMark was not passed, set it to 1.+ let high_water_mark = high_water_mark.unwrap_or(1.0);++ // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.+ let size_algorithm = size_algorithm.unwrap_or(SizeAlgorithm::ReturnsOne);++ // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.+ assert!(high_water_mark >= 0.0);++ // 4. Let stream be a new ReadableStream.+ // 5. Perform ! InitializeReadableStream(stream).+ initialize_readable_stream(stream);++ // 6. Let controller be a new ReadableStreamDefaultController.+ let controller = allocate(cx.vm(), ReadableStreamDefaultController::new());++ // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm,+ // cancelAlgorithm, highWaterMark, sizeAlgorithm).+ set_up_readable_stream_default_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ high_water_mark,+ size_algorithm,+ )++ // 8. Return stream.+}++// https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream+pub(crate) fn create_readable_byte_stream(+ cx: &CallContext,+ start_algorithm: StartAlgorithm,+ pull_algorithm: PullAlgorithm,+ cancel_algorithm: CancelAlgorithm,+) -> WebIdlResult<Ref<ReadableStream>> {+ // 1. Let stream be a new ReadableStream.+ // 2. Perform ! InitializeReadableStream(stream).+ let stream = allocate(cx.vm(), ReadableStream::new(cx.realm()));++ // 3. Let controller be a new ReadableByteStreamController.+ let controller = allocate(cx.vm(), ReadableByteStreamController::new());++ // 4. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm,+ // cancelAlgorithm, 0, undefined).+ set_up_readable_byte_stream_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ 0.0,+ None,+ )?;++ // 5. Return stream.+ Ok(stream)+}++// https://streams.spec.whatwg.org/#initialize-readable-stream+pub(crate) fn initialize_readable_stream(stream: Ref<ReadableStream>) {+ // 1. Set stream.[[state]] to "readable".+ stream.set_state(ReadableStreamState::Readable);++ // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.+ stream.set_reader(None);+ stream.set_stored_error(Value::UNDEFINED);++ // 3. Set stream.[[disturbed]] to false.+ stream.set_disturbed(false);+}++// https://streams.spec.whatwg.org/#is-readable-stream-locked+pub(crate) fn is_readable_stream_locked(stream: Ref<ReadableStream>) -> bool {+ // 1. If stream.[[reader]] is undefined, return false.+ // 2. Return true.+ stream.reader().is_some()+}++// https://streams.spec.whatwg.org/#readable-stream-from-iterable+pub(crate) fn readable_stream_from_iterable(+ cx: &CallContext,+ async_iterable: Value,+) -> WebIdlResult<Ref<ReadableStream>> {+ // 1. Let stream be undefined.+ // NB: The algorithms below refer to the stream, so it is created here.+ let stream = allocate(cx.vm(), ReadableStream::new(cx.realm()));++ // 2. Let iteratorRecord be ? GetIterator(asyncIterable, async).+ let iterator_record = get_iterator(cx.vm(), async_iterable, IteratorHint::Async)?;++ // 3. Let startAlgorithm be an algorithm that returns undefined.+ let start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 4. Let pullAlgorithm be the following steps:+ let pull_algorithm = PullAlgorithm::FromIterable {+ stream,+ iterator_record,+ };++ // 5. Let cancelAlgorithm be the following steps, given reason:+ let cancel_algorithm = CancelAlgorithm::FromIterable { iterator_record };++ // 6. Set stream to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0).+ create_readable_stream_with_existing_stream(+ cx,+ stream,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ Some(0.0),+ None,+ )+ .must();++ // 7. Return stream.+ Ok(stream)+}++/// The pullAlgorithm of ReadableStreamFromIterable, https://streams.spec.whatwg.org/#readable-stream-from-iterable+pub(crate) fn readable_stream_from_iterable_pull_algorithm(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ iterator_record: Gc<IteratorRecord>,+) -> WebIdlPromise {+ let vm = cx.vm();++ // 1. Let nextResult be IteratorNext(iteratorRecord).+ let next_result = iterator_next(vm, &iterator_record, None);++ // 2. If nextResult is an abrupt completion, return a promise rejected with nextResult.[[Value]].+ let next_result = match next_result {+ Ok(next_result) => next_result,+ Err(throw) => return create_rejected_promise(vm, cx.realm(), throw.value()),+ };++ // 3. Let nextPromise be a promise resolved with nextResult.[[Value]].+ let next_promise = create_resolved_promise(vm, cx.realm(), Value::from_object(next_result));++ // 4. Return the result of reacting to nextPromise with the following fulfillment steps, given iterResult:+ upon_fulfillment(vm, next_promise, stream, |cx, stream, iter_result| {+ let vm = cx.vm();++ // 1. If iterResult is not an Object, throw a TypeError.+ if !iter_result.is_object() {+ return Err(Exception::type_error("iterResult is not an Object"));+ }++ // 2. Let done be ? IteratorComplete(iterResult).+ let done = iterator_complete(vm, iter_result.as_object())?;++ let Some(ReadableStreamController::ReadableStreamDefaultController(controller)) = stream.controller() else {+ panic!("a stream from an iterable has a ReadableStreamDefaultController");+ };++ // 3. If done is true:+ if done {+ // 1. Perform ! ReadableStreamDefaultControllerClose(stream.[[controller]]).+ readable_stream_default_controller_close(&stream.context(vm), controller);+ }+ // 4. Otherwise:+ else {+ // 1. Let value be ? IteratorValue(iterResult).+ let value = iterator_value(vm, iter_result.as_object())?;++ // 2. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], value).+ readable_stream_default_controller_enqueue(&stream.context(vm), controller, value).must();+ }+ Ok(Value::UNDEFINED)+ })+}++/// The cancelAlgorithm of ReadableStreamFromIterable, https://streams.spec.whatwg.org/#readable-stream-from-iterable+pub(crate) fn readable_stream_from_iterable_cancel_algorithm(+ cx: &CallContext,+ iterator_record: Gc<IteratorRecord>,+ reason: Value,+) -> WebIdlPromise {+ let vm = cx.vm();++ // 1. Let iterator be iteratorRecord.[[Iterator]].+ let iterator = iterator_record.iterator();++ // 2. Let returnMethod be GetMethod(iterator, "return").+ let return_method = Value::from_object(iterator).get_method(vm, &vm.names.return_);++ // 3. If returnMethod is an abrupt completion, return a promise rejected with returnMethod.[[Value]].+ let return_method = match return_method {+ Ok(return_method) => return_method,+ Err(throw) => return create_rejected_promise(vm, cx.realm(), throw.value()),+ };++ // 4. If returnMethod.[[Value]] is undefined, return a promise resolved with undefined.+ let Some(return_method) = return_method else {+ return create_resolved_promise(vm, cx.realm(), Value::UNDEFINED);+ };++ // 5. Let returnResult be Call(returnMethod.[[Value]], iterator, « reason »).+ let return_result = call(+ vm,+ Value::from_object(return_method),+ Value::from_object(iterator),+ &[reason],+ );++ // 6. If returnResult is an abrupt completion, return a promise rejected with returnResult.[[Value]].+ let return_result = match return_result {+ Ok(return_result) => return_result,+ Err(throw) => return create_rejected_promise(vm, cx.realm(), throw.value()),+ };++ // 7. Let returnPromise be a promise resolved with returnResult.[[Value]].+ let return_promise = create_resolved_promise(vm, cx.realm(), return_result);++ // 8. Return the result of reacting to returnPromise with the following fulfillment steps, given iterResult:+ upon_fulfillment(vm, return_promise, (), |_, (), iter_result| {+ // 1. If iterResult is not an Object, throw a TypeError.+ if !iter_result.is_object() {+ return Err(Exception::type_error("iterResult is not an Object"));+ }++ // 2. Return undefined.+ Ok(Value::UNDEFINED)+ })+}++// https://streams.spec.whatwg.org/#readable-stream-add-read-into-request+pub(crate) fn readable_stream_add_read_into_request(stream: Ref<ReadableStream>, read_into_request: ReadIntoRequest) {+ // 1. Assert: stream.[[reader]] implements ReadableStreamBYOBReader.+ let Some(ReadableStreamReader::ReadableStreamBYOBReader(reader)) = stream.reader() else {+ panic!("the stream is locked to a ReadableStreamBYOBReader");+ };++ // 2. Assert: stream.[[state]] is "readable" or "closed".+ assert!(matches!(+ stream.state(),+ ReadableStreamState::Readable | ReadableStreamState::Closed+ ));++ // 3. Append readRequest to stream.[[reader]].[[readIntoRequests]].+ reader.append_read_into_request(read_into_request);+}++// https://streams.spec.whatwg.org/#readable-stream-add-read-request+pub(crate) fn readable_stream_add_read_request(stream: Ref<ReadableStream>, read_request: ReadRequest) {+ // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.+ let Some(ReadableStreamReader::ReadableStreamDefaultReader(reader)) = stream.reader() else {+ panic!("the stream is locked to a ReadableStreamDefaultReader");+ };++ // 2. Assert: stream.[[state]] is "readable".+ assert!(stream.state() == ReadableStreamState::Readable);++ // 3. Append readRequest to stream.[[reader]].[[readRequests]].+ reader.append_read_request(read_request);+}++// https://streams.spec.whatwg.org/#readable-stream-cancel+pub(crate) fn readable_stream_cancel(cx: &CallContext, stream: Ref<ReadableStream>, reason: Value) -> WebIdlPromise {+ let vm = cx.vm();++ // 1. Set stream.[[disturbed]] to true.+ stream.set_disturbed(true);++ // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.+ if stream.state() == ReadableStreamState::Closed {+ return create_resolved_promise(vm, cx.realm(), Value::UNDEFINED);+ }++ // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].+ if stream.state() == ReadableStreamState::Errored {+ return create_rejected_promise(vm, cx.realm(), stream.stored_error());+ }++ // 4. Perform ! ReadableStreamClose(stream).+ readable_stream_close(vm, stream);++ // 5. Let reader be stream.[[reader]].+ // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,+ if let Some(ReadableStreamReader::ReadableStreamBYOBReader(reader)) = stream.reader() {+ // 1. Let readIntoRequests be reader.[[readIntoRequests]].+ // 2. Set reader.[[readIntoRequests]] to an empty list.+ let read_into_requests = reader.take_read_into_requests(vm);++ // 3. For each readIntoRequest of readIntoRequests,+ for index in 0..read_into_requests.len() {+ // 1. Perform readIntoRequest’s close steps, given undefined.+ read_into_requests+ .get(index)+ .expect("the index is in bounds")+ .close_steps(vm, Value::UNDEFINED);+ }+ }++ // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).+ let source_cancel_promise = match stream.controller().expect("a stream that is set up has a controller") {+ ReadableStreamController::ReadableStreamDefaultController(controller) => {+ ReadableStreamDefaultController::cancel_steps(controller, cx, reason)+ }+ ReadableStreamController::ReadableByteStreamController(controller) => {+ ReadableByteStreamController::cancel_steps(controller, cx, reason)+ }+ };++ // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.+ upon_fulfillment(vm, source_cancel_promise, (), |_, (), _| Ok(Value::UNDEFINED))+}++// https://streams.spec.whatwg.org/#readable-stream-close+pub(crate) fn readable_stream_close(vm: &Vm, stream: Ref<ReadableStream>) {+ // 1. Assert: stream.[[state]] is "readable".+ assert!(stream.state() == ReadableStreamState::Readable);++ // 2. Set stream.[[state]] to "closed".+ stream.set_state(ReadableStreamState::Closed);+ complete_rendering_pending_stream(stream);++ // 3. Let reader be stream.[[reader]].+ // 4. If reader is undefined, return.+ let Some(reader) = stream.reader() else {+ return;+ };++ // 5. Resolve reader.[[closedPromise]] with undefined.+ let closed_promise = reader+ .generic()+ .closed_promise()+ .expect("a reader of a stream has a closed promise");+ resolve_promise(vm, closed_promise, Value::UNDEFINED);++ // 6. If reader implements ReadableStreamDefaultReader,+ if let ReadableStreamReader::ReadableStreamDefaultReader(reader) = reader {+ // 1. Let readRequests be reader.[[readRequests]].+ // 2. Set reader.[[readRequests]] to an empty list.+ let read_requests = reader.take_read_requests(vm);++ // 3. For each readRequest of readRequests,+ for index in 0..read_requests.len() {+ // 1. Perform readRequest’s close steps.+ read_requests+ .get(index)+ .expect("the index is in bounds")+ .close_steps(vm);+ }+ }+}++// https://streams.spec.whatwg.org/#readable-stream-error+pub(crate) fn readable_stream_error(vm: &Vm, stream: Ref<ReadableStream>, error: Value) {+ // 1. Assert: stream.[[state]] is "readable".+ assert!(stream.state() == ReadableStreamState::Readable);++ // 2. Set stream.[[state]] to "errored".+ stream.set_state(ReadableStreamState::Errored);+ complete_rendering_pending_stream(stream);++ // 3. Set stream.[[storedError]] to e.+ stream.set_stored_error(error);++ // 4. Let reader be stream.[[reader]].+ // 5. If reader is undefined, return.+ let Some(reader) = stream.reader() else {+ return;+ };++ // 6. Reject reader.[[closedPromise]] with e.+ let closed_promise = reader+ .generic()+ .closed_promise()+ .expect("a reader of a stream has a closed promise");+ reject_promise(vm, closed_promise, error);++ // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, closed_promise);++ match reader {+ // 8. If reader implements ReadableStreamDefaultReader,+ ReadableStreamReader::ReadableStreamDefaultReader(reader) => {+ // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).+ crate::streams::readable_stream_default_reader::readable_stream_default_reader_error_read_requests(+ vm, reader, error,+ );+ }+ // 9. Otherwise,+ ReadableStreamReader::ReadableStreamBYOBReader(reader) => {+ // 1. Assert: reader implements ReadableStreamBYOBReader.+ // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).+ crate::streams::readable_stream_byob_reader::readable_stream_byob_reader_error_read_into_requests(+ vm, reader, error,+ );+ }+ }+}++// https://streams.spec.whatwg.org/#readable-stream-fulfill-read-into-request+pub(crate) fn readable_stream_fulfill_read_into_request(+ vm: &Vm,+ stream: Ref<ReadableStream>,+ chunk: Value,+ done: bool,+) {+ // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.+ // 2. Let reader be stream.[[reader]].+ let Some(ReadableStreamReader::ReadableStreamBYOBReader(reader)) = stream.reader() else {+ panic!("the stream has a ReadableStreamBYOBReader");+ };++ // 3. Assert: reader.[[readIntoRequests]] is not empty.+ // 4. Let readIntoRequest be reader.[[readIntoRequests]][0].+ // 5. Remove readIntoRequest from reader.[[readIntoRequests]].+ let read_into_request = reader.take_first_read_into_request();++ // 6. If done is true, perform readIntoRequest’s close steps, given chunk.+ if done {+ read_into_request.close_steps(vm, chunk);+ }+ // 7. Otherwise, perform readIntoRequest’s chunk steps, given chunk.+ else {+ read_into_request.chunk_steps(vm, chunk);+ }+}++// https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request+pub(crate) fn readable_stream_fulfill_read_request(vm: &Vm, stream: Ref<ReadableStream>, chunk: Value, done: bool) {+ // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.+ // 2. Let reader be stream.[[reader]].+ let Some(ReadableStreamReader::ReadableStreamDefaultReader(reader)) = stream.reader() else {+ panic!("the stream has a ReadableStreamDefaultReader");+ };++ // 3. Assert: reader.[[readRequests]] is not empty.+ // 4. Let readRequest be reader.[[readRequests]][0].+ // 5. Remove readRequest from reader.[[readRequests]].+ let read_request = reader.take_first_read_request();++ // 6. If done is true, perform readRequest’s close steps.+ if done {+ read_request.close_steps(vm);+ }+ // 7. Otherwise, perform readRequest’s chunk steps, given chunk.+ else {+ read_request.chunk_steps(vm, chunk);+ }+}++// https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests+pub(crate) fn readable_stream_get_num_read_into_requests(stream: Ref<ReadableStream>) -> usize {+ // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.+ let Some(ReadableStreamReader::ReadableStreamBYOBReader(reader)) = stream.reader() else {+ panic!("the stream has a ReadableStreamBYOBReader");+ };++ // 2. Return stream.[[reader]].[[readIntoRequests]]'s size.+ reader.read_into_requests_len()+}++// https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests+pub(crate) fn readable_stream_get_num_read_requests(stream: Ref<ReadableStream>) -> usize {+ // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.+ let Some(ReadableStreamReader::ReadableStreamDefaultReader(reader)) = stream.reader() else {+ panic!("the stream has a ReadableStreamDefaultReader");+ };++ // 2. Return stream.[[reader]].[[readRequests]]'s size.+ reader.read_requests_len()+}++// https://streams.spec.whatwg.org/#readable-stream-has-byob-reader+pub(crate) fn readable_stream_has_byob_reader(stream: Ref<ReadableStream>) -> bool {+ // 1. Let reader be stream.[[reader]].+ // 2. If reader is undefined, return false.+ // 3. If reader implements ReadableStreamBYOBReader, return true.+ // 4. Return false.+ matches!(stream.reader(), Some(ReadableStreamReader::ReadableStreamBYOBReader(_)))+}++// https://streams.spec.whatwg.org/#readable-stream-has-default-reader+pub(crate) fn readable_stream_has_default_reader(stream: Ref<ReadableStream>) -> bool {+ // 1. Let reader be stream.[[reader]].+ // 2. If reader is undefined, return false.+ // 3. If reader implements ReadableStreamDefaultReader, return true.+ // 4. Return false.+ matches!(+ stream.reader(),+ Some(ReadableStreamReader::ReadableStreamDefaultReader(_))+ )+}++/// The composite reason of the cancel algorithms of a tee, ! CreateArrayFromList(« reason1, reason2 »).+pub(crate) fn create_array_from_list(cx: &CallContext, values: &[Value]) -> Value {+ Value::from_object(Array::create_from(cx.vm(), cx.realm(), values).upcast::<Object>())+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rsnew file mode 100644index 00000000000..a96484d7376--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_reader.rs@@ -0,0 +1,296 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamBYOBReader, https://streams.spec.whatwg.org/#byob-reader-class++use std::collections::VecDeque;++use libjs_rust::api::{GcRefCell, MarkedVec, Trace, Value, Vm};++use crate::bindings::conversions::{ArrayBufferView, BufferSource};+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_rejected_promise_from_exception, exception_value,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::read_request::ReadIntoRequest;+use crate::streams::readable_byte_stream_controller::readable_byte_stream_controller_pull_into;+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamReader, ReadableStreamState, is_readable_stream_locked,+};+use crate::streams::readable_stream_generic_reader::{+ ReadableStreamGenericReader, readable_stream_reader_generic_initialize, readable_stream_reader_generic_release,+};+use crate::streams::underlying_source::ReadableStreamController;++/// The dictionary ReadableStreamBYOBReaderReadOptions of Streams/ReadableStreamBYOBReader.idl, whose members the+/// bindings convert.+pub(crate) struct ReadableStreamBYOBReaderReadOptions {+ pub(crate) min: u64,+}++// https://streams.spec.whatwg.org/#readablestreambyobreader+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStreamBYOBReader {+ generic: ReadableStreamGenericReader,+ // https://streams.spec.whatwg.org/#readablestreambyobreader-readintorequests+ read_into_requests: GcRefCell<VecDeque<ReadIntoRequest>>,+}++impl Wrappable for ReadableStreamBYOBReader {}++impl ReadableStreamBYOBReader {+ pub(crate) fn new() -> Self {+ Self {+ generic: ReadableStreamGenericReader::default(),+ read_into_requests: GcRefCell::new(VecDeque::new()),+ }+ }++ pub(crate) fn generic(&self) -> &ReadableStreamGenericReader {+ &self.generic+ }++ pub(crate) fn append_read_into_request(&self, read_into_request: ReadIntoRequest) {+ self.read_into_requests.borrow_mut().push_back(read_into_request);+ }++ /// Takes the reader's [[readIntoRequests]], leaving an empty list.+ pub(crate) fn take_read_into_requests<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, ReadIntoRequest> {+ let read_into_requests = MarkedVec::with_capacity(vm, self.read_into_requests.borrow().len());+ for read_into_request in self.read_into_requests.borrow().iter() {+ read_into_requests.push(read_into_request.clone());+ }+ self.read_into_requests.borrow_mut().clear();+ read_into_requests+ }++ /// Removes the first of the reader's [[readIntoRequests]], which are not empty.+ pub(crate) fn take_first_read_into_request(&self) -> ReadIntoRequest {+ self.read_into_requests+ .borrow_mut()+ .pop_front()+ .expect("the reader has a read-into request")+ }++ pub(crate) fn read_into_requests_len(&self) -> usize {+ self.read_into_requests.borrow().len()+ }++ pub(crate) fn read_into_requests_is_empty(&self) -> bool {+ self.read_into_requests.borrow().is_empty()+ }++ // https://streams.spec.whatwg.org/#byob-reader-constructor+ pub(crate) fn construct(cx: &mut CallContext, stream: Ref<ReadableStream>) -> WebIdlResult<Ref<Self>> {+ let reader = allocate(cx.vm(), Self::new());++ // 1. Perform ? SetUpReadableStreamBYOBReader(this, stream).+ set_up_readable_stream_byob_reader(cx, reader, stream)?;+ Ok(reader)+ }++ // https://streams.spec.whatwg.org/#generic-reader-closed+ pub(crate) fn closed(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ self.generic.closed()+ }++ // https://streams.spec.whatwg.org/#byob-reader-read+ pub(crate) fn read(+ this: &Ref<Self>,+ cx: &mut CallContext,+ view: ArrayBufferView,+ options: ReadableStreamBYOBReaderReadOptions,+ ) -> WebIdlResult<WebIdlPromise> {+ let cx = &this.generic.context(cx.vm());+ let vm = cx.vm();+ let extent = BufferSource::from(view).extent();++ // 1. If view.[[ByteLength]] is 0, return a promise rejected with a TypeError exception.+ if extent.byte_length == 0 {+ let exception = Exception::type_error("Cannot read in an empty buffer");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }++ // 2. If view.[[ViewedArrayBuffer]].[[ByteLength]] is 0, return a promise rejected with a TypeError+ // exception.+ if extent.buffer.byte_length() == 0 {+ let exception = Exception::type_error("Cannot read in an empty buffer");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }++ // 3. If ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is true, return a promise rejected with a TypeError+ // exception.+ if extent.buffer.is_detached() {+ let exception = Exception::type_error("Cannot read in a detached buffer");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }++ // 4. If options["min"] is 0, return a promise rejected with a TypeError exception.+ if options.min == 0 {+ let exception = Exception::type_error("options[\"min\"] cannot have a value of 0.");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }++ match view {+ // 5. If view has a [[TypedArrayName]] internal slot,+ ArrayBufferView::TypedArray(_) => {+ // 1. If options["min"] > view.[[ArrayLength]], return a promise rejected with a RangeError exception.+ let array_length = extent.byte_length / extent.element_size;+ if options.min > array_length as u64 {+ let exception =+ Exception::range_error("options[\"min\"] cannot be larger than the length of the view.");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }+ }+ // 6. Otherwise (i.e., it is a DataView),+ ArrayBufferView::DataView(_) => {+ // 1. If options["min"] > view.[[ByteLength]], return a promise rejected with a RangeError exception.+ if options.min > extent.byte_length as u64 {+ let exception =+ Exception::range_error("options[\"min\"] cannot be larger than the length of the view.");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }+ }+ }++ // 7. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.+ if this.generic.stream().is_none() {+ let exception = Exception::type_error("Cannot read from an empty stream");+ return Ok(create_rejected_promise_from_exception(vm, cx.realm(), exception));+ }++ // 8. Let promise be a new promise.+ let promise = create_promise(vm, cx.realm());++ // 9. Let readIntoRequest be a new read-into request with the following items:+ // chunk steps, given chunk+ // 1. Resolve promise with «[ "value" → chunk, "done" → false ]».+ // close steps, given chunk+ // 1. Resolve promise with «[ "value" → chunk, "done" → true ]».+ // error steps, given e+ // 1. Reject promise with e.+ let read_into_request = ReadIntoRequest::BYOBReaderRead(promise);++ // 10. Perform ! ReadableStreamBYOBReaderRead(this, view, options["min"], readIntoRequest).+ readable_stream_byob_reader_read(vm, *this, view, options.min, read_into_request);++ // 11. Return promise.+ Ok(promise)+ }++ // https://streams.spec.whatwg.org/#byob-reader-release-lock+ pub(crate) fn release_lock(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. If this.[[stream]] is undefined, return.+ if this.generic.stream().is_none() {+ return Ok(());+ }++ // 2. Perform ! ReadableStreamBYOBReaderRelease(this).+ readable_stream_byob_reader_release(cx.vm(), *this);+ Ok(())+ }++ // https://streams.spec.whatwg.org/#generic-reader-cancel+ pub(crate) fn cancel(this: &Ref<Self>, cx: &mut CallContext, reason: Option<Value>) -> WebIdlResult<WebIdlPromise> {+ let reader = ReadableStreamReader::ReadableStreamBYOBReader(*this);+ Ok(ReadableStreamGenericReader::cancel(cx.vm(), reader, reason))+ }+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreadererrorreadintorequests+pub(crate) fn readable_stream_byob_reader_error_read_into_requests(+ vm: &Vm,+ reader: Ref<ReadableStreamBYOBReader>,+ error: Value,+) {+ // 1. Let readIntoRequests be reader.[[readIntoRequests]].+ // 2. Set reader.[[readIntoRequests]] to a new empty list.+ let read_into_requests = reader.take_read_into_requests(vm);++ // 3. For each readIntoRequest of readIntoRequests,+ for index in 0..read_into_requests.len() {+ // 1. Perform readIntoRequest’s error steps, given e.+ read_into_requests+ .get(index)+ .expect("the index is in bounds")+ .error_steps(vm, error);+ }+}++// https://streams.spec.whatwg.org/#readable-stream-byob-reader-read+pub(crate) fn readable_stream_byob_reader_read(+ vm: &Vm,+ reader: Ref<ReadableStreamBYOBReader>,+ view: ArrayBufferView,+ min: u64,+ read_into_request: ReadIntoRequest,+) {+ let cx = &reader.generic.context(vm);++ // 1. Let stream be reader.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = reader.generic.stream().expect("a reader that reads has a stream");++ // 3. Set stream.[[disturbed]] to true.+ stream.set_disturbed(true);++ // 4. If stream.[[state]] is "errored", perform readIntoRequest’s error steps given stream.[[storedError]].+ if stream.state() == ReadableStreamState::Errored {+ read_into_request.error_steps(vm, stream.stored_error());+ }+ // 5. Otherwise, perform ! ReadableByteStreamControllerPullInto(stream.[[controller]], view, min, readIntoRequest).+ else {+ let Some(ReadableStreamController::ReadableByteStreamController(controller)) = stream.controller() else {+ panic!("a stream with a BYOB reader has a ReadableByteStreamController");+ };+ readable_byte_stream_controller_pull_into(cx, controller, view, min, read_into_request);+ }+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreaderrelease+pub(crate) fn readable_stream_byob_reader_release(vm: &Vm, reader: Ref<ReadableStreamBYOBReader>) {+ let realm = reader.generic.closed_promise_realm();++ // 1. Perform ! ReadableStreamReaderGenericRelease(reader).+ readable_stream_reader_generic_release(vm, ReadableStreamReader::ReadableStreamBYOBReader(reader));++ // 2. Let e be a new TypeError exception.+ let exception = exception_value(vm, realm, Exception::type_error("Reader has been released"));++ // 3. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).+ readable_stream_byob_reader_error_read_into_requests(vm, reader, exception);+}++// https://streams.spec.whatwg.org/#set-up-readable-stream-byob-reader+pub(crate) fn set_up_readable_stream_byob_reader(+ cx: &CallContext,+ reader: Ref<ReadableStreamBYOBReader>,+ stream: Ref<ReadableStream>,+) -> WebIdlResult<()> {+ // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.+ if is_readable_stream_locked(stream) {+ return Err(Exception::type_error("Cannot create stream reader for a locked stream"));+ }++ // 2. If stream.[[controller]] does not implement ReadableByteStreamController, throw a TypeError exception.+ if !matches!(+ stream.controller(),+ Some(ReadableStreamController::ReadableByteStreamController(_))+ ) {+ return Err(Exception::type_error(+ "BYOB reader cannot set up reader from non-byte stream",+ ));+ }++ // 3. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).+ readable_stream_reader_generic_initialize(cx, ReadableStreamReader::ReadableStreamBYOBReader(reader), stream);++ // 4. Set reader.[[readIntoRequests]] to a new empty list.+ reader.read_into_requests.borrow_mut().clear();+ Ok(())+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_request.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_request.rsnew file mode 100644index 00000000000..24bfe043df1--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_byob_request.rs@@ -0,0 +1,107 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamBYOBRequest, https://streams.spec.whatwg.org/#rs-byob-request-class++use core::cell::Cell;++use libjs_rust::api::{Gc, Trace, TypedArrayBase};++use crate::bindings::conversions::{ArrayBufferView, BufferSource};+use crate::bindings::interface::{Ref, Wrappable};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::readable_byte_stream_controller::{+ ReadableByteStreamController, readable_byte_stream_controller_respond,+ readable_byte_stream_controller_respond_with_new_view,+};++// https://streams.spec.whatwg.org/#readablestreambyobrequest+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStreamBYOBRequest {+ // https://streams.spec.whatwg.org/#readablestreambyobrequest-controller+ controller: Cell<Option<Ref<ReadableByteStreamController>>>,+ // https://streams.spec.whatwg.org/#readablestreambyobrequest-view+ view: Cell<Option<Gc<TypedArrayBase>>>,+}++impl Wrappable for ReadableStreamBYOBRequest {}++impl ReadableStreamBYOBRequest {+ pub(crate) fn new() -> Self {+ Self {+ controller: Cell::new(None),+ view: Cell::new(None),+ }+ }++ pub(crate) fn controller(&self) -> Option<Ref<ReadableByteStreamController>> {+ self.controller.get()+ }++ pub(crate) fn set_controller(&self, controller: Option<Ref<ReadableByteStreamController>>) {+ self.controller.set(controller);+ }++ /// The request's [[view]], a Uint8Array.+ pub(crate) fn current_view(&self) -> Option<Gc<TypedArrayBase>> {+ self.view.get()+ }++ pub(crate) fn set_view(&self, view: Option<Gc<TypedArrayBase>>) {+ self.view.set(view);+ }++ // https://streams.spec.whatwg.org/#rs-byob-request-view+ pub(crate) fn view(&self, _: &mut CallContext) -> WebIdlResult<Option<Gc<TypedArrayBase>>> {+ Ok(self.current_view())+ }++ // https://streams.spec.whatwg.org/#rs-byob-request-respond+ pub(crate) fn respond(this: &Ref<Self>, cx: &mut CallContext, bytes_written: u64) -> WebIdlResult<()> {+ // 1. If this.[[controller]] is undefined, throw a TypeError exception.+ let Some(controller) = this.controller() else {+ return Err(Exception::type_error("Controller is undefined"));+ };++ // 2. If ! IsDetachedBuffer(this.[[view]].[[ArrayBuffer]]) is true, throw a TypeError exception.+ let view = this+ .current_view()+ .expect("a BYOB request with a controller has a view");+ if view.viewed_array_buffer().is_detached() {+ return Err(Exception::type_error("Unable to respond to detached ArrayBuffer"));+ }++ // 3. Assert: this.[[view]].[[ByteLength]] > 0.+ assert!(BufferSource::TypedArray(view).extent().byte_length > 0);++ // 4. Assert: this.[[view]].[[ViewedArrayBuffer]].[[ByteLength]] > 0.+ assert!(view.viewed_array_buffer().byte_length() > 0);++ // 5. Perform ? ReadableByteStreamControllerRespond(this.[[controller]], bytesWritten).+ readable_byte_stream_controller_respond(cx, controller, bytes_written)+ }++ // https://streams.spec.whatwg.org/#rs-byob-request-respond-with-new-view+ pub(crate) fn respond_with_new_view(+ this: &Ref<Self>,+ cx: &mut CallContext,+ view: ArrayBufferView,+ ) -> WebIdlResult<()> {+ // 1. If this.[[controller]] is undefined, throw a TypeError exception.+ let Some(controller) = this.controller() else {+ return Err(Exception::type_error("Controller is undefined"));+ };++ // 2. If ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is true, throw a TypeError exception.+ if BufferSource::from(view).extent().buffer.is_detached() {+ return Err(Exception::type_error("Unable to respond with a detached ArrayBuffer"));+ }++ // 3. Return ? ReadableByteStreamControllerRespondWithNewView(this.[[controller]], view).+ readable_byte_stream_controller_respond_with_new_view(cx, controller, view)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_controller.rsnew file mode 100644index 00000000000..aa410958b31--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_controller.rs@@ -0,0 +1,615 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamDefaultController, https://streams.spec.whatwg.org/#rs-default-controller-class, and its abstract+//! operations, https://streams.spec.whatwg.org/#rs-default-controller-abstract-ops++use core::cell::Cell;++use libjs_rust::api::{GcRefCell, Throw, Trace, Value, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{WebIdlPromise, create_resolved_promise, exception_value, react_to_promise};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::algorithms::{CancelAlgorithm, PullAlgorithm, SizeAlgorithm, StartAlgorithm};+use crate::streams::queue_with_sizes::QueueWithSizes;+use crate::streams::read_request::ReadRequest;+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamState, complete_rendering_pending_stream, is_readable_stream_locked,+ readable_stream_add_read_request, readable_stream_close, readable_stream_error,+ readable_stream_fulfill_read_request, readable_stream_get_num_read_requests,+};+use crate::streams::underlying_source::{ReadableStreamController, UnderlyingSource};++// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStreamDefaultController {+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-cancelalgorithm+ cancel_algorithm: GcRefCell<Option<CancelAlgorithm>>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-closerequested+ close_requested: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullagain+ pull_again: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullalgorithm+ pull_algorithm: GcRefCell<Option<PullAlgorithm>>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pulling+ pulling: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-queue+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-queuetotalsize+ queue: QueueWithSizes,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-started+ started: Cell<bool>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-strategyhwm+ #[gc(untraced)]+ strategy_hwm: Cell<f64>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-strategysizealgorithm+ strategy_size_algorithm: GcRefCell<Option<SizeAlgorithm>>,+ // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-stream+ stream: Cell<Option<Ref<ReadableStream>>>,+}++impl Wrappable for ReadableStreamDefaultController {}++impl ReadableStreamDefaultController {+ pub(crate) fn new() -> Self {+ Self {+ cancel_algorithm: GcRefCell::new(None),+ close_requested: Cell::new(false),+ pull_again: Cell::new(false),+ pull_algorithm: GcRefCell::new(None),+ pulling: Cell::new(false),+ queue: QueueWithSizes::default(),+ started: Cell::new(false),+ strategy_hwm: Cell::new(0.0),+ strategy_size_algorithm: GcRefCell::new(None),+ stream: Cell::new(None),+ }+ }++ pub(crate) fn close_requested(&self) -> bool {+ self.close_requested.get()+ }++ /// The controller's [[stream]], which it has once it is set up.+ pub(crate) fn stream(&self) -> Ref<ReadableStream> {+ self.stream.get().expect("a controller that is set up has a stream")+ }++ /// The controller's [[pullAlgorithm]], which it has until its algorithms are cleared.+ pub(crate) fn pull_algorithm(&self) -> Option<PullAlgorithm> {+ self.pull_algorithm.borrow().clone()+ }++ /// The controller's [[cancelAlgorithm]], which it has until its algorithms are cleared.+ pub(crate) fn cancel_algorithm(&self) -> Option<CancelAlgorithm> {+ self.cancel_algorithm.borrow().clone()+ }++ /// The controller's [[strategySizeAlgorithm]], which it has until its algorithms are cleared.+ pub(crate) fn strategy_size_algorithm(&self) -> Option<SizeAlgorithm> {+ self.strategy_size_algorithm.borrow().clone()+ }++ // https://streams.spec.whatwg.org/#rs-default-controller-desired-size+ pub(crate) fn desired_size(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<Option<f64>> {+ // 1. Return ! ReadableStreamDefaultControllerGetDesiredSize(this).+ Ok(readable_stream_default_controller_get_desired_size(*this))+ }++ // https://streams.spec.whatwg.org/#rs-default-controller-close+ pub(crate) fn close(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false, throw a TypeError exception.+ if !readable_stream_default_controller_can_close_or_enqueue(*this) {+ return Err(Exception::type_error("Stream is not closable"));+ }++ // 2. Perform ! ReadableStreamDefaultControllerClose(this).+ readable_stream_default_controller_close(cx, *this);+ Ok(())+ }++ // https://streams.spec.whatwg.org/#rs-default-controller-enqueue+ pub(crate) fn enqueue(this: &Ref<Self>, cx: &mut CallContext, chunk: Option<Value>) -> WebIdlResult<()> {+ // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false, throw a TypeError exception.+ if !readable_stream_default_controller_can_close_or_enqueue(*this) {+ return Err(Exception::type_error("Cannot enqueue chunk to stream"));+ }++ // 2. Perform ? ReadableStreamDefaultControllerEnqueue(this, chunk).+ readable_stream_default_controller_enqueue(cx, *this, chunk.unwrap_or(Value::UNDEFINED))+ }++ // https://streams.spec.whatwg.org/#rs-default-controller-error+ pub(crate) fn error(this: &Ref<Self>, cx: &mut CallContext, e: Option<Value>) -> WebIdlResult<()> {+ // 1. Perform ! ReadableStreamDefaultControllerError(this, e).+ readable_stream_default_controller_error(cx, *this, e.unwrap_or(Value::UNDEFINED));+ Ok(())+ }++ // https://streams.spec.whatwg.org/#rs-default-controller-private-cancel+ pub(crate) fn cancel_steps(this: Ref<Self>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Perform ! ResetQueue(this).+ this.queue.reset_queue();++ // 2. Let result be the result of performing this.[[cancelAlgorithm]], passing reason.+ let cancel_algorithm = this+ .cancel_algorithm()+ .expect("a controller that cancels has a cancel algorithm");+ let result = cancel_algorithm.run(&this.stream().context(cx.vm()), reason);++ // 3. Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).+ readable_stream_default_controller_clear_algorithms(this);++ // 4. Return result.+ result+ }++ // https://streams.spec.whatwg.org/#rs-default-controller-private-pull+ pub(crate) fn pull_steps(this: Ref<Self>, vm: &Vm, read_request: ReadRequest) {+ // 1. Let stream be this.[[stream]].+ let stream = this.stream();+ let cx = &stream.context(vm);++ // 2. If this.[[queue]] is not empty,+ if !this.queue.is_empty() {+ // 1. Let chunk be ! DequeueValue(this).+ let chunk = this.queue.dequeue_value();++ // 2. If this.[[closeRequested]] is true and this.[[queue]] is empty,+ if this.close_requested() && this.queue.is_empty() {+ // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).+ readable_stream_default_controller_clear_algorithms(this);++ // 2. Perform ! ReadableStreamClose(stream).+ readable_stream_close(vm, stream);+ }+ // 3. Otherwise, perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).+ else {+ readable_stream_default_controller_call_pull_if_needed(cx, this);+ }++ // 4. Perform readRequest’s chunk steps, given chunk.+ read_request.chunk_steps(vm, chunk);+ }+ // 3. Otherwise,+ else {+ // 1. Perform ! ReadableStreamAddReadRequest(stream, readRequest).+ readable_stream_add_read_request(stream, read_request);++ // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).+ readable_stream_default_controller_call_pull_if_needed(cx, this);+ }+ }++ // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultcontroller-releasesteps+ pub(crate) fn release_steps(_: Ref<Self>) {+ // 1. Return.+ }+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed+pub(crate) fn readable_stream_default_controller_call_pull_if_needed(+ cx: &CallContext,+ controller: Ref<ReadableStreamDefaultController>,+) {+ let vm = cx.vm();++ // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).+ let should_pull = readable_stream_default_controller_should_call_pull(controller);++ // 2. If shouldPull is false, return.+ if !should_pull {+ return;+ }++ // 3. If controller.[[pulling]] is true,+ if controller.pulling.get() {+ // 1. Set controller.[[pullAgain]] to true.+ controller.pull_again.set(true);++ // 2. Return.+ return;+ }++ // 4. Assert: controller.[[pullAgain]] is false.+ assert!(!controller.pull_again.get());++ // 5. Set controller.[[pulling]] to true.+ controller.pulling.set(true);++ // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].+ let pull_algorithm = controller+ .pull_algorithm()+ .expect("a controller that pulls has a pull algorithm");+ let pull_promise = pull_algorithm.run(&controller.stream().context(vm));++ react_to_promise(+ vm,+ pull_promise,+ controller,+ // 7. Upon fulfillment of pullPromise,+ Some(|cx, controller, _| {+ // 1. Set controller.[[pulling]] to false.+ controller.pulling.set(false);++ // 2. If controller.[[pullAgain]] is true,+ if controller.pull_again.get() {+ // 1. Set controller.[[pullAgain]] to false.+ controller.pull_again.set(false);++ // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).+ readable_stream_default_controller_call_pull_if_needed(cx, controller);+ }+ Ok(Value::UNDEFINED)+ }),+ // 8. Upon rejection of pullPromise with reason e,+ Some(|cx, controller, error| {+ // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).+ readable_stream_default_controller_error(cx, controller, error);+ Ok(Value::UNDEFINED)+ }),+ );+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull+pub(crate) fn readable_stream_default_controller_should_call_pull(+ controller: Ref<ReadableStreamDefaultController>,+) -> bool {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.+ if !readable_stream_default_controller_can_close_or_enqueue(controller) {+ return false;+ }++ // 3. If controller.[[started]] is false, return false.+ if !controller.started.get() {+ return false;+ }++ // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.+ if is_readable_stream_locked(stream) && readable_stream_get_num_read_requests(stream) > 0 {+ return true;+ }++ // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).+ // 6. Assert: desiredSize is not null.+ let desired_size =+ readable_stream_default_controller_get_desired_size(controller).expect("the desired size is not null");++ // 7. If desiredSize > 0, return true.+ if desired_size > 0.0 {+ return true;+ }++ // 8. Return false.+ false+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms+pub(crate) fn readable_stream_default_controller_clear_algorithms(controller: Ref<ReadableStreamDefaultController>) {+ // 1. Set controller.[[pullAlgorithm]] to undefined.+ *controller.pull_algorithm.borrow_mut() = None;++ // 2. Set controller.[[cancelAlgorithm]] to undefined.+ *controller.cancel_algorithm.borrow_mut() = None;++ // 3. Set controller.[[strategySizeAlgorithm]] to undefined.+ *controller.strategy_size_algorithm.borrow_mut() = None;+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-close+pub(crate) fn readable_stream_default_controller_close(+ cx: &CallContext,+ controller: Ref<ReadableStreamDefaultController>,+) {+ // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.+ if !readable_stream_default_controller_can_close_or_enqueue(controller) {+ return;+ }++ // 2. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 3. Set controller.[[closeRequested]] to true.+ controller.close_requested.set(true);+ complete_rendering_pending_stream(stream);++ // 4. If controller.[[queue]] is empty,+ if controller.queue.is_empty() {+ // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).+ readable_stream_default_controller_clear_algorithms(controller);++ // 2. Perform ! ReadableStreamClose(stream).+ readable_stream_close(cx.vm(), stream);+ }+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue+pub(crate) fn readable_stream_default_controller_enqueue(+ cx: &CallContext,+ controller: Ref<ReadableStreamDefaultController>,+ chunk: Value,+) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.+ if !readable_stream_default_controller_can_close_or_enqueue(controller) {+ return Ok(());+ }++ // 2. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform+ // ! ReadableStreamFulfillReadRequest(stream, chunk, false).+ if is_readable_stream_locked(stream) && readable_stream_get_num_read_requests(stream) > 0 {+ readable_stream_fulfill_read_request(vm, stream, chunk, false);+ }+ // 4. Otherwise,+ else {+ // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and+ // interpreting the result as a completion record.+ let strategy_size_algorithm = controller+ .strategy_size_algorithm()+ .expect("a controller that enqueues has a strategy size algorithm");+ let result = strategy_size_algorithm.run(&stream.context(vm), chunk);++ // 2. If result is an abrupt completion,+ let chunk_size = match result {+ Err(throw) => {+ // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).+ readable_stream_default_controller_error(cx, controller, throw.value());++ // 2. Return result.+ return Err(Exception::Thrown(throw));+ }+ // 3. Let chunkSize be result.[[Value]].+ Ok(chunk_size) => chunk_size,+ };++ // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).+ let enqueue_result = controller.queue.enqueue_value_with_size(chunk, chunk_size);++ // 5. If enqueueResult is an abrupt completion,+ if let Err(exception) = enqueue_result {+ let error = exception_value(vm, cx.realm(), exception);++ // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).+ readable_stream_default_controller_error(cx, controller, error);++ // 2. Return enqueueResult.+ return Err(Exception::Thrown(Throw::new(error)));+ }+ }++ // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).+ readable_stream_default_controller_call_pull_if_needed(cx, controller);+ Ok(())+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-error+pub(crate) fn readable_stream_default_controller_error(+ cx: &CallContext,+ controller: Ref<ReadableStreamDefaultController>,+ error: Value,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If stream.[[state]] is not "readable", return.+ if stream.state() != ReadableStreamState::Readable {+ return;+ }++ // 3. Perform ! ResetQueue(controller).+ controller.queue.reset_queue();++ // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).+ readable_stream_default_controller_clear_algorithms(controller);++ // 5. Perform ! ReadableStreamError(stream, e).+ readable_stream_error(cx.vm(), stream, error);+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size+pub(crate) fn readable_stream_default_controller_get_desired_size(+ controller: Ref<ReadableStreamDefaultController>,+) -> Option<f64> {+ // 1. Let state be controller.[[stream]].[[state]].+ let state = controller.stream().state();++ // 2. If state is "errored", return null.+ if state == ReadableStreamState::Errored {+ return None;+ }++ // 3. If state is "closed", return 0.+ if state == ReadableStreamState::Closed {+ return Some(0.0);+ }++ // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].+ Some(controller.strategy_hwm.get() - controller.queue.total_size())+}++// https://streams.spec.whatwg.org/#rs-default-controller-has-backpressure+pub(crate) fn readable_stream_default_controller_has_backpressure(+ controller: Ref<ReadableStreamDefaultController>,+) -> bool {+ // 1. If ! ReadableStreamDefaultControllerShouldCallPull(controller) is true, return false.+ if readable_stream_default_controller_should_call_pull(controller) {+ return false;+ }++ // 2. Otherwise, return true.+ true+}++// https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue+pub(crate) fn readable_stream_default_controller_can_close_or_enqueue(+ controller: Ref<ReadableStreamDefaultController>,+) -> bool {+ // 1. Let state be controller.[[stream]].[[state]].+ let state = controller.stream().state();++ // 2. If controller.[[closeRequested]] is false and state is "readable", return true.+ if !controller.close_requested() && state == ReadableStreamState::Readable {+ return true;+ }++ // 3. Otherwise, return false.+ false+}++// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller+#[allow(clippy::too_many_arguments, reason = "the abstract operation takes these arguments")]+pub(crate) fn set_up_readable_stream_default_controller(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ controller: Ref<ReadableStreamDefaultController>,+ start_algorithm: StartAlgorithm,+ pull_algorithm: PullAlgorithm,+ cancel_algorithm: CancelAlgorithm,+ high_water_mark: f64,+ size_algorithm: SizeAlgorithm,+) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Assert: stream.[[controller]] is undefined.+ assert!(stream.controller().is_none());++ // 2. Set controller.[[stream]] to stream.+ controller.stream.set(Some(stream));++ // 3. Perform ! ResetQueue(controller).+ controller.queue.reset_queue();++ // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and+ // controller.[[pulling]] to false.+ controller.started.set(false);+ controller.close_requested.set(false);+ controller.pull_again.set(false);+ controller.pulling.set(false);++ // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.+ *controller.strategy_size_algorithm.borrow_mut() = Some(size_algorithm);+ controller.strategy_hwm.set(high_water_mark);++ // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.+ *controller.pull_algorithm.borrow_mut() = Some(pull_algorithm);++ // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.+ *controller.cancel_algorithm.borrow_mut() = Some(cancel_algorithm);++ // 8. Set stream.[[controller]] to controller.+ stream.set_controller(Some(ReadableStreamController::ReadableStreamDefaultController(+ controller,+ )));++ // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)+ let start_result = start_algorithm.run()?;++ // 10. Let startPromise be a promise resolved with startResult.+ let start_promise = create_resolved_promise(vm, cx.realm(), start_result);++ react_to_promise(+ vm,+ start_promise,+ controller,+ // 11. Upon fulfillment of startPromise,+ Some(|cx, controller, _| {+ // 1. Set controller.[[started]] to true.+ controller.started.set(true);++ // 2. Assert: controller.[[pulling]] is false.+ assert!(!controller.pulling.get());++ // 3. Assert: controller.[[pullAgain]] is false.+ assert!(!controller.pull_again.get());++ // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).+ readable_stream_default_controller_call_pull_if_needed(cx, controller);+ Ok(Value::UNDEFINED)+ }),+ // 12. Upon rejection of startPromise with reason r,+ Some(|cx, controller, reason| {+ // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).+ readable_stream_default_controller_error(cx, controller, reason);+ Ok(Value::UNDEFINED)+ }),+ );+ Ok(())+}++// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source+pub(crate) fn set_up_readable_stream_default_controller_from_underlying_source(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ underlying_source: Value,+ underlying_source_dict: UnderlyingSource,+ high_water_mark: f64,+ size_algorithm: SizeAlgorithm,+) -> WebIdlResult<()> {+ // 1. Let controller be a new ReadableStreamDefaultController.+ let controller = allocate(cx.vm(), ReadableStreamDefaultController::new());++ // 2. Let startAlgorithm be an algorithm that returns undefined.+ let mut start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut pull_algorithm = PullAlgorithm::ReturnsResolvedUndefined;++ // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut cancel_algorithm = CancelAlgorithm::ReturnsResolvedUndefined;++ // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of+ // invoking underlyingSourceDict["start"] with argument list « controller » and callback this value+ // underlyingSource.+ if let Some(start) = underlying_source_dict.start {+ start_algorithm = StartAlgorithm::Callback {+ start,+ this_value: underlying_source,+ controller: ReadableStreamController::ReadableStreamDefaultController(controller).to_js(cx),+ };+ }++ // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of+ // invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value+ // underlyingSource.+ if let Some(pull) = underlying_source_dict.pull {+ pull_algorithm = PullAlgorithm::Callback {+ pull,+ underlying_source,+ controller: ReadableStreamController::ReadableStreamDefaultController(controller),+ };+ }++ // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument+ // reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and+ // callback this value underlyingSource.+ if let Some(cancel) = underlying_source_dict.cancel {+ cancel_algorithm = CancelAlgorithm::Callback {+ cancel,+ this_value: underlying_source,+ };+ }++ // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm,+ // cancelAlgorithm, highWaterMark, sizeAlgorithm).+ set_up_readable_stream_default_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ pull_algorithm,+ cancel_algorithm,+ high_water_mark,+ size_algorithm,+ )+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rsnew file mode 100644index 00000000000..1ac2139480e--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_default_reader.rs@@ -0,0 +1,355 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamDefaultReader, https://streams.spec.whatwg.org/#default-reader-class++use std::collections::VecDeque;++use core::cell::Cell;++use libjs_rust::api::{+ EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, MarkedVec, Realm, Trace, TypedArrayBase, TypedArrayKind,+ Value, Vm,+};++use crate::bindings::conversions::BufferSource;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_rejected_promise_from_exception, exception_value,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::cpp::{CppBytesSteps, CppReadRequest, CppValueSteps};+use crate::streams::read_request::ReadRequest;+use crate::streams::readable_byte_stream_controller::ReadableByteStreamController;+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamReader, ReadableStreamState, is_readable_stream_locked,+};+use crate::streams::readable_stream_default_controller::ReadableStreamDefaultController;+use crate::streams::readable_stream_generic_reader::{+ ReadableStreamGenericReader, readable_stream_reader_generic_initialize, readable_stream_reader_generic_release,+};+use crate::streams::readable_stream_pipe_to::PipeToRef;+use crate::streams::underlying_source::ReadableStreamController;++/// The dictionary ReadableStreamReadResult of Streams/ReadableStreamDefaultReader.idl, which the bindings convert.+/// NB: The read requests resolve their promises with iterator result objects, as LibWeb's C++ does, so nothing+/// creates this.+pub(crate) struct ReadableStreamReadResult {+ pub(crate) done: Option<bool>,+ pub(crate) value: Option<Value>,+}++// https://streams.spec.whatwg.org/#readablestreamdefaultreader+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStreamDefaultReader {+ generic: ReadableStreamGenericReader,+ // https://streams.spec.whatwg.org/#readablestreamdefaultreader-readrequests+ read_requests: GcRefCell<VecDeque<ReadRequest>>,+ /// The pipe that reads from the reader's stream, which the reader keeps alive.+ pipe_to: Cell<Option<PipeToRef>>,+}++impl Wrappable for ReadableStreamDefaultReader {}++impl ReadableStreamDefaultReader {+ pub(crate) fn new() -> Self {+ Self {+ generic: ReadableStreamGenericReader::default(),+ read_requests: GcRefCell::new(VecDeque::new()),+ pipe_to: Cell::new(None),+ }+ }++ pub(crate) fn set_pipe_to(&self, pipe_to: Option<PipeToRef>) {+ self.pipe_to.set(pipe_to);+ }++ pub(crate) fn generic(&self) -> &ReadableStreamGenericReader {+ &self.generic+ }++ pub(crate) fn append_read_request(&self, read_request: ReadRequest) {+ self.read_requests.borrow_mut().push_back(read_request);+ }++ /// Takes the reader's [[readRequests]], leaving an empty list.+ pub(crate) fn take_read_requests<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, ReadRequest> {+ let read_requests = MarkedVec::with_capacity(vm, self.read_requests.borrow().len());+ for read_request in self.read_requests.borrow().iter() {+ read_requests.push(read_request.clone());+ }+ self.read_requests.borrow_mut().clear();+ read_requests+ }++ /// Removes the first of the reader's [[readRequests]], which are not empty.+ pub(crate) fn take_first_read_request(&self) -> ReadRequest {+ self.read_requests+ .borrow_mut()+ .pop_front()+ .expect("the reader has a read request")+ }++ pub(crate) fn read_requests_len(&self) -> usize {+ self.read_requests.borrow().len()+ }++ pub(crate) fn read_requests_is_empty(&self) -> bool {+ self.read_requests.borrow().is_empty()+ }++ // https://streams.spec.whatwg.org/#default-reader-constructor+ pub(crate) fn construct(cx: &mut CallContext, stream: Ref<ReadableStream>) -> WebIdlResult<Ref<Self>> {+ let reader = allocate(cx.vm(), Self::new());++ // 1. Perform ? SetUpReadableStreamDefaultReader(this, stream).+ set_up_readable_stream_default_reader(cx, reader, stream)?;+ Ok(reader)+ }++ // https://streams.spec.whatwg.org/#generic-reader-closed+ pub(crate) fn closed(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ self.generic.closed()+ }++ // https://streams.spec.whatwg.org/#default-reader-read+ pub(crate) fn read(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ let cx = &this.generic.context(cx.vm());++ // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.+ if this.generic.stream().is_none() {+ let exception = Exception::type_error("Cannot read from an empty stream");+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 2. Let promise be a new promise.+ let promise = create_promise(cx.vm(), cx.realm());++ // 3. Let readRequest be a new read request with the following items:+ // chunk steps, given chunk+ // 1. Resolve promise with «[ "value" → chunk, "done" → false ]».+ // close steps+ // 1. Resolve promise with «[ "value" → undefined, "done" → true ]».+ // error steps, given e+ // 1. Reject promise with e.+ let read_request = ReadRequest::DefaultReaderRead(promise);++ // 4. Perform ! ReadableStreamDefaultReaderRead(this, readRequest).+ readable_stream_default_reader_read(cx.vm(), *this, read_request);++ // 5. Return promise.+ Ok(promise)+ }++ // https://streams.spec.whatwg.org/#default-reader-release-lock+ pub(crate) fn release_lock(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. If this.[[stream]] is undefined, return.+ if this.generic.stream().is_none() {+ return Ok(());+ }++ // 2. Perform ! ReadableStreamDefaultReaderRelease(this).+ readable_stream_default_reader_release(cx.vm(), *this);+ Ok(())+ }++ // https://streams.spec.whatwg.org/#generic-reader-cancel+ pub(crate) fn cancel(this: &Ref<Self>, cx: &mut CallContext, reason: Option<Value>) -> WebIdlResult<WebIdlPromise> {+ let reader = ReadableStreamReader::ReadableStreamDefaultReader(*this);+ Ok(ReadableStreamGenericReader::cancel(cx.vm(), reader, reason))+ }++ /// To read a chunk from a ReadableStreamDefaultReader reader, given a read request readRequest,+ /// https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-a-chunk+ pub(crate) fn read_a_chunk(vm: &Vm, reader: Ref<Self>, read_request: CppReadRequest) {+ // To read a chunk from a ReadableStreamDefaultReader reader, given a read request readRequest,+ // perform ! ReadableStreamDefaultReaderRead(reader, readRequest).+ readable_stream_default_reader_read(vm, reader, ReadRequest::Cpp(read_request));+ }++ // https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes+ pub(crate) fn read_all_bytes(+ vm: &Vm,+ reader: Ref<Self>,+ success_steps: CppBytesSteps,+ failure_steps: CppValueSteps,+ ) {+ let realm = reader.generic.closed_promise_realm();++ // To read all bytes from a ReadableStreamDefaultReader reader, given successSteps, which is an algorithm+ // accepting a byte sequence, and failureSteps, which is an algorithm accepting a JavaScript value: read-loop+ // given reader, a new byte sequence, successSteps, and failureSteps.++ // https://streams.spec.whatwg.org/#read-loop+ // 1. Let readRequest be a new read request with the following items:+ // NOTE: The items are the steps of ReadLoop.+ let read_request = READ_LOOP_CLASS.allocate(+ vm,+ ReadLoop {+ realm,+ reader,+ bytes: core::cell::RefCell::new(Vec::new()),+ success_steps,+ failure_steps,+ },+ );++ // 2. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).+ readable_stream_default_reader_read(vm, reader, ReadRequest::ReadLoop(read_request));+ }+}++/// The state of a read-loop, https://streams.spec.whatwg.org/#read-loop, whose read request reads the next chunk with+/// the same state.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadLoop {+ realm: Gc<Realm>,+ reader: Ref<ReadableStreamDefaultReader>,+ #[gc(untraced)]+ bytes: core::cell::RefCell<Vec<u8>>,+ success_steps: CppBytesSteps,+ failure_steps: CppValueSteps,+}++static READ_LOOP_CLASS: EmbedderClass<ReadLoop> = EmbedderClass::new("ReadLoop");++impl EmbedderValue for ReadLoop {+ const CLASS: &'static EmbedderClass<Self> = &READ_LOOP_CLASS;+}++impl ReadLoop {+ // chunk steps, given chunk+ pub(crate) fn chunk_steps(this: Gc<EmbedderCell<Self>>, vm: &Vm, chunk: Value) {+ // 1. If chunk is not a Uint8Array object, call failureSteps with a TypeError and abort these steps.+ let typed_array = if chunk.is_object() {+ chunk.as_object().downcast::<TypedArrayBase>()+ } else {+ None+ };+ let Some(array) = typed_array.filter(|typed_array| typed_array.kind() == TypedArrayKind::Uint8Array) else {+ let error = exception_value(vm, this.realm, Exception::type_error("Chunk data is not Uint8Array"));+ this.failure_steps.call(error);+ return;+ };++ // 2. Append the bytes represented by chunk to bytes.+ // NB: Since a chunk is whatever the stream enqueued, and enqueue() takes an 'any', this Uint8Array may well be+ // a view onto an SAB with no conversion having had the chance to reject one. So, use with_bytes() to read+ // it through — rather than handing over a pointer into memory that another agent can be writing.+ // SAFETY: Appending the bytes to bytes neither runs script nor allocates a cell.+ unsafe { BufferSource::TypedArray(array).with_bytes(|bytes| this.bytes.borrow_mut().extend_from_slice(bytes)) };++ // FIXME: As the spec suggests, implement this non-recursively - instead of directly. It is not too big of a+ // deal currently as we enqueue the entire blob buffer in one go, meaning that we only recurse a single+ // time. Once we begin queuing up more than one chunk at a time, we may run into stack overflow problems.+ //+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.+ readable_stream_default_reader_read(vm, this.reader, ReadRequest::ReadLoop(this));+ }++ // close steps+ pub(crate) fn close_steps(&self) {+ // 1. Call successSteps with bytes.+ let bytes = core::mem::take(&mut *self.bytes.borrow_mut());+ self.success_steps.call(&bytes);+ }++ // error steps, given e+ pub(crate) fn error_steps(&self, error: Value) {+ // 1. Call failureSteps with e.+ self.failure_steps.call(error);+ }+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests+pub(crate) fn readable_stream_default_reader_error_read_requests(+ vm: &Vm,+ reader: Ref<ReadableStreamDefaultReader>,+ error: Value,+) {+ // 1. Let readRequests be reader.[[readRequests]].+ // 2. Set reader.[[readRequests]] to a new empty list.+ let read_requests = reader.take_read_requests(vm);++ // 3. For each readRequest of readRequests,+ for index in 0..read_requests.len() {+ // 1. Perform readRequest’s error steps, given e.+ read_requests+ .get(index)+ .expect("the index is in bounds")+ .error_steps(vm, error);+ }+}++// https://streams.spec.whatwg.org/#readable-stream-default-reader-read+pub(crate) fn readable_stream_default_reader_read(+ vm: &Vm,+ reader: Ref<ReadableStreamDefaultReader>,+ read_request: ReadRequest,+) {+ // 1. Let stream be reader.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = reader.generic.stream().expect("a reader that reads has a stream");++ // 3. Set stream.[[disturbed]] to true.+ stream.set_disturbed(true);++ match stream.state() {+ // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.+ ReadableStreamState::Closed => read_request.close_steps(vm),+ // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given+ // stream.[[storedError]].+ ReadableStreamState::Errored => read_request.error_steps(vm, stream.stored_error()),+ // 6. Otherwise,+ ReadableStreamState::Readable => {+ // 1. Assert: stream.[[state]] is "readable".+ // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).+ match stream.controller().expect("a stream that is set up has a controller") {+ ReadableStreamController::ReadableStreamDefaultController(controller) => {+ ReadableStreamDefaultController::pull_steps(controller, vm, read_request);+ }+ ReadableStreamController::ReadableByteStreamController(controller) => {+ ReadableByteStreamController::pull_steps(controller, &reader.generic.context(vm), read_request);+ }+ }+ }+ }+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease+pub(crate) fn readable_stream_default_reader_release(vm: &Vm, reader: Ref<ReadableStreamDefaultReader>) {+ let realm = reader.generic.closed_promise_realm();++ // 1. Perform ! ReadableStreamReaderGenericRelease(reader).+ readable_stream_reader_generic_release(vm, ReadableStreamReader::ReadableStreamDefaultReader(reader));++ // 2. Let e be a new TypeError exception.+ let exception = exception_value(vm, realm, Exception::type_error("Reader has been released"));++ // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).+ readable_stream_default_reader_error_read_requests(vm, reader, exception);+}++// https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader+pub(crate) fn set_up_readable_stream_default_reader(+ cx: &CallContext,+ reader: Ref<ReadableStreamDefaultReader>,+ stream: Ref<ReadableStream>,+) -> WebIdlResult<()> {+ // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.+ if is_readable_stream_locked(stream) {+ return Err(Exception::type_error("Cannot create stream reader for a locked stream"));+ }++ // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).+ readable_stream_reader_generic_initialize(cx, ReadableStreamReader::ReadableStreamDefaultReader(reader), stream);++ // 3. Set reader.[[readRequests]] to a new empty list.+ reader.read_requests.borrow_mut().clear();+ Ok(())+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_generic_reader.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_generic_reader.rsnew file mode 100644index 00000000000..98dedebee53--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_generic_reader.rs@@ -0,0 +1,196 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamGenericReader, https://streams.spec.whatwg.org/#generic-reader-mixin, and the abstract operations of+//! readers, https://streams.spec.whatwg.org/#rs-reader-abstract-ops++use core::cell::Cell;++use libjs_rust::api::{Gc, Realm, Trace, Value, Vm};++use crate::bindings::interface::Ref;+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_rejected_promise, create_rejected_promise_from_exception,+ create_resolved_promise, exception_value, mark_promise_as_handled, promise_realm, reject_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::readable_byte_stream_controller::ReadableByteStreamController;+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamReader, ReadableStreamState, readable_stream_cancel,+};+use crate::streams::readable_stream_default_controller::ReadableStreamDefaultController;+use crate::streams::underlying_source::ReadableStreamController;++/// What a ReadableStreamDefaultReader and a ReadableStreamBYOBReader both are,+/// https://streams.spec.whatwg.org/#readablestreamgenericreader+#[derive(Default, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ReadableStreamGenericReader {+ // https://streams.spec.whatwg.org/#readablestreamgenericreader-closedpromise+ closed_promise: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#readablestreamgenericreader-stream+ stream: Cell<Option<Ref<ReadableStream>>>,+}++impl ReadableStreamGenericReader {+ pub(crate) fn closed_promise(&self) -> Option<WebIdlPromise> {+ self.closed_promise.get()+ }++ pub(crate) fn set_closed_promise(&self, promise: WebIdlPromise) {+ self.closed_promise.set(Some(promise));+ }++ pub(crate) fn stream(&self) -> Option<Ref<ReadableStream>> {+ self.stream.get()+ }++ pub(crate) fn set_stream(&self, stream: Option<Ref<ReadableStream>>) {+ self.stream.set(stream);+ }++ /// The realm of the reader's [[closedPromise]], which the promises and the exceptions of the reader are created+ /// in, as LibWeb's C++ creates them.+ pub(crate) fn closed_promise_realm(&self) -> Gc<Realm> {+ promise_realm(+ self.closed_promise()+ .expect("a reader that is set up has a closed promise"),+ )+ }++ /// The context of the realm of the reader's [[closedPromise]].+ pub(crate) fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, self.closed_promise_realm())+ }++ // https://streams.spec.whatwg.org/#generic-reader-closed+ pub(crate) fn closed(&self) -> WebIdlResult<WebIdlPromise> {+ // 1. Return this.[[closedPromise]].+ Ok(self+ .closed_promise()+ .expect("a reader that is set up has a closed promise"))+ }++ // https://streams.spec.whatwg.org/#generic-reader-cancel+ pub(crate) fn cancel(vm: &Vm, reader: ReadableStreamReader, reason: Option<Value>) -> WebIdlPromise {+ // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.+ if reader.generic().stream().is_none() {+ let exception = Exception::type_error("No stream present to cancel");+ let realm = reader.generic().closed_promise_realm();+ return create_rejected_promise_from_exception(vm, realm, exception);+ }++ // 2. Return ! ReadableStreamReaderGenericCancel(this, reason).+ readable_stream_reader_generic_cancel(vm, reader, reason.unwrap_or(Value::UNDEFINED))+ }+}++// https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel+pub(crate) fn readable_stream_reader_generic_cancel(+ vm: &Vm,+ reader: ReadableStreamReader,+ reason: Value,+) -> WebIdlPromise {+ // 1. Let stream be reader.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = reader.generic().stream().expect("a reader that cancels has a stream");++ // 3. Return ! ReadableStreamCancel(stream, reason).+ readable_stream_cancel(&reader.generic().context(vm), stream, reason)+}++// https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize+pub(crate) fn readable_stream_reader_generic_initialize(+ cx: &CallContext,+ reader: ReadableStreamReader,+ stream: Ref<ReadableStream>,+) {+ let vm = cx.vm();+ let generic = reader.generic();++ // 1. Set reader.[[stream]] to stream.+ generic.set_stream(Some(stream));++ // 2. Set stream.[[reader]] to reader.+ stream.set_reader(Some(reader));++ match stream.state() {+ // 3. If stream.[[state]] is "readable",+ ReadableStreamState::Readable => {+ // 1. Set reader.[[closedPromise]] to a new promise.+ generic.set_closed_promise(create_promise(vm, cx.realm()));+ }+ // 4. Otherwise, if stream.[[state]] is "closed",+ ReadableStreamState::Closed => {+ // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.+ generic.set_closed_promise(create_resolved_promise(vm, cx.realm(), Value::UNDEFINED));+ }+ // 5. Otherwise,+ ReadableStreamState::Errored => {+ // 1. Assert: stream.[[state]] is "errored".+ // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].+ let closed_promise = create_rejected_promise(vm, cx.realm(), stream.stored_error());+ generic.set_closed_promise(closed_promise);++ // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, closed_promise);+ }+ }+}++// https://streams.spec.whatwg.org/#readable-stream-reader-generic-release+pub(crate) fn readable_stream_reader_generic_release(vm: &Vm, reader: ReadableStreamReader) {+ let generic = reader.generic();++ // 1. Let stream be reader.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = generic.stream().expect("a reader that is released has a stream");++ // 3. Assert: stream.[[reader]] is reader.+ assert!(stream.reader() == Some(reader));++ let realm = generic.closed_promise_realm();+ let exception = exception_value(vm, realm, Exception::type_error("Reader has been released"));++ // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.+ if stream.state() == ReadableStreamState::Readable {+ reject_promise(+ vm,+ generic+ .closed_promise()+ .expect("a reader of a stream has a closed promise"),+ exception,+ );+ }+ // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.+ else {+ generic.set_closed_promise(create_rejected_promise(vm, realm, exception));+ }++ // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(+ vm,+ generic+ .closed_promise()+ .expect("a reader of a stream has a closed promise"),+ );++ // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().+ match stream.controller().expect("a stream that is set up has a controller") {+ ReadableStreamController::ReadableStreamDefaultController(controller) => {+ ReadableStreamDefaultController::release_steps(controller);+ }+ ReadableStreamController::ReadableByteStreamController(controller) => {+ ReadableByteStreamController::release_steps(controller);+ }+ }++ // 8. Set stream.[[reader]] to undefined.+ stream.set_reader(None);++ // 9. Set reader.[[stream]] to undefined.+ generic.set_stream(None);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_pipe_to.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_pipe_to.rsnew file mode 100644index 00000000000..c72826a0f81--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_pipe_to.rs@@ -0,0 +1,626 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamPipeTo, https://streams.spec.whatwg.org/#readable-stream-pipe-to, whose reading of chunks from its+//! source and writing them to its destination in parallel happens in the state of the pipe.++use core::cell::Cell;++use libjs_rust::api::{+ EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, MarkedVec, NativeFunction, PropertyKey, Trace, Value, Vm,+};++use crate::bindings::conversions::CppInterface;+use crate::bindings::interface::{Ref, with_temporary_execution_context_and_callbacks};+use crate::bindings::promise::{+ ReactionSteps, WebIdlPromise, create_promise, create_resolved_promise, exception_value,+ get_promise_for_wait_for_all, is_promise_fulfilled, mark_promise_as_handled, promise_realm, queue_a_microtask,+ react_to_promise, reject_promise, resolve_promise,+};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::streams::cpp::AbortSignal;+use crate::streams::read_request::ReadRequest;+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamState, acquire_readable_stream_default_reader, is_readable_stream_locked,+ readable_stream_cancel,+};+use crate::streams::readable_stream_default_reader::{+ ReadableStreamDefaultReader, readable_stream_default_reader_read, readable_stream_default_reader_release,+};+use crate::streams::writable_stream::{+ WritableStream, WritableStreamState, acquire_writable_stream_default_writer, is_writable_stream_locked,+ writable_stream_abort, writable_stream_close_queued_or_in_flight,+};+use crate::streams::writable_stream_default_writer::{+ WritableStreamDefaultWriter, writable_stream_default_writer_close_with_error_propagation,+ writable_stream_default_writer_release, writable_stream_default_writer_write,+};++/// The action that the pipe shuts down with, https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-with-action+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+enum ShutdownAction {+ /// ! WritableStreamAbort(dest, source.[[storedError]])+ AbortDestination,+ /// ! ReadableStreamCancel(source, dest.[[storedError]])+ CancelSourceWithDestinationError,+ /// ! ReadableStreamCancel(source, destClosed)+ CancelSource(Value),+ /// ! WritableStreamDefaultWriterCloseWithErrorPropagation(writer)+ CloseDestination,+ /// Getting a promise to wait for all of the actions of the abortAlgorithm, given the signal's abort reason.+ AbortAlgorithm(Value),+}++/// What shutting down the pipe does once every chunk that has been read has been written.+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+enum ShutdownSteps {+ /// The steps of shutting down with an action, passing along originalError if it was given.+ WithAction {+ action: ShutdownAction,+ original_error: Option<Value>,+ },+ /// The steps of shutting down, passing along error if it was given.+ WithoutAction { error: Option<Value> },+}++/// The state of a pipe, https://streams.spec.whatwg.org/#ref-for-in-parallel+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct PipeTo {+ promise: WebIdlPromise,+ source: Ref<ReadableStream>,+ destination: Ref<WritableStream>,+ reader: Ref<ReadableStreamDefaultReader>,+ writer: Ref<WritableStreamDefaultWriter>,+ signal: GcRefCell<Option<AbortSignal>>,+ #[gc(untraced)]+ signal_algorithm_id: Cell<Option<u64>>,+ last_write_promise: Cell<Option<WebIdlPromise>>,+ unwritten_chunks: GcRefCell<Vec<Value>>,+ #[gc(untraced)]+ prevent_close: bool,+ #[gc(untraced)]+ prevent_abort: bool,+ #[gc(untraced)]+ prevent_cancel: bool,+ // https://streams.spec.whatwg.org/#readable-stream-pipe-to: shuttingDown+ shutting_down: Cell<bool>,+}++static PIPE_TO_CLASS: EmbedderClass<PipeTo> = EmbedderClass::new("ReadableStreamPipeTo");++impl EmbedderValue for PipeTo {+ const CLASS: &'static EmbedderClass<Self> = &PIPE_TO_CLASS;+}++pub(crate) type PipeToRef = Gc<EmbedderCell<PipeTo>>;++impl PipeTo {+ /// The context of the realm of promise.+ fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, promise_realm(self.promise))+ }++ /// The reaction to the reader's and the writer's closed promises and to the rejection of the writer's ready+ /// promise, which checks whether the pipe has to shut down.+ fn on_shutdown(cx: &CallContext, this: PipeToRef, _: Value) -> WebIdlResult<Value> {+ Self::check_for_error_and_close_states(this, cx.vm());+ Ok(Value::UNDEFINED)+ }++ fn process(this: PipeToRef, vm: &Vm) {+ if Self::check_for_error_and_close_states(this, vm) {+ return;+ }++ let ready_promise = this.writer.ready_promise();++ if let Some(ready_promise) = ready_promise+ && is_promise_fulfilled(ready_promise)+ {+ Self::read_chunk(this, vm);+ return;+ }++ if let Some(ready_promise) = ready_promise {+ react_to_promise(+ vm,+ ready_promise,+ this,+ Some(|cx, this, _| {+ Self::read_chunk(this, cx.vm());+ Ok(Value::UNDEFINED)+ }),+ Some(Self::on_shutdown),+ );+ }+ }++ // abortAlgorithm+ fn abort_algorithm(this: PipeToRef, vm: &Vm, signal: &AbortSignal) {+ with_temporary_execution_context_and_callbacks(promise_realm(this.promise), || {+ // 1. Let error be signal’s abort reason.+ let error = signal.reason();++ // 5. Shutdown with an action consisting of getting a promise to wait for all of the actions in actions,+ // and with error.+ Self::shutdown_with_action(this, vm, ShutdownAction::AbortAlgorithm(error), Some(error));+ });+ }++ /// Performs the action that the pipe shuts down with.+ fn perform_action(this: PipeToRef, cx: &CallContext, action: ShutdownAction) -> WebIdlPromise {+ let vm = cx.vm();+ match action {+ ShutdownAction::AbortDestination => writable_stream_abort(cx, this.destination, this.source.stored_error()),+ ShutdownAction::CancelSourceWithDestinationError => {+ readable_stream_cancel(cx, this.source, this.destination.stored_error())+ }+ ShutdownAction::CancelSource(error) => readable_stream_cancel(cx, this.source, error),+ ShutdownAction::CloseDestination => {+ writable_stream_default_writer_close_with_error_propagation(vm, this.writer)+ }+ ShutdownAction::AbortAlgorithm(error) => {+ // 2. Let actions be an empty ordered set.+ let actions = MarkedVec::new(vm);++ // 3. If preventAbort is false, append the following action to actions:+ if !this.prevent_abort {+ // 1. If dest.[[state]] is "writable", return ! WritableStreamAbort(dest, error).+ if this.destination.state() == WritableStreamState::Writable {+ actions.push(writable_stream_abort(cx, this.destination, error));+ }+ // 2. Otherwise, return a promise resolved with undefined.+ else {+ actions.push(create_resolved_promise(vm, cx.realm(), Value::UNDEFINED));+ }+ }++ // 4. If preventCancel is false, append the following action action to actions:+ if !this.prevent_cancel {+ // 1. If source.[[state]] is "readable", return ! ReadableStreamCancel(source, error).+ if this.source.state() == ReadableStreamState::Readable {+ actions.push(readable_stream_cancel(cx, this.source, error));+ }+ // 2. Otherwise, return a promise resolved with undefined.+ else {+ actions.push(create_resolved_promise(vm, cx.realm(), Value::UNDEFINED));+ }+ }++ get_promise_for_wait_for_all(vm, cx.realm(), &actions.to_vec())+ }+ }+ }++ // https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-with-action+ fn shutdown_with_action(this: PipeToRef, vm: &Vm, action: ShutdownAction, original_error: Option<Value>) {+ // 1. If shuttingDown is true, abort these substeps.+ if this.shutting_down.get() {+ return;+ }++ // 2. Set shuttingDown to true.+ this.shutting_down.set(true);++ let steps = ShutdownSteps::WithAction { action, original_error };++ // 3. If dest.[[state]] is "writable" and ! WritableStreamCloseQueuedOrInFlight(dest) is false,+ if this.destination.state() == WritableStreamState::Writable+ && !writable_stream_close_queued_or_in_flight(this.destination)+ {+ // 1. If any chunks have been read but not yet written, write them to dest.+ Self::write_unwritten_chunks(this, vm);++ // 2. Wait until every chunk that has been read has been written (i.e. the corresponding promises have+ // settled).+ Self::wait_for_pending_writes_to_complete(this, vm, steps);+ } else {+ Self::on_pending_writes_complete(this, vm, steps);+ }+ }++ // https://streams.spec.whatwg.org/#rs-pipeTo-shutdown+ fn shutdown(this: PipeToRef, vm: &Vm, error: Option<Value>) {+ // 1. If shuttingDown is true, abort these substeps.+ if this.shutting_down.get() {+ return;+ }++ // 2. Set shuttingDown to true.+ this.shutting_down.set(true);++ let steps = ShutdownSteps::WithoutAction { error };++ // 3. If dest.[[state]] is "writable" and ! WritableStreamCloseQueuedOrInFlight(dest) is false,+ if this.destination.state() == WritableStreamState::Writable+ && !writable_stream_close_queued_or_in_flight(this.destination)+ {+ // 1. If any chunks have been read but not yet written, write them to dest.+ Self::write_unwritten_chunks(this, vm);++ // 2. Wait until every chunk that has been read has been written (i.e. the corresponding promises have+ // settled).+ Self::wait_for_pending_writes_to_complete(this, vm, steps);+ } else {+ Self::on_pending_writes_complete(this, vm, steps);+ }+ }++ /// The steps of shutting down that follow waiting until every chunk that has been read has been written.+ fn on_pending_writes_complete(this: PipeToRef, vm: &Vm, steps: ShutdownSteps) {+ with_temporary_execution_context_and_callbacks(promise_realm(this.promise), || match steps {+ ShutdownSteps::WithAction { action, original_error } => {+ // 4. Let p be the result of performing action.+ let promise = Self::perform_action(this, &this.context(vm), action);++ react_to_promise(+ vm,+ promise,+ (this, original_error),+ // 5. Upon fulfillment of p, finalize, passing along originalError if it was given.+ Some(|cx, (this, original_error), _| {+ Self::finish(this, cx.vm(), original_error);+ Ok(Value::UNDEFINED)+ }),+ // 6. Upon rejection of p with reason newError, finalize with newError.+ Some(|cx, (this, _), new_error| {+ Self::finish(this, cx.vm(), Some(new_error));+ Ok(Value::UNDEFINED)+ }),+ );+ }+ ShutdownSteps::WithoutAction { error } => {+ // 4. Finalize, passing along error if it was given.+ Self::finish(this, vm, error);+ }+ });+ }++ fn read_chunk(this: PipeToRef, vm: &Vm) {+ // Shutdown must stop activity: if shuttingDown becomes true, the user agent must not initiate further reads+ // from reader, and must only perform writes of already-read chunks, as described below. In particular, the+ // user agent must check the below conditions before performing any reads or writes, since they might lead to+ // immediate shutdown.+ if Self::check_for_error_and_close_states(this, vm) {+ return;+ }++ let read_request = ReadRequest::PipeTo(this);+ readable_stream_default_reader_read(vm, this.reader, read_request);+ }++ // chunk steps, given chunk, of the read request of the pipe+ pub(crate) fn read_request_chunk_steps(this: PipeToRef, vm: &Vm, chunk: Value) {+ this.unwritten_chunks.borrow_mut().push(chunk);++ if Self::check_for_error_and_close_states(this, vm) {+ return;+ }++ queue_a_microtask(vm, promise_realm(this.promise), this, |vm, this| {+ with_temporary_execution_context_and_callbacks(promise_realm(this.promise), || {+ Self::write_chunk(this, vm);+ Self::process(this, vm);+ });+ });+ }++ // close steps, of the read request of the pipe+ pub(crate) fn read_request_close_steps(this: PipeToRef, vm: &Vm) {+ if !Self::check_for_error_and_close_states(this, vm) {+ Self::finish(this, vm, None);+ }+ }++ // error steps, of the read request of the pipe+ pub(crate) fn read_request_error_steps(this: PipeToRef, vm: &Vm, _: Value) {+ Self::check_for_error_and_close_states(this, vm);+ }++ fn write_chunk(this: PipeToRef, vm: &Vm) {+ // Shutdown must stop activity: if shuttingDown becomes true, the user agent must not initiate further reads+ // from reader, and must only perform writes of already-read chunks, as described below. In particular, the+ // user agent must check the below conditions before performing any reads or writes, since they might lead to+ // immediate shutdown.+ if !this.shutting_down.get() && Self::check_for_error_and_close_states(this, vm) {+ return;+ }++ let chunk = this.unwritten_chunks.borrow_mut().remove(0);+ let promise = writable_stream_default_writer_write(vm, this.writer, chunk);+ mark_promise_as_handled(vm, promise);++ this.last_write_promise.set(Some(promise));+ }++ fn write_unwritten_chunks(this: PipeToRef, vm: &Vm) {+ while !this.unwritten_chunks.borrow().is_empty() {+ Self::write_chunk(this, vm);+ }+ }++ fn wait_for_pending_writes_to_complete(this: PipeToRef, vm: &Vm, steps: ShutdownSteps) {+ let Some(last_write_promise) = this.last_write_promise.take() else {+ queue_a_microtask(vm, promise_realm(this.promise), (this, steps), |vm, (this, steps)| {+ Self::on_pending_writes_complete(this, vm, steps);+ });+ return;+ };++ let run_complete_steps: ReactionSteps<(PipeToRef, ShutdownSteps)> = |cx, (this, steps), _| {+ Self::on_pending_writes_complete(this, cx.vm(), steps);+ Ok(Value::UNDEFINED)+ };+ react_to_promise(+ vm,+ last_write_promise,+ (this, steps),+ Some(run_complete_steps),+ Some(run_complete_steps),+ );+ }++ // https://streams.spec.whatwg.org/#rs-pipeTo-finalize+ fn finish(this: PipeToRef, vm: &Vm, error: Option<Value>) {+ // 1. Perform ! WritableStreamDefaultWriterRelease(writer).+ writable_stream_default_writer_release(vm, this.writer);++ // 2. If reader implements ReadableStreamBYOBReader, perform ! ReadableStreamBYOBReaderRelease(reader).+ // 3. Otherwise, perform ! ReadableStreamDefaultReaderRelease(reader).+ readable_stream_default_reader_release(vm, this.reader);++ // 4. If signal is not undefined, remove abortAlgorithm from signal.+ let signal = this.signal.borrow().clone();+ if let Some(signal) = signal {+ signal.remove_algorithm(+ this.signal_algorithm_id+ .get()+ .expect("an abort algorithm was added to the signal"),+ );+ }++ match error {+ // 5. If error was given, reject promise with error.+ Some(error) => reject_promise(vm, this.promise, error),+ // 6. Otherwise, resolve promise with undefined.+ None => resolve_promise(vm, this.promise, Value::UNDEFINED),+ }++ this.reader.set_pipe_to(None);+ }++ fn check_for_error_and_close_states(this: PipeToRef, vm: &Vm) -> bool {+ // Error and close states must be propagated: the following conditions must be applied in order.+ this.shutting_down.get()+ || Self::check_for_forward_errors(this, vm)+ || Self::check_for_backward_errors(this, vm)+ || Self::check_for_forward_close(this, vm)+ || Self::check_for_backward_close(this, vm)+ }++ fn check_for_forward_errors(this: PipeToRef, vm: &Vm) -> bool {+ // 1. Errors must be propagated forward: if source.[[state]] is or becomes "errored", then+ if this.source.state() == ReadableStreamState::Errored {+ // 1. If preventAbort is false, shutdown with an action of ! WritableStreamAbort(dest,+ // source.[[storedError]]) and with source.[[storedError]].+ if !this.prevent_abort {+ Self::shutdown_with_action(+ this,+ vm,+ ShutdownAction::AbortDestination,+ Some(this.source.stored_error()),+ );+ }+ // 2. Otherwise, shutdown with source.[[storedError]].+ else {+ Self::shutdown(this, vm, Some(this.source.stored_error()));+ }+ }++ this.shutting_down.get()+ }++ fn check_for_backward_errors(this: PipeToRef, vm: &Vm) -> bool {+ // 2. Errors must be propagated backward: if dest.[[state]] is or becomes "errored", then+ if this.destination.state() == WritableStreamState::Errored {+ // 1. If preventCancel is false, shutdown with an action of ! ReadableStreamCancel(source,+ // dest.[[storedError]]) and with dest.[[storedError]].+ if !this.prevent_cancel {+ Self::shutdown_with_action(+ this,+ vm,+ ShutdownAction::CancelSourceWithDestinationError,+ Some(this.destination.stored_error()),+ );+ }+ // 2. Otherwise, shutdown with dest.[[storedError]].+ else {+ Self::shutdown(this, vm, Some(this.destination.stored_error()));+ }+ }++ this.shutting_down.get()+ }++ fn check_for_forward_close(this: PipeToRef, vm: &Vm) -> bool {+ // 3. Closing must be propagated forward: if source.[[state]] is or becomes "closed", then+ if this.source.state() == ReadableStreamState::Closed {+ // 1. If preventClose is false, shutdown with an action of+ // ! WritableStreamDefaultWriterCloseWithErrorPropagation(writer).+ if !this.prevent_close {+ Self::shutdown_with_action(this, vm, ShutdownAction::CloseDestination, None);+ }+ // 2. Otherwise, shutdown.+ else {+ Self::shutdown(this, vm, None);+ }+ }++ this.shutting_down.get()+ }++ fn check_for_backward_close(this: PipeToRef, vm: &Vm) -> bool {+ // 4. Closing must be propagated backward: if ! WritableStreamCloseQueuedOrInFlight(dest) is true or+ // dest.[[state]] is "closed", then+ if writable_stream_close_queued_or_in_flight(this.destination)+ || this.destination.state() == WritableStreamState::Closed+ {+ // 1. Assert: no chunks have been read or written.++ // 2. Let destClosed be a new TypeError.+ let destination_closed = exception_value(+ vm,+ promise_realm(this.promise),+ Exception::type_error("Destination stream was closed during piping operation"),+ );++ // 3. If preventCancel is false, shutdown with an action of ! ReadableStreamCancel(source, destClosed)+ // and with destClosed.+ if !this.prevent_cancel {+ Self::shutdown_with_action(+ this,+ vm,+ ShutdownAction::CancelSource(destination_closed),+ Some(destination_closed),+ );+ }+ // 4. Otherwise, shutdown with destClosed.+ else {+ Self::shutdown(this, vm, Some(destination_closed));+ }+ }++ this.shutting_down.get()+ }+}++// https://streams.spec.whatwg.org/#readable-stream-pipe-to+pub(crate) fn readable_stream_pipe_to(+ cx: &CallContext,+ source: Ref<ReadableStream>,+ destination: Ref<WritableStream>,+ prevent_close: bool,+ prevent_abort: bool,+ prevent_cancel: bool,+ signal: Option<CppInterface>,+) -> WebIdlPromise {+ let vm = cx.vm();++ // 1. Assert: source implements ReadableStream.+ // 2. Assert: dest implements WritableStream.+ // 3. Assert: preventClose, preventAbort, and preventCancel are all booleans.++ // 4. If signal was not given, let signal be undefined.+ // 5. Assert: either signal is undefined, or signal implements AbortSignal.+ let signal = signal.map(AbortSignal::from_wrapper);++ // 6. Assert: ! IsReadableStreamLocked(source) is false.+ assert!(!is_readable_stream_locked(source));++ // 7. Assert: ! IsWritableStreamLocked(dest) is false.+ assert!(!is_writable_stream_locked(destination));++ // 8. If source.[[controller]] implements ReadableByteStreamController, let reader be either+ // ! AcquireReadableStreamBYOBReader(source) or ! AcquireReadableStreamDefaultReader(source), at the user+ // agent’s discretion.+ // 9. Otherwise, let reader be ! AcquireReadableStreamDefaultReader(source).+ let reader = acquire_readable_stream_default_reader(cx, source).must();++ // 10. Let writer be ! AcquireWritableStreamDefaultWriter(dest).+ let writer = acquire_writable_stream_default_writer(cx, destination).must();++ // 11. Set source.[[disturbed]] to true.+ source.set_disturbed(true);++ // 12. Let shuttingDown be false.+ // NOTE: This is internal to the state of the pipe.++ // 13. Let promise be a new promise.+ let promise = create_promise(vm, cx.realm());++ let this = PIPE_TO_CLASS.allocate(+ vm,+ PipeTo {+ promise,+ source,+ destination,+ reader,+ writer,+ signal: GcRefCell::new(None),+ signal_algorithm_id: Cell::new(None),+ last_write_promise: Cell::new(None),+ unwritten_chunks: GcRefCell::new(Vec::new()),+ prevent_close,+ prevent_abort,+ prevent_cancel,+ shutting_down: Cell::new(false),+ },+ );++ reader.set_pipe_to(Some(this));++ if let Some(reader_closed_promise) = reader.generic().closed_promise() {+ react_to_promise(+ vm,+ reader_closed_promise,+ this,+ Some(PipeTo::on_shutdown),+ Some(PipeTo::on_shutdown),+ );+ }+ if let Some(writer_closed_promise) = writer.closed_promise() {+ react_to_promise(+ vm,+ writer_closed_promise,+ this,+ Some(PipeTo::on_shutdown),+ Some(PipeTo::on_shutdown),+ );+ }++ // 14. If signal is not undefined,+ if let Some(signal) = signal {+ // 1. Let abortAlgorithm be the following steps:++ // 2. If signal is aborted, perform abortAlgorithm and return promise.+ if signal.aborted() {+ PipeTo::abort_algorithm(this, vm, &signal);+ return promise;+ }++ // 3. Add abortAlgorithm to signal.+ let abort_algorithm = NativeFunction::create(+ vm,+ (this, signal.clone()),+ |vm: &Vm, (this, signal): &(PipeToRef, AbortSignal)| {+ PipeTo::abort_algorithm(*this, vm, signal);+ Ok(Value::UNDEFINED)+ },+ 0,+ &PropertyKey::from_utf8(""),+ Some(cx.realm()),+ None,+ None,+ );+ let signal_id = signal+ .add_algorithm(abort_algorithm)+ .expect("a signal that is not aborted takes algorithms");+ *this.signal.borrow_mut() = Some(signal);+ this.signal_algorithm_id.set(Some(signal_id));+ }++ // 15. In parallel (but not really; see #905), using reader and writer, read all chunks from source and write them+ // to dest. Due to the locking provided by the reader and writer, the exact manner in which this happens is not+ // observable to author code, and so there is flexibility in how this is done. The following constraints apply+ // regardless of the exact algorithm used:+ PipeTo::process(this, vm);++ // 16. Return promise.+ promise+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_tee.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_tee.rsnew file mode 100644index 00000000000..f02b51c57dc--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream_tee.rs@@ -0,0 +1,1107 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ReadableStreamTee, https://streams.spec.whatwg.org/#readable-stream-tee, and the state that the algorithms and read+//! requests of a tee share.++use core::cell::Cell;++use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Value, Vm};++use crate::bindings::conversions::{ArrayBufferView, BufferSource, buffer_source_type_of};+use crate::bindings::interface::{Ref, with_temporary_execution_context_and_callbacks};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_resolved_promise, exception_value, promise_realm, queue_a_microtask,+ resolve_promise, upon_rejection,+};+use crate::bindings::{CallContext, MustNotThrow, WebIdlResult};+use crate::streams::abstract_operations::{clone_as_uint8_array, structured_clone};+use crate::streams::algorithms::{CancelAlgorithm, PullAlgorithm, StartAlgorithm};+use crate::streams::read_request::{ReadIntoRequest, ReadRequest};+use crate::streams::readable_byte_stream_controller::{+ ReadableByteStreamController, readable_byte_stream_controller_close, readable_byte_stream_controller_enqueue,+ readable_byte_stream_controller_error, readable_byte_stream_controller_get_byob_request,+ readable_byte_stream_controller_respond, readable_byte_stream_controller_respond_with_new_view,+};+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamReader, acquire_readable_stream_byob_reader, acquire_readable_stream_default_reader,+ create_array_from_list, create_readable_byte_stream, create_readable_stream, readable_stream_cancel,+};+use crate::streams::readable_stream_byob_reader::{+ readable_stream_byob_reader_read, readable_stream_byob_reader_release,+};+use crate::streams::readable_stream_default_controller::{+ ReadableStreamDefaultController, readable_stream_default_controller_close,+ readable_stream_default_controller_enqueue, readable_stream_default_controller_error,+};+use crate::streams::readable_stream_default_reader::{+ ReadableStreamDefaultReader, readable_stream_default_reader_read, readable_stream_default_reader_release,+};+use crate::streams::underlying_source::ReadableStreamController;++/// The variables of ReadableStreamDefaultTee that its algorithms and its read request share,+/// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DefaultTeeState {+ stream: Ref<ReadableStream>,+ reader: Ref<ReadableStreamDefaultReader>,+ reading: Cell<bool>,+ read_again: Cell<bool>,+ canceled1: Cell<bool>,+ canceled2: Cell<bool>,+ reason1: Cell<Value>,+ reason2: Cell<Value>,+ branch1: Cell<Option<Ref<ReadableStream>>>,+ branch2: Cell<Option<Ref<ReadableStream>>>,+ cancel_promise: WebIdlPromise,+ #[gc(untraced)]+ clone_for_branch2: bool,+}++static DEFAULT_TEE_STATE_CLASS: EmbedderClass<DefaultTeeState> = EmbedderClass::new("ReadableStreamDefaultTee");++impl EmbedderValue for DefaultTeeState {+ const CLASS: &'static EmbedderClass<Self> = &DEFAULT_TEE_STATE_CLASS;+}++impl DefaultTeeState {+ /// The context of the realm of cancelPromise, which the read request runs in.+ fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, promise_realm(self.cancel_promise))+ }++ /// branch1.[[controller]] and branch2.[[controller]].+ fn controllers(+ &self,+ ) -> (+ Ref<ReadableStreamDefaultController>,+ Ref<ReadableStreamDefaultController>,+ ) {+ let branch1 = self.branch1.get().expect("the tee has created its branches");+ let branch2 = self.branch2.get().expect("the tee has created its branches");+ (default_controller_of(branch1), default_controller_of(branch2))+ }++ /// The pullAlgorithm of the tee.+ pub(crate) fn pull_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext) -> WebIdlPromise {+ // 1. If reading is true,+ if this.reading.get() {+ // 1. Set readAgain to true.+ this.read_again.set(true);++ // 2. Return a promise resolved with undefined.+ return create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED);+ }++ // 2. Set reading to true.+ this.reading.set(true);++ // 3. Let readRequest be a read request with the following items:+ let read_request = ReadRequest::DefaultTee(this);++ // 4. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).+ readable_stream_default_reader_read(cx.vm(), this.reader, read_request);++ // 5. Return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }++ /// The cancel1Algorithm of the tee.+ pub(crate) fn cancel1_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Set canceled1 to true.+ this.canceled1.set(true);++ // 2. Set reason1 to reason.+ this.reason1.set(reason);++ // 3. If canceled2 is true,+ if this.canceled2.get() {+ // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).+ let composite_reason = create_array_from_list(cx, &[this.reason1.get(), this.reason2.get()]);++ // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).+ let cancel_result = readable_stream_cancel(cx, this.stream, composite_reason);++ // 3. Resolve cancelPromise with cancelResult.+ resolve_promise(+ cx.vm(),+ this.cancel_promise,+ Value::from_object(cancel_result.promise()),+ );+ }++ // 4. Return cancelPromise.+ this.cancel_promise+ }++ /// The cancel2Algorithm of the tee.+ pub(crate) fn cancel2_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Set canceled2 to true.+ this.canceled2.set(true);++ // 2. Set reason2 to reason.+ this.reason2.set(reason);++ // 3. If canceled1 is true,+ if this.canceled1.get() {+ // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).+ let composite_reason = create_array_from_list(cx, &[this.reason1.get(), this.reason2.get()]);++ // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).+ let cancel_result = readable_stream_cancel(cx, this.stream, composite_reason);++ // 3. Resolve cancelPromise with cancelResult.+ resolve_promise(+ cx.vm(),+ this.cancel_promise,+ Value::from_object(cancel_result.promise()),+ );+ }++ // 4. Return cancelPromise.+ this.cancel_promise+ }++ // chunk steps, given chunk+ pub(crate) fn read_request_chunk_steps(this: Gc<EmbedderCell<Self>>, vm: &Vm, chunk: Value) {+ // 1. Queue a microtask to perform the following steps:+ queue_a_microtask(+ vm,+ promise_realm(this.cancel_promise),+ (this, chunk),+ |vm, (this, chunk)| {+ with_temporary_execution_context_and_callbacks(promise_realm(this.cancel_promise), || {+ let cx = &this.context(vm);+ let (controller1, controller2) = this.controllers();++ // 1. Set readAgain to false.+ this.read_again.set(false);++ // 2. Let chunk1 and chunk2 be chunk.+ let chunk1 = chunk;+ let mut chunk2 = chunk;++ // 3. If canceled2 is false and cloneForBranch2 is true,+ if !this.canceled2.get() && this.clone_for_branch2 {+ // 1. Let cloneResult be StructuredClone(chunk2).+ let clone_result = structured_clone(cx, chunk2);++ match clone_result {+ // 2. If cloneResult is an abrupt completion,+ Err(exception) => {+ let error = exception_value(vm, cx.realm(), exception);++ // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]],+ // cloneResult.[[Value]]).+ readable_stream_default_controller_error(cx, controller1, error);++ // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]],+ // cloneResult.[[Value]]).+ readable_stream_default_controller_error(cx, controller2, error);++ // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).+ let cancel_result = readable_stream_cancel(cx, this.stream, error);++ // Note: We need to manually convert the result to an ECMAScript value here, by extracting+ // its [[Promise]] slot.+ resolve_promise(vm, this.cancel_promise, Value::from_object(cancel_result.promise()));++ // 4. Return.+ return;+ }+ // 3. Otherwise, set chunk2 to cloneResult.[[Value]].+ Ok(value) => chunk2 = value,+ }+ }++ // 4. If canceled1 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch1.[[controller]],+ // chunk1).+ if !this.canceled1.get() {+ readable_stream_default_controller_enqueue(cx, controller1, chunk1).must();+ }++ // 5. If canceled2 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch2.[[controller]],+ // chunk2).+ if !this.canceled2.get() {+ readable_stream_default_controller_enqueue(cx, controller2, chunk2).must();+ }++ // 6. Set reading to false.+ this.reading.set(false);++ // 7. If readAgain is true, perform pullAlgorithm.+ if this.read_again.get() {+ Self::pull_algorithm(this, cx);+ }+ });+ },+ );++ // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we+ // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we+ // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.+ }++ // close steps+ pub(crate) fn read_request_close_steps(this: Gc<EmbedderCell<Self>>, vm: &Vm) {+ let cx = &this.context(vm);+ let (controller1, controller2) = this.controllers();++ // 1. Set reading to false.+ this.reading.set(false);++ // 2. If canceled1 is false, perform ! ReadableStreamDefaultControllerClose(branch1.[[controller]]).+ if !this.canceled1.get() {+ readable_stream_default_controller_close(cx, controller1);+ }++ // 3. If canceled2 is false, perform ! ReadableStreamDefaultControllerClose(branch2.[[controller]]).+ if !this.canceled2.get() {+ readable_stream_default_controller_close(cx, controller2);+ }++ // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.+ if !this.canceled1.get() || !this.canceled2.get() {+ resolve_promise(vm, this.cancel_promise, Value::UNDEFINED);+ }+ }++ // error steps+ pub(crate) fn read_request_error_steps(this: Gc<EmbedderCell<Self>>, _: &Vm, _: Value) {+ // 1. Set reading to false.+ this.reading.set(false);+ }+}++/// The variables of ReadableByteStreamTee that its algorithms and its read requests share,+/// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamtee+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ByteTeeState {+ stream: Ref<ReadableStream>,+ reader: Cell<ReadableStreamReader>,+ reading: Cell<bool>,+ read_again_for_branch1: Cell<bool>,+ read_again_for_branch2: Cell<bool>,+ canceled1: Cell<bool>,+ canceled2: Cell<bool>,+ reason1: Cell<Value>,+ reason2: Cell<Value>,+ branch1: Cell<Option<Ref<ReadableStream>>>,+ branch2: Cell<Option<Ref<ReadableStream>>>,+ cancel_promise: WebIdlPromise,+}++static BYTE_TEE_STATE_CLASS: EmbedderClass<ByteTeeState> = EmbedderClass::new("ReadableByteStreamTee");++impl EmbedderValue for ByteTeeState {+ const CLASS: &'static EmbedderClass<Self> = &BYTE_TEE_STATE_CLASS;+}++impl ByteTeeState {+ /// The context of the realm of cancelPromise, which the read requests run in.+ fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, promise_realm(self.cancel_promise))+ }++ fn branch1(&self) -> Ref<ReadableStream> {+ self.branch1.get().expect("the tee has created its branches")+ }++ fn branch2(&self) -> Ref<ReadableStream> {+ self.branch2.get().expect("the tee has created its branches")+ }++ /// branch1.[[controller]] and branch2.[[controller]].+ fn controllers(&self) -> (Ref<ReadableByteStreamController>, Ref<ReadableByteStreamController>) {+ (byte_controller_of(self.branch1()), byte_controller_of(self.branch2()))+ }++ // forwardReaderError, given thisReader+ fn forward_reader_error(this: Gc<EmbedderCell<Self>>, cx: &CallContext, this_reader: ReadableStreamReader) {+ // 1. Upon rejection of thisReader.[[closedPromise]] with reason r,+ let closed_promise = this_reader+ .generic()+ .closed_promise()+ .expect("a reader of a stream has a closed promise");++ upon_rejection(+ cx.vm(),+ closed_promise,+ (this, this_reader),+ |cx, (this, this_reader), reason| {+ let (controller1, controller2) = this.controllers();++ // 1. If thisReader is not reader, return.+ if this_reader != this.reader.get() {+ return Ok(Value::UNDEFINED);+ }++ // 2. Perform ! ReadableByteStreamControllerError(branch1.[[controller]], r).+ readable_byte_stream_controller_error(cx, controller1, reason);++ // 3. Perform ! ReadableByteStreamControllerError(branch2.[[controller]], r).+ readable_byte_stream_controller_error(cx, controller2, reason);++ // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.+ if !this.canceled1.get() || !this.canceled2.get() {+ resolve_promise(cx.vm(), this.cancel_promise, Value::UNDEFINED);+ }++ Ok(Value::UNDEFINED)+ },+ );+ }++ // pullWithDefaultReader+ fn pull_with_default_reader(this: Gc<EmbedderCell<Self>>, cx: &CallContext) {+ // 1. If reader implements ReadableStreamBYOBReader,+ if let ReadableStreamReader::ReadableStreamBYOBReader(byob_reader) = this.reader.get() {+ // 1. Assert: reader.[[readIntoRequests]] is empty.+ assert!(byob_reader.read_into_requests_is_empty());++ // 2. Perform ! ReadableStreamBYOBReaderRelease(reader).+ readable_stream_byob_reader_release(cx.vm(), byob_reader);++ // 3. Set reader to ! AcquireReadableStreamDefaultReader(stream).+ let reader = acquire_readable_stream_default_reader(cx, this.stream).must();+ this.reader+ .set(ReadableStreamReader::ReadableStreamDefaultReader(reader));++ // 4. Perform forwardReaderError, given reader.+ Self::forward_reader_error(this, cx, this.reader.get());+ }++ // 2. Let readRequest be a read request with the following items:+ let read_request = ReadRequest::ByteTee(this);++ // 3. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).+ let ReadableStreamReader::ReadableStreamDefaultReader(reader) = this.reader.get() else {+ unreachable!("the reader is a ReadableStreamDefaultReader");+ };+ readable_stream_default_reader_read(cx.vm(), reader, read_request);+ }++ // pullWithBYOBReader, given view and forBranch2+ fn pull_with_byob_reader(this: Gc<EmbedderCell<Self>>, cx: &CallContext, view: ArrayBufferView, for_branch2: bool) {+ // 1. If reader implements ReadableStreamDefaultReader,+ if let ReadableStreamReader::ReadableStreamDefaultReader(default_reader) = this.reader.get() {+ // 2. Assert: reader.[[readRequests]] is empty.+ assert!(default_reader.read_requests_is_empty());++ // 3. Perform ! ReadableStreamDefaultReaderRelease(reader).+ readable_stream_default_reader_release(cx.vm(), default_reader);++ // 4. Set reader to ! AcquireReadableStreamBYOBReader(stream).+ let reader = acquire_readable_stream_byob_reader(cx, this.stream).must();+ this.reader.set(ReadableStreamReader::ReadableStreamBYOBReader(reader));++ // 5. Perform forwardReaderError, given reader.+ Self::forward_reader_error(this, cx, this.reader.get());+ }++ // 2. Let byobBranch be branch2 if forBranch2 is true, and branch1 otherwise.+ let byob_branch = if for_branch2 { this.branch2() } else { this.branch1() };++ // 3. Let otherBranch be branch2 if forBranch2 is false, and branch1 otherwise.+ let other_branch = if !for_branch2 { this.branch2() } else { this.branch1() };++ // 4. Let readIntoRequest be a read-into request with the following items:+ let read_into_request = ReadIntoRequest::ByteTee(BYTE_TEE_BYOB_READ_REQUEST_CLASS.allocate(+ cx.vm(),+ ByteTeeBYOBReadRequest {+ state: this,+ byob_branch,+ other_branch,+ for_branch2,+ },+ ));++ // 5. Perform ! ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest).+ let ReadableStreamReader::ReadableStreamBYOBReader(reader) = this.reader.get() else {+ unreachable!("the reader is a ReadableStreamBYOBReader");+ };+ readable_stream_byob_reader_read(cx.vm(), reader, view, 1, read_into_request);+ }++ /// The pull1Algorithm of the tee.+ pub(crate) fn pull1_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext) -> WebIdlPromise {+ // 1. If reading is true,+ if this.reading.get() {+ // 1. Set readAgainForBranch1 to true.+ this.read_again_for_branch1.set(true);++ // 2. Return a promise resolved with undefined.+ return create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED);+ }++ // 2. Set reading to true.+ this.reading.set(true);++ // 3. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(branch1.[[controller]]).+ let byob_request = readable_byte_stream_controller_get_byob_request(cx, byte_controller_of(this.branch1()));++ match byob_request {+ // 4. If byobRequest is null, perform pullWithDefaultReader.+ None => Self::pull_with_default_reader(this, cx),+ // 5. Otherwise, perform pullWithBYOBReader, given byobRequest.[[view]] and false.+ Some(byob_request) => {+ let view = byob_request+ .current_view()+ .expect("a BYOB request of a controller has a view");+ Self::pull_with_byob_reader(this, cx, ArrayBufferView::TypedArray(view), false);+ }+ }++ // 6. Return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }++ /// The pull2Algorithm of the tee.+ pub(crate) fn pull2_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext) -> WebIdlPromise {+ // 1. If reading is true,+ if this.reading.get() {+ // 1. Set readAgainForBranch2 to true.+ this.read_again_for_branch2.set(true);++ // 2. Return a promise resolved with undefined.+ return create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED);+ }++ // 2. Set reading to true.+ this.reading.set(true);++ // 3. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(branch2.[[controller]]).+ let byob_request = readable_byte_stream_controller_get_byob_request(cx, byte_controller_of(this.branch2()));++ match byob_request {+ // 4. If byobRequest is null, perform pullWithDefaultReader.+ None => Self::pull_with_default_reader(this, cx),+ // 5. Otherwise, perform pullWithBYOBReader, given byobRequest.[[view]] and true.+ Some(byob_request) => {+ let view = byob_request+ .current_view()+ .expect("a BYOB request of a controller has a view");+ Self::pull_with_byob_reader(this, cx, ArrayBufferView::TypedArray(view), true);+ }+ }++ // 6. Return a promise resolved with undefined.+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)+ }++ /// The cancel1Algorithm of the tee.+ pub(crate) fn cancel1_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Set canceled1 to true.+ this.canceled1.set(true);++ // 2. Set reason1 to reason.+ this.reason1.set(reason);++ // 3. If canceled2 is true,+ if this.canceled2.get() {+ // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).+ let composite_reason = create_array_from_list(cx, &[this.reason1.get(), this.reason2.get()]);++ // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).+ let cancel_result = readable_stream_cancel(cx, this.stream, composite_reason);++ // 3. Resolve cancelPromise with cancelResult.+ resolve_promise(+ cx.vm(),+ this.cancel_promise,+ Value::from_object(cancel_result.promise()),+ );+ }++ // 4. Return cancelPromise.+ this.cancel_promise+ }++ /// The cancel2Algorithm of the tee.+ pub(crate) fn cancel2_algorithm(this: Gc<EmbedderCell<Self>>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Set canceled2 to true.+ this.canceled2.set(true);++ // 2. Set reason2 to reason.+ this.reason2.set(reason);++ // 3. If canceled1 is true,+ if this.canceled1.get() {+ // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).+ let composite_reason = create_array_from_list(cx, &[this.reason1.get(), this.reason2.get()]);++ // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).+ let cancel_result = readable_stream_cancel(cx, this.stream, composite_reason);++ // 3. Resolve cancelPromise with cancelResult.+ resolve_promise(+ cx.vm(),+ this.cancel_promise,+ Value::from_object(cancel_result.promise()),+ );+ }++ // 4. Return cancelPromise.+ this.cancel_promise+ }++ // chunk steps, given chunk, of the read request of pullWithDefaultReader+ pub(crate) fn default_read_request_chunk_steps(this: Gc<EmbedderCell<Self>>, vm: &Vm, chunk: Value) {+ // 1. Queue a microtask to perform the following steps:+ queue_a_microtask(+ vm,+ promise_realm(this.cancel_promise),+ (this, chunk),+ |vm, (this, chunk)| {+ with_temporary_execution_context_and_callbacks(promise_realm(this.cancel_promise), || {+ let cx = &this.context(vm);+ let (controller1, controller2) = this.controllers();++ // 1. Set readAgainForBranch1 to false.+ this.read_again_for_branch1.set(false);++ // 2. Set readAgainForBranch2 to false.+ this.read_again_for_branch2.set(false);++ // 3. Let chunk1 and chunk2 be chunk.+ let chunk1 = chunk;+ let mut chunk2 = chunk;++ // 4. If canceled1 is false and canceled2 is false,+ if !this.canceled1.get() && !this.canceled2.get() {+ // 1. Let cloneResult be CloneAsUint8Array(chunk).+ let clone_result = clone_as_uint8_array(cx, array_buffer_view_of(chunk));++ match clone_result {+ // 2. If cloneResult is an abrupt completion,+ Err(exception) => {+ let error = exception_value(vm, cx.realm(), exception);++ // 1. Perform ! ReadableByteStreamControllerError(branch1.[[controller]],+ // cloneResult.[[Value]]).+ readable_byte_stream_controller_error(cx, controller1, error);++ // 2. Perform ! ReadableByteStreamControllerError(branch2.[[controller]],+ // cloneResult.[[Value]]).+ readable_byte_stream_controller_error(cx, controller2, error);++ // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).+ let cancel_result = readable_stream_cancel(cx, this.stream, error);+ resolve_promise(vm, this.cancel_promise, Value::from_object(cancel_result.promise()));++ // 4. Return.+ return;+ }+ // 3. Otherwise, set chunk2 to cloneResult.[[Value]].+ Ok(value) => chunk2 = value,+ }+ }++ // 5. If canceled1 is false, perform ! ReadableByteStreamControllerEnqueue(branch1.[[controller]],+ // chunk1).+ if !this.canceled1.get() {+ readable_byte_stream_controller_enqueue(cx, controller1, array_buffer_view_of(chunk1)).must();+ }++ // 6. If canceled2 is false, perform ! ReadableByteStreamControllerEnqueue(branch2.[[controller]],+ // chunk2).+ if !this.canceled2.get() {+ readable_byte_stream_controller_enqueue(cx, controller2, array_buffer_view_of(chunk2)).must();+ }++ // 7. Set reading to false.+ this.reading.set(false);++ // 8. If readAgainForBranch1 is true, perform pull1Algorithm.+ if this.read_again_for_branch1.get() {+ Self::pull1_algorithm(this, cx);+ }+ // 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.+ else if this.read_again_for_branch2.get() {+ Self::pull2_algorithm(this, cx);+ }+ });+ },+ );++ // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we+ // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we+ // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.+ }++ // close steps, of the read request of pullWithDefaultReader+ pub(crate) fn default_read_request_close_steps(this: Gc<EmbedderCell<Self>>, vm: &Vm) {+ let cx = &this.context(vm);+ let (controller1, controller2) = this.controllers();++ // 1. Set reading to false.+ this.reading.set(false);++ // 2. If canceled1 is false, perform ! ReadableByteStreamControllerClose(branch1.[[controller]]).+ if !this.canceled1.get() {+ readable_byte_stream_controller_close(cx, controller1).must();+ }++ // 3. If canceled2 is false, perform ! ReadableByteStreamControllerClose(branch2.[[controller]]).+ if !this.canceled2.get() {+ readable_byte_stream_controller_close(cx, controller2).must();+ }++ // 4. If branch1.[[controller]].[[pendingPullIntos]] is not empty, perform+ // ! ReadableByteStreamControllerRespond(branch1.[[controller]], 0).+ if !controller1.pending_pull_intos_is_empty() {+ readable_byte_stream_controller_respond(cx, controller1, 0).must();+ }++ // 5. If branch2.[[controller]].[[pendingPullIntos]] is not empty, perform+ // ! ReadableByteStreamControllerRespond(branch2.[[controller]], 0).+ if !controller2.pending_pull_intos_is_empty() {+ readable_byte_stream_controller_respond(cx, controller2, 0).must();+ }++ // 6. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.+ if !this.canceled1.get() || !this.canceled2.get() {+ resolve_promise(vm, this.cancel_promise, Value::UNDEFINED);+ }+ }++ // error steps, of the read request of pullWithDefaultReader+ pub(crate) fn default_read_request_error_steps(this: Gc<EmbedderCell<Self>>, _: &Vm, _: Value) {+ // 1. Set reading to false.+ this.reading.set(false);+ }+}++/// The read-into request of ReadableByteStreamTee's pullWithBYOBReader.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ByteTeeBYOBReadRequest {+ state: Gc<EmbedderCell<ByteTeeState>>,+ byob_branch: Ref<ReadableStream>,+ other_branch: Ref<ReadableStream>,+ #[gc(untraced)]+ for_branch2: bool,+}++static BYTE_TEE_BYOB_READ_REQUEST_CLASS: EmbedderClass<ByteTeeBYOBReadRequest> =+ EmbedderClass::new("ReadableByteStreamTeeBYOBReadRequest");++impl EmbedderValue for ByteTeeBYOBReadRequest {+ const CLASS: &'static EmbedderClass<Self> = &BYTE_TEE_BYOB_READ_REQUEST_CLASS;+}++impl ByteTeeBYOBReadRequest {+ // chunk steps, given chunk+ pub(crate) fn chunk_steps(&self, vm: &Vm, chunk: Value) {+ let captures = (self.state, self.byob_branch, self.other_branch, self.for_branch2, chunk);++ // 1. Queue a microtask to perform the following steps:+ queue_a_microtask(+ vm,+ promise_realm(self.state.cancel_promise),+ captures,+ |vm, (state, byob_branch, other_branch, for_branch2, chunk)| {+ with_temporary_execution_context_and_callbacks(promise_realm(state.cancel_promise), || {+ let cx = &state.context(vm);+ let chunk = array_buffer_view_of(chunk);+ let byob_controller = byte_controller_of(byob_branch);+ let other_controller = byte_controller_of(other_branch);++ // 1. Set readAgainForBranch1 to false.+ state.read_again_for_branch1.set(false);++ // 2. Set readAgainForBranch2 to false.+ state.read_again_for_branch2.set(false);++ // 3. Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.+ let byob_canceled = if for_branch2 {+ state.canceled2.get()+ } else {+ state.canceled1.get()+ };++ // 4. Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.+ let other_canceled = if !for_branch2 {+ state.canceled2.get()+ } else {+ state.canceled1.get()+ };++ // 5. If otherCanceled is false,+ if !other_canceled {+ // 1. Let cloneResult be CloneAsUint8Array(chunk).+ let clone_result = clone_as_uint8_array(cx, chunk);++ // 2. If cloneResult is an abrupt completion,+ let cloned_chunk = match clone_result {+ Err(exception) => {+ let error = exception_value(vm, cx.realm(), exception);++ // 1. Perform ! ReadableByteStreamControllerError(byobBranch.[[controller]],+ // cloneResult.[[Value]]).+ readable_byte_stream_controller_error(cx, byob_controller, error);++ // 2. Perform ! ReadableByteStreamControllerError(otherBranch.[[controller]],+ // cloneResult.[[Value]]).+ readable_byte_stream_controller_error(cx, other_controller, error);++ // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).+ let cancel_result = readable_stream_cancel(cx, state.stream, error);+ resolve_promise(vm, state.cancel_promise, Value::from_object(cancel_result.promise()));++ // 4. Return.+ return;+ }+ // 3. Otherwise, let clonedChunk be cloneResult.[[Value]].+ Ok(cloned_chunk) => cloned_chunk,+ };++ // 4. If byobCanceled is false, perform+ // ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).+ if !byob_canceled {+ readable_byte_stream_controller_respond_with_new_view(cx, byob_controller, chunk).must();+ }++ // 5. Perform ! ReadableByteStreamControllerEnqueue(otherBranch.[[controller]], clonedChunk).+ readable_byte_stream_controller_enqueue(+ cx,+ other_controller,+ array_buffer_view_of(cloned_chunk),+ )+ .must();+ }+ // 6. Otherwise, if byobCanceled is false, perform+ // ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).+ else if !byob_canceled {+ readable_byte_stream_controller_respond_with_new_view(cx, byob_controller, chunk).must();+ }++ // 7. Set reading to false.+ state.reading.set(false);++ // 8. If readAgainForBranch1 is true, perform pull1Algorithm.+ if state.read_again_for_branch1.get() {+ ByteTeeState::pull1_algorithm(state, cx);+ }+ // 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.+ else if state.read_again_for_branch2.get() {+ ByteTeeState::pull2_algorithm(state, cx);+ }+ });+ },+ );++ // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we+ // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we+ // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.+ }++ // close steps, given chunk+ pub(crate) fn close_steps(&self, vm: &Vm, chunk: Value) {+ let state = self.state;+ let cx = &state.context(vm);+ let byob_controller = byte_controller_of(self.byob_branch);+ let other_controller = byte_controller_of(self.other_branch);++ // 1. Set reading to false.+ state.reading.set(false);++ // 2. Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.+ let byob_canceled = if self.for_branch2 {+ state.canceled2.get()+ } else {+ state.canceled1.get()+ };++ // 3. Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.+ let other_canceled = if !self.for_branch2 {+ state.canceled2.get()+ } else {+ state.canceled1.get()+ };++ // 4. If byobCanceled is false, perform ! ReadableByteStreamControllerClose(byobBranch.[[controller]]).+ if !byob_canceled {+ readable_byte_stream_controller_close(cx, byob_controller).must();+ }++ // 5. If otherCanceled is false, perform ! ReadableByteStreamControllerClose(otherBranch.[[controller]]).+ if !other_canceled {+ readable_byte_stream_controller_close(cx, other_controller).must();+ }++ // 6. If chunk is not undefined,+ if !chunk.is_undefined() {+ // 1. Assert: chunk.[[ByteLength]] is 0.++ // 2. If byobCanceled is false, perform+ // ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).+ if !byob_canceled {+ readable_byte_stream_controller_respond_with_new_view(cx, byob_controller, array_buffer_view_of(chunk))+ .must();+ }++ // 3. If otherCanceled is false and otherBranch.[[controller]].[[pendingPullIntos]] is not empty,+ // perform ! ReadableByteStreamControllerRespond(otherBranch.[[controller]], 0).+ if !other_canceled && !other_controller.pending_pull_intos_is_empty() {+ readable_byte_stream_controller_respond(cx, other_controller, 0).must();+ }+ }++ // 7. If byobCanceled is false or otherCanceled is false, resolve cancelPromise with undefined.+ if !byob_canceled || !other_canceled {+ resolve_promise(vm, state.cancel_promise, Value::UNDEFINED);+ }+ }++ // error steps+ pub(crate) fn error_steps(&self, _: &Vm, _: Value) {+ // 1. Set reading to false.+ self.state.reading.set(false);+ }+}++/// The [[controller]] of a branch of ReadableStreamDefaultTee.+fn default_controller_of(branch: Ref<ReadableStream>) -> Ref<ReadableStreamDefaultController> {+ let Some(ReadableStreamController::ReadableStreamDefaultController(controller)) = branch.controller() else {+ panic!("a branch of a default tee has a ReadableStreamDefaultController");+ };+ controller+}++/// The [[controller]] of a branch of ReadableByteStreamTee.+fn byte_controller_of(branch: Ref<ReadableStream>) -> Ref<ReadableByteStreamController> {+ let Some(ReadableStreamController::ReadableByteStreamController(controller)) = branch.controller() else {+ panic!("a branch of a byte tee has a ReadableByteStreamController");+ };+ controller+}++/// A chunk of a byte stream, which is an ArrayBufferView, as one.+fn array_buffer_view_of(chunk: Value) -> ArrayBufferView {+ match buffer_source_type_of(chunk) {+ Some(BufferSource::TypedArray(typed_array)) => ArrayBufferView::TypedArray(typed_array),+ Some(BufferSource::DataView(view)) => ArrayBufferView::DataView(view),+ _ => panic!("a chunk of a byte stream is an ArrayBufferView"),+ }+}++// https://streams.spec.whatwg.org/#readable-stream-tee+pub(crate) fn readable_stream_tee(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ clone_for_branch2: bool,+) -> WebIdlResult<(Ref<ReadableStream>, Ref<ReadableStream>)> {+ // 1. Assert: stream implements ReadableStream.+ // 2. Assert: cloneForBranch2 is a boolean.++ // 3. If stream.[[controller]] implements ReadableByteStreamController, return ? ReadableByteStreamTee(stream).+ if let Some(ReadableStreamController::ReadableByteStreamController(_)) = stream.controller() {+ return readable_byte_stream_tee(cx, stream);+ }++ // 4. Return ? ReadableStreamDefaultTee(stream, cloneForBranch2).+ readable_stream_default_tee(cx, stream, clone_for_branch2)+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee+pub(crate) fn readable_stream_default_tee(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+ clone_for_branch2: bool,+) -> WebIdlResult<(Ref<ReadableStream>, Ref<ReadableStream>)> {+ let vm = cx.vm();++ // 1. Assert: stream implements ReadableStream.+ // 2. Assert: cloneForBranch2 is a boolean.++ // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).+ let reader = acquire_readable_stream_default_reader(cx, stream)?;++ // 4. Let reading be false.+ // 5. Let readAgain be false.+ // 6. Let canceled1 be false.+ // 7. Let canceled2 be false.+ // 8. Let reason1 be undefined.+ // 9. Let reason2 be undefined.+ // 10. Let branch1 be undefined.+ // 11. Let branch2 be undefined.+ // 12. Let cancelPromise be a new promise.+ let cancel_promise = create_promise(vm, cx.realm());+ let state = DEFAULT_TEE_STATE_CLASS.allocate(+ vm,+ DefaultTeeState {+ stream,+ reader,+ reading: Cell::new(false),+ read_again: Cell::new(false),+ canceled1: Cell::new(false),+ canceled2: Cell::new(false),+ reason1: Cell::new(Value::UNDEFINED),+ reason2: Cell::new(Value::UNDEFINED),+ branch1: Cell::new(None),+ branch2: Cell::new(None),+ cancel_promise,+ clone_for_branch2,+ },+ );++ // 13. Let pullAlgorithm be the following steps:+ // 14. Let cancel1Algorithm be the following steps, taking a reason argument:+ // 15. Let cancel2Algorithm be the following steps, taking a reason argument:+ // 16. Let startAlgorithm be an algorithm that returns undefined.++ // 17. Set branch1 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm).+ let branch1 = create_readable_stream(+ cx,+ StartAlgorithm::ReturnsUndefined,+ PullAlgorithm::DefaultTee(state),+ CancelAlgorithm::DefaultTee {+ state,+ for_branch2: false,+ },+ None,+ None,+ )+ .must();+ state.branch1.set(Some(branch1));++ // 18. Set branch2 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm).+ let branch2 = create_readable_stream(+ cx,+ StartAlgorithm::ReturnsUndefined,+ PullAlgorithm::DefaultTee(state),+ CancelAlgorithm::DefaultTee {+ state,+ for_branch2: true,+ },+ None,+ None,+ )+ .must();+ state.branch2.set(Some(branch2));++ // 19. Upon rejection of reader.[[closedPromise]] with reason r,+ let closed_promise = reader+ .generic()+ .closed_promise()+ .expect("a reader of a stream has a closed promise");+ upon_rejection(vm, closed_promise, state, |cx, state, reason| {+ let (controller1, controller2) = state.controllers();++ // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], r).+ readable_stream_default_controller_error(cx, controller1, reason);++ // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], r).+ readable_stream_default_controller_error(cx, controller2, reason);++ // 3. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.+ if !state.canceled1.get() || !state.canceled2.get() {+ resolve_promise(cx.vm(), state.cancel_promise, Value::UNDEFINED);+ }++ Ok(Value::UNDEFINED)+ });++ // 20. Return « branch1, branch2 ».+ Ok((branch1, branch2))+}++// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamtee+pub(crate) fn readable_byte_stream_tee(+ cx: &CallContext,+ stream: Ref<ReadableStream>,+) -> WebIdlResult<(Ref<ReadableStream>, Ref<ReadableStream>)> {+ let vm = cx.vm();++ // 1. Assert: stream implements ReadableStream.+ // 2. Assert: stream.[[controller]] implements ReadableByteStreamController.+ assert!(matches!(+ stream.controller(),+ Some(ReadableStreamController::ReadableByteStreamController(_))+ ));++ // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).+ let reader = acquire_readable_stream_default_reader(cx, stream)?;++ // 4. Let reading be false.+ // 5. Let readAgainForBranch1 be false.+ // 6. Let readAgainForBranch2 be false.+ // 7. Let canceled1 be false.+ // 8. Let canceled2 be false.+ // 9. Let reason1 be undefined.+ // 10. Let reason2 be undefined.+ // 11. Let branch1 be undefined.+ // 12. Let branch2 be undefined.+ // 13. Let cancelPromise be a new promise.+ let cancel_promise = create_promise(vm, cx.realm());+ let state = BYTE_TEE_STATE_CLASS.allocate(+ vm,+ ByteTeeState {+ stream,+ reader: Cell::new(ReadableStreamReader::ReadableStreamDefaultReader(reader)),+ reading: Cell::new(false),+ read_again_for_branch1: Cell::new(false),+ read_again_for_branch2: Cell::new(false),+ canceled1: Cell::new(false),+ canceled2: Cell::new(false),+ reason1: Cell::new(Value::UNDEFINED),+ reason2: Cell::new(Value::UNDEFINED),+ branch1: Cell::new(None),+ branch2: Cell::new(None),+ cancel_promise,+ },+ );++ // 14. Let forwardReaderError be the following steps, taking a thisReader argument:+ // 15. Let pullWithDefaultReader be the following steps:+ // 16. Let pullWithBYOBReader be the following steps, given view and forBranch2:+ // 17. Let pull1Algorithm be the following steps:+ // 18. Let pull2Algorithm be the following steps:+ // 19. Let cancel1Algorithm be the following steps, taking a reason argument:+ // 20. Let cancel2Algorithm be the following steps, taking a reason argument:+ // 21. Let startAlgorithm be an algorithm that returns undefined.++ // 22. Set branch1 to ! CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm).+ let branch1 = create_readable_byte_stream(+ cx,+ StartAlgorithm::ReturnsUndefined,+ PullAlgorithm::ByteTee {+ state,+ for_branch2: false,+ },+ CancelAlgorithm::ByteTee {+ state,+ for_branch2: false,+ },+ )+ .must();+ state.branch1.set(Some(branch1));++ // 23. Set branch2 to ! CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm).+ let branch2 = create_readable_byte_stream(+ cx,+ StartAlgorithm::ReturnsUndefined,+ PullAlgorithm::ByteTee {+ state,+ for_branch2: true,+ },+ CancelAlgorithm::ByteTee {+ state,+ for_branch2: true,+ },+ )+ .must();+ state.branch2.set(Some(branch2));++ // 24. Perform forwardReaderError, given reader.+ ByteTeeState::forward_reader_error(state, cx, ReadableStreamReader::ReadableStreamDefaultReader(reader));++ // 25. Return « branch1, branch2 ».+ Ok((branch1, branch2))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rsnew file mode 100644index 00000000000..335f72bc112--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream.rs@@ -0,0 +1,864 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! TransformStream, https://streams.spec.whatwg.org/#ts-class, and the abstract operations that work with transform+//! streams, https://streams.spec.whatwg.org/#ts-abstract-ops++use core::cell::Cell;++use libjs_rust::api::{Gc, Object, Realm, Throw, Trace, Value, Vm};++use crate::bindings::conversions::FromJs;+use crate::bindings::interface::{Ref, Wrappable, allocate, implementation_of, wrap};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_resolved_promise, promise_realm, react_to_promise, reject_promise,+ resolve_promise, upon_fulfillment,+};+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::streams::algorithms::{+ AbortAlgorithm, CancelAlgorithm, CloseAlgorithm, FlushAlgorithm, PullAlgorithm, SizeAlgorithm, StartAlgorithm,+ TransformAlgorithm, WriteAlgorithm,+};+use crate::streams::cross_realm_transform::{deserialize_with_transfer, serialize_with_transfer};+use crate::streams::queuing_strategy::{QueuingStrategy, extract_high_water_mark, extract_size_algorithm};+use crate::streams::readable_stream::{+ ReadableStream, ReadableStreamState, create_readable_stream, is_readable_stream_locked,+};+use crate::streams::readable_stream_default_controller::{+ ReadableStreamDefaultController, readable_stream_default_controller_close, readable_stream_default_controller_error,+};+use crate::streams::transform_stream_default_controller::{+ TransformStreamDefaultController, set_up_transform_stream_default_controller,+ set_up_transform_stream_default_controller_from_transformer, transform_stream_default_controller_clear_algorithms,+ transform_stream_default_controller_enqueue, transform_stream_default_controller_perform_transform,+};+use crate::streams::transformer::Transformer;+use crate::streams::underlying_source::ReadableStreamController;+use crate::streams::writable_stream::{+ WritableStream, WritableStreamState, create_writable_stream, is_writable_stream_locked,+};+use crate::streams::writable_stream_default_controller::writable_stream_default_controller_error_if_needed;++// https://streams.spec.whatwg.org/#transformstream+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TransformStream {+ /// The realm of the stream, which its promises and the results of its operations are created in.+ realm: Cell<Gc<Realm>>,+ // https://streams.spec.whatwg.org/#transformstream-backpressure+ #[gc(untraced)]+ backpressure: Cell<Option<bool>>,+ // https://streams.spec.whatwg.org/#transformstream-backpressurechangepromise+ backpressure_change_promise: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#transformstream-controller+ controller: Cell<Option<Ref<TransformStreamDefaultController>>>,+ // https://streams.spec.whatwg.org/#transformstream-detached+ detached: Cell<bool>,+ // https://streams.spec.whatwg.org/#transformstream-readable+ readable: Cell<Option<Ref<ReadableStream>>>,+ // https://streams.spec.whatwg.org/#transformstream-writable+ writable: Cell<Option<Ref<WritableStream>>>,+}++impl Wrappable for TransformStream {}++impl TransformStream {+ pub(crate) fn new(realm: Gc<Realm>) -> Self {+ Self {+ realm: Cell::new(realm),+ backpressure: Cell::new(Some(false)),+ backpressure_change_promise: Cell::new(None),+ controller: Cell::new(None),+ detached: Cell::new(false),+ readable: Cell::new(None),+ writable: Cell::new(None),+ }+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm.get()+ }++ /// The context of the realm of the stream.+ pub(crate) fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, self.realm())+ }++ /// The stream's [[readable]], which it has once it is initialized.+ pub(crate) fn readable_stream(&self) -> Ref<ReadableStream> {+ self.readable+ .get()+ .expect("a transform stream that is initialized has a readable stream")+ }++ /// The stream's [[writable]], which it has once it is initialized.+ pub(crate) fn writable_stream(&self) -> Ref<WritableStream> {+ self.writable+ .get()+ .expect("a transform stream that is initialized has a writable stream")+ }++ pub(crate) fn set_readable(&self, readable: Option<Ref<ReadableStream>>) {+ self.readable.set(readable);+ }++ pub(crate) fn set_writable(&self, writable: Option<Ref<WritableStream>>) {+ self.writable.set(writable);+ }++ pub(crate) fn controller(&self) -> Option<Ref<TransformStreamDefaultController>> {+ self.controller.get()+ }++ pub(crate) fn set_controller(&self, controller: Option<Ref<TransformStreamDefaultController>>) {+ self.controller.set(controller);+ }++ pub(crate) fn backpressure(&self) -> Option<bool> {+ self.backpressure.get()+ }++ pub(crate) fn set_backpressure(&self, backpressure: Option<bool>) {+ self.backpressure.set(backpressure);+ }++ pub(crate) fn backpressure_change_promise(&self) -> Option<WebIdlPromise> {+ self.backpressure_change_promise.get()+ }++ pub(crate) fn set_backpressure_change_promise(&self, promise: Option<WebIdlPromise>) {+ self.backpressure_change_promise.set(promise);+ }++ /// The realm of the stream's [[backpressureChangePromise]].+ pub(crate) fn backpressure_change_promise_realm(&self) -> Gc<Realm> {+ promise_realm(+ self.backpressure_change_promise()+ .expect("the stream has a backpressure change promise"),+ )+ }++ // https://streams.spec.whatwg.org/#ts-constructor+ pub(crate) fn construct(+ cx: &mut CallContext,+ transformer: Option<Gc<Object>>,+ writable_strategy: QueuingStrategy,+ readable_strategy: QueuingStrategy,+ ) -> WebIdlResult<Ref<Self>> {+ let this = allocate(cx.vm(), Self::new(cx.realm()));++ // 1. If transformer is missing, set it to null.+ let transformer = transformer.map_or(Value::NULL, Value::from_object);++ // 2. Let transformerDict be transformer, converted to an IDL value of type Transformer.+ let transformer_dict = Transformer::from_js(cx.vm(), transformer)?;++ // 3. If transformerDict["readableType"] exists, throw a RangeError exception.+ if transformer_dict.readable_type.is_some() {+ return Err(Exception::range_error("Invalid use of reserved key 'readableType'"));+ }++ // 4. If transformerDict["writableType"] exists, throw a RangeError exception.+ if transformer_dict.writable_type.is_some() {+ return Err(Exception::range_error("Invalid use of reserved key 'writableType'"));+ }++ // 5. Let readableHighWaterMark be ? ExtractHighWaterMark(readableStrategy, 0).+ let readable_high_water_mark = extract_high_water_mark(&readable_strategy, 0.0)?;++ // 6. Let readableSizeAlgorithm be ! ExtractSizeAlgorithm(readableStrategy).+ let readable_size_algorithm = extract_size_algorithm(&readable_strategy);++ // 7. Let writableHighWaterMark be ? ExtractHighWaterMark(writableStrategy, 1).+ let writable_high_water_mark = extract_high_water_mark(&writable_strategy, 1.0)?;++ // 8. Let writableSizeAlgorithm be ! ExtractSizeAlgorithm(writableStrategy).+ let writable_size_algorithm = extract_size_algorithm(&writable_strategy);++ // 9. Let startPromise be a new promise.+ let start_promise = create_promise(cx.vm(), cx.realm());++ // 10. Perform ! InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm,+ // readableHighWaterMark, readableSizeAlgorithm).+ initialize_transform_stream(+ cx,+ this,+ start_promise,+ writable_high_water_mark,+ writable_size_algorithm,+ readable_high_water_mark,+ readable_size_algorithm,+ );++ // 11. Perform ? SetUpTransformStreamDefaultControllerFromTransformer(this, transformer, transformerDict).+ let start = transformer_dict.start.clone();+ set_up_transform_stream_default_controller_from_transformer(cx, this, transformer, transformer_dict);++ // 12. If transformerDict["start"] exists, then resolve startPromise with the result of invoking+ // transformerDict["start"] with argument list « this.[[controller]] » and callback this value transformer.+ if let Some(start) = start {+ let controller = this+ .controller()+ .expect("a transform stream that is set up has a controller");+ let result = start.invoke(Some(transformer), &[Value::from_object(wrap(cx, controller))])?;+ resolve_promise(cx.vm(), start_promise, result);+ }+ // 13. Otherwise, resolve startPromise with undefined.+ else {+ resolve_promise(cx.vm(), start_promise, Value::UNDEFINED);+ }++ Ok(this)+ }++ // https://streams.spec.whatwg.org/#ts-readable+ pub(crate) fn readable(&self, _: &mut CallContext) -> WebIdlResult<Ref<ReadableStream>> {+ // 1. Return this.[[readable]].+ Ok(self.readable_stream())+ }++ // https://streams.spec.whatwg.org/#ts-writable+ pub(crate) fn writable(&self, _: &mut CallContext) -> WebIdlResult<Ref<WritableStream>> {+ // 1. Return this.[[writable]].+ Ok(self.writable_stream())+ }++ // https://streams.spec.whatwg.org/#transformstream-set-up+ pub(crate) fn set_up(+ this: Ref<Self>,+ cx: &CallContext,+ transform_algorithm: TransformAlgorithm,+ flush_algorithm: FlushAlgorithm,+ cancel_algorithm: CancelAlgorithm,+ ) {+ // 1. Let writableHighWaterMark be 1.+ let writable_high_water_mark = 1.0;++ // 2. Let writableSizeAlgorithm be an algorithm that returns 1.+ let writable_size_algorithm = SizeAlgorithm::ReturnsOne;++ // 3. Let readableHighWaterMark be 0.+ let readable_high_water_mark = 0.0;++ // 4. Let readableSizeAlgorithm be an algorithm that returns 1.+ let readable_size_algorithm = SizeAlgorithm::ReturnsOne;++ // 5. Let transformAlgorithmWrapper be an algorithm that runs these steps given a value chunk:+ let transform_algorithm_wrapper = transform_algorithm;++ // 6. Let flushAlgorithmWrapper be an algorithm that runs these steps:+ let flush_algorithm_wrapper = flush_algorithm;++ // 7. Let cancelAlgorithmWrapper be an algorithm that runs these steps given a value reason:+ let cancel_algorithm_wrapper = cancel_algorithm;++ // 8. Let startPromise be a promise resolved with undefined.+ let start_promise = create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED);++ // 9. Perform ! InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm,+ // readableHighWaterMark, readableSizeAlgorithm).+ initialize_transform_stream(+ cx,+ this,+ start_promise,+ writable_high_water_mark,+ writable_size_algorithm,+ readable_high_water_mark,+ readable_size_algorithm,+ );++ // 10. Let controller be a new TransformStreamDefaultController.+ let controller = allocate(cx.vm(), TransformStreamDefaultController::new());++ // 11. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithmWrapper,+ // flushAlgorithmWrapper, cancelAlgorithmWrapper).+ set_up_transform_stream_default_controller(+ this,+ controller,+ transform_algorithm_wrapper,+ flush_algorithm_wrapper,+ cancel_algorithm_wrapper,+ );+ }++ // https://streams.spec.whatwg.org/#transformstream-enqueue+ pub(crate) fn enqueue(this: Ref<Self>, vm: &Vm, chunk: Value) {+ // To enqueue the JavaScript value chunk into a TransformStream stream, perform+ // ! TransformStreamDefaultControllerEnqueue(stream.[[controller]], chunk).+ let controller = this+ .controller()+ .expect("a transform stream that is set up has a controller");+ transform_stream_default_controller_enqueue(+ &CallContext::new(vm, this.backpressure_change_promise_realm()),+ controller,+ chunk,+ )+ .must();+ }+}++impl Transferable for TransformStream {+ fn detached(&self) -> &Cell<bool> {+ &self.detached+ }++ // https://streams.spec.whatwg.org/#ref-for-transfer-steps②+ fn transfer_steps(+ this: &Ref<Self>,+ cx: &mut CallContext,+ data_holder: &mut TransferDataWriter,+ ) -> WebIdlResult<()> {+ // 1. Let readable be value.[[readable]].+ let readable = this.readable_stream();++ // 2. Let writable be value.[[writable]].+ let writable = this.writable_stream();++ // 3. If ! IsReadableStreamLocked(readable) is true, throw a "DataCloneError" DOMException.+ if is_readable_stream_locked(readable) {+ return Err(Exception::Dom(+ "DataCloneError",+ ak::Utf16String::from_ascii(b"Cannot transfer locked ReadableStream"),+ ));+ }++ // 4. If ! IsWritableStreamLocked(writable) is true, throw a "DataCloneError" DOMException.+ if is_writable_stream_locked(writable) {+ return Err(Exception::Dom(+ "DataCloneError",+ ak::Utf16String::from_ascii(b"Cannot transfer locked WritableStream"),+ ));+ }++ // 5. Set dataHolder.[[readable]] to ! StructuredSerializeWithTransfer(readable, « readable »).+ serialize_with_transfer(data_holder, Value::from_object(wrap(cx, readable)));++ // 6. Set dataHolder.[[writable]] to ! StructuredSerializeWithTransfer(writable, « writable »).+ serialize_with_transfer(data_holder, Value::from_object(wrap(cx, writable)));++ Ok(())+ }++ // https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps②+ fn transfer_receiving_steps(cx: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Ref<Self>> {+ let value = allocate(cx.vm(), Self::new(cx.realm()));++ // 1. Let readableRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[readable]], the current Realm).+ let readable_record = deserialize_with_transfer(data_holder);++ // 2. Let writableRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[writable]], the current Realm).+ let writable_record = deserialize_with_transfer(data_holder);++ // 3. Set value.[[readable]] to readableRecord.[[Deserialized]].+ assert!(readable_record.is_object());+ value.set_readable(Some(implementation_of::<ReadableStream>(readable_record.as_object())));++ // 4. Set value.[[writable]] to writableRecord.[[Deserialized]].+ assert!(writable_record.is_object());+ value.set_writable(Some(implementation_of::<WritableStream>(writable_record.as_object())));++ // 5. Set value.[[backpressure]], value.[[backpressureChangePromise]], and value.[[controller]] to undefined.+ value.set_backpressure(None);+ value.set_backpressure_change_promise(None);+ value.set_controller(None);++ Ok(value)+ }+}++/// The ReadableStreamDefaultController of the [[readable]] of a TransformStream.+pub(crate) fn readable_default_controller(readable: Ref<ReadableStream>) -> Ref<ReadableStreamDefaultController> {+ let Some(ReadableStreamController::ReadableStreamDefaultController(controller)) = readable.controller() else {+ panic!("the readable stream of a transform stream has a ReadableStreamDefaultController");+ };+ controller+}++// https://streams.spec.whatwg.org/#initialize-transform-stream+pub(crate) fn initialize_transform_stream(+ cx: &CallContext,+ stream: Ref<TransformStream>,+ start_promise: WebIdlPromise,+ writable_high_water_mark: f64,+ writable_size_algorithm: SizeAlgorithm,+ readable_high_water_mark: f64,+ readable_size_algorithm: SizeAlgorithm,+) {+ // 1. Let startAlgorithm be an algorithm that returns startPromise.+ let start_algorithm = || StartAlgorithm::ReturnsPromise(start_promise);++ // 2. Let writeAlgorithm be the following steps, taking a chunk argument:+ // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).+ let write_algorithm = WriteAlgorithm::TransformStream(stream);++ // 3. Let abortAlgorithm be the following steps, taking a reason argument:+ // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).+ let abort_algorithm = AbortAlgorithm::TransformStream(stream);++ // 4. Let closeAlgorithm be the following steps:+ // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).+ let close_algorithm = CloseAlgorithm::TransformStream(stream);++ // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm,+ // abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).+ let writable = create_writable_stream(+ cx,+ start_algorithm(),+ write_algorithm,+ close_algorithm,+ abort_algorithm,+ writable_high_water_mark,+ writable_size_algorithm,+ )+ .must();+ stream.set_writable(Some(writable));++ // 6. Let pullAlgorithm be the following steps:+ // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).+ let pull_algorithm = PullAlgorithm::TransformStream(stream);++ // 7. Let cancelAlgorithm be the following steps, taking a reason argument:+ // 1. Return ! TransformStreamDefaultSourceCancelAlgorithm(stream, reason).+ let cancel_algorithm = CancelAlgorithm::TransformStream(stream);++ // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm,+ // readableHighWaterMark, readableSizeAlgorithm).+ let readable = create_readable_stream(+ cx,+ start_algorithm(),+ pull_algorithm,+ cancel_algorithm,+ Some(readable_high_water_mark),+ Some(readable_size_algorithm),+ )+ .must();+ stream.set_readable(Some(readable));++ // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.+ stream.set_backpressure(None);+ stream.set_backpressure_change_promise(None);++ // 10. Perform ! TransformStreamSetBackpressure(stream, true).+ transform_stream_set_backpressure(cx, stream, true);++ // 11. Set stream.[[controller]] to undefined.+ stream.set_controller(None);+}++// https://streams.spec.whatwg.org/#transform-stream-error+pub(crate) fn transform_stream_error(cx: &CallContext, stream: Ref<TransformStream>, error: Value) {+ let readable_controller = readable_default_controller(stream.readable_stream());++ // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).+ readable_stream_default_controller_error(cx, readable_controller, error);++ // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).+ transform_stream_error_writable_and_unblock_write(cx, stream, error);+}++// https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write+pub(crate) fn transform_stream_error_writable_and_unblock_write(+ cx: &CallContext,+ stream: Ref<TransformStream>,+ error: Value,+) {+ // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).+ transform_stream_default_controller_clear_algorithms(+ stream+ .controller()+ .expect("a transform stream that is set up has a controller"),+ );++ // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).+ let writable_controller = stream+ .writable_stream()+ .controller()+ .expect("a writable stream has a controller");+ writable_stream_default_controller_error_if_needed(cx, writable_controller, error);++ // 3. Perform ! TransformStreamUnblockWrite(stream).+ transform_stream_unblock_write(cx, stream);+}++// https://streams.spec.whatwg.org/#transform-stream-set-backpressure+pub(crate) fn transform_stream_set_backpressure(cx: &CallContext, stream: Ref<TransformStream>, backpressure: bool) {+ // 1. Assert: stream.[[backpressure]] is not backpressure.+ assert!(stream.backpressure() != Some(backpressure));++ // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with+ // undefined.+ if let Some(backpressure_change_promise) = stream.backpressure_change_promise() {+ resolve_promise(cx.vm(), backpressure_change_promise, Value::UNDEFINED);+ }++ // 3. Set stream.[[backpressureChangePromise]] to a new promise.+ stream.set_backpressure_change_promise(Some(create_promise(cx.vm(), cx.realm())));++ // 4. Set stream.[[backpressure]] to backpressure.+ stream.set_backpressure(Some(backpressure));+}++// https://streams.spec.whatwg.org/#transform-stream-unblock-write+pub(crate) fn transform_stream_unblock_write(cx: &CallContext, stream: Ref<TransformStream>) {+ // 1. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).+ if stream.backpressure() == Some(true) {+ transform_stream_set_backpressure(+ &CallContext::new(cx.vm(), stream.backpressure_change_promise_realm()),+ stream,+ false,+ );+ }+}++// https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm+pub(crate) fn transform_stream_default_sink_write_algorithm(+ cx: &CallContext,+ stream: Ref<TransformStream>,+ chunk: Value,+) -> WebIdlPromise {+ // 1. Assert: stream.[[writable]].[[state]] is "writable".+ assert!(stream.writable_stream().state() == WritableStreamState::Writable);++ // 2. Let controller be stream.[[controller]].+ let controller = stream+ .controller()+ .expect("a transform stream that is set up has a controller");++ // 3. If stream.[[backpressure]] is true,+ if stream.backpressure() == Some(true) {+ // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].+ let backpressure_change_promise = stream.backpressure_change_promise();++ // 2. Assert: backpressureChangePromise is not undefined.+ let backpressure_change_promise =+ backpressure_change_promise.expect("a stream with backpressure has a backpressure change promise");++ // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:+ return upon_fulfillment(+ cx.vm(),+ backpressure_change_promise,+ (stream, controller, chunk),+ |cx, (stream, controller, chunk), _| {+ // 1. Let writable be stream.[[writable]].+ let writable = stream.writable_stream();++ // 2. Let state be writable.[[state]].+ let state = writable.state();++ // 3. If state is "erroring", throw writable.[[storedError]].+ if state == WritableStreamState::Erroring {+ return Err(Exception::Thrown(Throw::new(writable.stored_error())));+ }++ // 4. Assert: state is "writable".+ assert!(state == WritableStreamState::Writable);++ // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).+ let promise = transform_stream_default_controller_perform_transform(cx, controller, chunk);+ Ok(Value::from_object(promise.promise()))+ },+ );+ }++ // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).+ transform_stream_default_controller_perform_transform(cx, controller, chunk)+}++// https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm+pub(crate) fn transform_stream_default_sink_abort_algorithm(+ cx: &CallContext,+ stream: Ref<TransformStream>,+ reason: Value,+) -> WebIdlPromise {+ let vm = cx.vm();+ let realm = stream.backpressure_change_promise_realm();++ // 1. Let controller be stream.[[controller]].+ let controller = stream+ .controller()+ .expect("a transform stream that is set up has a controller");++ // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].+ if let Some(finish_promise) = controller.finish_promise() {+ return finish_promise;+ }++ // 3. Let readable be stream.[[readable]].+ let readable = stream.readable_stream();++ // 4. Let controller.[[finishPromise]] be a new promise.+ controller.set_finish_promise(Some(create_promise(vm, realm)));++ // 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.+ let cancel_algorithm = controller+ .cancel_algorithm()+ .expect("the controller's algorithms are not cleared");+ let cancel_promise = cancel_algorithm.run(&stream.context(vm), reason);++ // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).+ transform_stream_default_controller_clear_algorithms(controller);++ // 7. React to cancelPromise:+ react_to_promise(+ vm,+ cancel_promise,+ (readable, controller, reason),+ // 1. If cancelPromise was fulfilled, then:+ Some(|cx, (readable, controller, reason), _| {+ let vm = cx.vm();+ let finish_promise = controller+ .finish_promise()+ .expect("the controller has a finish promise");++ // 1. If readable.[[state]] is "errored", reject controller.[[finishPromise]] with readable.[[storedError]].+ if readable.state() == ReadableStreamState::Errored {+ reject_promise(vm, finish_promise, readable.stored_error());+ }+ // 2. Otherwise:+ else {+ // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], reason).+ readable_stream_default_controller_error(+ &readable.context(vm),+ readable_default_controller(readable),+ reason,+ );++ // 2. Resolve controller.[[finishPromise]] with undefined.+ resolve_promise(vm, finish_promise, Value::UNDEFINED);+ }++ Ok(Value::UNDEFINED)+ }),+ // 2. If cancelPromise was rejected with reason r, then:+ Some(|cx, (readable, controller, _), reason| {+ let vm = cx.vm();++ // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], r).+ readable_stream_default_controller_error(+ &readable.context(vm),+ readable_default_controller(readable),+ reason,+ );++ // 2. Reject controller.[[finishPromise]] with r.+ let finish_promise = controller+ .finish_promise()+ .expect("the controller has a finish promise");+ reject_promise(vm, finish_promise, reason);++ Ok(Value::UNDEFINED)+ }),+ );++ // 8. Return controller.[[finishPromise]].+ controller+ .finish_promise()+ .expect("the controller has a finish promise")+}++// https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm+pub(crate) fn transform_stream_default_sink_close_algorithm(+ cx: &CallContext,+ stream: Ref<TransformStream>,+) -> WebIdlPromise {+ let vm = cx.vm();+ let realm = stream.backpressure_change_promise_realm();++ // 1. Let controller be stream.[[controller]].+ let controller = stream+ .controller()+ .expect("a transform stream that is set up has a controller");++ // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].+ if let Some(finish_promise) = controller.finish_promise() {+ return finish_promise;+ }++ // 3. Let readable be stream.[[readable]].+ let readable = stream.readable_stream();++ // 4. Let controller.[[finishPromise]] be a new promise.+ controller.set_finish_promise(Some(create_promise(vm, realm)));++ // 5. Let flushPromise be the result of performing controller.[[flushAlgorithm]].+ let flush_algorithm = controller+ .flush_algorithm()+ .expect("the controller's algorithms are not cleared");+ let flush_promise = flush_algorithm.run(&stream.context(vm));++ // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).+ transform_stream_default_controller_clear_algorithms(controller);++ // 7. React to flushPromise:+ react_to_promise(+ vm,+ flush_promise,+ (controller, readable),+ // 1. If flushPromise was fulfilled, then:+ Some(|cx, (controller, readable), _| {+ let vm = cx.vm();+ let finish_promise = controller+ .finish_promise()+ .expect("the controller has a finish promise");++ // 1. If readable.[[state]] is "errored", reject controller.[[finishPromise]] with readable.[[storedError]].+ if readable.state() == ReadableStreamState::Errored {+ reject_promise(vm, finish_promise, readable.stored_error());+ }+ // 2. Otherwise:+ else {+ // 1. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).+ readable_stream_default_controller_close(&readable.context(vm), readable_default_controller(readable));++ // 2. Resolve controller.[[finishPromise]] with undefined.+ resolve_promise(vm, finish_promise, Value::UNDEFINED);+ }++ Ok(Value::UNDEFINED)+ }),+ // 2. If flushPromise was rejected with reason r, then:+ Some(|cx, (controller, readable), reason| {+ let vm = cx.vm();++ // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], r).+ readable_stream_default_controller_error(+ &readable.context(vm),+ readable_default_controller(readable),+ reason,+ );++ // 2. Reject controller.[[finishPromise]] with r.+ let finish_promise = controller+ .finish_promise()+ .expect("the controller has a finish promise");+ reject_promise(vm, finish_promise, reason);++ Ok(Value::UNDEFINED)+ }),+ );++ // 8. Return controller.[[finishPromise]].+ controller+ .finish_promise()+ .expect("the controller has a finish promise")+}++// https://streams.spec.whatwg.org/#transform-stream-default-source-cancel+pub(crate) fn transform_stream_default_source_cancel_algorithm(+ cx: &CallContext,+ stream: Ref<TransformStream>,+ reason: Value,+) -> WebIdlPromise {+ let vm = cx.vm();+ let realm = stream.backpressure_change_promise_realm();++ // 1. Let controller be stream.[[controller]].+ let controller = stream+ .controller()+ .expect("a transform stream that is set up has a controller");++ // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].+ if let Some(finish_promise) = controller.finish_promise() {+ return finish_promise;+ }++ // 3. Let writable be stream.[[writable]].+ let writable = stream.writable_stream();++ // 4. Let controller.[[finishPromise]] be a new promise.+ controller.set_finish_promise(Some(create_promise(vm, realm)));++ // 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.+ let cancel_algorithm = controller+ .cancel_algorithm()+ .expect("the controller's algorithms are not cleared");+ let cancel_promise = cancel_algorithm.run(&stream.context(vm), reason);++ // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).+ transform_stream_default_controller_clear_algorithms(controller);++ // 7. React to cancelPromise:+ react_to_promise(+ vm,+ cancel_promise,+ (stream, writable, controller, reason),+ // 1. If cancelPromise was fulfilled, then:+ Some(|cx, (stream, writable, controller, reason), _| {+ let vm = cx.vm();+ let finish_promise = controller+ .finish_promise()+ .expect("the controller has a finish promise");++ // 1. If writable.[[state]] is "errored", reject controller.[[finishPromise]] with writable.[[storedError]].+ if writable.state() == WritableStreamState::Errored {+ reject_promise(vm, finish_promise, writable.stored_error());+ }+ // 2. Otherwise:+ else {+ // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(writable.[[controller]], reason).+ let writable_controller = writable.controller().expect("a writable stream has a controller");+ writable_stream_default_controller_error_if_needed(&writable.context(vm), writable_controller, reason);++ // 2. Perform ! TransformStreamUnblockWrite(stream).+ transform_stream_unblock_write(cx, stream);++ // 3. Resolve controller.[[finishPromise]] with undefined.+ resolve_promise(vm, finish_promise, Value::UNDEFINED);+ }++ Ok(Value::UNDEFINED)+ }),+ // 2. If cancelPromise was rejected with reason r, then:+ Some(|cx, (stream, writable, controller, _), reason| {+ let vm = cx.vm();++ // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(writable.[[controller]], r).+ let writable_controller = writable.controller().expect("a writable stream has a controller");+ writable_stream_default_controller_error_if_needed(&writable.context(vm), writable_controller, reason);++ // 2. Perform ! TransformStreamUnblockWrite(stream).+ transform_stream_unblock_write(cx, stream);++ // 3. Reject controller.[[finishPromise]] with r.+ let finish_promise = controller+ .finish_promise()+ .expect("the controller has a finish promise");+ reject_promise(vm, finish_promise, reason);++ Ok(Value::UNDEFINED)+ }),+ );++ // 8. Return controller.[[finishPromise]].+ controller+ .finish_promise()+ .expect("the controller has a finish promise")+}++// https://streams.spec.whatwg.org/#transform-stream-default-source-pull+pub(crate) fn transform_stream_default_source_pull_algorithm(+ cx: &CallContext,+ stream: Ref<TransformStream>,+) -> WebIdlPromise {+ // 1. Assert: stream.[[backpressure]] is true.+ assert!(stream.backpressure() == Some(true));++ // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.+ assert!(stream.backpressure_change_promise().is_some());++ // 3. Perform ! TransformStreamSetBackpressure(stream, false).+ transform_stream_set_backpressure(+ &CallContext::new(cx.vm(), stream.backpressure_change_promise_realm()),+ stream,+ false,+ );++ // 4. Return stream.[[backpressureChangePromise]].+ stream+ .backpressure_change_promise()+ .expect("the stream has a backpressure change promise")+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rsnew file mode 100644index 00000000000..1deabb7d030--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/transform_stream_default_controller.rs@@ -0,0 +1,346 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! TransformStreamDefaultController, https://streams.spec.whatwg.org/#ts-default-controller-class, and its abstract+//! operations, https://streams.spec.whatwg.org/#ts-default-controller-abstract-ops++use core::cell::Cell;++use libjs_rust::api::{GcRefCell, Throw, Trace, Value};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{WebIdlPromise, exception_value, upon_rejection};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::algorithms::{CancelAlgorithm, FlushAlgorithm, TransformAlgorithm};+use crate::streams::readable_stream_default_controller::{+ readable_stream_default_controller_can_close_or_enqueue, readable_stream_default_controller_close,+ readable_stream_default_controller_enqueue, readable_stream_default_controller_get_desired_size,+ readable_stream_default_controller_has_backpressure,+};+use crate::streams::transform_stream::{+ TransformStream, readable_default_controller, transform_stream_error,+ transform_stream_error_writable_and_unblock_write, transform_stream_set_backpressure,+};+use crate::streams::transformer::Transformer;++// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TransformStreamDefaultController {+ // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-cancelalgorithm+ cancel_algorithm: GcRefCell<Option<CancelAlgorithm>>,+ // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-finishpromise+ finish_promise: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-flushalgorithm+ flush_algorithm: GcRefCell<Option<FlushAlgorithm>>,+ // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-transformalgorithm+ transform_algorithm: GcRefCell<Option<TransformAlgorithm>>,+ // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-stream+ stream: Cell<Option<Ref<TransformStream>>>,+}++impl Wrappable for TransformStreamDefaultController {}++impl TransformStreamDefaultController {+ pub(crate) fn new() -> Self {+ Self {+ cancel_algorithm: GcRefCell::new(None),+ finish_promise: Cell::new(None),+ flush_algorithm: GcRefCell::new(None),+ transform_algorithm: GcRefCell::new(None),+ stream: Cell::new(None),+ }+ }++ /// The controller's [[stream]], which it has once it is set up.+ pub(crate) fn stream(&self) -> Ref<TransformStream> {+ self.stream.get().expect("a controller that is set up has a stream")+ }++ pub(crate) fn set_stream(&self, stream: Ref<TransformStream>) {+ self.stream.set(Some(stream));+ }++ pub(crate) fn finish_promise(&self) -> Option<WebIdlPromise> {+ self.finish_promise.get()+ }++ pub(crate) fn set_finish_promise(&self, promise: Option<WebIdlPromise>) {+ self.finish_promise.set(promise);+ }++ pub(crate) fn cancel_algorithm(&self) -> Option<CancelAlgorithm> {+ self.cancel_algorithm.borrow().clone()+ }++ pub(crate) fn set_cancel_algorithm(&self, algorithm: Option<CancelAlgorithm>) {+ *self.cancel_algorithm.borrow_mut() = algorithm;+ }++ pub(crate) fn flush_algorithm(&self) -> Option<FlushAlgorithm> {+ self.flush_algorithm.borrow().clone()+ }++ pub(crate) fn set_flush_algorithm(&self, algorithm: Option<FlushAlgorithm>) {+ *self.flush_algorithm.borrow_mut() = algorithm;+ }++ pub(crate) fn transform_algorithm(&self) -> Option<TransformAlgorithm> {+ self.transform_algorithm.borrow().clone()+ }++ pub(crate) fn set_transform_algorithm(&self, algorithm: Option<TransformAlgorithm>) {+ *self.transform_algorithm.borrow_mut() = algorithm;+ }++ // https://streams.spec.whatwg.org/#ts-default-controller-desired-size+ pub(crate) fn desired_size(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<Option<f64>> {+ // 1. Let readableController be this.[[stream]].[[readable]].[[controller]].+ let readable_controller = readable_default_controller(this.stream().readable_stream());++ // 2. Return ! ReadableStreamDefaultControllerGetDesiredSize(readableController).+ Ok(readable_stream_default_controller_get_desired_size(readable_controller))+ }++ // https://streams.spec.whatwg.org/#ts-default-controller-enqueue+ pub(crate) fn enqueue(this: &Ref<Self>, cx: &mut CallContext, chunk: Option<Value>) -> WebIdlResult<()> {+ let cx = &CallContext::new(cx.vm(), this.stream().backpressure_change_promise_realm());++ // 1. Perform ? TransformStreamDefaultControllerEnqueue(this, chunk).+ transform_stream_default_controller_enqueue(cx, *this, chunk.unwrap_or(Value::UNDEFINED))+ }++ // https://streams.spec.whatwg.org/#ts-default-controller-error+ pub(crate) fn error(this: &Ref<Self>, cx: &mut CallContext, reason: Option<Value>) -> WebIdlResult<()> {+ let cx = &this.stream().context(cx.vm());++ // 1. Perform ? TransformStreamDefaultControllerError(this, e).+ transform_stream_default_controller_error(cx, *this, reason.unwrap_or(Value::UNDEFINED));+ Ok(())+ }++ // https://streams.spec.whatwg.org/#ts-default-controller-terminate+ pub(crate) fn terminate(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ let cx = &this.stream().context(cx.vm());++ // 1. Perform ? TransformStreamDefaultControllerTerminate(this).+ transform_stream_default_controller_terminate(cx, *this);+ Ok(())+ }+}++// https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller+pub(crate) fn set_up_transform_stream_default_controller(+ stream: Ref<TransformStream>,+ controller: Ref<TransformStreamDefaultController>,+ transform_algorithm: TransformAlgorithm,+ flush_algorithm: FlushAlgorithm,+ cancel_algorithm: CancelAlgorithm,+) {+ // 1. Assert: stream implements TransformStream.+ // 2. Assert: stream.[[controller]] is undefined.+ assert!(stream.controller().is_none());++ // 3. Set controller.[[stream]] to stream.+ controller.set_stream(stream);++ // 4. Set stream.[[controller]] to controller.+ stream.set_controller(Some(controller));++ // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.+ controller.set_transform_algorithm(Some(transform_algorithm));++ // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.+ controller.set_flush_algorithm(Some(flush_algorithm));++ // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.+ controller.set_cancel_algorithm(Some(cancel_algorithm));+}++// https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer+pub(crate) fn set_up_transform_stream_default_controller_from_transformer(+ cx: &CallContext,+ stream: Ref<TransformStream>,+ transformer: Value,+ transformer_dict: Transformer,+) {+ // 1. Let controller be a new TransformStreamDefaultController.+ let controller = allocate(cx.vm(), TransformStreamDefaultController::new());++ // 2. Let transformAlgorithm be the following steps, taking a chunk argument:+ let mut transform_algorithm = TransformAlgorithm::Enqueue(controller);++ // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.+ let mut flush_algorithm = FlushAlgorithm::ReturnsResolvedUndefined;++ // 4. Let cancelAlgorithm be an algorithm which returns a promise resolved with undefined.+ let mut cancel_algorithm = CancelAlgorithm::ReturnsResolvedUndefined;++ // 5. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk+ // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and+ // callback this value transformer.+ if let Some(transform) = transformer_dict.transform {+ transform_algorithm = TransformAlgorithm::Callback {+ transform,+ transformer,+ controller,+ };+ }++ // 6. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking+ // transformerDict["flush"] with argument list « controller » and callback this value transformer.+ if let Some(flush) = transformer_dict.flush {+ flush_algorithm = FlushAlgorithm::Callback {+ flush,+ transformer,+ controller,+ };+ }++ // 7. If transformerDict["cancel"] exists, set cancelAlgorithm to an algorithm which takes an argument reason and+ // returns the result of invoking transformerDict["cancel"] with argument list « reason » and callback this value+ // transformer.+ if let Some(cancel) = transformer_dict.cancel {+ cancel_algorithm = CancelAlgorithm::Callback {+ cancel,+ this_value: transformer,+ };+ }++ // 8. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm,+ // cancelAlgorithm).+ set_up_transform_stream_default_controller(+ stream,+ controller,+ transform_algorithm,+ flush_algorithm,+ cancel_algorithm,+ );+}++// https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms+pub(crate) fn transform_stream_default_controller_clear_algorithms(controller: Ref<TransformStreamDefaultController>) {+ // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.+ // 1. Set controller.[[transformAlgorithm]] to undefined.+ controller.set_transform_algorithm(None);++ // 2. Set controller.[[flushAlgorithm]] to undefined.+ controller.set_flush_algorithm(None);++ // 3. Set controller.[[cancelAlgorithm]] to undefined.+ controller.set_cancel_algorithm(None);+}++// https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue+pub(crate) fn transform_stream_default_controller_enqueue(+ cx: &CallContext,+ controller: Ref<TransformStreamDefaultController>,+ chunk: Value,+) -> WebIdlResult<()> {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. Let readableController be stream.[[readable]].[[controller]].+ let readable_controller = readable_default_controller(stream.readable_stream());++ // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError+ // exception.+ if !readable_stream_default_controller_can_close_or_enqueue(readable_controller) {+ return Err(Exception::type_error(+ "ReadableController is either closed or not readable.",+ ));+ }++ // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).+ let enqueue_result = readable_stream_default_controller_enqueue(cx, readable_controller, chunk);++ // 5. If enqueueResult is an abrupt completion,+ if let Err(exception) = enqueue_result {+ let error = exception_value(cx.vm(), cx.realm(), exception);++ // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).+ transform_stream_error_writable_and_unblock_write(cx, stream, error);++ // 2. Throw stream.[[readable]].[[storedError]].+ return Err(Exception::Thrown(Throw::new(stream.readable_stream().stored_error())));+ }++ // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).+ let backpressure = readable_stream_default_controller_has_backpressure(readable_controller);++ // 7. If backpressure is not stream.[[backpressure]],+ if Some(backpressure) != stream.backpressure() {+ // 1. Assert: backpressure is true.+ assert!(backpressure);++ // 2. Perform ! TransformStreamSetBackpressure(stream, true).+ transform_stream_set_backpressure(+ &CallContext::new(cx.vm(), stream.backpressure_change_promise_realm()),+ stream,+ true,+ );+ }++ Ok(())+}++// https://streams.spec.whatwg.org/#transform-stream-default-controller-error+pub(crate) fn transform_stream_default_controller_error(+ cx: &CallContext,+ controller: Ref<TransformStreamDefaultController>,+ error: Value,+) {+ // 1. Perform ! TransformStreamError(controller.[[stream]], e).+ transform_stream_error(cx, controller.stream(), error);+}++// https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform+pub(crate) fn transform_stream_default_controller_perform_transform(+ cx: &CallContext,+ controller: Ref<TransformStreamDefaultController>,+ chunk: Value,+) -> WebIdlPromise {+ let vm = cx.vm();++ // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.+ let transform_algorithm = controller+ .transform_algorithm()+ .expect("the controller's algorithms are not cleared");+ let transform_promise = transform_algorithm.run(&controller.stream().context(vm), chunk);++ // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:+ upon_rejection(vm, transform_promise, controller, |cx, controller, reason| {+ let stream = controller.stream();++ // 1. Perform ! TransformStreamError(controller.[[stream]], r).+ transform_stream_error(&stream.context(cx.vm()), stream, reason);++ // 2. Throw r.+ Err(Exception::Thrown(Throw::new(reason)))+ })+}++// https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate+pub(crate) fn transform_stream_default_controller_terminate(+ cx: &CallContext,+ controller: Ref<TransformStreamDefaultController>,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();+ let realm = stream.backpressure_change_promise_realm();++ // 2. Let readableController be stream.[[readable]].[[controller]].+ let readable_controller = readable_default_controller(stream.readable_stream());++ // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).+ readable_stream_default_controller_close(cx, readable_controller);++ // 4. Let error be a TypeError exception indicating that the stream has been terminated.+ let error = exception_value(cx.vm(), realm, Exception::type_error("Stream has been terminated."));++ // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).+ transform_stream_error_writable_and_unblock_write(cx, stream, error);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/transformer.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/transformer.rsnew file mode 100644index 00000000000..2ee18f80927--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/transformer.rs@@ -0,0 +1,34 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Transformer, https://streams.spec.whatwg.org/#transformer-api++use libjs_rust::api::Value;+#[cfg(not(web_idl_bindings))]+use libjs_rust::api::{ThrowCompletionOr, Vm};++use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};+#[cfg(not(web_idl_bindings))]+use crate::bindings::conversions::FromJs;++/// The dictionary Transformer of Streams/Transformer.idl, whose members the bindings convert.+pub(crate) struct Transformer {+ pub(crate) cancel: Option<PromiseCallbackFunction>,+ pub(crate) flush: Option<PromiseCallbackFunction>,+ pub(crate) readable_type: Option<Value>,+ pub(crate) start: Option<CallbackFunction>,+ pub(crate) transform: Option<PromiseCallbackFunction>,+ pub(crate) writable_type: Option<Value>,+}++/// Without the generated bindings, which a build of the crate on its own leaves out, nothing converts a JS value to the+/// dictionary. This stands in for the conversion so that the constructor that uses it compiles.+#[cfg(not(web_idl_bindings))]+impl FromJs for Transformer {+ fn from_js(_: &Vm, _: Value) -> ThrowCompletionOr<Self> {+ unreachable!("a JS value has no conversion without the bindings")+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/underlying_sink.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/underlying_sink.rsnew file mode 100644index 00000000000..4f0fb8fb38b--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/underlying_sink.rs@@ -0,0 +1,33 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! UnderlyingSink, https://streams.spec.whatwg.org/#underlying-sink-api++use libjs_rust::api::Value;+#[cfg(not(web_idl_bindings))]+use libjs_rust::api::{ThrowCompletionOr, Vm};++use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};+#[cfg(not(web_idl_bindings))]+use crate::bindings::conversions::FromJs;++/// The dictionary UnderlyingSink of Streams/UnderlyingSink.idl, whose members the bindings convert.+pub(crate) struct UnderlyingSink {+ pub(crate) abort: Option<PromiseCallbackFunction>,+ pub(crate) close: Option<PromiseCallbackFunction>,+ pub(crate) start: Option<CallbackFunction>,+ pub(crate) r#type: Option<Value>,+ pub(crate) write: Option<PromiseCallbackFunction>,+}++/// Without the generated bindings, which a build of the crate on its own leaves out, nothing converts a JS value to the+/// dictionary. This stands in for the conversion so that the constructor that uses it compiles.+#[cfg(not(web_idl_bindings))]+impl FromJs for UnderlyingSink {+ fn from_js(_: &Vm, _: Value) -> ThrowCompletionOr<Self> {+ unreachable!("a JS value has no conversion without the bindings")+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/underlying_source.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/underlying_source.rsnew file mode 100644index 00000000000..d775ab86d3f--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/underlying_source.rs@@ -0,0 +1,61 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! UnderlyingSource, https://streams.spec.whatwg.org/#underlying-source-api++#[cfg(not(web_idl_bindings))]+use libjs_rust::api::{ThrowCompletionOr, Vm};+use libjs_rust::api::{Trace, Value};++use crate::bindings::CallContext;+use crate::bindings::callback::{CallbackFunction, PromiseCallbackFunction};+#[cfg(not(web_idl_bindings))]+use crate::bindings::conversions::FromJs;+use crate::bindings::interface::{Ref, wrap};+use crate::streams::readable_byte_stream_controller::ReadableByteStreamController;+use crate::streams::readable_stream_default_controller::ReadableStreamDefaultController;++/// The dictionary UnderlyingSource of Streams/UnderlyingSource.idl, whose members the bindings convert.+pub(crate) struct UnderlyingSource {+ pub(crate) auto_allocate_chunk_size: Option<u64>,+ pub(crate) cancel: Option<PromiseCallbackFunction>,+ pub(crate) pull: Option<PromiseCallbackFunction>,+ pub(crate) start: Option<CallbackFunction>,+ pub(crate) r#type: Option<ReadableStreamType>,+}++/// Without the generated bindings, which a build of the crate on its own leaves out, nothing converts a JS value to the+/// dictionary. This stands in for the conversion so that the constructor that uses it compiles.+#[cfg(not(web_idl_bindings))]+impl FromJs for UnderlyingSource {+ fn from_js(_: &Vm, _: Value) -> ThrowCompletionOr<Self> {+ unreachable!("a JS value has no conversion without the bindings")+ }+}++// https://streams.spec.whatwg.org/#enumdef-readablestreamtype+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ReadableStreamType {+ Bytes,+}++/// https://streams.spec.whatwg.org/#typedefdef-readablestreamcontroller+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum ReadableStreamController {+ ReadableStreamDefaultController(Ref<ReadableStreamDefaultController>),+ ReadableByteStreamController(Ref<ReadableByteStreamController>),+}++impl ReadableStreamController {+ /// The controller converted to a JS value, as the underlying source's callbacks are invoked with it.+ pub(crate) fn to_js(self, cx: &CallContext) -> Value {+ Value::from_object(match self {+ Self::ReadableStreamDefaultController(controller) => wrap(cx, controller),+ Self::ReadableByteStreamController(controller) => wrap(cx, controller),+ })+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rsnew file mode 100644index 00000000000..8ae0f8a8c74--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs@@ -0,0 +1,1010 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! WritableStream, https://streams.spec.whatwg.org/#ws-class, and the abstract operations that work with writable+//! streams, https://streams.spec.whatwg.org/#ws-abstract-ops++use std::collections::VecDeque;++use core::cell::Cell;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, MarkedVec, Object, Realm, Trace, Value, Vm};++use crate::bindings::conversions::FromJs;+use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context_and_callbacks};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_rejected_promise, create_rejected_promise_from_exception,+ create_resolved_promise, exception_value, mark_promise_as_handled, react_to_promise, reject_promise,+ resolve_promise,+};+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::abstract_operations::is_non_negative_number;+use crate::streams::algorithms::{AbortAlgorithm, CloseAlgorithm, SizeAlgorithm, StartAlgorithm, WriteAlgorithm};+use crate::streams::cross_realm_transform::{+ create_entangled_ports, deserialize_message_port, serialize_message_port, set_up_cross_realm_transform_readable,+ set_up_cross_realm_transform_writable,+};+use crate::streams::queuing_strategy::{QueuingStrategy, extract_high_water_mark, extract_size_algorithm};+use crate::streams::readable_stream::ReadableStream;+use crate::streams::readable_stream_pipe_to::readable_stream_pipe_to;+use crate::streams::underlying_sink::UnderlyingSink;+use crate::streams::writable_stream_default_controller::{+ WritableStreamDefaultController, set_up_writable_stream_default_controller,+ set_up_writable_stream_default_controller_from_underlying_sink, writable_stream_default_controller_close,+};+use crate::streams::writable_stream_default_writer::{+ WritableStreamDefaultWriter, writable_stream_default_writer_ensure_ready_promise_rejected,+};++// https://streams.spec.whatwg.org/#writablestream-state+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum WritableStreamState {+ Writable,+ Closed,+ Erroring,+ Errored,+}++// https://streams.spec.whatwg.org/#pending-abort-request+#[derive(Clone, Copy, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct PendingAbortRequest {+ // https://streams.spec.whatwg.org/#pending-abort-request-promise+ pub(crate) promise: WebIdlPromise,+ // https://streams.spec.whatwg.org/#pending-abort-request-reason+ pub(crate) reason: Value,+ // https://streams.spec.whatwg.org/#pending-abort-request-was-already-erroring+ #[gc(untraced)]+ pub(crate) was_already_erroring: bool,+}++// https://streams.spec.whatwg.org/#writablestream+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct WritableStream {+ /// The realm of the stream, which its promises and the results of its operations are created in.+ realm: Cell<Gc<Realm>>,+ // https://streams.spec.whatwg.org/#writablestream-backpressure+ backpressure: Cell<bool>,+ // https://streams.spec.whatwg.org/#writablestream-closerequest+ close_request: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#writablestream-controller+ controller: Cell<Option<Ref<WritableStreamDefaultController>>>,+ // https://streams.spec.whatwg.org/#writablestream-detached+ detached: Cell<bool>,+ // https://streams.spec.whatwg.org/#writablestream-inflightwriterequest+ in_flight_write_request: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#writablestream-inflightcloserequest+ in_flight_close_request: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#writablestream-pendingabortrequest+ pending_abort_request: Cell<Option<PendingAbortRequest>>,+ // https://streams.spec.whatwg.org/#writablestream-state+ #[gc(untraced)]+ state: Cell<WritableStreamState>,+ // https://streams.spec.whatwg.org/#writablestream-storederror+ stored_error: Cell<Value>,+ // https://streams.spec.whatwg.org/#writablestream-writer+ writer: Cell<Option<Ref<WritableStreamDefaultWriter>>>,+ // https://streams.spec.whatwg.org/#writablestream-writerequests+ write_requests: GcRefCell<VecDeque<WebIdlPromise>>,+}++impl Wrappable for WritableStream {}++impl WritableStream {+ /// A new WritableStream in the realm, which InitializeWritableStream has initialized.+ pub(crate) fn new(realm: Gc<Realm>) -> Self {+ Self {+ realm: Cell::new(realm),+ backpressure: Cell::new(false),+ close_request: Cell::new(None),+ controller: Cell::new(None),+ detached: Cell::new(false),+ in_flight_write_request: Cell::new(None),+ in_flight_close_request: Cell::new(None),+ pending_abort_request: Cell::new(None),+ state: Cell::new(WritableStreamState::Writable),+ stored_error: Cell::new(Value::UNDEFINED),+ writer: Cell::new(None),+ write_requests: GcRefCell::new(VecDeque::new()),+ }+ }++ pub(crate) fn realm(&self) -> Gc<Realm> {+ self.realm.get()+ }++ /// The context of the realm of the stream.+ pub(crate) fn context<'vm>(&self, vm: &'vm Vm) -> CallContext<'vm> {+ CallContext::new(vm, self.realm())+ }++ pub(crate) fn state(&self) -> WritableStreamState {+ self.state.get()+ }++ pub(crate) fn stored_error(&self) -> Value {+ self.stored_error.get()+ }++ pub(crate) fn writer(&self) -> Option<Ref<WritableStreamDefaultWriter>> {+ self.writer.get()+ }++ pub(crate) fn controller(&self) -> Option<Ref<WritableStreamDefaultController>> {+ self.controller.get()+ }++ pub(crate) fn set_controller(&self, controller: Option<Ref<WritableStreamDefaultController>>) {+ self.controller.set(controller);+ }++ pub(crate) fn set_writer(&self, writer: Option<Ref<WritableStreamDefaultWriter>>) {+ self.writer.set(writer);+ }++ pub(crate) fn in_flight_write_request(&self) -> Option<WebIdlPromise> {+ self.in_flight_write_request.get()+ }++ /// Takes the stream's [[writeRequests]], leaving an empty list.+ fn take_write_requests<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, WebIdlPromise> {+ let write_requests = MarkedVec::with_capacity(vm, self.write_requests.borrow().len());+ for write_request in self.write_requests.borrow().iter() {+ write_requests.push(*write_request);+ }+ self.write_requests.borrow_mut().clear();+ write_requests+ }++ // https://streams.spec.whatwg.org/#ws-constructor+ pub(crate) fn construct(+ cx: &mut CallContext,+ underlying_sink: Option<Gc<Object>>,+ strategy: QueuingStrategy,+ ) -> WebIdlResult<Ref<Self>> {+ // 1. If underlyingSink is missing, set it to null.+ let underlying_sink = underlying_sink.map_or(Value::NULL, Value::from_object);++ // 2. Let underlyingSinkDict be underlyingSink, converted to an IDL value of type UnderlyingSink.+ let underlying_sink_dict = UnderlyingSink::from_js(cx.vm(), underlying_sink)?;++ // 3. If underlyingSinkDict["type"] exists, throw a RangeError exception.+ if underlying_sink_dict.r#type.is_some() {+ return Err(Exception::range_error("Invalid use of reserved key 'type'"));+ }++ // 4. Perform ! InitializeWritableStream(this).+ let this = allocate(cx.vm(), Self::new(cx.realm()));++ // 5. Let sizeAlgorithm be ! ExtractSizeAlgorithm(strategy).+ let size_algorithm = extract_size_algorithm(&strategy);++ // 6. Let highWaterMark be ? ExtractHighWaterMark(strategy, 1).+ let high_water_mark = extract_high_water_mark(&strategy, 1.0)?;++ // 7. Perform ? SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, underlyingSinkDict,+ // highWaterMark, sizeAlgorithm).+ set_up_writable_stream_default_controller_from_underlying_sink(+ cx,+ this,+ underlying_sink,+ underlying_sink_dict,+ high_water_mark,+ size_algorithm,+ )?;+ Ok(this)+ }++ // https://streams.spec.whatwg.org/#ws-locked+ pub(crate) fn locked(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<bool> {+ // 1. Return ! IsWritableStreamLocked(this).+ Ok(is_writable_stream_locked(*this))+ }++ // https://streams.spec.whatwg.org/#ws-abort+ pub(crate) fn abort(this: &Ref<Self>, cx: &mut CallContext, reason: Option<Value>) -> WebIdlResult<WebIdlPromise> {+ // 1. If ! IsWritableStreamLocked(this) is true, return a promise rejected with a TypeError exception.+ if is_writable_stream_locked(*this) {+ let exception = Exception::type_error("Cannot abort a locked stream");+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 2. Return ! WritableStreamAbort(this, reason).+ Ok(writable_stream_abort(cx, *this, reason.unwrap_or(Value::UNDEFINED)))+ }++ // https://streams.spec.whatwg.org/#ws-close+ pub(crate) fn close(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ // 1. If ! IsWritableStreamLocked(this) is true, return a promise rejected with a TypeError exception.+ if is_writable_stream_locked(*this) {+ let exception = Exception::type_error("Cannot close a locked stream");+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 2. If ! WritableStreamCloseQueuedOrInFlight(this) is true, return a promise rejected with a TypeError+ // exception.+ if writable_stream_close_queued_or_in_flight(*this) {+ let exception = Exception::type_error("Cannot close a stream that is already closed or errored");+ return Ok(create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception));+ }++ // 3. Return ! WritableStreamClose(this).+ Ok(writable_stream_close(cx, *this))+ }++ // https://streams.spec.whatwg.org/#ws-get-writer+ pub(crate) fn get_writer(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Ref<WritableStreamDefaultWriter>> {+ // 1. Return ? AcquireWritableStreamDefaultWriter(this).+ acquire_writable_stream_default_writer(cx, *this)+ }+}++impl Transferable for WritableStream {+ fn detached(&self) -> &Cell<bool> {+ &self.detached+ }++ // https://streams.spec.whatwg.org/#ref-for-transfer-steps①+ fn transfer_steps(+ this: &Ref<Self>,+ cx: &mut CallContext,+ data_holder: &mut TransferDataWriter,+ ) -> WebIdlResult<()> {+ let this = *this;+ let cx: &CallContext = cx;+ with_temporary_execution_context_and_callbacks(cx.realm(), || {+ // 1. If ! IsWritableStreamLocked(value) is true, throw a "DataCloneError" DOMException.+ if is_writable_stream_locked(this) {+ return Err(Exception::Dom(+ "DataCloneError",+ Utf16String::from_ascii(b"Cannot transfer locked WritableStream"),+ ));+ }++ // 2. Let port1 be a new MessagePort in the current Realm.+ // 3. Let port2 be a new MessagePort in the current Realm.+ // 4. Entangle port1 and port2.+ let (port1, port2) = create_entangled_ports(cx);++ // 5. Let readable be a new ReadableStream in the current Realm.+ let readable = allocate(cx.vm(), ReadableStream::new(cx.realm()));++ // 6. Perform ! SetUpCrossRealmTransformReadable(readable, port1).+ set_up_cross_realm_transform_readable(cx, readable, port1);++ // 7. Let promise be ! ReadableStreamPipeTo(readable, value, false, false, false).+ let promise = readable_stream_pipe_to(cx, readable, this, false, false, false, None);++ // 8. Set promise.[[PromiseIsHandled]] to true.+ mark_promise_as_handled(cx.vm(), promise);++ // 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).+ serialize_message_port(cx, data_holder, &port2);+ Ok(())+ })+ }++ // https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps①+ fn transfer_receiving_steps(cx: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Ref<Self>> {+ let cx: &CallContext = cx;+ with_temporary_execution_context_and_callbacks(cx.realm(), || {+ let value = allocate(cx.vm(), Self::new(cx.realm()));++ // 1. Let deserializedRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[port]], the current+ // Realm).+ // 2. Let port be deserializedRecord.[[Deserialized]].+ let port = deserialize_message_port(cx, data_holder);++ // 3. Perform ! SetUpCrossRealmTransformWritable(value, port).+ set_up_cross_realm_transform_writable(cx, value, port);+ Ok(value)+ })+ }+}++// https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer+pub(crate) fn acquire_writable_stream_default_writer(+ cx: &CallContext,+ stream: Ref<WritableStream>,+) -> WebIdlResult<Ref<WritableStreamDefaultWriter>> {+ // 1. Let writer be a new WritableStreamDefaultWriter.+ let writer = allocate(cx.vm(), WritableStreamDefaultWriter::new());++ // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).+ set_up_writable_stream_default_writer(cx, writer, stream)?;++ // 3. Return writer.+ Ok(writer)+}++// https://streams.spec.whatwg.org/#create-writable-stream+#[allow(clippy::too_many_arguments, reason = "the abstract operation takes these arguments")]+pub(crate) fn create_writable_stream(+ cx: &CallContext,+ start_algorithm: StartAlgorithm,+ write_algorithm: WriteAlgorithm,+ close_algorithm: CloseAlgorithm,+ abort_algorithm: AbortAlgorithm,+ high_water_mark: f64,+ size_algorithm: SizeAlgorithm,+) -> WebIdlResult<Ref<WritableStream>> {+ // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.+ assert!(is_non_negative_number(Value::from_f64(high_water_mark)));++ // 2. Let stream be a new WritableStream.+ let stream = allocate(cx.vm(), WritableStream::new(cx.realm()));++ // 3. Perform ! InitializeWritableStream(stream).+ initialize_writable_stream(stream);++ // 4. Let controller be a new WritableStreamDefaultController.+ let controller = allocate(cx.vm(), WritableStreamDefaultController::new());++ // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm,+ // closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).+ set_up_writable_stream_default_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ write_algorithm,+ close_algorithm,+ abort_algorithm,+ high_water_mark,+ size_algorithm,+ )?;++ // 6. Return stream.+ Ok(stream)+}++// https://streams.spec.whatwg.org/#initialize-writable-stream+pub(crate) fn initialize_writable_stream(stream: Ref<WritableStream>) {+ // 1. Set stream.[[state]] to "writable".+ stream.state.set(WritableStreamState::Writable);++ // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],+ // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.+ stream.stored_error.set(Value::UNDEFINED);+ stream.writer.set(None);+ stream.controller.set(None);+ stream.in_flight_write_request.set(None);+ stream.close_request.set(None);+ stream.in_flight_close_request.set(None);+ stream.pending_abort_request.set(None);++ // 3. Set stream.[[writeRequests]] to a new empty list.+ stream.write_requests.borrow_mut().clear();++ // 4. Set stream.[[backpressure]] to false.+ stream.backpressure.set(false);+}++// https://streams.spec.whatwg.org/#is-writable-stream-locked+pub(crate) fn is_writable_stream_locked(stream: Ref<WritableStream>) -> bool {+ // 1. If stream.[[writer]] is undefined, return false.+ // 2. Return true.+ stream.writer().is_some()+}++// https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer+pub(crate) fn set_up_writable_stream_default_writer(+ cx: &CallContext,+ writer: Ref<WritableStreamDefaultWriter>,+ stream: Ref<WritableStream>,+) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = cx.realm();++ // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.+ if is_writable_stream_locked(stream) {+ return Err(Exception::type_error("Stream is locked"));+ }++ // 2. Set writer.[[stream]] to stream.+ writer.set_stream(Some(stream));++ // 3. Set stream.[[writer]] to writer.+ stream.set_writer(Some(writer));++ // 4. Let state be stream.[[state]].+ let state = stream.state();++ match state {+ // 5. If state is "writable",+ WritableStreamState::Writable => {+ // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set+ // writer.[[readyPromise]] to a new promise.+ if !writable_stream_close_queued_or_in_flight(stream) && stream.backpressure.get() {+ writer.set_ready_promise(create_promise(vm, realm));+ }+ // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.+ else {+ writer.set_ready_promise(create_resolved_promise(vm, realm, Value::UNDEFINED));+ }++ // 3. Set writer.[[closedPromise]] to a new promise.+ writer.set_closed_promise(create_promise(vm, realm));+ }+ // 6. Otherwise, if state is "erroring",+ WritableStreamState::Erroring => {+ // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].+ let ready_promise = create_rejected_promise(vm, realm, stream.stored_error());+ writer.set_ready_promise(ready_promise);++ // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, ready_promise);++ // 3. Set writer.[[closedPromise]] to a new promise.+ writer.set_closed_promise(create_promise(vm, realm));+ }+ // 7. Otherwise, if state is "closed",+ WritableStreamState::Closed => {+ // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.+ writer.set_ready_promise(create_resolved_promise(vm, realm, Value::UNDEFINED));++ // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.+ writer.set_closed_promise(create_resolved_promise(vm, realm, Value::UNDEFINED));+ }+ // 8. Otherwise,+ WritableStreamState::Errored => {+ // 1. Assert: state is "errored".++ // 2. Let storedError be stream.[[storedError]].+ let stored_error = stream.stored_error();++ // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.+ let ready_promise = create_rejected_promise(vm, realm, stored_error);+ writer.set_ready_promise(ready_promise);++ // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, ready_promise);++ // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.+ let closed_promise = create_rejected_promise(vm, realm, stored_error);+ writer.set_closed_promise(closed_promise);++ // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, closed_promise);+ }+ }+ Ok(())+}++// https://streams.spec.whatwg.org/#writable-stream-abort+pub(crate) fn writable_stream_abort(cx: &CallContext, stream: Ref<WritableStream>, reason: Value) -> WebIdlPromise {+ let vm = cx.vm();+ let realm = cx.realm();+ let mut reason = reason;++ // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.+ if matches!(+ stream.state(),+ WritableStreamState::Closed | WritableStreamState::Errored+ ) {+ return create_resolved_promise(vm, realm, Value::UNDEFINED);+ }++ // 2. Signal abort on stream.[[controller]].[[abortController]] with reason.+ let mut signal_abort_reason = reason;+ if signal_abort_reason.is_undefined() {+ signal_abort_reason = exception_value(+ vm,+ realm,+ Exception::Dom("AbortError", Utf16String::from_ascii(b"Aborted without reason")),+ );+ }+ let controller = stream.controller().expect("a stream that is set up has a controller");+ controller.abort_signal().signal_abort(signal_abort_reason, realm);++ // 3. Let state be stream.[[state]].+ let state = stream.state();++ // 4. If state is "closed" or "errored", return a promise resolved with undefined.+ if state == WritableStreamState::Closed || state == WritableStreamState::Errored {+ return create_resolved_promise(vm, realm, Value::UNDEFINED);+ }++ // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.+ if let Some(pending_abort_request) = stream.pending_abort_request.get() {+ return pending_abort_request.promise;+ }++ // 6. Assert: state is "writable" or "erroring".+ assert!(state == WritableStreamState::Writable || state == WritableStreamState::Erroring);++ // 7. Let wasAlreadyErroring be false.+ let mut was_already_erroring = false;++ // 8. If state is "erroring",+ if state == WritableStreamState::Erroring {+ // 1. Set wasAlreadyErroring to true.+ was_already_erroring = true;++ // 2. Set reason to undefined.+ reason = Value::UNDEFINED;+ }++ // 9. Let promise be a new promise.+ let promise = create_promise(vm, realm);++ // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason,+ // and was already erroring is wasAlreadyErroring.+ stream.pending_abort_request.set(Some(PendingAbortRequest {+ promise,+ reason,+ was_already_erroring,+ }));++ // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).+ if !was_already_erroring {+ writable_stream_start_erroring(cx, stream, reason);+ }++ // 12. Return promise.+ promise+}++// https://streams.spec.whatwg.org/#writable-stream-close+pub(crate) fn writable_stream_close(cx: &CallContext, stream: Ref<WritableStream>) -> WebIdlPromise {+ let vm = cx.vm();+ let realm = cx.realm();++ // 1. Let state be stream.[[state]].+ let state = stream.state();++ // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.+ if state == WritableStreamState::Closed || state == WritableStreamState::Errored {+ let message = if state == WritableStreamState::Closed {+ "Cannot close a closed stream"+ } else {+ "Cannot close an errored stream"+ };+ let exception = Exception::type_error(message);++ return create_rejected_promise_from_exception(vm, realm, exception);+ }++ // 3. Assert: state is "writable" or "erroring".+ assert!(state == WritableStreamState::Writable || state == WritableStreamState::Erroring);++ // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.+ assert!(!writable_stream_close_queued_or_in_flight(stream));++ // 5. Let promise be a new promise.+ let promise = create_promise(vm, realm);++ // 6. Set stream.[[closeRequest]] to promise.+ stream.close_request.set(Some(promise));++ // 7. Let writer be stream.[[writer]].+ let writer = stream.writer();++ // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve+ // writer.[[readyPromise]] with undefined.+ if let Some(writer) = writer+ && stream.backpressure.get()+ && state == WritableStreamState::Writable+ {+ let ready_promise = writer+ .ready_promise()+ .expect("a writer that is set up has a ready promise");+ resolve_promise(vm, ready_promise, Value::UNDEFINED);+ }++ // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).+ let controller = stream.controller().expect("a stream that is set up has a controller");+ writable_stream_default_controller_close(cx, controller);++ // 10. Return promise.+ promise+}++// https://streams.spec.whatwg.org/#writable-stream-add-write-request+pub(crate) fn writable_stream_add_write_request(cx: &CallContext, stream: Ref<WritableStream>) -> WebIdlPromise {+ // 1. Assert: ! IsWritableStreamLocked(stream) is true.+ assert!(is_writable_stream_locked(stream));++ // 2. Assert: stream.[[state]] is "writable".+ assert!(stream.state() == WritableStreamState::Writable);++ // 3. Let promise be a new promise.+ let promise = create_promise(cx.vm(), cx.realm());++ // 4. Append promise to stream.[[writeRequests]].+ stream.write_requests.borrow_mut().push_back(promise);++ // 5. Return promise.+ promise+}++// https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight+pub(crate) fn writable_stream_close_queued_or_in_flight(stream: Ref<WritableStream>) -> bool {+ // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.+ // 2. Return true.+ stream.close_request.get().is_some() || stream.in_flight_close_request.get().is_some()+}++// https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection+pub(crate) fn writable_stream_deal_with_rejection(cx: &CallContext, stream: Ref<WritableStream>, error: Value) {+ // 1. Let state be stream.[[state]].+ let state = stream.state();++ // 2. If state is "writable",+ if state == WritableStreamState::Writable {+ // 1. Perform ! WritableStreamStartErroring(stream, error).+ writable_stream_start_erroring(cx, stream, error);++ // 2. Return.+ return;+ }++ // 3. Assert: state is "erroring".+ assert!(state == WritableStreamState::Erroring);++ // 4. Perform ! WritableStreamFinishErroring(stream).+ writable_stream_finish_erroring(cx, stream);+}++// https://streams.spec.whatwg.org/#writable-stream-finish-erroring+pub(crate) fn writable_stream_finish_erroring(cx: &CallContext, stream: Ref<WritableStream>) {+ let vm = cx.vm();++ // 1. Assert: stream.[[state]] is "erroring".+ assert!(stream.state() == WritableStreamState::Erroring);++ // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.+ assert!(!writable_stream_has_operation_marked_in_flight(stream));++ // 3. Set stream.[[state]] to "errored".+ stream.state.set(WritableStreamState::Errored);++ // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().+ let controller = stream.controller().expect("a stream that is set up has a controller");+ WritableStreamDefaultController::error_steps(controller);++ // 5. Let storedError be stream.[[storedError]].+ let stored_error = stream.stored_error();++ // 6. For each writeRequest of stream.[[writeRequests]]:+ // 7. Set stream.[[writeRequests]] to an empty list.+ let write_requests = stream.take_write_requests(vm);+ for index in 0..write_requests.len() {+ // 1. Reject writeRequest with storedError.+ reject_promise(+ vm,+ write_requests.get(index).expect("the index is in bounds"),+ stored_error,+ );+ }++ // 8. If stream.[[pendingAbortRequest]] is undefined,+ if stream.pending_abort_request.get().is_none() {+ // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).+ writable_stream_reject_close_and_closed_promise_if_needed(cx, stream);++ // 2. Return.+ return;+ }++ // 9. Let abortRequest be stream.[[pendingAbortRequest]].+ // 10. Set stream.[[pendingAbortRequest]] to undefined.+ let abort_request = stream+ .pending_abort_request+ .take()+ .expect("the stream has a pending abort request");++ // 11. If abortRequest’s was already erroring is true,+ if abort_request.was_already_erroring {+ // 1. Reject abortRequest’s promise with storedError.+ reject_promise(vm, abort_request.promise, stored_error);++ // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).+ writable_stream_reject_close_and_closed_promise_if_needed(cx, stream);++ // 3. Return.+ return;+ }++ // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).+ let promise = WritableStreamDefaultController::abort_steps(controller, cx, abort_request.reason);++ react_to_promise(+ vm,+ promise,+ (stream, abort_request.promise),+ // 13. Upon fulfillment of promise,+ Some(|cx, (stream, abort_promise), _| {+ // 1. Resolve abortRequest’s promise with undefined.+ resolve_promise(cx.vm(), abort_promise, Value::UNDEFINED);++ // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).+ writable_stream_reject_close_and_closed_promise_if_needed(cx, stream);++ Ok(Value::UNDEFINED)+ }),+ // 14. Upon rejection of promise with reason reason,+ Some(|cx, (stream, abort_promise), reason| {+ // 1. Reject abortRequest’s promise with reason.+ reject_promise(cx.vm(), abort_promise, reason);++ // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).+ writable_stream_reject_close_and_closed_promise_if_needed(cx, stream);++ Ok(Value::UNDEFINED)+ }),+ );+}++// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close+pub(crate) fn writable_stream_finish_in_flight_close(cx: &CallContext, stream: Ref<WritableStream>) {+ let vm = cx.vm();++ // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.+ // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.+ // 3. Set stream.[[inFlightCloseRequest]] to undefined.+ let in_flight_close_request = stream+ .in_flight_close_request+ .take()+ .expect("a stream finishes an in-flight close request");+ resolve_promise(vm, in_flight_close_request, Value::UNDEFINED);++ // 4. Let state be stream.[[state]].+ let state = stream.state();++ // 5. Assert: stream.[[state]] is "writable" or "erroring".+ assert!(state == WritableStreamState::Writable || state == WritableStreamState::Erroring);++ // 6. If state is "erroring",+ if state == WritableStreamState::Erroring {+ // 1. Set stream.[[storedError]] to undefined.+ stream.stored_error.set(Value::UNDEFINED);++ // 2. If stream.[[pendingAbortRequest]] is not undefined,+ // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.+ // 2. Set stream.[[pendingAbortRequest]] to undefined.+ if let Some(pending_abort_request) = stream.pending_abort_request.take() {+ resolve_promise(vm, pending_abort_request.promise, Value::UNDEFINED);+ }+ }++ // 7. Set stream.[[state]] to "closed".+ stream.state.set(WritableStreamState::Closed);++ // 8. Let writer be stream.[[writer]].+ // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.+ if let Some(writer) = stream.writer() {+ let closed_promise = writer+ .closed_promise()+ .expect("a writer that is set up has a closed promise");+ resolve_promise(vm, closed_promise, Value::UNDEFINED);+ }++ // 10. Assert: stream.[[pendingAbortRequest]] is undefined.+ assert!(stream.pending_abort_request.get().is_none());++ // 11. Assert: stream.[[storedError]] is undefined.+ assert!(stream.stored_error().is_undefined());+}++// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error+pub(crate) fn writable_stream_finish_in_flight_close_with_error(+ cx: &CallContext,+ stream: Ref<WritableStream>,+ error: Value,+) {+ let vm = cx.vm();++ // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.+ // 2. Reject stream.[[inFlightCloseRequest]] with error.+ // 3. Set stream.[[inFlightCloseRequest]] to undefined.+ let in_flight_close_request = stream+ .in_flight_close_request+ .take()+ .expect("a stream finishes an in-flight close request");+ reject_promise(vm, in_flight_close_request, error);++ // 4. Assert: stream.[[state]] is "writable" or "erroring".+ assert!(matches!(+ stream.state(),+ WritableStreamState::Writable | WritableStreamState::Erroring+ ));++ // 5. If stream.[[pendingAbortRequest]] is not undefined,+ // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.+ // 2. Set stream.[[pendingAbortRequest]] to undefined.+ if let Some(pending_abort_request) = stream.pending_abort_request.take() {+ reject_promise(vm, pending_abort_request.promise, error);+ }++ // 6. Perform ! WritableStreamDealWithRejection(stream, error).+ writable_stream_deal_with_rejection(cx, stream, error);+}++// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write+pub(crate) fn writable_stream_finish_in_flight_write(cx: &CallContext, stream: Ref<WritableStream>) {+ // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.+ // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.+ // 3. Set stream.[[inFlightWriteRequest]] to undefined.+ let in_flight_write_request = stream+ .in_flight_write_request+ .take()+ .expect("a stream finishes an in-flight write request");+ resolve_promise(cx.vm(), in_flight_write_request, Value::UNDEFINED);+}++// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error+pub(crate) fn writable_stream_finish_in_flight_write_with_error(+ cx: &CallContext,+ stream: Ref<WritableStream>,+ error: Value,+) {+ // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.+ // 2. Reject stream.[[inFlightWriteRequest]] with error.+ // 3. Set stream.[[inFlightWriteRequest]] to undefined.+ let in_flight_write_request = stream+ .in_flight_write_request+ .take()+ .expect("a stream finishes an in-flight write request");+ reject_promise(cx.vm(), in_flight_write_request, error);++ // 4. Assert: stream.[[state]] is "writable" or "erroring".+ assert!(matches!(+ stream.state(),+ WritableStreamState::Writable | WritableStreamState::Erroring+ ));++ // 5. Perform ! WritableStreamDealWithRejection(stream, error).+ writable_stream_deal_with_rejection(cx, stream, error);+}++// https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight+pub(crate) fn writable_stream_has_operation_marked_in_flight(stream: Ref<WritableStream>) -> bool {+ // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return+ // false.+ // 2. Return true.+ stream.in_flight_write_request.get().is_some() || stream.in_flight_close_request.get().is_some()+}++// https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight+pub(crate) fn writable_stream_mark_close_request_in_flight(stream: Ref<WritableStream>) {+ // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.+ assert!(stream.in_flight_close_request.get().is_none());++ // 2. Assert: stream.[[closeRequest]] is not undefined.+ // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].+ // 4. Set stream.[[closeRequest]] to undefined.+ let close_request = stream+ .close_request+ .take()+ .expect("a stream has a close request to mark in flight");+ stream.in_flight_close_request.set(Some(close_request));+}++// https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight+pub(crate) fn writable_stream_mark_first_write_request_in_flight(stream: Ref<WritableStream>) {+ // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.+ assert!(stream.in_flight_write_request.get().is_none());++ // 2. Assert: stream.[[writeRequests]] is not empty.+ // 3. Let writeRequest be stream.[[writeRequests]][0].+ // 4. Remove writeRequest from stream.[[writeRequests]].+ let write_request = stream+ .write_requests+ .borrow_mut()+ .pop_front()+ .expect("a stream has a write request to mark in flight");++ // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.+ stream.in_flight_write_request.set(Some(write_request));+}++// https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed+pub(crate) fn writable_stream_reject_close_and_closed_promise_if_needed(cx: &CallContext, stream: Ref<WritableStream>) {+ let vm = cx.vm();++ // 1. Assert: stream.[[state]] is "errored".+ assert!(stream.state() == WritableStreamState::Errored);++ // 2. If stream.[[closeRequest]] is not undefined,+ if let Some(close_request) = stream.close_request.get() {+ // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.+ assert!(stream.in_flight_close_request.get().is_none());++ // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].+ reject_promise(vm, close_request, stream.stored_error());++ // 3. Set stream.[[closeRequest]] to undefined.+ stream.close_request.set(None);+ }++ // 3. Let writer be stream.[[writer]].+ // 4. If writer is not undefined,+ if let Some(writer) = stream.writer() {+ let closed_promise = writer+ .closed_promise()+ .expect("a writer that is set up has a closed promise");++ // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].+ reject_promise(vm, closed_promise, stream.stored_error());++ // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(vm, closed_promise);+ }+}++// https://streams.spec.whatwg.org/#writable-stream-start-erroring+pub(crate) fn writable_stream_start_erroring(cx: &CallContext, stream: Ref<WritableStream>, reason: Value) {+ // 1. Assert: stream.[[storedError]] is undefined.+ assert!(stream.stored_error().is_undefined());++ // 2. Assert: stream.[[state]] is "writable".+ assert!(stream.state() == WritableStreamState::Writable);++ // 3. Let controller be stream.[[controller]].+ // 4. Assert: controller is not undefined.+ let controller = stream+ .controller()+ .expect("a stream that starts erroring has a controller");++ // 5. Set stream.[[state]] to "erroring".+ stream.state.set(WritableStreamState::Erroring);++ // 6. Set stream.[[storedError]] to reason.+ stream.stored_error.set(reason);++ // 7. Let writer be stream.[[writer]].+ // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).+ if let Some(writer) = stream.writer() {+ writable_stream_default_writer_ensure_ready_promise_rejected(cx.vm(), writer, reason);+ }++ // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true,+ // perform ! WritableStreamFinishErroring(stream).+ if !writable_stream_has_operation_marked_in_flight(stream) && controller.started() {+ writable_stream_finish_erroring(cx, stream);+ }+}++// https://streams.spec.whatwg.org/#writable-stream-update-backpressure+pub(crate) fn writable_stream_update_backpressure(cx: &CallContext, stream: Ref<WritableStream>, backpressure: bool) {+ let vm = cx.vm();++ // 1. Assert: stream.[[state]] is "writable".+ assert!(stream.state() == WritableStreamState::Writable);++ // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.+ assert!(!writable_stream_close_queued_or_in_flight(stream));++ // 3. Let writer be stream.[[writer]].+ // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],+ if let Some(writer) = stream.writer()+ && backpressure != stream.backpressure.get()+ {+ let realm = writer.ready_promise_realm();++ // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.+ if backpressure {+ writer.set_ready_promise(create_promise(vm, realm));+ }+ // 2. Otherwise,+ else {+ // 1. Assert: backpressure is false.++ // 2. Resolve writer.[[readyPromise]] with undefined.+ let ready_promise = writer+ .ready_promise()+ .expect("a writer that is set up has a ready promise");+ resolve_promise(vm, ready_promise, Value::UNDEFINED);+ }+ }++ // 5. Set stream.[[backpressure]] to backpressure.+ stream.backpressure.set(backpressure);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rsnew file mode 100644index 00000000000..65efa7857db--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_controller.rs@@ -0,0 +1,660 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! WritableStreamDefaultController, https://streams.spec.whatwg.org/#ws-default-controller-class, and its abstract+//! operations, https://streams.spec.whatwg.org/#ws-default-controller-abstract-ops++use core::cell::Cell;++use libjs_rust::api::{GcRefCell, Trace, Value};++use crate::bindings::conversions::CppInterface;+use crate::bindings::interface::{Ref, Wrappable, allocate, wrap};+use crate::bindings::promise::{WebIdlPromise, create_resolved_promise, exception_value, react_to_promise};+use crate::bindings::{CallContext, MustNotThrow, WebIdlResult};+use crate::streams::algorithms::{AbortAlgorithm, CloseAlgorithm, SizeAlgorithm, StartAlgorithm, WriteAlgorithm};+use crate::streams::cpp::AbortSignal;+use crate::streams::queue_with_sizes::QueueWithSizes;+use crate::streams::underlying_sink::UnderlyingSink;+use crate::streams::writable_stream::{+ WritableStream, WritableStreamState, writable_stream_close_queued_or_in_flight,+ writable_stream_deal_with_rejection, writable_stream_finish_erroring, writable_stream_finish_in_flight_close,+ writable_stream_finish_in_flight_close_with_error, writable_stream_finish_in_flight_write,+ writable_stream_finish_in_flight_write_with_error, writable_stream_mark_close_request_in_flight,+ writable_stream_mark_first_write_request_in_flight, writable_stream_start_erroring,+ writable_stream_update_backpressure,+};++// https://streams.spec.whatwg.org/#close-sentinel+fn create_close_sentinel() -> Value {+ // The close sentinel is a unique value enqueued into [[queue]], in lieu of a chunk, to signal that the stream is+ // closed. It is only used internally, and is never exposed to web developers.+ Value::EMPTY+}++// https://streams.spec.whatwg.org/#close-sentinel+fn is_close_sentinel(value: Value) -> bool {+ value.is_empty()+}++// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct WritableStreamDefaultController {+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-abortalgorithm+ abort_algorithm: GcRefCell<Option<AbortAlgorithm>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-closealgorithm+ close_algorithm: GcRefCell<Option<CloseAlgorithm>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-queue+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-queuetotalsize+ queue: QueueWithSizes,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-abortcontroller, of which LibWeb's C++ keeps the+ // signal.+ signal: GcRefCell<Option<AbortSignal>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-started+ started: Cell<bool>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-strategyhwm+ #[gc(untraced)]+ strategy_hwm: Cell<f64>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-strategysizealgorithm+ strategy_size_algorithm: GcRefCell<Option<SizeAlgorithm>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-stream+ stream: Cell<Option<Ref<WritableStream>>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-writealgorithm+ write_algorithm: GcRefCell<Option<WriteAlgorithm>>,+}++impl Wrappable for WritableStreamDefaultController {}++impl WritableStreamDefaultController {+ pub(crate) fn new() -> Self {+ Self {+ abort_algorithm: GcRefCell::new(None),+ close_algorithm: GcRefCell::new(None),+ queue: QueueWithSizes::default(),+ signal: GcRefCell::new(None),+ started: Cell::new(false),+ strategy_hwm: Cell::new(0.0),+ strategy_size_algorithm: GcRefCell::new(None),+ stream: Cell::new(None),+ write_algorithm: GcRefCell::new(None),+ }+ }++ /// The controller's [[stream]], which it has once it is set up.+ pub(crate) fn stream(&self) -> Ref<WritableStream> {+ self.stream.get().expect("a controller that is set up has a stream")+ }++ pub(crate) fn started(&self) -> bool {+ self.started.get()+ }++ /// The controller's [[writeAlgorithm]], which it has until its algorithms are cleared.+ fn write_algorithm(&self) -> Option<WriteAlgorithm> {+ self.write_algorithm.borrow().clone()+ }++ /// The controller's [[closeAlgorithm]], which it has until its algorithms are cleared.+ fn close_algorithm(&self) -> Option<CloseAlgorithm> {+ self.close_algorithm.borrow().clone()+ }++ /// The controller's [[abortAlgorithm]], which it has until its algorithms are cleared.+ fn abort_algorithm(&self) -> Option<AbortAlgorithm> {+ self.abort_algorithm.borrow().clone()+ }++ /// The controller's [[strategySizeAlgorithm]], which it has until its algorithms are cleared.+ fn strategy_size_algorithm(&self) -> Option<SizeAlgorithm> {+ self.strategy_size_algorithm.borrow().clone()+ }++ /// The signal of the controller's [[abortController]].+ pub(crate) fn abort_signal(&self) -> AbortSignal {+ self.signal+ .borrow()+ .clone()+ .expect("a controller that is set up has a signal")+ }++ // https://streams.spec.whatwg.org/#ws-default-controller-signal+ pub(crate) fn signal(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ Ok(self.abort_signal().wrapper(cx.realm()))+ }++ // https://streams.spec.whatwg.org/#ws-default-controller-error+ pub(crate) fn error(this: &Ref<Self>, cx: &mut CallContext, e: Option<Value>) -> WebIdlResult<()> {+ // 1. Let state be this.[[stream]].[[state]].+ let state = this.stream().state();++ // 2. If state is not "writable", return.+ if state != WritableStreamState::Writable {+ return Ok(());+ }++ // 3. Perform ! WritableStreamDefaultControllerError(this, e).+ writable_stream_default_controller_error(cx, *this, e.unwrap_or(Value::UNDEFINED));+ Ok(())+ }++ // https://streams.spec.whatwg.org/#ws-default-controller-private-abort+ pub(crate) fn abort_steps(this: Ref<Self>, cx: &CallContext, reason: Value) -> WebIdlPromise {+ // 1. Let result be the result of performing this.[[abortAlgorithm]], passing reason.+ let abort_algorithm = this+ .abort_algorithm()+ .expect("a controller that aborts has an abort algorithm");+ let result = abort_algorithm.run(&this.stream().context(cx.vm()), reason);++ // 2. Perform ! WritableStreamDefaultControllerClearAlgorithms(this).+ writable_stream_default_controller_clear_algorithms(this);++ // 3. Return result.+ result+ }++ // https://streams.spec.whatwg.org/#ws-default-controller-private-error+ pub(crate) fn error_steps(this: Ref<Self>) {+ // 1. Perform ! ResetQueue(this).+ this.queue.reset_queue();+ }+}++// https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller+#[allow(clippy::too_many_arguments, reason = "the abstract operation takes these arguments")]+pub(crate) fn set_up_writable_stream_default_controller(+ cx: &CallContext,+ stream: Ref<WritableStream>,+ controller: Ref<WritableStreamDefaultController>,+ start_algorithm: StartAlgorithm,+ write_algorithm: WriteAlgorithm,+ close_algorithm: CloseAlgorithm,+ abort_algorithm: AbortAlgorithm,+ high_water_mark: f64,+ size_algorithm: SizeAlgorithm,+) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Assert: stream implements WritableStream.++ // 2. Assert: stream.[[controller]] is undefined.+ assert!(stream.controller().is_none());++ // 3. Set controller.[[stream]] to stream.+ controller.stream.set(Some(stream));++ // 4. Set stream.[[controller]] to controller.+ stream.set_controller(Some(controller));++ // 5. Perform ! ResetQueue(controller).+ controller.queue.reset_queue();++ // 6. Set controller.[[abortController]] to a new AbortController.+ let signal = AbortSignal::create();+ *controller.signal.borrow_mut() = Some(signal);++ // 7. Set controller.[[started]] to false.+ controller.started.set(false);++ // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.+ *controller.strategy_size_algorithm.borrow_mut() = Some(size_algorithm);++ // 9. Set controller.[[strategyHWM]] to highWaterMark.+ controller.strategy_hwm.set(high_water_mark);++ // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.+ *controller.write_algorithm.borrow_mut() = Some(write_algorithm);++ // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.+ *controller.close_algorithm.borrow_mut() = Some(close_algorithm);++ // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.+ *controller.abort_algorithm.borrow_mut() = Some(abort_algorithm);++ // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).+ let backpressure = writable_stream_default_controller_get_backpressure(controller);++ // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).+ writable_stream_update_backpressure(cx, stream, backpressure);++ // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)+ let start_result = start_algorithm.run()?;++ // 16. Let startPromise be a promise resolved with startResult.+ let start_promise = create_resolved_promise(vm, cx.realm(), start_result);++ react_to_promise(+ vm,+ start_promise,+ (controller, stream),+ // 17. Upon fulfillment of startPromise,+ Some(|cx, (controller, stream), _| {+ let cx = &stream.context(cx.vm());++ // 1. Assert: stream.[[state]] is "writable" or "erroring".+ assert!(matches!(+ stream.state(),+ WritableStreamState::Writable | WritableStreamState::Erroring+ ));++ // 2. Set controller.[[started]] to true.+ controller.started.set(true);++ // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).+ writable_stream_default_controller_advance_queue_if_needed(cx, controller);++ Ok(Value::UNDEFINED)+ }),+ // 18. Upon rejection of startPromise with reason r,+ Some(|cx, (controller, stream), reason| {+ let cx = &stream.context(cx.vm());++ // 1. Assert: stream.[[state]] is "writable" or "erroring".+ assert!(matches!(+ stream.state(),+ WritableStreamState::Writable | WritableStreamState::Erroring+ ));++ // 2. Set controller.[[started]] to true.+ controller.started.set(true);++ // 3. Perform ! WritableStreamDealWithRejection(stream, r).+ writable_stream_deal_with_rejection(cx, stream, reason);++ Ok(Value::UNDEFINED)+ }),+ );+ Ok(())+}++// https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink+pub(crate) fn set_up_writable_stream_default_controller_from_underlying_sink(+ cx: &CallContext,+ stream: Ref<WritableStream>,+ underlying_sink: Value,+ underlying_sink_dict: UnderlyingSink,+ high_water_mark: f64,+ size_algorithm: SizeAlgorithm,+) -> WebIdlResult<()> {+ // 1. Let controller be a new WritableStreamDefaultController.+ let controller = allocate(cx.vm(), WritableStreamDefaultController::new());++ // 2. Let startAlgorithm be an algorithm that returns undefined.+ let mut start_algorithm = StartAlgorithm::ReturnsUndefined;++ // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut write_algorithm = WriteAlgorithm::ReturnsResolvedUndefined;++ // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut close_algorithm = CloseAlgorithm::ReturnsResolvedUndefined;++ // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.+ let mut abort_algorithm = AbortAlgorithm::ReturnsResolvedUndefined;++ // 6. If underlyingSinkDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of+ // invoking underlyingSinkDict["start"] with argument list « controller », exception behavior "rethrow", and+ // callback this value underlyingSink.+ if let Some(start) = underlying_sink_dict.start {+ start_algorithm = StartAlgorithm::Callback {+ start,+ this_value: underlying_sink,+ controller: Value::from_object(wrap(cx, controller)),+ };+ }++ // 7. If underlyingSinkDict["write"] exists, then set writeAlgorithm to an algorithm which takes an argument chunk+ // and returns the result of invoking underlyingSinkDict["write"] with argument list « chunk, controller » and+ // callback this value underlyingSink.+ if let Some(write) = underlying_sink_dict.write {+ write_algorithm = WriteAlgorithm::Callback {+ write,+ underlying_sink,+ controller,+ };+ }++ // 8. If underlyingSinkDict["close"] exists, then set closeAlgorithm to an algorithm which returns the result of+ // invoking underlyingSinkDict["close"] with argument list «» and callback this value underlyingSink.+ if let Some(close) = underlying_sink_dict.close {+ close_algorithm = CloseAlgorithm::Callback { close, underlying_sink };+ }++ // 9. If underlyingSinkDict["abort"] exists, then set abortAlgorithm to an algorithm which takes an argument reason+ // and returns the result of invoking underlyingSinkDict["abort"] with argument list « reason » and callback this+ // value underlyingSink.+ if let Some(abort) = underlying_sink_dict.abort {+ abort_algorithm = AbortAlgorithm::Callback { abort, underlying_sink };+ }++ // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm,+ // closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).+ set_up_writable_stream_default_controller(+ cx,+ stream,+ controller,+ start_algorithm,+ write_algorithm,+ close_algorithm,+ abort_algorithm,+ high_water_mark,+ size_algorithm,+ )+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed+pub(crate) fn writable_stream_default_controller_advance_queue_if_needed(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. If controller.[[started]] is false, return.+ if !controller.started() {+ return;+ }++ // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.+ if stream.in_flight_write_request().is_some() {+ return;+ }++ // 4. Let state be stream.[[state]].+ let state = stream.state();++ // 5. Assert: state is not "closed" or "errored".+ assert!(state != WritableStreamState::Closed && state != WritableStreamState::Errored);++ // 6. If state is "erroring",+ if state == WritableStreamState::Erroring {+ // 1. Perform ! WritableStreamFinishErroring(stream).+ writable_stream_finish_erroring(cx, stream);++ // 2. Return.+ return;+ }++ // 7. If controller.[[queue]] is empty, return.+ if controller.queue.is_empty() {+ return;+ }++ // 8. Let value be ! PeekQueueValue(controller).+ let value = controller.queue.peek_queue_value();++ // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).+ if is_close_sentinel(value) {+ writable_stream_default_controller_process_close(cx, controller);+ }+ // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).+ else {+ writable_stream_default_controller_process_write(cx, controller, value);+ }+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms+pub(crate) fn writable_stream_default_controller_clear_algorithms(controller: Ref<WritableStreamDefaultController>) {+ // 1. Set controller.[[writeAlgorithm]] to undefined.+ *controller.write_algorithm.borrow_mut() = None;++ // 2. Set controller.[[closeAlgorithm]] to undefined.+ *controller.close_algorithm.borrow_mut() = None;++ // 3. Set controller.[[abortAlgorithm]] to undefined.+ *controller.abort_algorithm.borrow_mut() = None;++ // 4. Set controller.[[strategySizeAlgorithm]] to undefined.+ *controller.strategy_size_algorithm.borrow_mut() = None;+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-close+pub(crate) fn writable_stream_default_controller_close(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+) {+ // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).+ controller+ .queue+ .enqueue_value_with_size(create_close_sentinel(), Value::from_f64(0.0))+ .must();++ // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).+ writable_stream_default_controller_advance_queue_if_needed(cx, controller);+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-error+pub(crate) fn writable_stream_default_controller_error(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+ error: Value,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. Assert: stream.[[state]] is "writable".+ assert!(stream.state() == WritableStreamState::Writable);++ // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).+ writable_stream_default_controller_clear_algorithms(controller);++ // 4. Perform ! WritableStreamStartErroring(stream, error).+ writable_stream_start_erroring(cx, stream, error);+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed+pub(crate) fn writable_stream_default_controller_error_if_needed(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+ error: Value,+) {+ // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller,+ // error).+ if controller.stream().state() == WritableStreamState::Writable {+ writable_stream_default_controller_error(cx, controller, error);+ }+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure+pub(crate) fn writable_stream_default_controller_get_backpressure(+ controller: Ref<WritableStreamDefaultController>,+) -> bool {+ // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).+ let desired_size = writable_stream_default_controller_get_desired_size(controller);++ // 2. Return true if desiredSize ≤ 0, or false otherwise.+ desired_size <= 0.0+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size+pub(crate) fn writable_stream_default_controller_get_chunk_size(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+ chunk: Value,+) -> Value {+ // 1. If controller.[[strategySizeAlgorithm]] is undefined, then:+ let Some(strategy_size_algorithm) = controller.strategy_size_algorithm() else {+ // 1. Assert: controller.[[stream]].[[state]] is not "writable".+ assert!(controller.stream().state() != WritableStreamState::Writable);++ // 2. Return 1.+ return Value::from_f64(1.0);+ };++ // 2. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and+ // interpreting the result as a completion record.+ let return_value = strategy_size_algorithm.run(&controller.stream().context(cx.vm()), chunk);++ match return_value {+ // 3. If returnValue is an abrupt completion,+ Err(throw) => {+ // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).+ writable_stream_default_controller_error_if_needed(cx, controller, throw.value());++ // 2. Return 1.+ Value::from_f64(1.0)+ }+ // 4. Return returnValue.[[Value]].+ Ok(value) => value,+ }+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size+pub(crate) fn writable_stream_default_controller_get_desired_size(+ controller: Ref<WritableStreamDefaultController>,+) -> f64 {+ // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].+ controller.strategy_hwm.get() - controller.queue.total_size()+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close+pub(crate) fn writable_stream_default_controller_process_close(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).+ writable_stream_mark_close_request_in_flight(stream);++ // 3. Perform ! DequeueValue(controller).+ controller.queue.dequeue_value();++ // 4. Assert: controller.[[queue]] is empty.+ assert!(controller.queue.is_empty());++ // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].+ let close_algorithm = controller+ .close_algorithm()+ .expect("a controller that closes has a close algorithm");+ let sink_close_promise = close_algorithm.run(&stream.context(cx.vm()));++ // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).+ writable_stream_default_controller_clear_algorithms(controller);++ react_to_promise(+ cx.vm(),+ sink_close_promise,+ stream,+ // 7. Upon fulfillment of sinkClosePromise,+ Some(|cx, stream, _| {+ // 1. Perform ! WritableStreamFinishInFlightClose(stream).+ writable_stream_finish_in_flight_close(cx, stream);++ Ok(Value::UNDEFINED)+ }),+ // 8. Upon rejection of sinkClosePromise with reason reason,+ Some(|cx, stream, reason| {+ // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).+ writable_stream_finish_in_flight_close_with_error(cx, stream, reason);++ Ok(Value::UNDEFINED)+ }),+ );+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write+pub(crate) fn writable_stream_default_controller_process_write(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+ chunk: Value,+) {+ // 1. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).+ writable_stream_mark_first_write_request_in_flight(stream);++ // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.+ let write_algorithm = controller+ .write_algorithm()+ .expect("a controller that writes has a write algorithm");+ let sink_write_promise = write_algorithm.run(&stream.context(cx.vm()), chunk);++ react_to_promise(+ cx.vm(),+ sink_write_promise,+ (controller, stream),+ // 4. Upon fulfillment of sinkWritePromise,+ Some(|cx, (controller, stream), _| {+ // 1. Perform ! WritableStreamFinishInFlightWrite(stream).+ writable_stream_finish_in_flight_write(cx, stream);++ // 2. Let state be stream.[[state]].+ let state = stream.state();++ // 3. Assert: state is "writable" or "erroring".+ assert!(state == WritableStreamState::Writable || state == WritableStreamState::Erroring);++ // 4. Perform ! DequeueValue(controller).+ controller.queue.dequeue_value();++ // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",+ if !writable_stream_close_queued_or_in_flight(stream) && state == WritableStreamState::Writable {+ // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).+ let backpressure = writable_stream_default_controller_get_backpressure(controller);++ // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).+ writable_stream_update_backpressure(cx, stream, backpressure);+ }++ // 6. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).+ writable_stream_default_controller_advance_queue_if_needed(cx, controller);++ Ok(Value::UNDEFINED)+ }),+ // 5. Upon rejection of sinkWritePromise with reason,+ Some(|cx, (controller, stream), reason| {+ // 1. If stream.[[state]] is "writable", perform+ // ! WritableStreamDefaultControllerClearAlgorithms(controller).+ if stream.state() == WritableStreamState::Writable {+ writable_stream_default_controller_clear_algorithms(controller);+ }++ // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).+ writable_stream_finish_in_flight_write_with_error(cx, stream, reason);++ Ok(Value::UNDEFINED)+ }),+ );+}++// https://streams.spec.whatwg.org/#writable-stream-default-controller-write+pub(crate) fn writable_stream_default_controller_write(+ cx: &CallContext,+ controller: Ref<WritableStreamDefaultController>,+ chunk: Value,+ chunk_size: Value,+) {+ // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).+ let enqueue_result = controller.queue.enqueue_value_with_size(chunk, chunk_size);++ // 2. If enqueueResult is an abrupt completion,+ if let Err(exception) = enqueue_result {+ let error = exception_value(cx.vm(), cx.realm(), exception);++ // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).+ writable_stream_default_controller_error_if_needed(cx, controller, error);++ // 2. Return.+ return;+ }++ // 3. Let stream be controller.[[stream]].+ let stream = controller.stream();++ // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",+ if !writable_stream_close_queued_or_in_flight(stream) && stream.state() == WritableStreamState::Writable {+ // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).+ let backpressure = writable_stream_default_controller_get_backpressure(controller);++ // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).+ writable_stream_update_backpressure(cx, stream, backpressure);+ }++ // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).+ writable_stream_default_controller_advance_queue_if_needed(cx, controller);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_writer.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_writer.rsnew file mode 100644index 00000000000..5615dbd0379--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream_default_writer.rs@@ -0,0 +1,447 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! WritableStreamDefaultWriter, https://streams.spec.whatwg.org/#default-writer-class, and the abstract operations of+//! writers, https://streams.spec.whatwg.org/#ws-writer-abstract-ops++use core::cell::Cell;++use libjs_rust::api::{Gc, Promise, PromiseState, Realm, Trace, Value, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{+ WebIdlPromise, create_rejected_promise, create_rejected_promise_from_exception, create_resolved_promise,+ exception_value, mark_promise_as_handled, promise_realm, reject_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::streams::writable_stream::{+ WritableStream, WritableStreamState, set_up_writable_stream_default_writer, writable_stream_abort,+ writable_stream_add_write_request, writable_stream_close, writable_stream_close_queued_or_in_flight,+};+use crate::streams::writable_stream_default_controller::{+ writable_stream_default_controller_get_chunk_size, writable_stream_default_controller_get_desired_size,+ writable_stream_default_controller_write,+};++// https://streams.spec.whatwg.org/#writablestreamdefaultwriter+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct WritableStreamDefaultWriter {+ // https://streams.spec.whatwg.org/#writablestreamdefaultwriter-closedpromise+ closed_promise: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultwriter-readypromise+ ready_promise: Cell<Option<WebIdlPromise>>,+ // https://streams.spec.whatwg.org/#writablestreamdefaultwriter-stream+ stream: Cell<Option<Ref<WritableStream>>>,+}++impl Wrappable for WritableStreamDefaultWriter {}++impl WritableStreamDefaultWriter {+ pub(crate) fn new() -> Self {+ Self {+ closed_promise: Cell::new(None),+ ready_promise: Cell::new(None),+ stream: Cell::new(None),+ }+ }++ pub(crate) fn closed_promise(&self) -> Option<WebIdlPromise> {+ self.closed_promise.get()+ }++ pub(crate) fn ready_promise(&self) -> Option<WebIdlPromise> {+ self.ready_promise.get()+ }++ pub(crate) fn stream(&self) -> Option<Ref<WritableStream>> {+ self.stream.get()+ }++ pub(crate) fn set_closed_promise(&self, promise: WebIdlPromise) {+ self.closed_promise.set(Some(promise));+ }++ pub(crate) fn set_ready_promise(&self, promise: WebIdlPromise) {+ self.ready_promise.set(Some(promise));+ }++ pub(crate) fn set_stream(&self, stream: Option<Ref<WritableStream>>) {+ self.stream.set(stream);+ }++ /// The realm of the writer's [[closedPromise]], which most promises and exceptions of the writer are created in,+ /// as LibWeb's C++ creates them.+ pub(crate) fn closed_promise_realm(&self) -> Gc<Realm> {+ promise_realm(+ self.closed_promise()+ .expect("a writer that is set up has a closed promise"),+ )+ }++ /// The realm of the writer's [[readyPromise]], which the promises of the writer's write() are created in, as+ /// LibWeb's C++ creates them.+ pub(crate) fn ready_promise_realm(&self) -> Gc<Realm> {+ promise_realm(+ self.ready_promise()+ .expect("a writer that is set up has a ready promise"),+ )+ }++ // https://streams.spec.whatwg.org/#default-writer-constructor+ pub(crate) fn construct(cx: &mut CallContext, stream: Ref<WritableStream>) -> WebIdlResult<Ref<Self>> {+ let this = allocate(cx.vm(), Self::new());++ // 1. Perform ? SetUpWritableStreamDefaultWriter(this, stream).+ set_up_writable_stream_default_writer(cx, this, stream)?;+ Ok(this)+ }++ // https://streams.spec.whatwg.org/#default-writer-closed+ pub(crate) fn closed(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ // 1. Return this.[[closedPromise]].+ Ok(self+ .closed_promise()+ .expect("a writer that is set up has a closed promise"))+ }++ // https://streams.spec.whatwg.org/#default-writer-desired-size+ pub(crate) fn desired_size(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<Option<f64>> {+ // 1. If this.[[stream]] is undefined, throw a TypeError exception.+ if this.stream().is_none() {+ return Err(Exception::type_error(+ "Cannot get desired size of writer that has no locked stream",+ ));+ }++ // 2. Return ! WritableStreamDefaultWriterGetDesiredSize(this).+ Ok(writable_stream_default_writer_get_desired_size(*this))+ }++ // https://streams.spec.whatwg.org/#default-writer-ready+ pub(crate) fn ready(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ // 1. Return this.[[readyPromise]].+ Ok(self+ .ready_promise()+ .expect("a writer that is set up has a ready promise"))+ }++ // https://streams.spec.whatwg.org/#default-writer-abort+ pub(crate) fn abort(this: &Ref<Self>, cx: &mut CallContext, reason: Option<Value>) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();+ let realm = this.closed_promise_realm();++ // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.+ if this.stream().is_none() {+ let exception = Exception::type_error("Cannot abort a writer that has no locked stream");+ return Ok(create_rejected_promise_from_exception(vm, realm, exception));+ }++ // 2. Return ! WritableStreamDefaultWriterAbort(this, reason).+ Ok(writable_stream_default_writer_abort(+ vm,+ *this,+ reason.unwrap_or(Value::UNDEFINED),+ ))+ }++ // https://streams.spec.whatwg.org/#default-writer-close+ pub(crate) fn close(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();+ let realm = this.closed_promise_realm();++ // 1. Let stream be this.[[stream]].+ // 2. If stream is undefined, return a promise rejected with a TypeError exception.+ let Some(stream) = this.stream() else {+ let exception = Exception::type_error("Cannot close a writer that has no locked stream");+ return Ok(create_rejected_promise_from_exception(vm, realm, exception));+ };++ // 3. If ! WritableStreamCloseQueuedOrInFlight(stream) is true, return a promise rejected with a TypeError+ // exception.+ if writable_stream_close_queued_or_in_flight(stream) {+ let exception = Exception::type_error("Cannot close a stream that is already closed or errored");+ return Ok(create_rejected_promise_from_exception(vm, realm, exception));+ }++ // 4. Return ! WritableStreamDefaultWriterClose(this).+ Ok(writable_stream_default_writer_close(vm, *this))+ }++ // https://streams.spec.whatwg.org/#default-writer-release-lock+ pub(crate) fn release_lock(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {+ // 1. Let stream be this.[[stream]].+ // 2. If stream is undefined, return.+ let Some(stream) = this.stream() else {+ return Ok(());+ };++ // 3. Assert: stream.[[writer]] is not undefined.+ assert!(stream.writer().is_some());++ // 4. Perform ! WritableStreamDefaultWriterRelease(this).+ writable_stream_default_writer_release(cx.vm(), *this);+ Ok(())+ }++ // https://streams.spec.whatwg.org/#default-writer-write+ pub(crate) fn write(this: &Ref<Self>, cx: &mut CallContext, chunk: Option<Value>) -> WebIdlResult<WebIdlPromise> {+ let vm = cx.vm();+ let realm = this.ready_promise_realm();++ // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.+ if this.stream().is_none() {+ let exception = Exception::type_error("Cannot write to a writer that has no locked stream");+ return Ok(create_rejected_promise_from_exception(vm, realm, exception));+ }++ // 2. Return ! WritableStreamDefaultWriterWrite(this, chunk).+ Ok(writable_stream_default_writer_write(+ vm,+ *this,+ chunk.unwrap_or(Value::UNDEFINED),+ ))+ }+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-abort+pub(crate) fn writable_stream_default_writer_abort(+ vm: &Vm,+ writer: Ref<WritableStreamDefaultWriter>,+ reason: Value,+) -> WebIdlPromise {+ // 1. Let stream be writer.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = writer.stream().expect("a writer that aborts its stream has a stream");++ // 3. Return ! WritableStreamAbort(stream, reason).+ writable_stream_abort(&CallContext::new(vm, writer.closed_promise_realm()), stream, reason)+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-close+pub(crate) fn writable_stream_default_writer_close(vm: &Vm, writer: Ref<WritableStreamDefaultWriter>) -> WebIdlPromise {+ // 1. Let stream be writer.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = writer.stream().expect("a writer that closes its stream has a stream");++ // 3. Return ! WritableStreamClose(stream).+ writable_stream_close(&CallContext::new(vm, writer.closed_promise_realm()), stream)+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-close-with-error-propagation+pub(crate) fn writable_stream_default_writer_close_with_error_propagation(+ vm: &Vm,+ writer: Ref<WritableStreamDefaultWriter>,+) -> WebIdlPromise {+ let realm = writer.closed_promise_realm();++ // 1. Let stream be writer.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = writer.stream().expect("a writer that closes its stream has a stream");++ // 3. Let state be stream.[[state]].+ let state = stream.state();++ // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is true or state is "closed", return a promise resolved with+ // undefined.+ if writable_stream_close_queued_or_in_flight(stream) || state == WritableStreamState::Closed {+ return create_resolved_promise(vm, realm, Value::UNDEFINED);+ }++ // 5. If state is "errored", return a promise rejected with stream.[[storedError]].+ if state == WritableStreamState::Errored {+ return create_rejected_promise(vm, realm, stream.stored_error());+ }++ // 6. Assert: state is "writable" or "erroring".+ assert!(state == WritableStreamState::Writable || state == WritableStreamState::Erroring);++ // 7. Return ! WritableStreamDefaultWriterClose(writer).+ writable_stream_default_writer_close(vm, writer)+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected+pub(crate) fn writable_stream_default_writer_ensure_closed_promise_rejected(+ vm: &Vm,+ writer: Ref<WritableStreamDefaultWriter>,+ error: Value,+) {+ let realm = writer.closed_promise_realm();+ let closed_promise = writer+ .closed_promise()+ .expect("a writer that is set up has a closed promise");++ // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.+ let state = closed_promise+ .promise()+ .downcast::<Promise>()+ .expect("a writer's promises are Promises")+ .state();+ if state == PromiseState::Pending {+ reject_promise(vm, closed_promise, error);+ }+ // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.+ else {+ writer.set_closed_promise(create_rejected_promise(vm, realm, error));+ }++ // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(+ vm,+ writer+ .closed_promise()+ .expect("a writer that is set up has a closed promise"),+ );+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected+pub(crate) fn writable_stream_default_writer_ensure_ready_promise_rejected(+ vm: &Vm,+ writer: Ref<WritableStreamDefaultWriter>,+ error: Value,+) {+ let realm = writer.ready_promise_realm();+ let ready_promise = writer+ .ready_promise()+ .expect("a writer that is set up has a ready promise");++ // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.+ let state = ready_promise+ .promise()+ .downcast::<Promise>()+ .expect("a writer's promises are Promises")+ .state();+ if state == PromiseState::Pending {+ reject_promise(vm, ready_promise, error);+ }+ // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.+ else {+ writer.set_ready_promise(create_rejected_promise(vm, realm, error));+ }++ // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.+ mark_promise_as_handled(+ vm,+ writer+ .ready_promise()+ .expect("a writer that is set up has a ready promise"),+ );+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size+pub(crate) fn writable_stream_default_writer_get_desired_size(writer: Ref<WritableStreamDefaultWriter>) -> Option<f64> {+ // 1. Let stream be writer.[[stream]].+ let stream = writer+ .stream()+ .expect("a writer whose desired size is gotten has a stream");++ // 2. Let state be stream.[[state]].+ let state = stream.state();++ // 3. If state is "errored" or "erroring", return null.+ if state == WritableStreamState::Errored || state == WritableStreamState::Erroring {+ return None;+ }++ // 4. If state is "closed", return 0.+ if state == WritableStreamState::Closed {+ return Some(0.0);+ }++ // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).+ Some(writable_stream_default_controller_get_desired_size(+ stream.controller().expect("a stream that is set up has a controller"),+ ))+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-release+pub(crate) fn writable_stream_default_writer_release(vm: &Vm, writer: Ref<WritableStreamDefaultWriter>) {+ let realm = writer.closed_promise_realm();++ // 1. Let stream be writer.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = writer.stream().expect("a writer that is released has a stream");++ // 3. Assert: stream.[[writer]] is writer.+ assert!(stream.writer() == Some(writer));++ // 4. Let releasedError be a new TypeError.+ let released_error = exception_value(+ vm,+ realm,+ Exception::type_error("Writer's stream lock has been released"),+ );++ // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).+ writable_stream_default_writer_ensure_ready_promise_rejected(vm, writer, released_error);++ // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).+ writable_stream_default_writer_ensure_closed_promise_rejected(vm, writer, released_error);++ // 7. Set stream.[[writer]] to undefined.+ stream.set_writer(None);++ // 8. Set writer.[[stream]] to undefined.+ writer.set_stream(None);+}++// https://streams.spec.whatwg.org/#writable-stream-default-writer-write+pub(crate) fn writable_stream_default_writer_write(+ vm: &Vm,+ writer: Ref<WritableStreamDefaultWriter>,+ chunk: Value,+) -> WebIdlPromise {+ let realm = writer.ready_promise_realm();+ let cx = &CallContext::new(vm, realm);++ // 1. Let stream be writer.[[stream]].+ // 2. Assert: stream is not undefined.+ let stream = writer.stream().expect("a writer that writes has a stream");++ // 3. Let controller be stream.[[controller]].+ let controller = stream.controller().expect("a stream that is set up has a controller");++ // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).+ let chunk_size = writable_stream_default_controller_get_chunk_size(cx, controller, chunk);++ // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.+ if writer.stream() != Some(stream) {+ let exception = Exception::type_error("Writer's locked stream changed during write");+ return create_rejected_promise_from_exception(vm, realm, exception);+ }++ // 6. Let state be stream.[[state]].+ let state = stream.state();++ // 7. If state is "errored", return a promise rejected with stream.[[storedError]].+ if state == WritableStreamState::Errored {+ return create_rejected_promise(vm, realm, stream.stored_error());+ }++ // 8. If ! WritableStreamCloseQueuedOrInFlight(stream) is true or state is "closed", return a promise rejected with+ // a TypeError exception indicating that the stream is closing or closed.+ if writable_stream_close_queued_or_in_flight(stream) || state == WritableStreamState::Closed {+ let exception = Exception::type_error("Cannot write to a writer whose stream is closing or already closed");+ return create_rejected_promise_from_exception(vm, realm, exception);+ }++ // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].+ if state == WritableStreamState::Erroring {+ return create_rejected_promise(vm, realm, stream.stored_error());+ }++ // 10. Assert: state is "writable".+ assert!(state == WritableStreamState::Writable);++ // 11. Let promise be ! WritableStreamAddWriteRequest(stream).+ let promise = writable_stream_add_write_request(cx, stream);++ // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).+ writable_stream_default_controller_write(cx, controller, chunk, chunk_size);++ // 13. Return promise.+ promise+}diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 6a8b7c07218..95678cb3ffd 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -846,26 +846,8 @@ set(SOURCESStorageAPI/StorageKey.cppStorageAPI/StorageManager.cppStorageAPI/StorageShelf.cpp- Streams/AbstractOperations.cpp- Streams/GenericTransformStream.cpp- Streams/ReadableByteStreamController.cppStreams/ReadableStream.cpp- Streams/ReadableStreamAsyncIterator.cpp- Streams/ReadableStreamBYOBReader.cpp- Streams/ReadableStreamBYOBRequest.cpp- Streams/ReadableStreamDefaultController.cpp- Streams/ReadableStreamDefaultReader.cpp- Streams/ReadableStreamGenericReader.cpp- Streams/ReadableStreamOperations.cpp- Streams/ReadableStreamPipeTo.cpp- Streams/ReadableStreamTee.cppStreams/TransformStream.cpp- Streams/TransformStreamDefaultController.cpp- Streams/TransformStreamOperations.cpp- Streams/WritableStream.cpp- Streams/WritableStreamDefaultController.cpp- Streams/WritableStreamDefaultWriter.cpp- Streams/WritableStreamOperations.cppSVG/AttributeNames.cppSVG/AttributeParsing.cppSVG/Path.cppdiff --git a/Libraries/LibWeb/Fetch/BodyInit.cpp b/Libraries/LibWeb/Fetch/BodyInit.cppindex 2115aa4cd07..3a7917740a6 100644--- a/Libraries/LibWeb/Fetch/BodyInit.cpp+++ b/Libraries/LibWeb/Fetch/BodyInit.cpp@@ -54,7 +54,7 @@ WebIDL::ExceptionOr<Infrastructure::BodyWithType> extract_body(JS::Realm& realm,}// 4. Otherwise, set stream to a new ReadableStream object, and set up stream with byte reading support.else {- stream = GC::Heap::the().allocate<Streams::ReadableStream>();+ stream = Streams::ReadableStream::create(realm);stream->set_up_with_byte_reading_support(realm);}diff --git a/Libraries/LibWeb/Fetch/FetchMethod.cpp b/Libraries/LibWeb/Fetch/FetchMethod.cppindex 4f026bc4dc3..e771c14bc43 100644--- a/Libraries/LibWeb/Fetch/FetchMethod.cpp+++ b/Libraries/LibWeb/Fetch/FetchMethod.cpp@@ -23,7 +23,7 @@#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>+#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOr.h>#include <LibWeb/WebIDL/Promise.h>@@ -201,7 +201,6 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi// https://fetch.spec.whatwg.org/#abort-fetchvoid abort_fetch(WebIDL::Promise const& promise, GC::Ref<Infrastructure::Request> request, GC::Ptr<Response> response_object, JS::Value error){- auto& realm = WebIDL::promise_realm(promise);dbgln_if(WEB_FETCH_DEBUG, "Fetch: Aborting fetch with: request @ {}, error = {}", request.ptr(), error);// 1. Reject promise with error.@@ -211,7 +210,7 @@ void abort_fetch(WebIDL::Promise const& promise, GC::Ref<Infrastructure::Request// 2. If request’s body is non-null and is readable, then cancel request’s body with error.if (auto* body = request->body().get_pointer<GC::Ref<Infrastructure::Body>>(); body != nullptr && (*body)->stream()->is_readable()) {// NOTE: Cancel here is different than the cancel method of stream and refers to https://streams.spec.whatwg.org/#readablestream-cancel- Streams::readable_stream_cancel(realm, (*body)->stream(), error);+ (*body)->stream()->cancel(error);}// 3. If responseObject is null, then return.diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cppindex 7144235e2e9..a789e3f5d22 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/FetchedDataReceiver.cpp@@ -14,9 +14,7 @@#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>namespace Web::Fetch::Fetching {@@ -211,16 +209,13 @@ void FetchedDataReceiver::enqueue_into_stream(JS::Realm& realm, ReadonlyBytes byif (!m_stream->is_readable())return;- auto& controller = m_stream->controller()->get<GC::Ref<Streams::ReadableByteStreamController>>();HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Pull from bytes buffer into stream.- auto byte_buffer = MUST(ByteBuffer::copy(bytes));-- if (auto result = Streams::readable_byte_stream_controller_enqueue_native_bytes(realm, *controller, move(byte_buffer)); result.is_error()) {+ if (auto result = m_stream->enqueue_bytes(bytes); result.is_error()) {auto throw_completion = WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error());// 2. If stream is errored, then terminate fetchParams’s controller.- Streams::readable_byte_stream_controller_error(*controller, throw_completion.value());+ m_stream->error(throw_completion.value());if (m_fetch_params)m_fetch_params->controller()->terminate();}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 1d3652c0267..39fdd569a1a 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -69,8 +69,6 @@#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/Streams/ReadableStreamDefaultReader.h>#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/TransformStreamDefaultController.h>-#include <LibWeb/Streams/TransformStreamOperations.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWebCommon/Fetch/Infrastructure/DataURL.h>@@ -985,11 +983,11 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constHTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Let transformStream be a new TransformStream.- auto transform_stream = GC::Heap::the().allocate<Streams::TransformStream>();+ auto transform_stream = Streams::TransformStream::create(realm);// 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.auto identity_transform_algorithm = GC::create_function(GC::Heap::the(), [&realm, transform_stream](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {- if (auto result = Streams::transform_stream_default_controller_enqueue(realm, *transform_stream->controller(), chunk); result.is_error())+ if (auto result = transform_stream->enqueue(chunk); result.is_error())return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());return WebIDL::create_resolved_promise(realm, JS::js_undefined());@@ -2369,7 +2367,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 10. Let stream be a new ReadableStream.- auto stream = GC::Heap::the().allocate<Streams::ReadableStream>();+ auto stream = Streams::ReadableStream::create(realm);// 9. Let buffer be an empty byte sequence.auto fetched_data_receiver = GC::Heap::the().allocate<FetchedDataReceiver>(fetch_params, stream, move(http_cache));diff --git a/Libraries/LibWeb/FileAPI/Blob.cpp b/Libraries/LibWeb/FileAPI/Blob.cppindex 9a7317831f4..c5cfbb40d1b 100644--- a/Libraries/LibWeb/FileAPI/Blob.cpp+++ b/Libraries/LibWeb/FileAPI/Blob.cpp@@ -20,8 +20,8 @@#include <LibWeb/FileAPI/Blob.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/StructuredSerialize.h>+#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWeb/WebIDL/Promise.h>@@ -61,7 +61,7 @@ bool web_blob_is_file(void* blob);// Called by Bindings/Rust/src/file_api/blob.rs.void web_blob_bytes_destroy(BlobBytes*);-JSObject* web_blob_get_stream(void* realm, ReadonlyBytes);+void* web_blob_get_stream(void* realm, ReadonlyBytes);WebIDL::Promise* web_blob_text(void* realm, ReadonlyBytes);WebIDL::Promise* web_blob_array_buffer(void* realm, ReadonlyBytes);WebIDL::Promise* web_blob_bytes(void* realm, ReadonlyBytes);@@ -122,7 +122,7 @@ bool Blob::is_file() conststatic GC::Ref<Streams::ReadableStream> get_stream(JS::Realm& realm, ReadonlyBytes blob_bytes){// 1. Let stream be a new ReadableStream created in blob’s relevant Realm.- auto stream = GC::Heap::the().allocate<Streams::ReadableStream>();+ auto stream = Streams::ReadableStream::create(realm);// 2. Set up stream with byte reading support.stream->set_up_with_byte_reading_support(realm);@@ -150,7 +150,7 @@ static GC::Ref<Streams::ReadableStream> get_stream(JS::Realm& realm, ReadonlyByt});if (maybe_error.is_error()) {- Streams::readable_stream_error(*stream, maybe_error.release_error().value());+ stream->error(maybe_error.release_error().value());return;}@@ -181,13 +181,10 @@ static GC::Ref<WebIDL::Promise> read_all_blob_bytes(JS::Realm& realm, ReadonlyBy}// https://w3c.github.io/FileAPI/#dom-blob-stream-JSObject* web_blob_get_stream(void* realm, ReadonlyBytes blob_bytes)+void* web_blob_get_stream(void* realm, ReadonlyBytes blob_bytes){- auto& js_realm = *static_cast<JS::Realm*>(realm);-// The stream() method, when invoked, must return the result of calling get stream on this.- auto stream = get_stream(js_realm, blob_bytes);- return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, stream).ptr());+ return get_stream(*static_cast<JS::Realm*>(realm), blob_bytes).ptr();}// https://w3c.github.io/FileAPI/#dom-blob-textdiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex bdd927a8f1f..ef63e096346 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -1087,23 +1087,11 @@ class SpeechSynthesisVoice;namespace Web::Streams {-class ReadableByteStreamController;class ReadableStream;-class ReadableStreamAsyncIterator;-class ReadableStreamBYOBReader;-class ReadableStreamBYOBRequest;-class ReadableStreamDefaultController;class ReadableStreamDefaultReader;-class ReadableStreamGenericReaderMixin;-class ReadIntoRequest;class ReadRequest;class TransformStream;-class TransformStreamDefaultController;class WritableStream;-class WritableStreamDefaultController;-class WritableStreamDefaultWriter;--struct PullIntoDescriptor;}diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cppindex 90475d01d93..0a62b781dfd 100644--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp@@ -263,7 +263,7 @@ static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::R// populate_session_history_entry_document() decides whether to load it as a document or transfer it again.request->set_body_delivery_paused(true);- auto stream = realm.heap().allocate<Streams::ReadableStream>();+ auto stream = Streams::ReadableStream::create(realm);auto pull_algorithm = GC::create_function(realm.heap(), [&realm]() {return WebIDL::create_resolved_promise(realm, JS::js_undefined());});diff --git a/Libraries/LibWeb/Page/RenderingStats.cpp b/Libraries/LibWeb/Page/RenderingStats.cppindex 891b1d9974f..30bea2241d2 100644--- a/Libraries/LibWeb/Page/RenderingStats.cpp+++ b/Libraries/LibWeb/Page/RenderingStats.cpp@@ -17,9 +17,7 @@#include <LibWeb/HTML/NavigableContainer.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Page/RenderingStats.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>namespace Web {@@ -192,7 +190,7 @@ void Detail::track_rendering_pending_stream(GC::Cell const* token, Streams::Readreturn;// Closing a source with unread queued bytes need not close its identity transform. Observe the source's// close request, before fetch installs that transform, so an unread response cannot keep the page pending.- if (!stream.is_readable() || (stream.controller().has_value() && stream.controller()->visit([](auto controller) { return controller->close_requested(); }))) {+ if (!stream.is_readable() || stream.close_requested()) {end_rendering_pending_operation(token);return;}diff --git a/Libraries/LibWeb/Serial/SerialPort.h b/Libraries/LibWeb/Serial/SerialPort.hindex f81cd9ee8c2..cac74820ab9 100644--- a/Libraries/LibWeb/Serial/SerialPort.h+++ b/Libraries/LibWeb/Serial/SerialPort.h@@ -53,10 +53,8 @@ public:bool connected() const { return m_connected; }// https://wicg.github.io/serial/#readable-attributeGC::Ptr<Streams::ReadableStream> readable() { return m_readable; }- static constexpr size_t readable_offset() { return offsetof(SerialPort, m_readable); }// https://wicg.github.io/serial/#writable-attributeGC::Ptr<Streams::WritableStream> writable() { return m_writable; }- static constexpr size_t writable_offset() { return offsetof(SerialPort, m_writable); }// https://wicg.github.io/serial/#onconnect-attribute-0void set_onconnect(WebIDL::CallbackType*);diff --git a/Libraries/LibWeb/Serial/SerialPort.idl b/Libraries/LibWeb/Serial/SerialPort.idlindex bf8708dc753..f6331fb8447 100644--- a/Libraries/LibWeb/Serial/SerialPort.idl+++ b/Libraries/LibWeb/Serial/SerialPort.idl@@ -4,8 +4,8 @@ interface SerialPort : EventTarget {attribute EventHandler onconnect;attribute EventHandler ondisconnect;readonly attribute boolean connected;- [DirectGetter] readonly attribute ReadableStream? readable;- [DirectGetter] readonly attribute WritableStream? writable;+ readonly attribute ReadableStream? readable;+ readonly attribute WritableStream? writable;SerialPortInfo getInfo();diff --git a/Libraries/LibWeb/Streams/AbstractOperations.cpp b/Libraries/LibWeb/Streams/AbstractOperations.cppdeleted file mode 100644index aaa107484ea..00000000000--- a/Libraries/LibWeb/Streams/AbstractOperations.cpp+++ /dev/null@@ -1,559 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/NativeFunction.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/DOM/IDLEventListener.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/MessageEvent.h>-#include <LibWeb/HTML/MessagePort.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/BindingsGlue.h>-#include <LibWeb/Streams/QueuingStrategy.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultController.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#validate-and-normalize-high-water-mark-WebIDL::ExceptionOr<double> extract_high_water_mark(QueuingStrategy const& strategy, double default_hwm)-{- // 1. If strategy["highWaterMark"] does not exist, return defaultHWM.- if (!strategy.high_water_mark.has_value())- return default_hwm;-- // 2. Let highWaterMark be strategy["highWaterMark"].- auto high_water_mark = strategy.high_water_mark.value();-- // 3. If highWaterMark is NaN or highWaterMark < 0, throw a RangeError exception.- if (isnan(high_water_mark) || high_water_mark < 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid value for high water mark"_utf16 };-- // 4. Return highWaterMark.- return high_water_mark;-}--// https://streams.spec.whatwg.org/#make-size-algorithm-from-size-function-GC::Ref<SizeAlgorithm> extract_size_algorithm(JS::VM&, QueuingStrategy const& strategy)-{- // 1. If strategy["size"] does not exist, return an algorithm that returns 1.- if (!strategy.size)- return GC::create_function(GC::Heap::the(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });-- // 2. Return an algorithm that performs the following steps, taking a chunk argument:- return GC::create_function(GC::Heap::the(), [size = strategy.size](JS::Value chunk) {- // 1. Return the result of invoking strategy["size"] with argument list « chunk ».- return Bindings::invoke_queuing_strategy_size_callback(*size, chunk);- });-}--}--namespace Web::Bindings {--JS::Completion invoke_queuing_strategy_size_callback(WebIDL::CallbackType& callback, JS::Value chunk)-{- return WebIDL::invoke_callback(callback, {}, { { chunk } });-}--}--namespace Web::Streams {--struct PromiseHolder : public JS::Cell {- GC_CELL(PromiseHolder, JS::Cell);- GC_DECLARE_ALLOCATOR(PromiseHolder);-- explicit PromiseHolder(GC::Ptr<WebIDL::Promise> promise)- : promise(promise)- {- }-- virtual void visit_edges(JS::Cell::Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(promise);- }-- GC::Ptr<WebIDL::Promise> promise;-};--GC_DEFINE_ALLOCATOR(PromiseHolder);--static void add_message_event_listener(JS::Realm& realm, HTML::MessagePort& port, Utf16FlyString const& name, Function<void(JS::VM&, HTML::MessageEvent const&)> handler)-{- auto behavior = [handler = GC::create_function(GC::Heap::the(), move(handler))](JS::VM& vm) {- auto* message_event = Bindings::impl_from<HTML::MessageEvent>(&vm.argument(0).as_object());- VERIFY(message_event);- handler->function()(vm, *message_event);-- return JS::js_undefined();- };-- auto function = JS::NativeFunction::create(realm, move(behavior), 1, Utf16FlyString {}, &realm);- auto callback = GC::Heap::the().allocate<WebIDL::CallbackType>(function, realm);- auto listener = DOM::IDLEventListener::create(callback);-- port.add_event_listener_without_options(name, listener);-}--// https://streams.spec.whatwg.org/#abstract-opdef-crossrealmtransformsenderror-void cross_realm_transform_send_error(JS::Realm& realm, HTML::MessagePort& port, JS::Value error)-{- // 1. Perform PackAndPostMessage(port, "error", error), discarding the result.- (void)pack_and_post_message(realm, port, "error"sv, error);-}--// https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessagehandlingerror-WebIDL::ExceptionOr<void> pack_and_post_message(JS::Realm& realm, HTML::MessagePort& port, StringView type, JS::Value value)-{- auto& vm = realm.vm();-- // 1. Let message be OrdinaryObjectCreate(null).- auto message = JS::Object::create(realm, nullptr);-- // 2. Perform ! CreateDataProperty(message, "type", type).- MUST(message->create_data_property(vm.names.type, JS::PrimitiveString::create(vm, Utf16String::from_ascii_without_validation(type.bytes()))));-- // 3. Perform ! CreateDataProperty(message, "value", value).- MUST(message->create_data_property(vm.names.value, value));-- // 4. Let targetPort be the port with which port is entangled, if any; otherwise let it be null.- auto target_port = port.entangled_port();-- // 5. Let options be «[ "transfer" → « » ]».- HTML::StructuredSerializeOptions options;-- // 6. Run the message port post message steps providing targetPort, message, and options.- return port.message_port_post_message_steps(realm, target_port, message, options);-}--// https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessagehandlingerror-WebIDL::ExceptionOr<void> pack_and_post_message_handling_error(JS::Realm& realm, HTML::MessagePort& port, StringView type, JS::Value value)-{- // 1. Let result be PackAndPostMessage(port, type, value).- auto result = pack_and_post_message(realm, port, type, value);-- // 2. If result is an abrupt completion,- if (result.is_exception()) {- auto error = WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error());-- // 1. Perform ! CrossRealmTransformSendError(port, result.[[Value]]).- cross_realm_transform_send_error(realm, port, error.value());- }-- // 3. Return result as a completion record.- return result;-}--// https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable-void set_up_cross_realm_transform_readable(JS::Realm& realm, ReadableStream& stream, HTML::MessagePort& port)-{- stream.set_realm(realm);-- // 1. Perform ! InitializeReadableStream(stream).- initialize_readable_stream(stream);-- // 2. Let controller be a new ReadableStreamDefaultController.- auto controller = GC::Heap::the().allocate<ReadableStreamDefaultController>();-- // 3. Add a handler for port’s message event with the following steps:- add_message_event_listener(realm, port, HTML::EventNames::message,- [&realm, &port, controller](JS::VM& vm, HTML::MessageEvent const& message) {- // 1. Let data be the data of the message.- auto data = message.data();-- // 2. Assert: data is an Object.- VERIFY(data.is_object());-- // 3. Let type be ! Get(data, "type").- auto type = MUST(data.get(vm, vm.names.type));-- // 4. Let value be ! Get(data, "value").- auto value = MUST(data.get(vm, vm.names.value));-- // 5. Assert: type is a String.- auto type_string = type.as_string().utf16_string_view();-- // 6. If type is "chunk",- if (type_string == "chunk"sv) {- // 1. Perform ! ReadableStreamDefaultControllerEnqueue(controller, value).- MUST(readable_stream_default_controller_enqueue(realm, controller, value));- }- // 7. Otherwise, if type is "close",- else if (type_string == "close"sv) {- // 1. Perform ! ReadableStreamDefaultControllerClose(controller).- readable_stream_default_controller_close(controller);-- // 2. Disentangle port.- port.disentangle();- }- // 8. Otherwise, if type is "error",- else if (type_string == "error"sv) {- // 1. Perform ! ReadableStreamDefaultControllerError(controller, value).- readable_stream_default_controller_error(controller, value);-- // 2. Disentangle port.- port.disentangle();- }- });-- // 4. Add a handler for port’s messageerror event with the following steps:- add_message_event_listener(realm, port, HTML::EventNames::messageerror,- [&realm, &port, controller](JS::VM&, HTML::MessageEvent const&) {- // 1. Let error be a new "DataCloneError" DOMException.- auto error = WebIDL::DataCloneError::create("Unable to transfer stream"_utf16);- auto error_value = throw_completion(realm, error).value();-- // 2. Perform ! CrossRealmTransformSendError(port, error).- cross_realm_transform_send_error(realm, port, error_value);-- // 3. Perform ! ReadableStreamDefaultControllerError(controller, error).- readable_stream_default_controller_error(controller, error_value);-- // 4. Disentangle port.- port.disentangle();- });-- // 5. Enable port’s port message queue.- port.enable();-- // 6. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 7. Let pullAlgorithm be the following steps:- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&realm, &port]() -> GC::Ref<WebIDL::Promise> {- // 1. Perform ! PackAndPostMessage(port, "pull", undefined).- MUST(pack_and_post_message(realm, port, "pull"sv, JS::js_undefined()));-- // 2. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 8. Let cancelAlgorithm be the following steps, taking a reason argument:- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [&realm, &port](JS::Value reason) -> GC::Ref<WebIDL::Promise> {- // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).- auto result = pack_and_post_message_handling_error(realm, port, "error"sv, reason);-- // 2. Disentangle port.- port.disentangle();-- // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].- if (result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());-- // 4. Otherwise, return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 9. Let sizeAlgorithm be an algorithm that returns 1.- auto size_algorithm = GC::create_function(GC::Heap::the(), [](JS::Value) -> JS::Completion {- return JS::Value { 1 };- });-- // 10. Perform ! SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, sizeAlgorithm).- MUST(set_up_readable_stream_default_controller(realm, stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, 0, size_algorithm));-}--// https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable-void set_up_cross_realm_transform_writable(JS::Realm& realm, WritableStream& stream, HTML::MessagePort& port)-{- // 1. Perform ! InitializeWritableStream(stream).- initialize_writable_stream(stream);-- // 2. Let controller be a new WritableStreamDefaultController.- auto controller = GC::Heap::the().allocate<WritableStreamDefaultController>();-- // 3. Let backpressurePromise be a new promise.- auto backpressure_promise = GC::Heap::the().allocate<PromiseHolder>(WebIDL::create_promise(realm));-- // 4. Add a handler for port’s message event with the following steps:- add_message_event_listener(realm, port, HTML::EventNames::message,- [controller, backpressure_promise](JS::VM& vm, HTML::MessageEvent const& message) {- // 1. Let data be the data of the message.- auto data = message.data();-- // 2. Assert: data is an Object.- VERIFY(data.is_object());-- // 3. Let type be ! Get(data, "type").- auto type = MUST(data.get(vm, vm.names.type));-- // 4. Let value be ! Get(data, "value").- auto value = MUST(data.get(vm, vm.names.value));-- // 5. Assert: type is a String.- auto type_string = type.as_string().utf16_string_view();-- // 6. If type is "pull",- if (type_string == "pull"sv) {- // 1. If backpressurePromise is not undefined,- if (backpressure_promise->promise) {- // 1. Resolve backpressurePromise with undefined.- WebIDL::resolve_promise(*backpressure_promise->promise);-- // 2. Set backpressurePromise to undefined.- backpressure_promise->promise = nullptr;- }- }- // 7. Otherwise, if type is "error",- else if (type_string == "error"sv) {- // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, value).- writable_stream_default_controller_error_if_needed(controller, value);-- // 2. If backpressurePromise is not undefined,- if (backpressure_promise->promise) {- // 1. Resolve backpressurePromise with undefined.- WebIDL::resolve_promise(*backpressure_promise->promise);-- // 2. Set backpressurePromise to undefined.- backpressure_promise->promise = nullptr;- }- }- });-- // 5. Add a handler for port’s messageerror event with the following steps:- add_message_event_listener(realm, port, HTML::EventNames::messageerror,- [&realm, &port, controller](JS::VM&, HTML::MessageEvent const&) {- // 1. Let error be a new "DataCloneError" DOMException- auto error = WebIDL::DataCloneError::create("Unable to transfer stream"_utf16);- auto error_value = throw_completion(realm, error).value();-- // 2. Perform ! CrossRealmTransformSendError(port, error).- cross_realm_transform_send_error(realm, port, error_value);-- // 3. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, error).- writable_stream_default_controller_error_if_needed(controller, error_value);-- // 4. Disentangle port.- port.disentangle();- });-- // 6. Enable port’s port message queue.- port.enable();-- // 7. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 8. Let writeAlgorithm be the following steps, taking a chunk argument:- auto write_algorithm = GC::create_function(GC::Heap::the(), [&realm, &port, backpressure_promise](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {- // 1. If backpressurePromise is undefined, set backpressurePromise to a promise resolved with undefined.- if (!backpressure_promise->promise)- backpressure_promise->promise = WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // FIXME: The steps below ("Return a promise rejected/resolved with ...") seem to indicate we should be creating- // a promise on-the-fly. But in order for the error from PackAndPostMessageHandlingError to be propagated- // back to the original ReadableStream, we must actually fulfill the promise created from reacting to the- // backpressure promise. This is explicitly tested by WPT.- auto reaction_promise = GC::Heap::the().allocate<PromiseHolder>(nullptr);-- // 2. Return the result of reacting to backpressurePromise with the following fulfillment steps:- reaction_promise->promise = WebIDL::upon_fulfillment(*backpressure_promise->promise,- GC::create_function(GC::Heap::the(), [&realm, &port, backpressure_promise, reaction_promise, chunk](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Set backpressurePromise to a new promise.- backpressure_promise->promise = WebIDL::create_promise(realm);-- // 2. Let result be PackAndPostMessageHandlingError(port, "chunk", chunk).- auto result = pack_and_post_message_handling_error(realm, port, "chunk"sv, chunk);-- // 3. If result is an abrupt completion,- if (result.is_error()) {- // 1. Disentangle port.- port.disentangle();-- // 2. Return a promise rejected with result.[[Value]].- auto error = WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error());- WebIDL::reject_promise(*reaction_promise->promise, error.value());- }- // 4. Otherwise, return a promise resolved with undefined.- else {- WebIDL::resolve_promise(*reaction_promise->promise);- }-- return JS::js_undefined();- }));-- return *reaction_promise->promise;- });-- // 9. Let closeAlgorithm be the following steps:- auto close_algorithm = GC::create_function(GC::Heap::the(), [&realm, &port]() -> GC::Ref<WebIDL::Promise> {- // 1. Perform ! PackAndPostMessage(port, "close", undefined).- MUST(pack_and_post_message(realm, port, "close"sv, JS::js_undefined()));-- // 2. Disentangle port.- port.disentangle();-- // 3. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 10. Let abortAlgorithm be the following steps, taking a reason argument:- auto abort_algorithm = GC::create_function(GC::Heap::the(), [&realm, &port](JS::Value reason) -> GC::Ref<WebIDL::Promise> {- // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).- auto result = pack_and_post_message_handling_error(realm, port, "error"sv, reason);-- // 2. Disentangle port.- port.disentangle();-- // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].- if (result.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());-- // 4. Otherwise, return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 11. Let sizeAlgorithm be an algorithm that returns 1.- auto size_algorithm = GC::create_function(GC::Heap::the(), [](JS::Value) -> JS::Completion {- return JS::Value { 1 };- });-- // 12. Perform ! SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, 1, sizeAlgorithm).- MUST(set_up_writable_stream_default_controller(realm, stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, 1, size_algorithm));-}--// https://streams.spec.whatwg.org/#can-transfer-array-buffer-bool can_transfer_array_buffer(JS::ArrayBuffer const& array_buffer)-{- // 1. Assert: O is an Object.- // 2. Assert: O has an [[ArrayBufferData]] internal slot.-- // 3. If ! IsDetachedBuffer(O) is true, return false.- if (array_buffer.is_detached())- return false;-- // 4. If SameValue(O.[[ArrayBufferDetachKey]], undefined) is false, return false.- if (!JS::same_value(array_buffer.detach_key(), JS::js_undefined()))- return false;-- // 5. Return true.- return true;-}--// https://streams.spec.whatwg.org/#is-non-negative-number-bool is_non_negative_number(JS::Value value)-{- // 1. If v is not a Number, return false.- if (!value.is_number())- return false;-- // 2. If v is NaN, return false.- if (value.is_nan())- return false;-- // 3. If v < 0, return false.- if (value.as_double() < 0.0)- return false;-- // 4. Return true.- return true;-}--// https://streams.spec.whatwg.org/#transfer-array-buffer-WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer)-{- auto& vm = realm.vm();-- // 1. Assert: ! IsDetachedBuffer(O) is false.- VERIFY(!buffer.is_detached());-- // 2. Let arrayBufferData be O.[[ArrayBufferData]].- // 3. Let arrayBufferByteLength be O.[[ArrayBufferByteLength]].- // 4. Perform ? DetachArrayBuffer(O).- // NB: We steal the underlying data block and detach atomically so the transfer is zero-copy.- auto block = TRY(buffer.detach_and_take_data_block(vm));-- // 5. Return a new ArrayBuffer object, created in the current Realm, whose [[ArrayBufferData]] internal slot value is arrayBufferData and whose [[ArrayBufferByteLength]] internal slot value is arrayBufferByteLength.- return JS::ArrayBuffer::create(realm, move(block));-}--// https://streams.spec.whatwg.org/#abstract-opdef-cloneasuint8array-WebIDL::ExceptionOr<JS::Value> clone_as_uint8_array(JS::Realm& realm, WebIDL::ArrayBufferView view)-{- auto& vm = realm.vm();-- // 1. Assert: O is an Object.- // 2. Assert: O has an [[ViewedArrayBuffer]] internal slot.-- // 3. Assert: ! IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false.- VERIFY(!view.viewed_array_buffer()->is_detached());-- // 4. Let buffer be ? CloneArrayBuffer(O.[[ViewedArrayBuffer]], O.[[ByteOffset]], O.[[ByteLength]], %ArrayBuffer%).- auto* buffer = TRY(JS::clone_array_buffer(vm, *view.viewed_array_buffer(), view.byte_offset(), view.byte_length()));-- // 5. Let array be ! Construct(%Uint8Array%, « buffer »).- auto array = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), buffer));-- // 5. Return array.- return array;-}--// https://streams.spec.whatwg.org/#abstract-opdef-structuredclone-WebIDL::ExceptionOr<JS::Value> structured_clone(JS::Realm& realm, JS::Value value)-{- auto& vm = realm.vm();-- // 1. Let serialized be ? StructuredSerialize(v).- auto serialized = TRY(HTML::structured_serialize(vm, value));-- // 2. Return ? StructuredDeserialize(serialized, the current Realm).- return TRY(HTML::structured_deserialize(vm, serialized, realm));-}--// https://streams.spec.whatwg.org/#abstract-opdef-cancopydatablockbytes-bool can_copy_data_block_bytes_buffer(JS::ArrayBuffer const& to_buffer, u64 to_index, JS::ArrayBuffer const& from_buffer, u64 from_index, u64 count)-{- // 1. Assert: toBuffer is an Object.- // 2. Assert: toBuffer has an [[ArrayBufferData]] internal slot.- // 3. Assert: fromBuffer is an Object.- // 4. Assert: fromBuffer has an [[ArrayBufferData]] internal slot.-- // 5. If toBuffer is fromBuffer, return false.- if (&to_buffer == &from_buffer)- return false;-- // 6. If ! IsDetachedBuffer(toBuffer) is true, return false.- if (to_buffer.is_detached())- return false;-- // 7. If ! IsDetachedBuffer(fromBuffer) is true, return false.- if (from_buffer.is_detached())- return false;-- // 8. If toIndex + count > toBuffer.[[ArrayBufferByteLength]], return false.- if (to_index + count > to_buffer.byte_length())- return false;-- // 9. If fromIndex + count > fromBuffer.[[ArrayBufferByteLength]], return false.- if (from_index + count > from_buffer.byte_length())- return false;-- // 10. Return true.- return true;-}--}diff --git a/Libraries/LibWeb/Streams/AbstractOperations.h b/Libraries/LibWeb/Streams/AbstractOperations.hdeleted file mode 100644index bc4d5478415..00000000000--- a/Libraries/LibWeb/Streams/AbstractOperations.h+++ /dev/null@@ -1,126 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Ptr.h>-#include <LibWeb/Export.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/Streams/QueuingStrategy.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--// 7.4. Abstract operations, https://streams.spec.whatwg.org/#qs-abstract-ops-WEB_API WebIDL::ExceptionOr<double> extract_high_water_mark(QueuingStrategy const&, double default_hwm);-WEB_API GC::Ref<SizeAlgorithm> extract_size_algorithm(JS::VM&, QueuingStrategy const&);--// 8.2. Transferable streams, https://streams.spec.whatwg.org/#transferrable-streams-void cross_realm_transform_send_error(JS::Realm&, HTML::MessagePort&, JS::Value error);-WebIDL::ExceptionOr<void> pack_and_post_message(JS::Realm&, HTML::MessagePort&, StringView type, JS::Value value);-WebIDL::ExceptionOr<void> pack_and_post_message_handling_error(JS::Realm&, HTML::MessagePort&, StringView type, JS::Value value);-WEB_API void set_up_cross_realm_transform_readable(JS::Realm&, ReadableStream&, HTML::MessagePort&);-WEB_API void set_up_cross_realm_transform_writable(JS::Realm&, WritableStream&, HTML::MessagePort&);--// 8.3. Miscellaneous, https://streams.spec.whatwg.org/#misc-abstract-ops-WEB_API bool can_transfer_array_buffer(JS::ArrayBuffer const& array_buffer);-WEB_API bool is_non_negative_number(JS::Value);-WEB_API WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> transfer_array_buffer(JS::Realm& realm, JS::ArrayBuffer& buffer);-WEB_API WebIDL::ExceptionOr<JS::Value> clone_as_uint8_array(JS::Realm&, WebIDL::ArrayBufferView);-WEB_API WebIDL::ExceptionOr<JS::Value> structured_clone(JS::Realm&, JS::Value value);-WEB_API bool can_copy_data_block_bytes_buffer(JS::ArrayBuffer const& to_buffer, u64 to_index, JS::ArrayBuffer const& from_buffer, u64 from_index, u64 count);--// 8.1. Queue-with-sizes, https://streams.spec.whatwg.org/#queue-with-sizes--// https://streams.spec.whatwg.org/#value-with-size-struct ValueWithSize {- JS::Value value;- double size { 0 };-};--// https://streams.spec.whatwg.org/#dequeue-value-template<typename T>-JS::Value dequeue_value(T& container)-{- // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.-- // 2. Assert: container.[[queue]] is not empty.- VERIFY(!container.queue().is_empty());-- // 3. Let valueWithSize be container.[[queue]][0].- // 4. Remove valueWithSize from container.[[queue]].- auto value_with_size = container.queue().take_first();-- // 5. Set container.[[queueTotalSize]] to container.[[queueTotalSize]] − valueWithSize’s size.- container.set_queue_total_size(container.queue_total_size() - value_with_size.size);-- // 6. If container.[[queueTotalSize]] < 0, set container.[[queueTotalSize]] to 0. (This can occur due to rounding errors.)- if (container.queue_total_size() < 0.0)- container.set_queue_total_size(0.0);-- // 7. Return valueWithSize’s value.- return value_with_size.value;-}--// https://streams.spec.whatwg.org/#enqueue-value-with-size-template<typename T>-WebIDL::ExceptionOr<void> enqueue_value_with_size(T& container, JS::Value value, JS::Value size)-{- // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.-- // 2. If ! IsNonNegativeNumber(size) is false, throw a RangeError exception.- if (!is_non_negative_number(size))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Chunk has non-positive size"_utf16 };-- // 3. If size is +∞, throw a RangeError exception.- if (size.is_positive_infinity())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Chunk has infinite size"_utf16 };-- // 4. Append a new value-with-size with value value and size size to container.[[queue]].- container.queue().append({ value, size.as_double() });-- // 5. Set container.[[queueTotalSize]] to container.[[queueTotalSize]] + size.- container.set_queue_total_size(container.queue_total_size() + size.as_double());-- return {};-}--// https://streams.spec.whatwg.org/#peek-queue-value-template<typename T>-JS::Value peek_queue_value(T& container)-{- // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.-- // 2. Assert: container.[[queue]] is not empty.- VERIFY(!container.queue().is_empty());-- // 3. Let valueWithSize be container.[[queue]][0].- auto& value_with_size = container.queue().first();-- // 4. Return valueWithSize’s value.- return value_with_size.value;-}--// https://streams.spec.whatwg.org/#reset-queue-template<typename T>-void reset_queue(T& container)-{- // 1. Assert: container has [[queue]] and [[queueTotalSize]] internal slots.-- // 2. Set container.[[queue]] to a new empty list.- container.queue().clear();-- // 3. Set container.[[queueTotalSize]] to 0.- container.set_queue_total_size(0);-}--}diff --git a/Libraries/LibWeb/Streams/Algorithms.h b/Libraries/LibWeb/Streams/Algorithms.hindex 3f0c481456c..4781b8544c1 100644--- a/Libraries/LibWeb/Streams/Algorithms.h+++ b/Libraries/LibWeb/Streams/Algorithms.h@@ -6,36 +6,16 @@#pragma once-#include <AK/Optional.h>#include <LibGC/Function.h>-#include <LibGC/Ptr.h>-#include <LibWeb/Bindings/Transformer.h>-#include <LibWeb/Bindings/UnderlyingSink.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/ExceptionOr.h>+#include <LibJS/Runtime/Value.h>#include <LibWeb/WebIDL/Promise.h>namespace Web::Streams {-using SizeAlgorithm = GC::Function<JS::Completion(JS::Value)>;+// The algorithms that the specifications that LibWeb implements in C++ set streams up with.using PullAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>()>;using CancelAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;-using StartAlgorithm = GC::Function<WebIDL::ExceptionOr<JS::Value>()>;-using AbortAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;-using CloseAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>()>;-using WriteAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;using FlushAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>()>;using TransformAlgorithm = GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>;-struct UnderlyingSource {- Optional<u64> auto_allocate_chunk_size {};- GC::Ptr<WebIDL::CallbackType> cancel {};- GC::Ptr<WebIDL::CallbackType> pull {};- GC::Ptr<WebIDL::CallbackType> start {};- bool is_bytes { false };-};--using UnderlyingSink = Bindings::UnderlyingSink;-using Transformer = Bindings::Transformer;-}diff --git a/Libraries/LibWeb/Streams/BindingsGlue.h b/Libraries/LibWeb/Streams/BindingsGlue.hdeleted file mode 100644index 5d495a7882d..00000000000--- a/Libraries/LibWeb/Streams/BindingsGlue.h+++ /dev/null@@ -1,50 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Forward.h>-#include <LibJS/Forward.h>-#include <LibJS/Runtime/Completion.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Export.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--class ReadableByteStreamController;-class ReadableStream;-class ReadableStreamDefaultController;-class TransformStream;-class TransformStreamDefaultController;-class WritableStream;-class WritableStreamDefaultController;--}--namespace Web::Bindings {--WEB_API WebIDL::ExceptionOr<JS::Value> invoke_readable_byte_stream_start_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::ReadableByteStreamController>);-WEB_API GC::Ref<WebIDL::Promise> invoke_readable_byte_stream_pull_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::ReadableByteStreamController>);-WEB_API Streams::ReadableStream* readable_stream_from_object(JS::Object&);-WEB_API void serialize_readable_stream_with_transfer(JS::Realm&, HTML::TransferDataEncoder&, GC::Ref<Streams::ReadableStream>);-WEB_API JS::Completion invoke_queuing_strategy_size_callback(WebIDL::CallbackType&, JS::Value);-WEB_API WebIDL::ExceptionOr<JS::Value> invoke_readable_stream_start_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::ReadableStreamDefaultController>);-WEB_API GC::Ref<WebIDL::Promise> invoke_readable_stream_pull_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::ReadableStreamDefaultController>);-WEB_API void prepare_transform_stream_readable_writable_wrappers(JS::Realm&, Streams::TransformStream&);-WEB_API WebIDL::ExceptionOr<JS::Value> invoke_transform_stream_start_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::TransformStreamDefaultController>);-WEB_API GC::Ref<WebIDL::Promise> invoke_transform_stream_transform_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, JS::Value, GC::Ref<Streams::TransformStreamDefaultController>);-WEB_API GC::Ref<WebIDL::Promise> invoke_transform_stream_flush_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::TransformStreamDefaultController>);-WEB_API Streams::WritableStream* writable_stream_from_object(JS::Object&);-WEB_API void serialize_writable_stream_with_transfer(JS::Realm&, HTML::TransferDataEncoder&, GC::Ref<Streams::WritableStream>);-WEB_API WebIDL::ExceptionOr<JS::Value> invoke_writable_stream_start_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, GC::Ref<Streams::WritableStreamDefaultController>);-WEB_API GC::Ref<WebIDL::Promise> invoke_writable_stream_write_algorithm_callback(JS::Realm&, WebIDL::CallbackType&, JS::Value, JS::Value, GC::Ref<Streams::WritableStreamDefaultController>);--}diff --git a/Libraries/LibWeb/Streams/GenericTransformStream.cpp b/Libraries/LibWeb/Streams/GenericTransformStream.cppdeleted file mode 100644index b686b7cbcef..00000000000--- a/Libraries/LibWeb/Streams/GenericTransformStream.cpp+++ /dev/null@@ -1,71 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * 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/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);-}--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/Libraries/LibWeb/Streams/QueuingStrategy.h b/Libraries/LibWeb/Streams/QueuingStrategy.hdeleted file mode 100644index 761eb61fdb5..00000000000--- a/Libraries/LibWeb/Streams/QueuingStrategy.h+++ /dev/null@@ -1,15 +0,0 @@-/*- * Copyright (c) 2023, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Bindings/QueuingStrategy.h>--namespace Web::Streams {--using QueuingStrategy = Bindings::QueuingStrategy;--}diff --git a/Libraries/LibWeb/Streams/ReadableByteStreamController.cpp b/Libraries/LibWeb/Streams/ReadableByteStreamController.cppdeleted file mode 100644index 0f1b2b6c987..00000000000--- a/Libraries/LibWeb/Streams/ReadableByteStreamController.cpp+++ /dev/null@@ -1,203 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/DataView.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamBYOBRequest.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/WebIDL/Buffers.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(PullIntoDescriptor);-GC_DEFINE_ALLOCATOR(ReadableByteStreamController);--void PullIntoDescriptor::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(buffer);- visitor.visit(view_constructor);-}--// https://streams.spec.whatwg.org/#rbs-controller-desired-size-Optional<double> ReadableByteStreamController::desired_size() const-{- // 1. Return ! ReadableByteStreamControllerGetDesiredSize(this).- return readable_byte_stream_controller_get_desired_size(*this);-}--// https://streams.spec.whatwg.org/#rbs-controller-byob-request-GC::Ptr<ReadableStreamBYOBRequest> ReadableByteStreamController::byob_request(JS::Realm& realm)-{- // 1. Return ! ReadableByteStreamControllerGetBYOBRequest(this).- return readable_byte_stream_controller_get_byob_request(realm, *this);-}--// https://streams.spec.whatwg.org/#rbs-controller-close-WebIDL::ExceptionOr<void> ReadableByteStreamController::close(JS::Realm& realm)-{- // 1. If this.[[closeRequested]] is true, throw a TypeError exception.- if (m_close_requested)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Controller is already closed"_utf16 };-- // 2. If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.- if (m_stream->state() != ReadableStream::State::Readable) {- auto message = m_stream->state() == ReadableStream::State::Closed ? "Cannot close a closed stream"_utf16 : "Cannot close an errored stream"_utf16;- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, message };- }-- // 3. Perform ? ReadableByteStreamControllerClose(this).- TRY(readable_byte_stream_controller_close(realm, *this));-- return {};-}--// https://streams.spec.whatwg.org/#rbs-controller-error-void ReadableByteStreamController::error(Optional<JS::Value> error)-{- // 1. Perform ! ReadableByteStreamControllerError(this, e).- readable_byte_stream_controller_error(*this, error.value_or(JS::js_undefined()));-}--// https://streams.spec.whatwg.org/#rbs-controller-enqueue-WebIDL::ExceptionOr<void> ReadableByteStreamController::enqueue(JS::Realm& realm, WebIDL::ArrayBufferViewVariant const& chunk)-{- WebIDL::ArrayBufferView chunk_view { chunk };-- // 1. If chunk.[[ByteLength]] is 0, throw a TypeError exception.- // 2. If chunk.[[ViewedArrayBuffer]].[[ByteLength]] is 0, throw a TypeError exception.- if (chunk_view.byte_length() == 0 || chunk_view.viewed_array_buffer()->byte_length() == 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot enqueue chunk with byte length of zero"_utf16 };-- // 3. If this.[[closeRequested]] is true, throw a TypeError exception.- if (m_close_requested)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Close is requested for controller"_utf16 };-- // 4. If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.- if (!m_stream->is_readable())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is not readable"_utf16 };-- // 5. Return ? ReadableByteStreamControllerEnqueue(this, chunk).- auto chunk_object = chunk.visit([](auto const& view) -> GC::Ref<JS::Object> { return view; });- return readable_byte_stream_controller_enqueue(realm, *this, chunk_object);-}--// https://streams.spec.whatwg.org/#rbs-controller-private-cancel-GC::Ref<WebIDL::Promise> ReadableByteStreamController::cancel_steps(JS::Value reason)-{- // 1. Perform ! ReadableByteStreamControllerClearPendingPullIntos(this).- readable_byte_stream_controller_clear_pending_pull_intos(*this);-- // 2. Perform ! ResetQueue(this).- reset_queue(*this);-- // 3. Let result be the result of performing this.[[cancelAlgorithm]], passing in reason.- auto result = m_cancel_algorithm->function()(reason);-- // 4. Perform ! ReadableByteStreamControllerClearAlgorithms(this).- readable_byte_stream_controller_clear_algorithms(*this);-- // 5. Return result.- return result;-}--// https://streams.spec.whatwg.org/#rbs-controller-private-pull-void ReadableByteStreamController::pull_steps(JS::Realm& realm, GC::Ref<ReadRequest> read_request)-{- // 1. Let stream be this.[[stream]].-- // 2. Assert: ! ReadableStreamHasDefaultReader(stream) is true.- VERIFY(readable_stream_has_default_reader(*m_stream));-- // 3. If this.[[queueTotalSize]] > 0,- if (m_queue_total_size > 0) {- // 1. Assert: ! ReadableStreamGetNumReadRequests(stream) is 0.- VERIFY(readable_stream_get_num_read_requests(*m_stream) == 0);-- // 2. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest).- readable_byte_stream_controller_fill_read_request_from_queue(realm, *this, read_request);-- // 3. Return.- return;- }-- // 4. Let autoAllocateChunkSize be this.[[autoAllocateChunkSize]].-- // 5. If autoAllocateChunkSize is not undefined,- if (m_auto_allocate_chunk_size.has_value()) {- // 1. Let buffer be Construct(%ArrayBuffer%, « autoAllocateChunkSize »).- auto buffer = JS::ArrayBuffer::create(realm, *m_auto_allocate_chunk_size);-- // 2. If buffer is an abrupt completion,- if (buffer.is_throw_completion()) {- // 1. Perform readRequest’s error steps, given buffer.[[Value]].- read_request->on_error(buffer.throw_completion().value());-- // 2. Return.- return;- }-- // 3. Let pullIntoDescriptor be a new pull-into descriptor with buffer buffer.[[Value]], buffer byte length autoAllocateChunkSize, byte offset 0,- // byte length autoAllocateChunkSize, bytes filled 0, element size 1, view constructor %Uint8Array%, and reader type "default".- auto pull_into_descriptor = GC::Heap::the().allocate<PullIntoDescriptor>(- buffer.release_value(),- *m_auto_allocate_chunk_size,- 0,- *m_auto_allocate_chunk_size,- 0,- 1,- 1,- *realm.intrinsics().uint8_array_constructor(),- ReaderType::Default);-- // 4. Append pullIntoDescriptor to this.[[pendingPullIntos]].- m_pending_pull_intos.append(pull_into_descriptor);- }-- // 6. Perform ! ReadableStreamAddReadRequest(stream, readRequest).- readable_stream_add_read_request(*m_stream, read_request);-- // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(this).- readable_byte_stream_controller_call_pull_if_needed(*this);-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontroller-releasesteps-void ReadableByteStreamController::release_steps()-{- // 1. If this.[[pendingPullIntos]] is not empty,- if (!m_pending_pull_intos.is_empty()) {- // 1. Let firstPendingPullInto be this.[[pendingPullIntos]][0].- auto& first_pending_pull_into = *m_pending_pull_intos.first();-- // 2. Set firstPendingPullInto’s reader type to "none".- first_pending_pull_into.reader_type = ReaderType::None;-- // 3. Set this.[[pendingPullIntos]] to the list « firstPendingPullInto ».- m_pending_pull_intos.clear();- m_pending_pull_intos.append(first_pending_pull_into);- }-}--void ReadableByteStreamController::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_byob_request);- for (auto const& pending_pull_into : m_pending_pull_intos)- visitor.visit(pending_pull_into);- for (auto const& item : m_queue)- visitor.visit(item.buffer);- visitor.visit(m_stream);- visitor.visit(m_cancel_algorithm);- visitor.visit(m_pull_algorithm);-}--}diff --git a/Libraries/LibWeb/Streams/ReadableByteStreamController.h b/Libraries/LibWeb/Streams/ReadableByteStreamController.hdeleted file mode 100644index c16d0acb53e..00000000000--- a/Libraries/LibWeb/Streams/ReadableByteStreamController.h+++ /dev/null@@ -1,227 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2025, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/SinglyLinkedList.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/WebIDL/Buffers.h>--namespace Web::Streams {--enum class ReaderType {- Default,- Byob,- None,-};--// https://streams.spec.whatwg.org/#pull-into-descriptor-struct PullIntoDescriptor : public GC::Cell {- GC_CELL(PullIntoDescriptor, GC::Cell);- GC_DECLARE_ALLOCATOR(PullIntoDescriptor);-- // https://streams.spec.whatwg.org/#pull-into-descriptor-buffer- // An ArrayBuffer- GC::Ref<JS::ArrayBuffer> buffer;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-buffer-byte-length- // A positive integer representing the initial byte length of buffer- u64 buffer_byte_length;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-byte-offset- // A nonnegative integer byte offset into the buffer where the underlying byte source will start writing- u64 byte_offset;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-byte-length- // A positive integer number of bytes which can be written into the buffer- u64 byte_length;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-bytes-filled- // A nonnegative integer number of bytes that have been written into the buffer so far- u64 bytes_filled;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-minimum-fill- // A positive integer representing the minimum number of bytes that must be written into the buffer before the associated read() request may be fulfilled. By default, this equals the element size.- u64 minimum_fill;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-element-size- // A positive integer representing the number of bytes that can be written into the buffer at a time, using views of the type described by the view constructor- u64 element_size;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-view-constructor- // A typed array constructor or %DataView%, which will be used for constructing a view with which to write into the buffer- GC::Ref<JS::NativeFunction> view_constructor;-- // https://streams.spec.whatwg.org/#pull-into-descriptor-reader-type- // Either "default" or "byob", indicating what type of readable stream reader initiated this request, or "none" if the initiating reader was released- ReaderType reader_type;--protected:- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- PullIntoDescriptor(- GC::Ref<JS::ArrayBuffer> buffer,- u64 buffer_byte_length,- u64 byte_offset,- u64 byte_length,- u64 bytes_filled,- u64 minimum_fill,- u64 element_size,- GC::Ref<JS::NativeFunction> view_constructor,- ReaderType reader_type)- : buffer(buffer)- , buffer_byte_length(buffer_byte_length)- , byte_offset(byte_offset)- , byte_length(byte_length)- , bytes_filled(bytes_filled)- , minimum_fill(minimum_fill)- , element_size(element_size)- , view_constructor(view_constructor)- , reader_type(reader_type)- {- }-};--// https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-struct ReadableByteStreamQueueEntry {- // https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-buffer- // An ArrayBuffer, which will be a transferred version of the one originally supplied by the underlying byte source- GC::Ref<JS::ArrayBuffer> buffer;-- // https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-byte-offset- // A nonnegative integer number giving the byte offset derived from the view originally supplied by the underlying byte source- u64 byte_offset;-- // https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-byte-length- // A nonnegative integer number giving the byte length derived from the view originally supplied by the underlying byte source- u64 byte_length;-};--// https://streams.spec.whatwg.org/#readablebytestreamcontroller-class ReadableByteStreamController : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(ReadableByteStreamController, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ReadableByteStreamController);--public:- virtual ~ReadableByteStreamController() override = default;-- // IDL getter, returns current [[byobRequest]] (if any), and otherwise the [[byobRequest]] for the next pending pull into request- GC::Ptr<ReadableStreamBYOBRequest> byob_request(JS::Realm&);-- void set_byob_request(GC::Ptr<ReadableStreamBYOBRequest> request) { m_byob_request = request; }-- // Raw [[byobRequest]] slot- GC::Ptr<ReadableStreamBYOBRequest const> raw_byob_request() const { return m_byob_request; }- GC::Ptr<ReadableStreamBYOBRequest> raw_byob_request() { return m_byob_request; }-- Optional<double> desired_size() const;- WebIDL::ExceptionOr<void> close(JS::Realm&);- void error(Optional<JS::Value> error);- WebIDL::ExceptionOr<void> enqueue(JS::Realm&, WebIDL::ArrayBufferViewVariant const&);-- Optional<u64> const& auto_allocate_chunk_size() { return m_auto_allocate_chunk_size; }- void set_auto_allocate_chunk_size(Optional<u64> value) { m_auto_allocate_chunk_size = value; }-- GC::Ptr<CancelAlgorithm> cancel_algorithm() { return m_cancel_algorithm; }- void set_cancel_algorithm(GC::Ptr<CancelAlgorithm> value) { m_cancel_algorithm = value; }-- bool close_requested() const { return m_close_requested; }- void set_close_requested(bool value) { m_close_requested = value; }-- bool pull_again() const { return m_pull_again; }- void set_pull_again(bool value) { m_pull_again = value; }-- GC::Ptr<PullAlgorithm> pull_algorithm() { return m_pull_algorithm; }- void set_pull_algorithm(GC::Ptr<PullAlgorithm> value) { m_pull_algorithm = value; }-- bool pulling() const { return m_pulling; }- void set_pulling(bool value) { m_pulling = value; }-- SinglyLinkedList<GC::Ref<PullIntoDescriptor>>& pending_pull_intos() { return m_pending_pull_intos; }- SinglyLinkedList<GC::Ref<PullIntoDescriptor>> const& pending_pull_intos() const { return m_pending_pull_intos; }-- SinglyLinkedList<ReadableByteStreamQueueEntry>& queue() { return m_queue; }-- double queue_total_size() const { return m_queue_total_size; }- void set_queue_total_size(double size) { m_queue_total_size = size; }-- bool started() const { return m_started; }- void set_started(bool value) { m_started = value; }-- double strategy_hwm() const { return m_strategy_hwm; }- void set_strategy_hwm(double value) { m_strategy_hwm = value; }-- GC::Ptr<ReadableStream const> stream() const { return m_stream; }- GC::Ptr<ReadableStream> stream() { return m_stream; }- void set_stream(GC::Ptr<ReadableStream> stream) { m_stream = stream; }-- GC::Ref<WebIDL::Promise> cancel_steps(JS::Value reason);- void pull_steps(JS::Realm&, GC::Ref<ReadRequest>);- void release_steps();--private:- ReadableByteStreamController() = default;-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#readablebytestreamcontroller-autoallocatechunksize- // A positive integer, when the automatic buffer allocation feature is enabled. In that case, this value specifies the size of buffer to allocate. It is undefined otherwise.- Optional<u64> m_auto_allocate_chunk_size;-- // https://streams.spec.whatwg.org/#readablebytestreamcontroller-byobrequest- // A ReadableStreamBYOBRequest instance representing the current BYOB pull request, or null if there are no pending requests- GC::Ptr<ReadableStreamBYOBRequest> m_byob_request;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-cancelalgorithm- // A promise-returning algorithm, taking one argument (the cancel reason), which communicates a requested cancelation to the underlying source- GC::Ptr<CancelAlgorithm> m_cancel_algorithm;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-closerequested- // A boolean flag indicating whether the stream has been closed by its underlying source, but still has chunks in its internal queue that have not yet been read- bool m_close_requested { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullagain- // A boolean flag set to true if the stream’s mechanisms requested a call to the underlying source's pull algorithm to pull more data, but the pull could not yet be done since a previous call is still executing- bool m_pull_again { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullalgorithm- // A promise-returning algorithm that pulls data from the underlying source- GC::Ptr<PullAlgorithm> m_pull_algorithm;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pulling- // A boolean flag set to true while the underlying source's pull algorithm is executing and the returned promise has not yet fulfilled, used to prevent reentrant calls- bool m_pulling { false };-- // https://streams.spec.whatwg.org/#readablebytestreamcontroller-pendingpullintos- // A list of pull-into descriptors- SinglyLinkedList<GC::Ref<PullIntoDescriptor>> m_pending_pull_intos;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-queue- // A list representing the stream’s internal queue of chunks- SinglyLinkedList<ReadableByteStreamQueueEntry> m_queue;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-queuetotalsize- // The total size of all the chunks stored in [[queue]]- double m_queue_total_size { 0 };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-started- // A boolean flag indicating whether the underlying source has finished starting- bool m_started { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-strategyhwm- // A number supplied to the constructor as part of the stream’s queuing strategy, indicating the point at which the stream will apply backpressure to its underlying source- double m_strategy_hwm { 0 };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-stream- // The ReadableStream instance controlled- GC::Ptr<ReadableStream> m_stream;-};--}diff --git a/Libraries/LibWeb/Streams/ReadableByteStreamController.idl b/Libraries/LibWeb/Streams/ReadableByteStreamController.idlindex f83ccb93271..d069260591b 100644--- a/Libraries/LibWeb/Streams/ReadableByteStreamController.idl+++ b/Libraries/LibWeb/Streams/ReadableByteStreamController.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#rbs-controller-class-definition- [Exposed=*]+ [Exposed=*, ImplementedIn=Rust]interface ReadableByteStreamController {readonly attribute ReadableStreamBYOBRequest? byobRequest;readonly attribute unrestricted double? desiredSize;diff --git a/Libraries/LibWeb/Streams/ReadableStream.cpp b/Libraries/LibWeb/Streams/ReadableStream.cppindex 076f16b93f7..b6551145c2e 100644--- a/Libraries/LibWeb/Streams/ReadableStream.cpp+++ b/Libraries/LibWeb/Streams/ReadableStream.cpp@@ -6,516 +6,416 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibJS/Runtime/TypedArray.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/NativeFunction.h>+#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/VM.h>-#include <LibWeb/Bindings/ReadableStream.h>-#include <LibWeb/Bindings/UnderlyingSource.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustSerialization.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/DOM/AbortSignal.h>+#include <LibWeb/DOM/IDLEventListener.h>+#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/HTML/MessageEvent.h>#include <LibWeb/HTML/MessagePort.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/Page/RenderingStats.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/BindingsGlue.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamAsyncIterator.h>-#include <LibWeb/Streams/ReadableStreamBYOBReader.h>-#include <LibWeb/Streams/ReadableStreamBYOBRequest.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/ExceptionOr.h>+#include <LibWeb/WebIDL/CallbackType.h>+#include <LibWeb/WebIDL/ExceptionOrUtils.h>namespace Web::Streams {-GC_DEFINE_ALLOCATOR(ReadableStream);--static UnderlyingSource underlying_source_from_bindings(Bindings::UnderlyingSource const& underlying_source)+extern "C" {++// Defined in Bindings/Rust/src/streams/exports.rs.+void* web_rust_readable_stream_create(JSVM*, void* realm);+void web_rust_readable_stream_set_up_with_byte_reading_support(JSVM*, void* realm, void* stream, PullAlgorithm* pull_algorithm, CancelAlgorithm* cancel_algorithm, double high_water_mark);+u8 web_rust_readable_stream_state(void* stream);+bool web_rust_readable_stream_is_locked(void* stream);+bool web_rust_readable_stream_is_disturbed(void* stream);+bool web_rust_readable_stream_close_requested(void* stream);+JSCompletion web_rust_readable_stream_enqueue(JSVM*, void* stream, JSValue chunk);+JSCompletion web_rust_readable_stream_enqueue_native_bytes(JSVM*, void* stream, ReadonlyBytes);+void web_rust_readable_stream_close(JSVM*, void* stream);+void web_rust_readable_stream_error(JSVM*, void* stream, JSValue error);+void* web_rust_readable_stream_cancel(JSVM*, void* stream, JSValue reason);+JSCompletion web_rust_readable_stream_tee(JSVM*, void* stream, void** branch1, void** branch2);+JSCompletion web_rust_readable_stream_get_a_reader(JSVM*, void* stream, void** reader);+void* web_rust_readable_stream_piped_through(JSVM*, void* stream, void* transform, bool prevent_close, bool prevent_abort, bool prevent_cancel);+void web_rust_readable_stream_default_reader_read_a_chunk(JSVM*, void* reader, ReadRequest* read_request);+void web_rust_readable_stream_default_reader_read_all_bytes(JSVM*, void* reader, ReadableStreamDefaultReader::SuccessSteps* success_steps, ReadableStreamDefaultReader::FailureSteps* failure_steps);+void* web_rust_readable_stream_default_reader_read(JSVM*, void* reader);+void* web_rust_readable_stream_default_reader_cancel(JSVM*, void* reader, JSValue reason);+void* web_rust_readable_stream_default_reader_closed_promise_realm(void* reader);++// Called by Bindings/Rust/src/streams.+void* web_streams_call_promise_algorithm(GC::Function<GC::Ref<WebIDL::Promise>()>*);+void* web_streams_call_promise_algorithm_with_argument(GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>*, JSValue argument);+void web_streams_read_request_chunk_steps(ReadRequest*, JSValue chunk);+void web_streams_read_request_close_steps(ReadRequest*);+void web_streams_read_request_error_steps(ReadRequest*, JSValue error);+void web_streams_call_bytes_steps(ReadableStreamDefaultReader::SuccessSteps*, ReadonlyBytes);+void web_streams_call_value_steps(ReadableStreamDefaultReader::FailureSteps*, JSValue);+void web_streams_complete_rendering_pending_stream(ReadableStream*);+JSCompletion web_streams_structured_clone(void* realm, JSValue);+void* web_streams_abort_signal_from_wrapper(JSObject* wrapper);+JSObject* web_streams_abort_signal_wrapper(void* realm, DOM::AbortSignal*);+void* web_streams_create_abort_signal();+bool web_streams_abort_signal_aborted(DOM::AbortSignal*);+JSValue web_streams_abort_signal_reason(DOM::AbortSignal*);+bool web_streams_abort_signal_add_algorithm(DOM::AbortSignal*, JSObject* function, u64* id);+void web_streams_abort_signal_remove_algorithm(DOM::AbortSignal*, u64 id);+void web_streams_abort_signal_signal_abort(DOM::AbortSignal*, JSValue reason, void* realm);+void web_streams_create_entangled_ports(void* realm, void** port1, void** port2);+void web_streams_message_port_add_handlers(void* realm, HTML::MessagePort*, JSObject* on_message, JSObject* on_message_error);+JSValue web_streams_message_event_data(JSValue event);+JSCompletion web_streams_message_port_post_message(void* realm, HTML::MessagePort*, JSValue message);+void web_streams_message_port_disentangle(HTML::MessagePort*);+void web_streams_message_port_enable(HTML::MessagePort*);+void* web_streams_message_port_from_object(JSObject*);+JSObject* web_streams_message_port_wrapper(void* realm, HTML::MessagePort*);+void web_streams_serialize_with_transfer(Bindings::RustTransferDataWriter*, JSValue);+JSValue web_streams_deserialize_with_transfer(Bindings::RustTransferDataReader*);+}++static JSVM* vm_abi(){- return {- .auto_allocate_chunk_size = underlying_source.auto_allocate_chunk_size,- .cancel = underlying_source.cancel,- .pull = underlying_source.pull,- .start = underlying_source.start,- .is_bytes = underlying_source.type.has_value() && underlying_source.type.value() == Bindings::ReadableStreamType::Bytes,- };+ return JS::HostABI::vm_to_abi(JS::VM::the());}-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> ReadableStream::create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<JS::Object> underlying_source_object, QueuingStrategy const& strategy)+static JS::Realm& realm_of(void* realm){- auto& realm = HTML::relevant_realm(relevant_global_object);- auto underlying_source = underlying_source_object ? JS::Value { underlying_source_object } : JS::js_null();- auto underlying_source_dict = TRY(Bindings::convert_to_idl_value_for_underlying_source(realm.vm(), underlying_source));- return create(realm, underlying_source_object, underlying_source_from_bindings(underlying_source_dict), strategy);+ return *static_cast<JS::Realm*>(realm);}-// https://streams.spec.whatwg.org/#rs-constructor-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> ReadableStream::create(JS::Realm& realm, GC::Ptr<JS::Object> underlying_source_object, UnderlyingSource const& underlying_source_dict, QueuingStrategy const& strategy)+static WebIDL::ExceptionOr<void> exception_or_void(JSCompletion completion){- auto& vm = realm.vm();-- auto readable_stream = GC::Heap::the().allocate<ReadableStream>();- readable_stream->set_realm(realm);-- // 1. If underlyingSource is missing, set it to null.- auto underlying_source = underlying_source_object ? JS::Value(underlying_source_object) : JS::js_null();-- // 3. Perform ! InitializeReadableStream(this).-- // 4. If underlyingSourceDict["type"] is "bytes":- if (underlying_source_dict.is_bytes) {- // 1. If strategy["size"] exists, throw a RangeError exception.- if (strategy.size)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Size strategy not allowed for byte stream"_utf16 };-- // 2. Let highWaterMark be ? ExtractHighWaterMark(strategy, 0).- auto high_water_mark = TRY(extract_high_water_mark(strategy, 0));-- // 3. Perform ? SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, underlyingSourceDict, highWaterMark).- TRY(set_up_readable_byte_stream_controller_from_underlying_source(realm, *readable_stream, underlying_source, underlying_source_dict, high_water_mark));- }- // 5. Otherwise,- else {- // 1. Assert: underlyingSourceDict["type"] does not exist.- VERIFY(!underlying_source_dict.is_bytes);-- // 2. Let sizeAlgorithm be ! ExtractSizeAlgorithm(strategy).- auto size_algorithm = extract_size_algorithm(vm, strategy);-- // 3. Let highWaterMark be ? ExtractHighWaterMark(strategy, 1).- auto high_water_mark = TRY(extract_high_water_mark(strategy, 1));-- // 4. Perform ? SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, underlyingSourceDict, highWaterMark, sizeAlgorithm).- TRY(set_up_readable_stream_default_controller_from_underlying_source(realm, *readable_stream, underlying_source, underlying_source_dict, high_water_mark, size_algorithm));- }-- return readable_stream;+ auto result = JS::HostABI::completion_from_abi<JS::Value>(completion);+ if (result.is_error())+ return result.release_error();+ return {};}-// https://streams.spec.whatwg.org/#rs-from-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> ReadableStream::from(JS::Realm& realm, JS::Value async_iterable)+GC::Ref<ReadableStream> ReadableStream::create(JS::Realm& realm){- // 1. Return ? ReadableStreamFromIterable(asyncIterable).- return TRY(readable_stream_from_iterable(realm, async_iterable));+ return GC::Ref { *static_cast<ReadableStream*>(web_rust_readable_stream_create(vm_abi(), &realm)) };}-ReadableStream::ReadableStream()+void ReadableStream::set_up_with_byte_reading_support(JS::Realm& realm, GC::Ptr<PullAlgorithm> pull_algorithm, GC::Ptr<CancelAlgorithm> cancel_algorithm, double high_water_mark){+ web_rust_readable_stream_set_up_with_byte_reading_support(vm_abi(), &realm, this, pull_algorithm.ptr(), cancel_algorithm.ptr(), high_water_mark);}+bool ReadableStream::is_readable() const+{+ return web_rust_readable_stream_state(const_cast<ReadableStream*>(this)) == 0;}-namespace Web::Bindings {--Streams::ReadableStream* readable_stream_from_object(JS::Object& object)+bool ReadableStream::is_closed() const{- return Bindings::impl_from<Streams::ReadableStream>(&object);+ return web_rust_readable_stream_state(const_cast<ReadableStream*>(this)) == 1;}-void serialize_readable_stream_with_transfer(JS::Realm& realm, HTML::TransferDataEncoder& data_holder, GC::Ref<Streams::ReadableStream> stream)+bool ReadableStream::is_errored() const{- JS::Value wrapped_stream = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, stream);- auto result = MUST(HTML::structured_serialize_with_transfer(realm, wrapped_stream, { { wrapped_stream.as_object() } }));- data_holder.extend(move(result.transfer_data_holders));+ return web_rust_readable_stream_state(const_cast<ReadableStream*>(this)) == 2;}+bool ReadableStream::is_locked() const+{+ return web_rust_readable_stream_is_locked(const_cast<ReadableStream*>(this));}-namespace Web::Streams {--ReadableStream::~ReadableStream() = default;--void ReadableStream::finalize()+bool ReadableStream::is_disturbed() const{- complete_rendering_pending_stream(*this);- Base::finalize();+ return web_rust_readable_stream_is_disturbed(const_cast<ReadableStream*>(this));}-void ReadableStream::visit_edges(GC::Cell::Visitor& visitor)+bool ReadableStream::close_requested() const{- Base::visit_edges(visitor);- visitor.visit(m_realm);- visitor.visit(m_result_realm);- if (m_controller.has_value())- m_controller->visit([&](auto& controller) { visitor.visit(controller); });- visitor.visit(m_stored_error);- if (m_reader.has_value())- m_reader->visit([&](auto& reader) { visitor.visit(reader); });+ return web_rust_readable_stream_close_requested(const_cast<ReadableStream*>(this));}-// https://streams.spec.whatwg.org/#rs-locked-bool ReadableStream::locked() const+WebIDL::ExceptionOr<void> ReadableStream::enqueue(JS::Value chunk){- // 1. Return ! IsReadableStreamLocked(this).- return is_readable_stream_locked(*this);+ return exception_or_void(web_rust_readable_stream_enqueue(vm_abi(), this, JS::HostABI::value_to_abi(chunk)));}-// https://streams.spec.whatwg.org/#rs-cancel-GC::Ref<WebIDL::Promise> ReadableStream::cancel(Optional<JS::Value> reason)+WebIDL::ExceptionOr<void> ReadableStream::enqueue_bytes(ReadonlyBytes bytes){- auto& realm = this->realm();- // 1. If ! IsReadableStreamLocked(this) is true, return a promise rejected with a TypeError exception.- if (is_readable_stream_locked(*this)) {- auto exception = JS::TypeError::create(realm, "Cannot cancel a locked stream"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }+ return exception_or_void(web_rust_readable_stream_enqueue_native_bytes(vm_abi(), this, bytes));+}- // 2. Return ! ReadableStreamCancel(this, reason).- return readable_stream_cancel(realm, *this, reason.value_or(JS::js_undefined()));+void ReadableStream::close()+{+ web_rust_readable_stream_close(vm_abi(), this);}-// https://streams.spec.whatwg.org/#rs-get-reader-WebIDL::ExceptionOr<ReadableStreamReader> ReadableStream::get_reader(ReadableStreamGetReaderOptions const& options)+void ReadableStream::error(JS::Value error){- auto& realm = this->realm();- // 1. If options["mode"] does not exist, return ? AcquireReadableStreamDefaultReader(this).- if (!options.mode.has_value())- return ReadableStreamReader { TRY(acquire_readable_stream_default_reader(realm, *this)) };+ web_rust_readable_stream_error(vm_abi(), this, JS::HostABI::value_to_abi(error));+}- // 3. Return ? AcquireReadableStreamBYOBReader(this).- return ReadableStreamReader { TRY(acquire_readable_stream_byob_reader(realm, *this)) };+GC::Ref<WebIDL::Promise> ReadableStream::cancel(JS::Value reason)+{+ return GC::Ref { *static_cast<WebIDL::Promise*>(web_rust_readable_stream_cancel(vm_abi(), this, JS::HostABI::value_to_abi(reason))) };}-// https://streams.spec.whatwg.org/#rs-pipe-through-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> ReadableStream::pipe_through(ReadableWritablePair transform, StreamPipeOptions const& options)+WebIDL::ExceptionOr<ReadableStreamPair> ReadableStream::tee(){- auto& realm = this->realm();- // 1. If ! IsReadableStreamLocked(this) is true, throw a TypeError exception.- if (is_readable_stream_locked(*this))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Failed to execute 'pipeThrough' on 'ReadableStream': Cannot pipe a locked stream"_utf16 };+ void* branch1 = nullptr;+ void* branch2 = nullptr;+ TRY(exception_or_void(web_rust_readable_stream_tee(vm_abi(), this, &branch1, &branch2)));+ return ReadableStreamPair { *static_cast<ReadableStream*>(branch1), *static_cast<ReadableStream*>(branch2) };+}- // 2. If ! IsWritableStreamLocked(transform["writable"]) is true, throw a TypeError exception.- if (is_writable_stream_locked(*transform.writable))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Failed to execute 'pipeThrough' on 'ReadableStream': parameter 1's 'writable' is locked"_utf16 };+WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> ReadableStream::get_a_reader()+{+ void* reader = nullptr;+ TRY(exception_or_void(web_rust_readable_stream_get_a_reader(vm_abi(), this, &reader)));+ return GC::Ref { *static_cast<ReadableStreamDefaultReader*>(reader) };+}- // 3. Let signal be options["signal"] if it exists, or undefined otherwise.- GC::Ptr<DOM::AbortSignal> signal = options.signal;+GC::Ref<ReadableStream> ReadableStream::piped_through(GC::Ref<TransformStream> transform, bool prevent_close, bool prevent_abort, bool prevent_cancel)+{+ return GC::Ref { *static_cast<ReadableStream*>(web_rust_readable_stream_piped_through(vm_abi(), this, transform.ptr(), prevent_close, prevent_abort, prevent_cancel)) };+}- // 4. Let promise be ! ReadableStreamPipeTo(this, transform["writable"], options["preventClose"], options["preventAbort"], options["preventCancel"], signal).- auto promise = readable_stream_pipe_to(realm, *this, *transform.writable, options.prevent_close, options.prevent_abort, options.prevent_cancel, signal);+GC::Ref<WebIDL::Promise> ReadableStreamDefaultReader::read()+{+ return GC::Ref { *static_cast<WebIDL::Promise*>(web_rust_readable_stream_default_reader_read(vm_abi(), this)) };+}- // 5. Set promise.[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*promise);+void ReadableStreamDefaultReader::read_a_chunk(ReadRequest& read_request)+{+ web_rust_readable_stream_default_reader_read_a_chunk(vm_abi(), this, &read_request);+}- // 6. Return transform["readable"].- return GC::Ref { *transform.readable };+void ReadableStreamDefaultReader::read_all_bytes(GC::Ref<SuccessSteps> success_steps, GC::Ref<FailureSteps> failure_steps)+{+ web_rust_readable_stream_default_reader_read_all_bytes(vm_abi(), this, success_steps.ptr(), failure_steps.ptr());}-// https://streams.spec.whatwg.org/#rs-pipe-to-GC::Ref<WebIDL::Promise> ReadableStream::pipe_to(WritableStream& destination, StreamPipeOptions const& options)+// FIXME: This function is a promise-based wrapper around "read all bytes". The spec changed this function to not use promises+// in https://github.com/whatwg/streams/commit/f894acdd417926a2121710803cef593e15127964 - however, it seems that the+// FileAPI blob specification has not been updated to match, see: https://github.com/w3c/FileAPI/issues/187.+GC::Ref<WebIDL::Promise> ReadableStreamDefaultReader::read_all_bytes_deprecated(){- auto& realm = this->realm();- auto& vm = realm.vm();+ auto& realm = closed_promise_realm();++ auto promise = WebIDL::create_promise(realm);- // 1. If ! IsReadableStreamLocked(this) is true, return a promise rejected with a TypeError exception.- if (is_readable_stream_locked(*this)) {- return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::TypeError>("Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe a locked stream"_utf16));- }+ auto success_steps = GC::create_function(GC::Heap::the(), [promise, &realm](ByteBuffer bytes) {+ auto buffer = JS::ArrayBuffer::create(realm, move(bytes));+ WebIDL::resolve_promise(promise, buffer);+ });- // 2. If ! IsWritableStreamLocked(destination) is true, return a promise rejected with a TypeError exception.- if (is_writable_stream_locked(destination)) {- return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::TypeError>("Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe to a locked stream"_utf16));- }+ auto failure_steps = GC::create_function(GC::Heap::the(), [promise](JS::Value error) {+ WebIDL::reject_promise(promise, error);+ });- // 3. Let signal be options["signal"] if it exists, or undefined otherwise.- GC::Ptr<DOM::AbortSignal> signal = options.signal;+ read_all_bytes(success_steps, failure_steps);- // 4. Return ! ReadableStreamPipeTo(this, destination, options["preventClose"], options["preventAbort"], options["preventCancel"], signal).- return readable_stream_pipe_to(realm, *this, destination, options.prevent_close, options.prevent_abort, options.prevent_cancel, signal);+ return promise;}-WebIDL::ExceptionOr<GC::Ref<JS::Object>> ReadableStream::values(ReadableStreamIteratorOptions options)+GC::Ref<WebIDL::Promise> ReadableStreamDefaultReader::cancel(JS::Value reason){- auto& realm = this->realm();- return TRY(ReadableStreamAsyncIterator::create(realm, JS::Object::PropertyKind::Value, *this, options));+ return GC::Ref { *static_cast<WebIDL::Promise*>(web_rust_readable_stream_default_reader_cancel(vm_abi(), this, JS::HostABI::value_to_abi(reason))) };}-// https://streams.spec.whatwg.org/#readablestream-tee-WebIDL::ExceptionOr<ReadableStreamPair> ReadableStream::tee()+JS::Realm& ReadableStreamDefaultReader::closed_promise_realm() const{- auto& realm = this->realm();- // To tee a ReadableStream stream, return ? ReadableStreamTee(stream, true).- return TRY(readable_stream_tee(realm, *this, true));+ return realm_of(web_rust_readable_stream_default_reader_closed_promise_realm(const_cast<ReadableStreamDefaultReader*>(this)));}-// https://streams.spec.whatwg.org/#readablestream-close-void ReadableStream::close()+void* web_streams_call_promise_algorithm(GC::Function<GC::Ref<WebIDL::Promise>()>* algorithm){- auto& realm = this->realm();- controller()->visit(- // 1. If stream.[[controller]] implements ReadableByteStreamController- [&](GC::Ref<ReadableByteStreamController> controller) {- // 1. Perform ! ReadableByteStreamControllerClose(stream.[[controller]]).- MUST(readable_byte_stream_controller_close(realm, controller));-- // 2. If stream.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(stream.[[controller]], 0).- if (!controller->pending_pull_intos().is_empty())- MUST(readable_byte_stream_controller_respond(realm, controller, 0));- },-- // 2. Otherwise, perform ! ReadableStreamDefaultControllerClose(stream.[[controller]]).- [&](GC::Ref<ReadableStreamDefaultController> controller) {- readable_stream_default_controller_close(*controller);- });+ return algorithm->function()().ptr();}-// https://streams.spec.whatwg.org/#readablestream-error-void ReadableStream::error(JS::Value error)+void* web_streams_call_promise_algorithm_with_argument(GC::Function<GC::Ref<WebIDL::Promise>(JS::Value)>* algorithm, JSValue argument){- controller()->visit(- // 1. If stream.[[controller]] implements ReadableByteStreamController, then perform- // ! ReadableByteStreamControllerError(stream.[[controller]], e).- [&](GC::Ref<ReadableByteStreamController> controller) {- readable_byte_stream_controller_error(controller, error);- },-- // 2. Otherwise, perform ! ReadableStreamDefaultControllerError(stream.[[controller]], e).- [&](GC::Ref<ReadableStreamDefaultController> controller) {- readable_stream_default_controller_error(controller, error);- });+ return algorithm->function()(JS::HostABI::value_from_abi(argument)).ptr();}-// https://streams.spec.whatwg.org/#readablestream-locked-bool ReadableStream::is_readable() const+void web_streams_read_request_chunk_steps(ReadRequest* read_request, JSValue chunk){- // A ReadableStream stream is readable if stream.[[state]] is "readable".- return m_state == State::Readable;+ read_request->on_chunk(JS::HostABI::value_from_abi(chunk));}-// https://streams.spec.whatwg.org/#readablestream-closed-bool ReadableStream::is_closed() const+void web_streams_read_request_close_steps(ReadRequest* read_request){- // A ReadableStream stream is closed if stream.[[state]] is "closed".- return m_state == State::Closed;+ read_request->on_close();}-// https://streams.spec.whatwg.org/#readablestream-errored-bool ReadableStream::is_errored() const+void web_streams_read_request_error_steps(ReadRequest* read_request, JSValue error){- // A ReadableStream stream is errored if stream.[[state]] is "errored".- return m_state == State::Errored;+ read_request->on_error(JS::HostABI::value_from_abi(error));}-// https://streams.spec.whatwg.org/#readablestream-locked-bool ReadableStream::is_locked() const++void web_streams_call_bytes_steps(ReadableStreamDefaultReader::SuccessSteps* steps, ReadonlyBytes bytes){- // A ReadableStream stream is locked if ! IsReadableStreamLocked(stream) returns true.- return is_readable_stream_locked(*this);+ steps->function()(MUST(ByteBuffer::copy(bytes)));}-// https://streams.spec.whatwg.org/#is-readable-stream-disturbed-bool ReadableStream::is_disturbed() const+void web_streams_call_value_steps(ReadableStreamDefaultReader::FailureSteps* steps, JSValue value){- // A ReadableStream stream is disturbed if stream.[[disturbed]] is true.- return m_disturbed;+ steps->function()(JS::HostABI::value_from_abi(value));}-// https://streams.spec.whatwg.org/#readablestream-get-a-reader-WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> ReadableStream::get_a_reader()+void web_streams_complete_rendering_pending_stream(ReadableStream* stream){- auto& realm = this->realm();- // To get a reader for a ReadableStream stream, return ? AcquireReadableStreamDefaultReader(stream). The result will be a ReadableStreamDefaultReader.- return TRY(acquire_readable_stream_default_reader(realm, *this));+ complete_rendering_pending_stream(*stream);}-// https://streams.spec.whatwg.org/#readablestream-current-byob-request-view-Optional<WebIDL::ArrayBufferView> ReadableStream::current_byob_request_view()+// https://streams.spec.whatwg.org/#abstract-opdef-structuredclone+JSCompletion web_streams_structured_clone(void* realm, JSValue value){- auto& realm = this->realm();- // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.- VERIFY(m_controller->has<GC::Ref<ReadableByteStreamController>>());+ auto& js_realm = realm_of(realm);+ auto& vm = js_realm.vm();+ auto result = [&]() -> WebIDL::ExceptionOr<JS::Value> {+ // 1. Let serialized be ? StructuredSerialize(v).+ auto serialized = TRY(HTML::structured_serialize(vm, JS::HostABI::value_from_abi(value)));- // 2. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(stream.[[controller]]).- auto byob_request = readable_byte_stream_controller_get_byob_request(realm, m_controller->get<GC::Ref<ReadableByteStreamController>>());-- // 3. If byobRequest is null, then return null.- if (!byob_request)- return {};-- // 4. Return byobRequest.[[view]].- auto view = byob_request->view();- VERIFY(view);- return WebIDL::ArrayBufferViewVariant { *view };+ // 2. Return ? StructuredDeserialize(serialized, the current Realm).+ return TRY(HTML::structured_deserialize(vm, serialized, js_realm));+ }();+ return Bindings::completion_to_abi(js_realm, move(result));}-// https://streams.spec.whatwg.org/#readablestream-enqueue-WebIDL::ExceptionOr<void> ReadableStream::enqueue(JS::Value chunk)+void* web_streams_abort_signal_from_wrapper(JSObject* wrapper){- auto& realm = this->realm();- VERIFY(m_controller.has_value());-- // 1. If stream.[[controller]] implements ReadableStreamDefaultController,- if (m_controller->has<GC::Ref<ReadableStreamDefaultController>>()) {- // 1. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], chunk).- MUST(readable_stream_default_controller_enqueue(realm, m_controller->get<GC::Ref<ReadableStreamDefaultController>>(), chunk));- }- // 2. Otherwise,- else {- // 1. Assert: stream.[[controller]] implements ReadableByteStreamController.- VERIFY(m_controller->has<GC::Ref<ReadableByteStreamController>>());- auto readable_byte_controller = m_controller->get<GC::Ref<ReadableByteStreamController>>();-- // 2. Assert: chunk is an ArrayBufferView.- VERIFY(chunk.is_object());- WebIDL::ArrayBufferView chunk_view { WebIDL::ArrayBufferView::from_object(chunk.as_object()) };-- // 3. Let byobView be the current BYOB request view for stream.- auto byob_view = current_byob_request_view();-- // 4. If byobView is non-null, and chunk.[[ViewedArrayBuffer]] is byobView.[[ViewedArrayBuffer]], then:- if (byob_view.has_value() && chunk_view.viewed_array_buffer() == byob_view->viewed_array_buffer()) {- // 1. Assert: chunk.[[ByteOffset]] is byobView.[[ByteOffset]].- VERIFY(chunk_view.byte_offset() == byob_view->byte_offset());-- // 2. Assert: chunk.[[ByteLength]] ≤ byobView.[[ByteLength]].- VERIFY(chunk_view.byte_length() <= byob_view->byte_length());-- // 3. Perform ? ReadableByteStreamControllerRespond(stream.[[controller]], chunk.[[ByteLength]]).- TRY(readable_byte_stream_controller_respond(realm, readable_byte_controller, chunk_view.byte_length()));- }- // 5. Otherwise, perform ? ReadableByteStreamControllerEnqueue(stream.[[controller]], chunk).- else {- TRY(readable_byte_stream_controller_enqueue(realm, readable_byte_controller, chunk));- }- }-- return {};+ auto* signal = Bindings::impl_from<DOM::AbortSignal>(JS::HostABI::object_from_abi(wrapper));+ VERIFY(signal);+ return signal;}-// https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support-void ReadableStream::set_up_with_byte_reading_support(JS::Realm& realm, GC::Ptr<PullAlgorithm> pull_algorithm, GC::Ptr<CancelAlgorithm> cancel_algorithm, double high_water_mark)+JSObject* web_streams_abort_signal_wrapper(void* realm, DOM::AbortSignal* signal){- set_realm(realm);-- // 1. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });-- // 2. Let pullAlgorithmWrapper be an algorithm that runs these steps:- auto pull_algorithm_wrapper = GC::create_function(GC::Heap::the(), [&realm, pull_algorithm]() {- // 1. Let result be the result of running pullAlgorithm, if pullAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.- GC::Ptr<JS::PromiseCapability> result = nullptr;- if (pull_algorithm)- result = pull_algorithm->function()();-- // 2. If result is a Promise, then return result.- if (result != nullptr)- return GC::Ref(*result);+ auto& js_realm = realm_of(realm);+ return JS::HostABI::object_to_abi(Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, GC::Ref { *signal }).ptr());+}- // 3. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });+void* web_streams_create_abort_signal()+{+ return DOM::AbortSignal::create().ptr();+}- // 3. Let cancelAlgorithmWrapper be an algorithm that runs these steps:- auto cancel_algorithm_wrapper = GC::create_function(GC::Heap::the(), [&realm, cancel_algorithm](JS::Value c) {- // 1. Let result be the result of running cancelAlgorithm, if cancelAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.- GC::Ptr<JS::PromiseCapability> result = nullptr;- if (cancel_algorithm)- result = cancel_algorithm->function()(c);+bool web_streams_abort_signal_aborted(DOM::AbortSignal* signal)+{+ return signal->aborted();+}- // 2. If result is a Promise, then return result.- if (result != nullptr)- return GC::Ref(*result);+JSValue web_streams_abort_signal_reason(DOM::AbortSignal* signal)+{+ return JS::HostABI::value_to_abi(signal->reason());+}- // 3. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());+bool web_streams_abort_signal_add_algorithm(DOM::AbortSignal* signal, JSObject* function, u64* id)+{+ GC::Ref<JS::FunctionObject> algorithm = as<JS::FunctionObject>(*JS::HostABI::object_from_abi(function));+ auto algorithm_id = signal->add_abort_algorithm([algorithm] {+ MUST(JS::call(algorithm->vm(), *algorithm, JS::js_undefined()));});-- // 4. Perform ! InitializeReadableStream(stream).- // 5. Let controller be a new ReadableByteStreamController.- auto controller = GC::Heap::the().allocate<ReadableByteStreamController>();-- // 6. Perform ! SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithmWrapper, cancelAlgorithmWrapper, highWaterMark, undefined).- MUST(set_up_readable_byte_stream_controller(realm, *this, controller, start_algorithm, pull_algorithm_wrapper, cancel_algorithm_wrapper, high_water_mark, JS::js_undefined()));+ if (!algorithm_id.has_value())+ return false;+ *id = algorithm_id.value();+ return true;}-// https://streams.spec.whatwg.org/#readablestream-pipe-through-GC::Ref<ReadableStream> ReadableStream::piped_through(GC::Ref<TransformStream> transform, bool prevent_close, bool prevent_abort, bool prevent_cancel, GC::Ptr<DOM::AbortSignal> signal)+void web_streams_abort_signal_remove_algorithm(DOM::AbortSignal* signal, u64 id){- auto& realm = this->realm();- // 1. Assert: ! IsReadableStreamLocked(readable) is false.- VERIFY(!is_readable_stream_locked(*this));-- // 2. Assert: ! IsWritableStreamLocked(transform.[[writable]]) is false.- VERIFY(!is_writable_stream_locked(transform->writable()));-- // 3. Let signalArg be signal if signal was given, or undefined otherwise.- // NOTE: Done by default arguments.-- // 4. Let promise be ! ReadableStreamPipeTo(readable, transform.[[writable]], preventClose, preventAbort, preventCancel, signalArg).- auto promise = readable_stream_pipe_to(realm, *this, transform->writable(), prevent_close, prevent_abort, prevent_cancel, signal);-- // 5. Set promise.[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*promise);-- // 6. Return transform.[[readable]].- return transform->readable();+ signal->remove_abort_algorithm(id);}-// https://streams.spec.whatwg.org/#ref-for-transfer-steps-WebIDL::ExceptionOr<void> ReadableStream::transfer_steps(JS::Realm& realm, HTML::TransferDataEncoder& data_holder)+void web_streams_abort_signal_signal_abort(DOM::AbortSignal* signal, JSValue reason, void* realm){- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 1. If ! IsReadableStreamLocked(value) is true, throw a "DataCloneError" DOMException.- if (is_readable_stream_locked(*this))- return WebIDL::DataCloneError::create("Cannot transfer locked ReadableStream"_utf16);+ signal->signal_abort(JS::HostABI::value_from_abi(reason), realm_of(realm).global_object());+}- // 2. Let port1 be a new MessagePort in the current Realm.- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(realm.global_object());+void web_streams_create_entangled_ports(void* realm, void** port1, void** port2)+{+ auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(realm_of(realm).global_object());VERIFY(global_scope);- auto port1 = HTML::MessagePort::create(global_scope->this_impl());-- // 3. Let port2 be a new MessagePort in the current Realm.- auto port2 = HTML::MessagePort::create(global_scope->this_impl());+ auto first_port = HTML::MessagePort::create(global_scope->this_impl());+ auto second_port = HTML::MessagePort::create(global_scope->this_impl());+ first_port->entangle_with(second_port);+ *port1 = first_port.ptr();+ *port2 = second_port.ptr();+}- // 4. Entangle port1 and port2.- port1->entangle_with(port2);+static void add_message_event_listener(JS::Realm& realm, HTML::MessagePort& port, Utf16FlyString const& name, JSObject* function)+{+ auto& callback_object = *JS::HostABI::object_from_abi(function);+ auto callback = GC::Heap::the().allocate<WebIDL::CallbackType>(callback_object, realm);+ port.add_event_listener_without_options(name, DOM::IDLEventListener::create(callback));+}- // 5. Let writable be a new WritableStream in the current Realm.- auto writable = GC::Heap::the().allocate<WritableStream>();+void web_streams_message_port_add_handlers(void* realm, HTML::MessagePort* port, JSObject* on_message, JSObject* on_message_error)+{+ add_message_event_listener(realm_of(realm), *port, HTML::EventNames::message, on_message);+ add_message_event_listener(realm_of(realm), *port, HTML::EventNames::messageerror, on_message_error);+}- // 6. Perform ! SetUpCrossRealmTransformWritable(writable, port1).- set_up_cross_realm_transform_writable(realm, writable, port1);+JSValue web_streams_message_event_data(JSValue event)+{+ auto* message_event = Bindings::impl_from<HTML::MessageEvent>(&JS::HostABI::value_from_abi(event).as_object());+ VERIFY(message_event);+ return JS::HostABI::value_to_abi(message_event->data());+}- // 7. Let promise be ! ReadableStreamPipeTo(value, writable, false, false, false).- auto promise = readable_stream_pipe_to(realm, *this, writable, false, false, false);+JSCompletion web_streams_message_port_post_message(void* realm, HTML::MessagePort* port, JSValue message)+{+ auto& js_realm = realm_of(realm);- // 8. Set promise.[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(promise);+ // 4. Let targetPort be the port with which port is entangled, if any; otherwise let it be null.+ auto target_port = port->entangled_port();- // 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).- Bindings::serialize_message_port_with_transfer(realm, data_holder, port2);+ // 5. Let options be «[ "transfer" → « » ]».+ HTML::StructuredSerializeOptions options;- return {};+ // 6. Run the message port post message steps providing targetPort, message, and options.+ auto result = port->message_port_post_message_steps(js_realm, target_port, JS::HostABI::value_from_abi(message), options);+ if (result.is_exception())+ return Bindings::completion_to_abi(js_realm, result.release_error());+ return Bindings::completion_to_abi(js_realm, JS::js_undefined());}-// https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps-WebIDL::ExceptionOr<void> ReadableStream::transfer_receiving_steps(JS::Realm& realm, HTML::TransferDataDecoder& data_holder)+void web_streams_message_port_disentangle(HTML::MessagePort* port){- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ port->disentangle();+}- // 1. Let deserializedRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[port]], the current Realm).- auto deserialized_record = MUST(HTML::structured_deserialize_with_transfer_internal(data_holder, realm));+void web_streams_message_port_enable(HTML::MessagePort* port)+{+ port->enable();+}- // 2. Let port be deserializedRecord.[[Deserialized]].- auto* port = Bindings::message_port_from_object(deserialized_record.as_object());+void* web_streams_message_port_from_object(JSObject* object)+{+ auto* port = Bindings::message_port_from_object(*JS::HostABI::object_from_abi(object));VERIFY(port);+ return port;+}- // 3. Perform ! SetUpCrossRealmTransformReadable(value, port).- set_up_cross_realm_transform_readable(realm, *this, *port);+JSObject* web_streams_message_port_wrapper(void* realm, HTML::MessagePort* port)+{+ return JS::HostABI::object_to_abi(Bindings::message_port(realm_of(realm), *port).ptr());+}- return {};+void web_streams_serialize_with_transfer(Bindings::RustTransferDataWriter* writer, JSValue value)+{+ auto js_value = JS::HostABI::value_from_abi(value);+ auto result = MUST(HTML::structured_serialize_with_transfer(writer->realm, js_value, { { js_value.as_object() } }));+ writer->data_holder.extend(move(result.transfer_data_holders));+}++JSValue web_streams_deserialize_with_transfer(Bindings::RustTransferDataReader* reader)+{+ return JS::HostABI::value_to_abi(MUST(HTML::structured_deserialize_with_transfer_internal(reader->data_holder, reader->realm)));}}diff --git a/Libraries/LibWeb/Streams/ReadableStream.h b/Libraries/LibWeb/Streams/ReadableStream.hindex 864c44e24c6..cecb58b9f27 100644--- a/Libraries/LibWeb/Streams/ReadableStream.h+++ b/Libraries/LibWeb/Streams/ReadableStream.h@@ -10,140 +10,75 @@#include <AK/Forward.h>#include <LibJS/Forward.h>#include <LibWeb/Bindings/ReadableStream.h>-#include <LibWeb/Bindings/Transferable.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>#include <LibWeb/Forward.h>#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/Streams/QueuingStrategy.h>-#include <LibWeb/WebIDL/Buffers.h>+#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Streams {-// https://streams.spec.whatwg.org/#typedefdef-readablestreamreader-using ReadableStreamReader = Variant<GC::Ref<ReadableStreamDefaultReader>, GC::Ref<ReadableStreamBYOBReader>>;--// https://streams.spec.whatwg.org/#typedefdef-readablestreamcontroller-using ReadableStreamController = Variant<GC::Ref<ReadableStreamDefaultController>, GC::Ref<ReadableByteStreamController>>;--using ReadableWritablePair = Bindings::ReadableWritablePair;-using StreamPipeOptions = Bindings::StreamPipeOptions;-using ReadableStreamGetReaderOptions = Bindings::ReadableStreamGetReaderOptions;-using ReadableStreamIteratorOptions = Bindings::ReadableStreamIteratorOptions;-struct ReadableStreamPair {- // Define a couple container-like methods so this type may be used as the return type of the IDL `tee` implementation.- size_t size() const { return 2; }-- GC::Ref<ReadableStream>& at(size_t index)- {- if (index == 0)- return first;- if (index == 1)- return second;- VERIFY_NOT_REACHED();- }-GC::Ref<ReadableStream> first;GC::Ref<ReadableStream> second;};// https://streams.spec.whatwg.org/#readablestream-class ReadableStream final- : public Bindings::GCAllocatedWrappable- , public Bindings::Transferable {- WEB_WRAPPABLE(ReadableStream, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ReadableStream);+// The C++ side of a ReadableStream, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/streams): what+// the specifications that LibWeb implements in C++ use to set up and read streams,+// https://streams.spec.whatwg.org/#other-specs-rs+class WEB_API ReadableStream : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(ReadableStream, readable_stream)public:- enum class State {- Readable,- Closed,- Errored,- };-- static WebIDL::ExceptionOr<GC::Ref<ReadableStream>> create_for_constructor(JS::Object&, GC::Ptr<JS::Object> underlying_source_object, QueuingStrategy const& = {});- static WebIDL::ExceptionOr<GC::Ref<ReadableStream>> create(JS::Realm&, GC::Ptr<JS::Object> underlying_source_object, UnderlyingSource const&, QueuingStrategy const& = {});-- static WebIDL::ExceptionOr<GC::Ref<ReadableStream>> from(JS::Realm&, JS::Value async_iterable);-- virtual ~ReadableStream() override;-- bool locked() const;- GC::Ref<WebIDL::Promise> cancel(Optional<JS::Value> reason);- WebIDL::ExceptionOr<ReadableStreamReader> get_reader(ReadableStreamGetReaderOptions const& = {});- WebIDL::ExceptionOr<GC::Ref<ReadableStream>> pipe_through(ReadableWritablePair transform, StreamPipeOptions const& = {});- GC::Ref<WebIDL::Promise> pipe_to(WritableStream& destination, StreamPipeOptions const& = {});- WebIDL::ExceptionOr<GC::Ref<JS::Object>> values(ReadableStreamIteratorOptions);- WebIDL::ExceptionOr<ReadableStreamPair> tee();-- void close();- void error(JS::Value);-- Optional<ReadableStreamController>& controller() { return m_controller; }- void set_controller(Optional<ReadableStreamController> value) { m_controller = move(value); }-- JS::Value stored_error() const { return m_stored_error; }- void set_stored_error(JS::Value value) { m_stored_error = value; }-- Optional<ReadableStreamReader> const& reader() const { return m_reader; }- void set_reader(Optional<ReadableStreamReader> value) { m_reader = move(value); }+ // A new ReadableStream in the realm, which set_up_with_byte_reading_support() then sets up.+ [[nodiscard]] static GC::Ref<ReadableStream> create(JS::Realm&);- bool is_disturbed() const;- void set_disturbed(bool value) { m_disturbed = value; }+ // https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support+ void set_up_with_byte_reading_support(JS::Realm&, GC::Ptr<PullAlgorithm> = {}, GC::Ptr<CancelAlgorithm> = {}, double high_water_mark = 0);+ // https://streams.spec.whatwg.org/#readablestream-readablebool is_readable() const;++ // https://streams.spec.whatwg.org/#readablestream-closedbool is_closed() const;++ // https://streams.spec.whatwg.org/#readablestream-erroredbool is_errored() const;++ // https://streams.spec.whatwg.org/#readablestream-lockedbool is_locked() const;- State state() const { return m_state; }- void set_state(State value) { m_state = value; }+ // https://streams.spec.whatwg.org/#is-readable-stream-disturbed+ bool is_disturbed() const;- JS::Realm& realm() const { return *m_realm; }- void set_realm(JS::Realm& realm) { m_realm = realm; }- GC::Ptr<JS::Realm> result_realm() const { return m_result_realm; }- void set_result_realm(JS::Realm& realm) { m_result_realm = realm; }+ // Whether the stream's controller has been asked to close.+ bool close_requested() const;- WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> get_a_reader();+ // https://streams.spec.whatwg.org/#readablestream-enqueueWebIDL::ExceptionOr<void> enqueue(JS::Value chunk);- void set_up_with_byte_reading_support(JS::Realm&, GC::Ptr<PullAlgorithm> = {}, GC::Ptr<CancelAlgorithm> = {}, double high_water_mark = 0);- GC::Ref<ReadableStream> piped_through(GC::Ref<TransformStream>, bool prevent_close = false, bool prevent_abort = false, bool prevent_cancel = false, GC::Ptr<DOM::AbortSignal> signal = {});- Optional<WebIDL::ArrayBufferView> current_byob_request_view();+ // ReadableByteStreamControllerEnqueue on the stream's controller, a ReadableByteStreamController, with a chunk of+ // the bytes.+ WebIDL::ExceptionOr<void> enqueue_bytes(ReadonlyBytes);- // ^Transferable- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) override;- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) override;- virtual HTML::TransferType primary_interface() const override { return HTML::TransferType::ReadableStream; }--private:- ReadableStream();-- virtual void visit_edges(GC::Cell::Visitor&) override;- virtual void finalize() override;-- GC::Ptr<JS::Realm> m_realm;- GC::Ptr<JS::Realm> m_result_realm;+ // https://streams.spec.whatwg.org/#readablestream-close+ void close();- // https://streams.spec.whatwg.org/#readablestream-controller- // A ReadableStreamDefaultController or ReadableByteStreamController created with the ability to control the state and queue of this stream- Optional<ReadableStreamController> m_controller;+ // https://streams.spec.whatwg.org/#readablestream-error+ void error(JS::Value);- // https://streams.spec.whatwg.org/#readablestream-disturbed- // A boolean flag set to true when the stream has been read from or canceled- bool m_disturbed { false };+ // https://streams.spec.whatwg.org/#readable-stream-cancel+ GC::Ref<WebIDL::Promise> cancel(JS::Value reason);- // https://streams.spec.whatwg.org/#readablestream-reader- // A ReadableStreamDefaultReader or ReadableStreamBYOBReader instance, if the stream is locked to a reader, or undefined if it is not- Optional<ReadableStreamReader> m_reader;+ // https://streams.spec.whatwg.org/#readablestream-tee+ WebIDL::ExceptionOr<ReadableStreamPair> tee();- // https://streams.spec.whatwg.org/#readablestream-state- // A string containing the stream’s current state, used internally; one of "readable", "closed", or "errored"- State m_state { State::Readable };+ // https://streams.spec.whatwg.org/#readablestream-get-a-reader+ WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> get_a_reader();- // https://streams.spec.whatwg.org/#readablestream-storederror- // A value indicating how the stream failed, to be given as a failure reason or exception when trying to operate on an errored stream- JS::Value m_stored_error { JS::js_undefined() };+ // https://streams.spec.whatwg.org/#readablestream-pipe-through+ GC::Ref<ReadableStream> piped_through(GC::Ref<TransformStream>, bool prevent_close = false, bool prevent_abort = false, bool prevent_cancel = false);};}diff --git a/Libraries/LibWeb/Streams/ReadableStream.idl b/Libraries/LibWeb/Streams/ReadableStream.idlindex e65bd5cddd5..0148b65191d 100644--- a/Libraries/LibWeb/Streams/ReadableStream.idl+++ b/Libraries/LibWeb/Streams/ReadableStream.idl@@ -24,7 +24,7 @@ dictionary ReadableStreamIteratorOptions {};// https://streams.spec.whatwg.org/#readablestream-[Exposed=*, Transferable, DefinesAsyncIteratorReturn]+[Exposed=*, Transferable, DefinesAsyncIteratorReturn, ImplementedIn=Rust]interface ReadableStream {constructor(optional object underlyingSource, optional QueuingStrategy strategy = {});diff --git a/Libraries/LibWeb/Streams/ReadableStreamAsyncIterator.cpp b/Libraries/LibWeb/Streams/ReadableStreamAsyncIterator.cppdeleted file mode 100644index 4fd81c0f490..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamAsyncIterator.cpp+++ /dev/null@@ -1,153 +0,0 @@-/*- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/HostClassBuilder.h>-#include <LibWeb/Bindings/Intrinsics.h>-#include <LibWeb/Bindings/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamAsyncIterator.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(ReadableStreamAsyncIterator);--static constexpr JSHostClass readable_stream_async_iterator_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "ReadableStreamAsyncIterator"sv, nullptr, nullptr, nullptr, 0);--ReadableStreamAsyncIterator::ReadableStreamAsyncIterator(JS::Realm& realm, JS::Object::PropertyKind kind, GC::Ref<ReadableStreamDefaultReader> reader, bool prevent_cancel)- : AsyncIterator(realm, kind)- , m_reader(reader)- , m_prevent_cancel(prevent_cancel)-{-}--ReadableStreamAsyncIterator::~ReadableStreamAsyncIterator() = default;--// https://streams.spec.whatwg.org/#ref-for-asynchronous-iterator-initialization-steps-WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> ReadableStreamAsyncIterator::create(JS::Realm& realm, JS::Object::PropertyKind kind, ReadableStream& stream, Options options)-{- // 1. Let reader be ? AcquireReadableStreamDefaultReader(stream).- // 2. Set iterator’s reader to reader.- auto reader = TRY(acquire_readable_stream_default_reader(realm, stream));-- // 3. Let preventCancel be args[0]["preventCancel"].- // 4. Set iterator’s prevent cancel to preventCancel.- auto iterator = realm.create<ReadableStreamAsyncIterator>(realm, kind, reader, options.prevent_cancel);-- static auto const& prototype_name = "ReadableStreamAsyncIterator"_utf16_fly_string;- auto& prototype = Bindings::ensure_web_prototype<Bindings::ReadableStreamAsyncIteratorPrototype>(realm, prototype_name);- return JS::HostObject::create(realm, readable_stream_async_iterator_host_class, prototype, {}, iterator);-}--void ReadableStreamAsyncIterator::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_reader);-}--class ReadableStreamAsyncIteratorReadRequest final : public ReadRequest {- GC_CELL(ReadableStreamAsyncIteratorReadRequest, ReadRequest);- GC_DECLARE_ALLOCATOR(ReadableStreamAsyncIteratorReadRequest);--public:- ReadableStreamAsyncIteratorReadRequest(ReadableStreamDefaultReader& reader, WebIDL::Promise& promise)- : m_reader(reader)- , m_promise(promise)- {- }-- // chunk steps, given chunk- virtual void on_chunk(JS::Value chunk) override- {- // 1. Resolve promise with chunk.- WebIDL::resolve_promise(m_promise, chunk);- }-- // close steps- virtual void on_close() override- {- // 1. Perform ! ReadableStreamDefaultReaderRelease(reader).- readable_stream_default_reader_release(m_reader);-- // 2. Resolve promise with end of iteration.- WebIDL::resolve_promise(m_promise, JS::js_special_empty_value());- }-- // error steps, given e- virtual void on_error(JS::Value error) override- {- // 1. Perform ! ReadableStreamDefaultReaderRelease(reader).- readable_stream_default_reader_release(m_reader);-- // 2. Reject promise with e.- WebIDL::reject_promise(m_promise, error);- }-- virtual void visit_edges(Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(m_reader);- visitor.visit(m_promise);- }-- GC::Ref<ReadableStreamDefaultReader> m_reader;- GC::Ref<WebIDL::Promise> m_promise;-};--GC_DEFINE_ALLOCATOR(ReadableStreamAsyncIteratorReadRequest);--// https://streams.spec.whatwg.org/#ref-for-dfn-get-the-next-iteration-result-GC::Ref<WebIDL::Promise> ReadableStreamAsyncIterator::next_iteration_result(JS::Realm& realm)-{- // 1. Let reader be iterator’s reader.- // 2. Assert: reader.[[stream]] is not undefined.- VERIFY(m_reader->stream());-- // 3. Let promise be a new promise.- auto promise = WebIDL::create_promise(realm);-- // 4. Let readRequest be a new read request with the following items:- auto read_request = GC::Heap::the().allocate<ReadableStreamAsyncIteratorReadRequest>(m_reader, promise);-- // 5. Perform ! ReadableStreamDefaultReaderRead(this, readRequest).- readable_stream_default_reader_read(m_reader, read_request);-- // 6. Return promise.- return promise;-}--// https://streams.spec.whatwg.org/#ref-for-asynchronous-iterator-return-GC::Ref<WebIDL::Promise> ReadableStreamAsyncIterator::iterator_return(JS::Realm& realm, JS::Value arg)-{- // 1. Let reader be iterator’s reader.- // 2. Assert: reader.[[stream]] is not undefined.- VERIFY(m_reader->stream());-- // 3. Assert: reader.[[readRequests]] is empty, as the async iterator machinery guarantees that any previous calls- // to next() have settled before this is called.- VERIFY(m_reader->read_requests().is_empty());-- // 4. If iterator’s prevent cancel is false:- if (!m_prevent_cancel) {- // 1. Let result be ! ReadableStreamReaderGenericCancel(reader, arg).- auto result = readable_stream_reader_generic_cancel(m_reader, arg);-- // 2. Perform ! ReadableStreamDefaultReaderRelease(reader).- readable_stream_default_reader_release(m_reader);-- // 3. Return result.- return result;- }-- // 5. Perform ! ReadableStreamDefaultReaderRelease(reader).- readable_stream_default_reader_release(m_reader);-- // 6. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamAsyncIterator.h b/Libraries/LibWeb/Streams/ReadableStreamAsyncIterator.hdeleted file mode 100644index 20ba7e483b7..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamAsyncIterator.h+++ /dev/null@@ -1,38 +0,0 @@-/*- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Bindings/ReadableStream.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/AsyncIterator.h>--namespace Web::Streams {--class ReadableStreamAsyncIterator final : public WebIDL::AsyncIterator {- GC_CELL(ReadableStreamAsyncIterator, WebIDL::AsyncIterator);- GC_DECLARE_ALLOCATOR(ReadableStreamAsyncIterator);--public:- using Options = Bindings::ReadableStreamIteratorOptions;-- static WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create(JS::Realm&, JS::Object::PropertyKind, ReadableStream&, Options);-- virtual ~ReadableStreamAsyncIterator() override;--private:- ReadableStreamAsyncIterator(JS::Realm&, JS::Object::PropertyKind, GC::Ref<ReadableStreamDefaultReader>, bool prevent_cancel);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- virtual GC::Ref<WebIDL::Promise> next_iteration_result(JS::Realm&) override;- virtual GC::Ref<WebIDL::Promise> iterator_return(JS::Realm&, JS::Value) override;-- GC::Ref<ReadableStreamDefaultReader> m_reader;- bool m_prevent_cancel { false };-};--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.cpp b/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.cppdeleted file mode 100644index f894c83ac8c..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.cpp+++ /dev/null@@ -1,173 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamBYOBReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(ReadableStreamBYOBReader);--ReadableStreamBYOBReader::ReadableStreamBYOBReader()-{-}--// https://streams.spec.whatwg.org/#byob-reader-constructor-WebIDL::ExceptionOr<GC::Ref<ReadableStreamBYOBReader>> ReadableStreamBYOBReader::create(JS::Realm& realm, GC::Ref<ReadableStream> stream)-{- auto reader = GC::Heap::the().allocate<ReadableStreamBYOBReader>();-- // 1. Perform ? SetUpReadableStreamBYOBReader(this, stream).- TRY(set_up_readable_stream_byob_reader(realm, reader, *stream));-- return reader;-}--// https://streams.spec.whatwg.org/#byob-reader-release-lock-void ReadableStreamBYOBReader::release_lock()-{- // 1. If this.[[stream]] is undefined, return.- if (!m_stream)- return;-- // 2. Perform ! ReadableStreamBYOBReaderRelease(this).- readable_stream_byob_reader_release(*this);-}--void ReadableStreamBYOBReader::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- ReadableStreamGenericReaderMixin::visit_edges(visitor);- visitor.visit(m_read_into_requests);-}--class BYOBReaderReadIntoRequest : public ReadIntoRequest {- GC_CELL(BYOBReaderReadIntoRequest, ReadIntoRequest);- GC_DECLARE_ALLOCATOR(BYOBReaderReadIntoRequest);--public:- explicit BYOBReaderReadIntoRequest(WebIDL::Promise& promise)- : m_promise(promise)- {- }-- // chunk steps, given chunk- virtual void on_chunk(JS::Value chunk) override- {- auto& realm = WebIDL::promise_realm(m_promise);-- // 1. Resolve promise with «[ "value" → chunk, "done" → false ]».- WebIDL::resolve_promise(m_promise, JS::create_iterator_result_object(realm.vm(), chunk, false));- }-- // close steps, given chunk- virtual void on_close(JS::Value chunk) override- {- auto& realm = WebIDL::promise_realm(m_promise);-- // 1. Resolve promise with «[ "value" → chunk, "done" → true ]».- WebIDL::resolve_promise(m_promise, JS::create_iterator_result_object(realm.vm(), chunk, true));- }-- // error steps, given e- virtual void on_error(JS::Value error) override- {- // 1. Reject promise with e.- WebIDL::reject_promise(m_promise, error);- }--private:- virtual void visit_edges(Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(m_promise);- }-- GC::Ref<WebIDL::Promise> m_promise;-};--GC_DEFINE_ALLOCATOR(BYOBReaderReadIntoRequest);--// https://streams.spec.whatwg.org/#byob-reader-read-GC::Ref<WebIDL::Promise> ReadableStreamBYOBReader::read(WebIDL::ArrayBufferView view, ReadableStreamBYOBReaderReadOptions options)-{- auto& realm = closed_promise_realm();-- // 1. If view.[[ByteLength]] is 0, return a promise rejected with a TypeError exception.- if (view.byte_length() == 0) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "Cannot read in an empty buffer"_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }-- // 2. If view.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]] is 0, return a promise rejected with a TypeError exception.- if (view.viewed_array_buffer()->byte_length() == 0) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "Cannot read in an empty buffer"_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }-- // 3. If ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is true, return a promise rejected with a TypeError exception.- if (view.viewed_array_buffer()->is_detached()) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "Cannot read in a detached buffer"_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }-- // 4. If options["min"] is 0, return a promise rejected with a TypeError exception.- if (options.min == 0) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "options[\"min\'] cannot have a value of 0."_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }-- // 5. If view has a [[TypedArrayName]] internal slot,- if (auto typed_array = view.typed_array_base()) {- // 1. If options["min"] > view.[[ArrayLength]], return a promise rejected with a RangeError exception.- if (options.min > typed_array->array_length().length()) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::RangeError, "options[\"min\"] cannot be larger than the length of the view."_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }- }- // 6. Otherwise (i.e., it is a DataView),- else {- VERIFY(view.array_buffer_view().has<GC::Ref<JS::DataView>>());- // 1. If options["min"] > view.[[ByteLength]], return a promise rejected with a RangeError exception.- if (options.min > view.byte_length()) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::RangeError, "options[\"min\"] cannot be larger than the length of the view."_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }- }-- // 7. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.- if (!m_stream) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "Cannot read from an empty stream"_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }-- // 8. Let promise be a new promise.- auto promise_capability = WebIDL::create_promise(realm);-- // 9. Let readIntoRequest be a new read-into request with the following items:- // chunk steps, given chunk- // Resolve promise with «[ "value" → chunk, "done" → false ]».- // close steps, given chunk- // Resolve promise with «[ "value" → chunk, "done" → true ]».- // error steps, given e- // Reject promise with e.- auto read_into_request = GC::Heap::the().allocate<BYOBReaderReadIntoRequest>(promise_capability);-- // 10. Perform ! ReadableStreamBYOBReaderRead(this, view, options["min"], readIntoRequest).- readable_stream_byob_reader_read(*this, view, options.min, *read_into_request);-- // 11. Return promise.- return promise_capability;-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.h b/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.hdeleted file mode 100644index f18769a3f66..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.h+++ /dev/null@@ -1,69 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Forward.h>-#include <AK/Function.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/ReadableStreamBYOBReader.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/ReadableStreamGenericReader.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWebCommon/WebIDL/Types.h>--namespace Web::Streams {--using ReadableStreamBYOBReaderReadOptions = Bindings::ReadableStreamBYOBReaderReadOptions;--// https://streams.spec.whatwg.org/#read-into-request-class ReadIntoRequest : public JS::Cell {- GC_CELL(ReadIntoRequest, JS::Cell);--public:- virtual ~ReadIntoRequest() = default;-- // An algorithm taking a chunk, called when a chunk is available for reading- virtual void on_chunk(JS::Value chunk) = 0;-- // An algorithm taking a chunk or undefined, called when no chunks are available because the stream is closed- virtual void on_close(JS::Value chunk_or_undefined) = 0;-- // An algorithm taking a JavaScript value, called when no chunks are available because the stream is errored- virtual void on_error(JS::Value error) = 0;-};--// https://streams.spec.whatwg.org/#readablestreambyobreader-class ReadableStreamBYOBReader final- : public Bindings::GCAllocatedWrappable- , public ReadableStreamGenericReaderMixin {- WEB_WRAPPABLE(ReadableStreamBYOBReader, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ReadableStreamBYOBReader);--public:- static WebIDL::ExceptionOr<GC::Ref<ReadableStreamBYOBReader>> create(JS::Realm&, GC::Ref<ReadableStream>);-- virtual ~ReadableStreamBYOBReader() override = default;-- GC::Ref<WebIDL::Promise> read(WebIDL::ArrayBufferView, ReadableStreamBYOBReaderReadOptions options = {});-- void release_lock();-- Vector<GC::Ref<ReadIntoRequest>>& read_into_requests() { return m_read_into_requests; }--private:- ReadableStreamBYOBReader();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#readablestreambyobreader-readintorequests- // A list of read-into requests, used when a consumer requests chunks sooner than they are available- Vector<GC::Ref<ReadIntoRequest>> m_read_into_requests;-};--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.idl b/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.idlindex 2234ee5ff16..b1c633503c2 100644--- a/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.idl+++ b/Libraries/LibWeb/Streams/ReadableStreamBYOBReader.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#readablestreambyobreader- [Exposed=*]+ [Exposed=*, ImplementedIn=Rust]interface ReadableStreamBYOBReader {constructor(ReadableStream stream);diff --git a/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.cpp b/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.cppdeleted file mode 100644index bec4275acce..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.cpp+++ /dev/null@@ -1,65 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibJS/Runtime/DataView.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>-#include <LibWeb/Streams/ReadableStreamBYOBRequest.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/WebIDL/Buffers.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(ReadableStreamBYOBRequest);--void ReadableStreamBYOBRequest::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_controller);- visitor.visit(m_view);-}--// https://streams.spec.whatwg.org/#rs-byob-request-respond-WebIDL::ExceptionOr<void> ReadableStreamBYOBRequest::respond(JS::Realm& realm, WebIDL::UnsignedLongLong bytes_written)-{- // 1. If this.[[controller]] is undefined, throw a TypeError exception.- if (!m_controller)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Controller is undefined"_utf16 };-- // 2. If ! IsDetachedBuffer(this.[[view]].[[ArrayBuffer]]) is true, throw a TypeError exception.- VERIFY(m_view);- if (m_view->viewed_array_buffer()->is_detached())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Unable to respond to detached ArrayBuffer"_utf16 };-- // 3. Assert: this.[[view]].[[ByteLength]] > 0.- VERIFY(m_view->viewed_array_buffer()->byte_length() > 0);-- // 4. Assert: this.[[view]].[[ViewedArrayBuffer]].[[ByteLength]] > 0.- VERIFY(m_view->viewed_array_buffer()->byte_length() > 0);-- // 5. Perform ? ReadableByteStreamControllerRespond(this.[[controller]], bytesWritten).- return readable_byte_stream_controller_respond(realm, *m_controller, bytes_written);-}--// https://streams.spec.whatwg.org/#rs-byob-request-respond-with-new-view-WebIDL::ExceptionOr<void> ReadableStreamBYOBRequest::respond_with_new_view(JS::Realm& realm, WebIDL::ArrayBufferViewVariant const& view)-{- WebIDL::ArrayBufferView array_buffer_view { view };-- // 1. If this.[[controller]] is undefined, throw a TypeError exception.- if (!m_controller)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Controller is undefined"_utf16 };-- // 2. If ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is true, throw a TypeError exception.- if (array_buffer_view.viewed_array_buffer()->is_detached())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Unable to respond with a detached ArrayBuffer"_utf16 };-- // 3. Return ? ReadableByteStreamControllerRespondWithNewView(this.[[controller]], view).- return TRY(readable_byte_stream_controller_respond_with_new_view(realm, *m_controller, array_buffer_view));-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.h b/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.hdeleted file mode 100644index 39f71fa093a..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWebCommon/WebIDL/Types.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#readablestreambyobrequest-class ReadableStreamBYOBRequest : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(ReadableStreamBYOBRequest, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ReadableStreamBYOBRequest);--public:- virtual ~ReadableStreamBYOBRequest() override = default;-- GC::Ptr<JS::Uint8Array> view() const { return m_view; }- void set_view(GC::Ptr<JS::Uint8Array> value) { m_view = value; }-- void set_controller(GC::Ptr<ReadableByteStreamController> value) { m_controller = value; }-- WebIDL::ExceptionOr<void> respond(JS::Realm&, WebIDL::UnsignedLongLong bytes_written);- WebIDL::ExceptionOr<void> respond_with_new_view(JS::Realm&, WebIDL::ArrayBufferViewVariant const& view);--private:- ReadableStreamBYOBRequest() = default;-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#readablestreambyobrequest-controller- // The parent ReadableByteStreamController instance- GC::Ptr<ReadableByteStreamController> m_controller;-- // https://streams.spec.whatwg.org/#readablestreambyobrequest-view- // A typed array representing the destination region to which the controller can write generated data, or null after the BYOB request has been invalidated.- GC::Ptr<JS::Uint8Array> m_view;-};--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.idl b/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.idlindex eccb457d3c4..cedc08c635a 100644--- a/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.idl+++ b/Libraries/LibWeb/Streams/ReadableStreamBYOBRequest.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#readablestreambyobrequest-[Exposed=*]+[Exposed=*, ImplementedIn=Rust]interface ReadableStreamBYOBRequest {readonly attribute Uint8Array? view;diff --git a/Libraries/LibWeb/Streams/ReadableStreamDefaultController.cpp b/Libraries/LibWeb/Streams/ReadableStreamDefaultController.cppdeleted file mode 100644index 543ee84fde7..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamDefaultController.cpp+++ /dev/null@@ -1,134 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(ReadableStreamDefaultController);--ReadableStreamDefaultController::ReadableStreamDefaultController()-{-}--// https://streams.spec.whatwg.org/#rs-default-controller-desired-size-Optional<double> ReadableStreamDefaultController::desired_size()-{- // 1. Return ! ReadableStreamDefaultControllerGetDesiredSize(this).- return readable_stream_default_controller_get_desired_size(*this);-}--// https://streams.spec.whatwg.org/#rs-default-controller-close-WebIDL::ExceptionOr<void> ReadableStreamDefaultController::close()-{- // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false, throw a TypeError exception.- if (!readable_stream_default_controller_can_close_or_enqueue(*this)) {- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is not closable"_utf16 };- }-- // 2. Perform ! ReadableStreamDefaultControllerClose(this).- readable_stream_default_controller_close(*this);-- return {};-}--// https://streams.spec.whatwg.org/#rs-default-controller-enqueue-WebIDL::ExceptionOr<void> ReadableStreamDefaultController::enqueue(JS::Realm& realm, Optional<JS::Value> chunk)-{- // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false, throw a TypeError exception.- if (!readable_stream_default_controller_can_close_or_enqueue(*this))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot enqueue chunk to stream"_utf16 };-- // 2. Perform ? ReadableStreamDefaultControllerEnqueue(this, chunk).- TRY(readable_stream_default_controller_enqueue(realm, *this, chunk.value_or(JS::js_undefined())));-- return {};-}--// https://streams.spec.whatwg.org/#rs-default-controller-error-void ReadableStreamDefaultController::error(Optional<JS::Value> error)-{- // 1. Perform ! ReadableStreamDefaultControllerError(this, e).- readable_stream_default_controller_error(*this, error.value_or(JS::js_undefined()));-}--// https://streams.spec.whatwg.org/#rs-default-controller-private-cancel-GC::Ref<WebIDL::Promise> ReadableStreamDefaultController::cancel_steps(JS::Value reason)-{- // 1. Perform ! ResetQueue(this).- reset_queue(*this);-- // 2. Let result be the result of performing this.[[cancelAlgorithm]], passing reason.- auto result = cancel_algorithm()->function()(reason);-- // 3. Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).- readable_stream_default_controller_clear_algorithms(*this);-- // 4. Return result.- return result;-}--// https://streams.spec.whatwg.org/#rs-default-controller-private-pull-void ReadableStreamDefaultController::pull_steps(Web::Streams::ReadRequest& read_request)-{- // 1. Let stream be this.[[stream]].- auto& stream = *m_stream;-- // 2. If this.[[queue]] is not empty,- if (!m_queue.is_empty()) {- // 1. Let chunk be ! DequeueValue(this).- auto chunk = dequeue_value(*this);-- // 2. If this.[[closeRequested]] is true and this.[[queue]] is empty,- if (m_close_requested && m_queue.is_empty()) {- // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).- readable_stream_default_controller_clear_algorithms(*this);-- // 2. Perform ! ReadableStreamClose(stream).- readable_stream_close(stream);- }- // 3. Otherwise, perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).- else {- readable_stream_default_controller_call_pull_if_needed(*this);- }-- // 4. Perform readRequest’s chunk steps, given chunk.- read_request.on_chunk(chunk);- }- // 3. Otherwise,- else {- // 1. Perform ! ReadableStreamAddReadRequest(stream, readRequest).- readable_stream_add_read_request(stream, read_request);-- // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).- readable_stream_default_controller_call_pull_if_needed(*this);- }-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultcontroller-releasesteps-void ReadableStreamDefaultController::release_steps()-{- // 1. Return.-}--void ReadableStreamDefaultController::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- for (auto const& item : m_queue)- visitor.visit(item.value);- visitor.visit(m_stream);- visitor.visit(m_cancel_algorithm);- visitor.visit(m_pull_algorithm);- visitor.visit(m_strategy_size_algorithm);-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamDefaultController.h b/Libraries/LibWeb/Streams/ReadableStreamDefaultController.hdeleted file mode 100644index e4dfcca357a..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamDefaultController.h+++ /dev/null@@ -1,119 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Forward.h>-#include <AK/Optional.h>-#include <AK/SinglyLinkedList.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-class ReadableStreamDefaultController : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(ReadableStreamDefaultController, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ReadableStreamDefaultController);--public:- ReadableStreamDefaultController();- virtual ~ReadableStreamDefaultController() override = default;-- Optional<double> desired_size();-- WebIDL::ExceptionOr<void> close();- WebIDL::ExceptionOr<void> enqueue(JS::Realm&, Optional<JS::Value> chunk);- void error(Optional<JS::Value> error);-- GC::Ptr<CancelAlgorithm> cancel_algorithm() { return m_cancel_algorithm; }- void set_cancel_algorithm(GC::Ptr<CancelAlgorithm> value) { m_cancel_algorithm = value; }-- bool close_requested() const { return m_close_requested; }- void set_close_requested(bool value) { m_close_requested = value; }-- bool pull_again() const { return m_pull_again; }- void set_pull_again(bool value) { m_pull_again = value; }-- GC::Ptr<PullAlgorithm> pull_algorithm() { return m_pull_algorithm; }- void set_pull_algorithm(GC::Ptr<PullAlgorithm> value) { m_pull_algorithm = value; }-- bool pulling() const { return m_pulling; }- void set_pulling(bool value) { m_pulling = value; }-- SinglyLinkedList<ValueWithSize>& queue() { return m_queue; }-- double queue_total_size() const { return m_queue_total_size; }- void set_queue_total_size(double value) { m_queue_total_size = value; }-- bool started() const { return m_started; }- void set_started(bool value) { m_started = value; }-- double strategy_hwm() const { return m_strategy_hwm; }- void set_strategy_hwm(double value) { m_strategy_hwm = value; }-- GC::Ptr<SizeAlgorithm> strategy_size_algorithm() { return m_strategy_size_algorithm; }- void set_strategy_size_algorithm(GC::Ptr<SizeAlgorithm> value) { m_strategy_size_algorithm = value; }-- GC::Ptr<ReadableStream> stream() { return m_stream; }- void set_stream(GC::Ptr<ReadableStream> value) { m_stream = value; }-- GC::Ref<WebIDL::Promise> cancel_steps(JS::Value reason);- void pull_steps(ReadRequest&);- void release_steps();--private:- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-cancelalgorithm- // A promise-returning algorithm, taking one argument (the cancel reason), which communicates a requested cancelation to the underlying source- GC::Ptr<CancelAlgorithm> m_cancel_algorithm;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-closerequested- // A boolean flag indicating whether the stream has been closed by its underlying source, but still has chunks in its internal queue that have not yet been read- bool m_close_requested { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullagain- // A boolean flag set to true if the stream’s mechanisms requested a call to the underlying source's pull algorithm to pull more data, but the pull could not yet be done since a previous call is still executing- bool m_pull_again { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pullalgorithm- // A promise-returning algorithm that pulls data from the underlying source- GC::Ptr<PullAlgorithm> m_pull_algorithm;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-pulling- // A boolean flag set to true while the underlying source's pull algorithm is executing and the returned promise has not yet fulfilled, used to prevent reentrant calls- bool m_pulling { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-queue- // A list representing the stream’s internal queue of chunks- SinglyLinkedList<ValueWithSize> m_queue;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-queuetotalsize- // The total size of all the chunks stored in [[queue]]- double m_queue_total_size { 0 };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-started- // A boolean flag indicating whether the underlying source has finished starting- bool m_started { false };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-strategyhwm- // A number supplied to the constructor as part of the stream’s queuing strategy, indicating the point at which the stream will apply backpressure to its underlying source- double m_strategy_hwm { 0 };-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-strategysizealgorithm- // An algorithm to calculate the size of enqueued chunks, as part of the stream’s queuing strategy- GC::Ptr<SizeAlgorithm> m_strategy_size_algorithm;-- // https://streams.spec.whatwg.org/#readablestreamdefaultcontroller-stream- // The ReadableStream instance controlled- GC::Ptr<ReadableStream> m_stream;-};--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamDefaultController.idl b/Libraries/LibWeb/Streams/ReadableStreamDefaultController.idlindex 9d68fbca443..07d3562d14e 100644--- a/Libraries/LibWeb/Streams/ReadableStreamDefaultController.idl+++ b/Libraries/LibWeb/Streams/ReadableStreamDefaultController.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller- [Exposed=*]+ [Exposed=*, ImplementedIn=Rust]interface ReadableStreamDefaultController {readonly attribute unrestricted double? desiredSize;diff --git a/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cpp b/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cppdeleted file mode 100644index d5e16cf6a47..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.cpp+++ /dev/null@@ -1,248 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/Error.h>-#include <LibJS/Runtime/Iterator.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibJS/Runtime/Realm.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Fetch/Infrastructure/IncrementalReadLoopReadRequest.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(ReadableStreamDefaultReader);-GC_DEFINE_ALLOCATOR(ReadLoopReadRequest);--// https://streams.spec.whatwg.org/#default-reader-constructor-WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> ReadableStreamDefaultReader::create(JS::Realm& realm, GC::Ref<ReadableStream> stream)-{- auto reader = GC::Heap::the().allocate<ReadableStreamDefaultReader>();-- // 1. Perform ? SetUpReadableStreamDefaultReader(this, stream);- TRY(set_up_readable_stream_default_reader(realm, reader, *stream));-- return reader;-}--ReadableStreamDefaultReader::ReadableStreamDefaultReader()-{-}--void ReadableStreamDefaultReader::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- ReadableStreamGenericReaderMixin::visit_edges(visitor);- for (auto& request : m_read_requests)- visitor.visit(request);- visitor.visit(m_readable_stream_pipe_to_operation);-}--// https://streams.spec.whatwg.org/#read-loop-ReadLoopReadRequest::ReadLoopReadRequest(JS::Realm& realm, ReadableStreamDefaultReader& reader, GC::Ref<SuccessSteps> success_steps, GC::Ref<FailureSteps> failure_steps)- : m_realm(realm)- , m_reader(reader)- , m_success_steps(success_steps)- , m_failure_steps(failure_steps)-{-}--void ReadLoopReadRequest::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_realm);- visitor.visit(m_reader);- visitor.visit(m_success_steps);- visitor.visit(m_failure_steps);-}--// chunk steps, given chunk-void ReadLoopReadRequest::on_chunk(JS::Value chunk)-{- // 1. If chunk is not a Uint8Array object, call failureSteps with a TypeError and abort these steps.- if (!chunk.is_object() || !is<JS::Uint8Array>(chunk.as_object())) {- m_failure_steps->function()(JS::TypeError::create(m_realm, "Chunk data is not Uint8Array"sv));- return;- }-- auto const& array = static_cast<JS::Uint8Array const&>(chunk.as_object());-- // 2. Append the bytes represented by chunk to bytes.- auto record = JS::make_typed_array_with_buffer_witness_record(array, JS::ArrayBuffer::Order::Unordered);- auto byte_length = JS::typed_array_byte_length(record);- if (byte_length > 0) {- // NB: Since a chunk is whatever the stream enqueued, and enqueue() takes an 'any', this Uint8Array may well be- // a view onto an SAB with no conversion having had the chance to reject one. So, use with_readonly_bytes()- // to read it through — rather than handing over a pointer into memory that another agent can be writing.- array.viewed_array_buffer()->with_readonly_bytes(array.byte_offset(), byte_length, [&](ReadonlyBytes bytes) {- m_bytes.append(bytes);- });- }-- // FIXME: As the spec suggests, implement this non-recursively - instead of directly. It is not too big of a deal currently- // as we enqueue the entire blob buffer in one go, meaning that we only recurse a single time. Once we begin queuing- // up more than one chunk at a time, we may run into stack overflow problems.- //- // 3. Read-loop given reader, bytes, successSteps, and failureSteps.- readable_stream_default_reader_read(m_reader, *this);-}--// close steps-void ReadLoopReadRequest::on_close()-{- // 1. Call successSteps with bytes.- m_success_steps->function()(move(m_bytes));-}--// error steps, given e-void ReadLoopReadRequest::on_error(JS::Value error)-{- // 1. Call failureSteps with e.- m_failure_steps->function()(error);-}--class DefaultReaderReadRequest final : public ReadRequest {- GC_CELL(DefaultReaderReadRequest, ReadRequest);- GC_DECLARE_ALLOCATOR(DefaultReaderReadRequest);--public:- DefaultReaderReadRequest(WebIDL::Promise& promise, GC::Ptr<JS::Realm> result_realm)- : m_promise(promise)- , m_result_realm(result_realm)- {- }-- virtual void on_chunk(JS::Value chunk) override- {- if (m_result_realm) {- WebIDL::resolve_promise(m_promise, JS::create_iterator_result_object(*m_result_realm, chunk, false));- } else {- auto& realm = WebIDL::promise_realm(m_promise);- WebIDL::resolve_promise(m_promise, JS::create_iterator_result_object(realm.vm(), chunk, false));- }- }-- virtual void on_close() override- {- if (m_result_realm) {- WebIDL::resolve_promise(m_promise, JS::create_iterator_result_object(*m_result_realm, JS::js_undefined(), true));- } else {- auto& realm = WebIDL::promise_realm(m_promise);- WebIDL::resolve_promise(m_promise, JS::create_iterator_result_object(realm.vm(), JS::js_undefined(), true));- }- }-- virtual void on_error(JS::Value error) override- {- WebIDL::reject_promise(m_promise, error);- }--private:- virtual void visit_edges(Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(m_promise);- visitor.visit(m_result_realm);- }-- GC::Ref<WebIDL::Promise> m_promise;- GC::Ptr<JS::Realm> m_result_realm;-};--GC_DEFINE_ALLOCATOR(DefaultReaderReadRequest);--// https://streams.spec.whatwg.org/#default-reader-read-GC::Ref<WebIDL::Promise> ReadableStreamDefaultReader::read()-{- auto& realm = closed_promise_realm();-- // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.- if (!m_stream) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "Cannot read from an empty stream"_utf16 };- return WebIDL::create_rejected_promise_from_exception(realm, move(exception));- }-- // 2. Let promise be a new promise.- auto promise_capability = WebIDL::create_promise(realm);-- // 3. Let readRequest be a new read request with the following items:- // chunk steps, given chunk- // Resolve promise with «[ "value" → chunk, "done" → false ]».- // close steps- // Resolve promise with «[ "value" → undefined, "done" → true ]».- // error steps, given e- // Reject promise with e.- auto read_request = GC::Heap::the().allocate<DefaultReaderReadRequest>(promise_capability, m_stream->result_realm());-- // 4. Perform ! ReadableStreamDefaultReaderRead(this, readRequest).- readable_stream_default_reader_read(*this, read_request);-- // 5. Return promise.- return promise_capability;-}--void ReadableStreamDefaultReader::read_a_chunk(Fetch::Infrastructure::IncrementalReadLoopReadRequest& read_request)-{- // To read a chunk from a ReadableStreamDefaultReader reader, given a read request readRequest,- // perform ! ReadableStreamDefaultReaderRead(reader, readRequest).- readable_stream_default_reader_read(*this, read_request);-}--// https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes-void ReadableStreamDefaultReader::read_all_bytes(GC::Ref<ReadLoopReadRequest::SuccessSteps> success_steps, GC::Ref<ReadLoopReadRequest::FailureSteps> failure_steps)-{- auto& realm = closed_promise_realm();-- // 1. Let readRequest be a new read request with the following items:- // NOTE: items and steps in ReadLoopReadRequest.- auto read_request = GC::Heap::the().allocate<ReadLoopReadRequest>(realm, *this, success_steps, failure_steps);-- // 2. Perform ! ReadableStreamDefaultReaderRead(this, readRequest).- readable_stream_default_reader_read(*this, read_request);-}--// FIXME: This function is a promise-based wrapper around "read all bytes". The spec changed this function to not use promises-// in https://github.com/whatwg/streams/commit/f894acdd417926a2121710803cef593e15127964 - however, it seems that the-// FileAPI blob specification has not been updated to match, see: https://github.com/w3c/FileAPI/issues/187.-GC::Ref<WebIDL::Promise> ReadableStreamDefaultReader::read_all_bytes_deprecated()-{- auto& realm = closed_promise_realm();-- auto promise = WebIDL::create_promise(realm);-- auto success_steps = GC::create_function(GC::Heap::the(), [promise, &realm](ByteBuffer bytes) {- auto buffer = JS::ArrayBuffer::create(realm, move(bytes));- WebIDL::resolve_promise(promise, buffer);- });-- auto failure_steps = GC::create_function(GC::Heap::the(), [promise](JS::Value error) {- WebIDL::reject_promise(promise, error);- });-- read_all_bytes(success_steps, failure_steps);-- return promise;-}--// https://streams.spec.whatwg.org/#default-reader-release-lock-void ReadableStreamDefaultReader::release_lock()-{- // 1. If this.[[stream]] is undefined, return.- if (!m_stream)- return;-- // 2. Perform ! ReadableStreamDefaultReaderRelease(this).- readable_stream_default_reader_release(*this);-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.h b/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.hindex 2eb8c94e0cf..7cbcf7b3af3 100644--- a/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.h+++ b/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.h@@ -6,96 +6,59 @@#pragma once-#include <AK/Function.h>-#include <AK/SinglyLinkedList.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <AK/ByteBuffer.h>+#include <LibGC/Function.h>+#include <LibJS/Heap/Cell.h>+#include <LibJS/Runtime/Value.h>+#include <LibWeb/Bindings/ReadableStreamDefaultReader.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>#include <LibWeb/Forward.h>-#include <LibWeb/Streams/ReadableStreamGenericReader.h>+#include <LibWeb/WebIDL/Promise.h>namespace Web::Streams {-struct ReadableStreamReadResult {- JS::Value value;- bool done;-};--namespace Detail {--class ReadableStreamPipeTo;--}--class ReadRequest : public JS::Cell {+// https://streams.spec.whatwg.org/#read-request+class WEB_API ReadRequest : public JS::Cell {GC_CELL(ReadRequest, JS::Cell);public:- virtual ~ReadRequest() = default;+ virtual ~ReadRequest() override = default;virtual void on_chunk(JS::Value chunk) = 0;virtual void on_close() = 0;virtual void on_error(JS::Value error) = 0;};-class ReadLoopReadRequest final : public ReadRequest {- GC_CELL(ReadLoopReadRequest, ReadRequest);- GC_DECLARE_ALLOCATOR(ReadLoopReadRequest);+// https://streams.spec.whatwg.org/#readablestreamdefaultreader+// The C++ side of a ReadableStreamDefaultReader, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/streams):+// what the specifications that LibWeb implements in C++ use to read streams.+class WEB_API ReadableStreamDefaultReader : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(ReadableStreamDefaultReader, readable_stream_default_reader)public:- // successSteps, which is an algorithm accepting a byte sequenceusing SuccessSteps = GC::Function<void(ByteBuffer)>;-- // failureSteps, which is an algorithm accepting a JavaScript valueusing FailureSteps = GC::Function<void(JS::Value error)>;-private:- ReadLoopReadRequest(JS::Realm&, ReadableStreamDefaultReader&, GC::Ref<SuccessSteps>, GC::Ref<FailureSteps>);-- virtual void visit_edges(Visitor&) override;-- virtual void on_chunk(JS::Value chunk) override;- virtual void on_close() override;- virtual void on_error(JS::Value error) override;-- GC::Ref<JS::Realm> m_realm;- GC::Ref<ReadableStreamDefaultReader> m_reader;- ByteBuffer m_bytes;- GC::Ref<SuccessSteps> m_success_steps;- GC::Ref<FailureSteps> m_failure_steps;-};--// https://streams.spec.whatwg.org/#readablestreamdefaultreader-class ReadableStreamDefaultReader final- : public Bindings::GCAllocatedWrappable- , public ReadableStreamGenericReaderMixin {- WEB_WRAPPABLE(ReadableStreamDefaultReader, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ReadableStreamDefaultReader);--public:- static WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> create(JS::Realm&, GC::Ref<ReadableStream>);-- virtual ~ReadableStreamDefaultReader() override = default;-+ // https://streams.spec.whatwg.org/#default-reader-readGC::Ref<WebIDL::Promise> read();- void read_a_chunk(Fetch::Infrastructure::IncrementalReadLoopReadRequest& read_request);- void read_all_bytes(GC::Ref<ReadLoopReadRequest::SuccessSteps>, GC::Ref<ReadLoopReadRequest::FailureSteps>);- GC::Ref<WebIDL::Promise> read_all_bytes_deprecated();-- void release_lock();-- SinglyLinkedList<GC::Ref<ReadRequest>>& read_requests() { return m_read_requests; }+ // https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-a-chunk+ void read_a_chunk(ReadRequest&);- void set_readable_stream_pipe_to_operation(Badge<Detail::ReadableStreamPipeTo>, GC::Ptr<JS::Cell> readable_stream_pipe_to_operation) { m_readable_stream_pipe_to_operation = readable_stream_pipe_to_operation; }+ // https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes+ void read_all_bytes(GC::Ref<SuccessSteps>, GC::Ref<FailureSteps>);-private:- ReadableStreamDefaultReader();-- virtual void visit_edges(GC::Cell::Visitor&) override;+ // FIXME: This function is a promise-based wrapper around "read all bytes". The spec changed this function to not use promises+ // in https://github.com/whatwg/streams/commit/f894acdd417926a2121710803cef593e15127964 - however, it seems that the+ // FileAPI blob specification has not been updated to match, see: https://github.com/w3c/FileAPI/issues/187.+ GC::Ref<WebIDL::Promise> read_all_bytes_deprecated();- SinglyLinkedList<GC::Ref<ReadRequest>> m_read_requests;+ // https://streams.spec.whatwg.org/#generic-reader-cancel+ GC::Ref<WebIDL::Promise> cancel(JS::Value reason);- GC::Ptr<JS::Cell> m_readable_stream_pipe_to_operation;+ // The realm of the reader's [[closedPromise]].+ JS::Realm& closed_promise_realm() const;};}diff --git a/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.idl b/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.idlindex 816630c6572..352a94026da 100644--- a/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.idl+++ b/Libraries/LibWeb/Streams/ReadableStreamDefaultReader.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#readablestreamdefaultreader- [Exposed=*]+ [Exposed=*, ImplementedIn=Rust]interface ReadableStreamDefaultReader {constructor(ReadableStream stream);diff --git a/Libraries/LibWeb/Streams/ReadableStreamGenericReader.cpp b/Libraries/LibWeb/Streams/ReadableStreamGenericReader.cppdeleted file mode 100644index 8387e61590f..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamGenericReader.cpp+++ /dev/null@@ -1,48 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibJS/Runtime/Promise.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamGenericReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#generic-reader-closed-GC::Ptr<WebIDL::Promise> ReadableStreamGenericReaderMixin::closed()-{- // 1. Return this.[[closedPromise]].- return m_closed_promise;-}--// https://streams.spec.whatwg.org/#generic-reader-cancel-GC::Ref<WebIDL::Promise> ReadableStreamGenericReaderMixin::cancel(Optional<JS::Value> reason)-{- // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.- if (!m_stream) {- WebIDL::SimpleException exception { WebIDL::SimpleExceptionType::TypeError, "No stream present to cancel"_utf16 };- return WebIDL::create_rejected_promise_from_exception(closed_promise_realm(), move(exception));- }-- // 2. Return ! ReadableStreamReaderGenericCancel(this, reason).- return readable_stream_reader_generic_cancel(*this, reason.value_or(JS::js_undefined()));-}--JS::Realm& ReadableStreamGenericReaderMixin::closed_promise_realm() const-{- VERIFY(m_closed_promise);- return WebIDL::promise_realm(*m_closed_promise);-}--void ReadableStreamGenericReaderMixin::visit_edges(JS::Cell::Visitor& visitor)-{- visitor.visit(m_closed_promise);- visitor.visit(m_stream);-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamGenericReader.h b/Libraries/LibWeb/Streams/ReadableStreamGenericReader.hdeleted file mode 100644index 243a99057a3..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamGenericReader.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Forward.h>-#include <LibJS/Forward.h>-#include <LibJS/Heap/Cell.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#readablestreamgenericreader-class ReadableStreamGenericReaderMixin {-public:- virtual ~ReadableStreamGenericReaderMixin() = default;-- GC::Ptr<WebIDL::Promise> closed();-- GC::Ref<WebIDL::Promise> cancel(Optional<JS::Value> reason);-- GC::Ptr<ReadableStream> stream() const { return m_stream; }- void set_stream(GC::Ptr<ReadableStream> stream) { m_stream = stream; }-- GC::Ptr<WebIDL::Promise> closed_promise_capability() { return m_closed_promise; }- void set_closed_promise_capability(GC::Ptr<WebIDL::Promise> promise) { m_closed_promise = promise; }-- JS::Realm& closed_promise_realm() const;--protected:- ReadableStreamGenericReaderMixin() = default;-- void visit_edges(JS::Cell::Visitor&);-- // https://streams.spec.whatwg.org/#readablestreamgenericreader-closedpromise- // A promise returned by the reader's closed getter- GC::Ptr<WebIDL::Promise> m_closed_promise;-- // https://streams.spec.whatwg.org/#readablestreamgenericreader-stream- // A ReadableStream instance that owns this reader- GC::Ptr<ReadableStream> m_stream;-};--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamOperations.cpp b/Libraries/LibWeb/Streams/ReadableStreamOperations.cppdeleted file mode 100644index b1223ed71a5..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamOperations.cpp+++ /dev/null@@ -1,2933 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/ByteBuffer.h>-#include <AK/GenericShorthands.h>-#include <AK/NumericLimits.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/DataViewConstructor.h>-#include <LibJS/Runtime/Intrinsics.h>-#include <LibJS/Runtime/Iterator.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibWeb/Bindings/ReadableByteStreamController.h>-#include <LibWeb/Bindings/ReadableStreamDefaultController.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/DOM/AbortSignal.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/Page/RenderingStats.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/BindingsGlue.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>-#include <LibWeb/Streams/ReadableStreamBYOBReader.h>-#include <LibWeb/Streams/ReadableStreamBYOBRequest.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamGenericReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/ReadableStreamPipeTo.h>-#include <LibWeb/Streams/ReadableStreamTee.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultWriter.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#acquire-readable-stream-byob-reader-WebIDL::ExceptionOr<GC::Ref<ReadableStreamBYOBReader>> acquire_readable_stream_byob_reader(JS::Realm& realm, ReadableStream& stream)-{- // 1. Let reader be a new ReadableStreamBYOBReader.- auto reader = GC::Heap::the().allocate<ReadableStreamBYOBReader>();-- // 2. Perform ? SetUpReadableStreamBYOBReader(reader, stream).- TRY(set_up_readable_stream_byob_reader(realm, reader, stream));-- // 3. Return reader.- return reader;-}--}--namespace Web::Bindings {--WebIDL::ExceptionOr<JS::Value> invoke_readable_byte_stream_start_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value underlying_source, GC::Ref<Streams::ReadableByteStreamController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return TRY(WebIDL::invoke_callback(callback, underlying_source, { { wrapped_controller } }));-}--GC::Ref<WebIDL::Promise> invoke_readable_byte_stream_pull_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value underlying_source, GC::Ref<Streams::ReadableByteStreamController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return WebIDL::invoke_promise_callback(callback, underlying_source, { { wrapped_controller } });-}--WebIDL::ExceptionOr<JS::Value> invoke_readable_stream_start_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value underlying_source, GC::Ref<Streams::ReadableStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return TRY(WebIDL::invoke_callback(callback, underlying_source, { { wrapped_controller } }));-}--GC::Ref<WebIDL::Promise> invoke_readable_stream_pull_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value underlying_source, GC::Ref<Streams::ReadableStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return WebIDL::invoke_promise_callback(callback, underlying_source, { { wrapped_controller } });-}--}--namespace Web::Streams {--// https://streams.spec.whatwg.org/#acquire-readable-stream-reader-WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(JS::Realm& realm, ReadableStream& stream)-{- // 1. Let reader be a new ReadableStreamDefaultReader.- auto reader = GC::Heap::the().allocate<ReadableStreamDefaultReader>();-- // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).- TRY(set_up_readable_stream_default_reader(realm, reader, stream));-- // 3. Return reader.- return reader;-}--// AD-HOC: Can be used instead of CreateReadableStream in cases where we need to set up a newly allocated ReadableStream-// before initialization of said ReadableStream, i.e. ReadableStream is captured by lambdas in an uninitialized-// state.-//-// https://streams.spec.whatwg.org/#create-readable-stream-static WebIDL::ExceptionOr<void> create_readable_stream_with_existing_stream(JS::Realm& realm, ReadableStream& stream, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm, Optional<double> high_water_mark = {}, GC::Ptr<SizeAlgorithm> size_algorithm = {})-{- // 1. If highWaterMark was not passed, set it to 1.- if (!high_water_mark.has_value())- high_water_mark = 1.0;-- // 2. If sizeAlgorithm was not passed, set it to an algorithm that returns 1.- if (!size_algorithm)- size_algorithm = GC::create_function(GC::Heap::the(), [](JS::Value) { return JS::normal_completion(JS::Value(1)); });-- // 3. Assert: ! IsNonNegativeNumber(highWaterMark) is true.- VERIFY(is_non_negative_number(JS::Value { *high_water_mark }));-- // 4. Let stream be a new ReadableStream.- // NOTE: The ReadableStream is allocated outside the scope of this method.- stream.set_realm(realm);-- // 5. Perform ! InitializeReadableStream(stream).- initialize_readable_stream(stream);-- // 6. Let controller be a new ReadableStreamDefaultController.- auto controller = GC::Heap::the().allocate<ReadableStreamDefaultController>();-- // 7. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).- TRY(set_up_readable_stream_default_controller(realm, stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, *high_water_mark, *size_algorithm));-- return {};-}--// https://streams.spec.whatwg.org/#create-readable-stream-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> create_readable_stream(JS::Realm& realm, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm, Optional<double> high_water_mark, GC::Ptr<SizeAlgorithm> size_algorithm)-{- auto stream = GC::Heap::the().allocate<ReadableStream>();- TRY(create_readable_stream_with_existing_stream(realm, stream, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, size_algorithm));-- return stream;-}--// https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> create_readable_byte_stream(JS::Realm& realm, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm)-{- // 1. Let stream be a new ReadableStream.- auto stream = GC::Heap::the().allocate<ReadableStream>();- stream->set_realm(realm);-- // 2. Perform ! InitializeReadableStream(stream).- initialize_readable_stream(stream);-- // 3. Let controller be a new ReadableByteStreamController.- auto controller = GC::Heap::the().allocate<ReadableByteStreamController>();-- // 4. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).- TRY(set_up_readable_byte_stream_controller(realm, stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, 0, JS::js_undefined()));-- // 5. Return stream.- return stream;-}--// https://streams.spec.whatwg.org/#initialize-readable-stream-void initialize_readable_stream(ReadableStream& stream)-{- // 1. Set stream.[[state]] to "readable".- stream.set_state(ReadableStream::State::Readable);-- // 2. Set stream.[[reader]] and stream.[[storedError]] to undefined.- stream.set_reader({});- stream.set_stored_error({});-- // 3. Set stream.[[disturbed]] to false.- stream.set_disturbed(false);-}--// https://streams.spec.whatwg.org/#is-readable-stream-locked-bool is_readable_stream_locked(ReadableStream const& stream)-{- // 1. If stream.[[reader]] is undefined, return false.- if (!stream.reader().has_value())- return false;-- // 2. Return true.- return true;-}--// https://streams.spec.whatwg.org/#readable-stream-from-iterable-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> readable_stream_from_iterable(JS::Realm& realm, JS::Value async_iterable)-{- auto& vm = realm.vm();-- // 1. Let stream be undefined.- // AD-HOC: We capture 'stream' in a lambda later, so it needs to be allocated now.- auto stream = GC::Heap::the().allocate<ReadableStream>();- stream->set_realm(realm);-- // 2. Let iteratorRecord be ? GetIterator(asyncIterable, async).- auto iterator_record = TRY(JS::get_iterator(vm, async_iterable, JS::IteratorHint::Async));-- // 3. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 4. Let pullAlgorithm be the following steps:- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&vm, &realm, stream, iterator_record]() mutable {- // 1. Let nextResult be IteratorNext(iteratorRecord).- auto next_result = JS::iterator_next(vm, iterator_record);-- // 2. If nextResult is an abrupt completion, return a promise rejected with nextResult.[[Value]].- if (next_result.is_error())- return WebIDL::create_rejected_promise(realm, next_result.throw_completion().release_value());-- // 3. Let nextPromise be a promise resolved with nextResult.[[Value]].- auto next_promise = WebIDL::create_resolved_promise(realm, next_result.release_value());-- // 4. Return the result of reacting to nextPromise with the following fulfillment steps, given iterResult:- return WebIDL::upon_fulfillment(next_promise,- GC::create_function(GC::Heap::the(), [&vm, &realm, stream](JS::Value iter_result) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If iterResult is not an Object, throw a TypeError.- if (!iter_result.is_object())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "iterResult is not an Object"_utf16 };-- // 2. Let done be ? IteratorComplete(iterResult).- auto done = TRY(JS::iterator_complete(vm, iter_result.as_object()));-- // 3. If done is true:- if (done) {- // 1. Perform ! ReadableStreamDefaultControllerClose(stream.[[controller]]).- readable_stream_default_controller_close(stream->controller()->get<GC::Ref<ReadableStreamDefaultController>>());- }- // 4. Otherwise:- else {- // 1. Let value be ? IteratorValue(iterResult).- auto value = TRY(JS::iterator_value(vm, iter_result.as_object()));-- // 2. Perform ! ReadableStreamDefaultControllerEnqueue(stream.[[controller]], value).- MUST(readable_stream_default_controller_enqueue(realm, stream->controller()->get<GC::Ref<ReadableStreamDefaultController>>(), value));- }-- return JS::js_undefined();- }));- });-- // 5. Let cancelAlgorithm be the following steps, given reason:- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [&vm, &realm, iterator_record](JS::Value reason) {- // 1. Let iterator be iteratorRecord.[[Iterator]].- auto iterator = iterator_record->iterator;-- // 2. Let returnMethod be GetMethod(iterator, "return").- auto return_method = iterator->get(vm.names.return_);-- // 3. If returnMethod is an abrupt completion, return a promise rejected with returnMethod.[[Value]].- if (return_method.is_error())- return WebIDL::create_rejected_promise(realm, return_method.throw_completion().release_value());-- // 4. If returnMethod.[[Value]] is undefined, return a promise resolved with undefined.- if (return_method.value().is_undefined())- return WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // 5. Let returnResult be Call(returnMethod.[[Value]], iterator, « reason »).- auto return_result = JS::call(vm, return_method.value(), reason);-- // 6. If returnResult is an abrupt completion, return a promise rejected with returnResult.[[Value]].- if (return_result.is_error())- return WebIDL::create_rejected_promise(realm, return_result.throw_completion().release_value());-- // 7. Let returnPromise be a promise resolved with returnResult.[[Value]].- auto return_promise = WebIDL::create_resolved_promise(realm, return_result.release_value());-- // 8. Return the result of reacting to returnPromise with the following fulfillment steps, given iterResult:- return WebIDL::upon_fulfillment(return_promise,- GC::create_function(GC::Heap::the(), [](JS::Value iter_result) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If iterResult is not an Object, throw a TypeError.- if (!iter_result.is_object())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "iterResult is not an Object"_utf16 };-- // 2. Return undefined.- return JS::js_undefined();- }));- });-- // 6. Set stream to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0).- MUST(create_readable_stream_with_existing_stream(realm, stream, start_algorithm, pull_algorithm, cancel_algorithm, 0));-- // 7. Return stream.- return stream;-}--// https://streams.spec.whatwg.org/#readable-stream-pipe-to-GC::Ref<WebIDL::Promise> readable_stream_pipe_to(JS::Realm& realm, ReadableStream& source, WritableStream& dest, bool prevent_close, bool prevent_abort, bool prevent_cancel, GC::Ptr<DOM::AbortSignal> signal)-{- // 1. Assert: source implements ReadableStream.- // 2. Assert: dest implements WritableStream.- // 3. Assert: preventClose, preventAbort, and preventCancel are all booleans.-- // 4. If signal was not given, let signal be undefined.- // 5. Assert: either signal is undefined, or signal implements AbortSignal.-- // 6. Assert: ! IsReadableStreamLocked(source) is false.- VERIFY(!is_readable_stream_locked(source));-- // 7. Assert: ! IsWritableStreamLocked(dest) is false.- VERIFY(!is_writable_stream_locked(dest));-- // 8. If source.[[controller]] implements ReadableByteStreamController, let reader be either ! AcquireReadableStreamBYOBReader(source)- // or ! AcquireReadableStreamDefaultReader(source), at the user agent’s discretion.- // 9. Otherwise, let reader be ! AcquireReadableStreamDefaultReader(source).- auto reader = MUST(source.controller()->visit([&realm](auto const& controller) {- return acquire_readable_stream_default_reader(realm, *controller->stream());- }));-- // 10. Let writer be ! AcquireWritableStreamDefaultWriter(dest).- auto writer = MUST(acquire_writable_stream_default_writer(realm, dest));-- // 11. Set source.[[disturbed]] to true.- source.set_disturbed(true);-- // 12. Let shuttingDown be false.- // NOTE: This is internal to the ReadableStreamPipeTo class.-- // 13. Let promise be a new promise.- auto promise = WebIDL::create_promise(realm);-- auto operation = GC::Heap::the().allocate<Detail::ReadableStreamPipeTo>(promise, source, dest, reader, writer, prevent_close, prevent_abort, prevent_cancel);-- // 14. If signal is not undefined,- if (signal) {- // 1. Let abortAlgorithm be the following steps:- auto abort_algorithm = [&realm, operation, source = GC::Ref { source }, dest = GC::Ref { dest }, prevent_abort, prevent_cancel, signal]() {- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 1. Let error be signal’s abort reason.- auto error = signal->reason();-- // 2. Let actions be an empty ordered set.- GC::Ptr<GC::Function<GC::Ref<WebIDL::Promise>()>> abort_destination;- GC::Ptr<GC::Function<GC::Ref<WebIDL::Promise>()>> cancel_source;-- // 3. If preventAbort is false, append the following action to actions:- if (!prevent_abort) {- abort_destination = GC::create_function(GC::Heap::the(), [&realm, dest, error]() {- // 1. If dest.[[state]] is "writable", return ! WritableStreamAbort(dest, error).- if (dest->state() == WritableStream::State::Writable)- return writable_stream_abort(realm, dest, error);-- // 2. Otherwise, return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });- }-- // 4. If preventCancel is false, append the following action action to actions:- if (!prevent_cancel) {- cancel_source = GC::create_function(GC::Heap::the(), [&realm, source, error]() {- // 1. If source.[[state]] is "readable", return ! ReadableStreamCancel(source, error).- if (source->state() == ReadableStream::State::Readable)- return readable_stream_cancel(realm, source, error);-- // 2. Otherwise, return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });- }-- // 5. Shutdown with an action consisting of getting a promise to wait for all of the actions in actions, and with error.- auto action = GC::create_function(GC::Heap::the(), [&realm, abort_destination, cancel_source]() {- GC::RootVector<GC::Ref<WebIDL::Promise>> actions {};-- if (abort_destination)- actions.append(abort_destination->function()());- if (cancel_source)- actions.append(cancel_source->function()());-- return WebIDL::get_promise_for_wait_for_all(realm, actions);- });-- operation->shutdown_with_action(action, error);- };-- // 2. If signal is aborted, perform abortAlgorithm and return promise.- if (signal->aborted()) {- abort_algorithm();- return promise;- }-- // 3. Add abortAlgorithm to signal.- auto signal_id = signal->add_abort_algorithm(move(abort_algorithm));- operation->set_abort_signal(*signal, signal_id.value());- }-- // 15. In parallel (but not really; see #905), using reader and writer, read all chunks from source and write them- // to dest. Due to the locking provided by the reader and writer, the exact manner in which this happens is not- // observable to author code, and so there is flexibility in how this is done.- operation->process();-- // 16. Return promise.- return promise;-}--// https://streams.spec.whatwg.org/#readable-stream-tee-WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2)-{- // 1. Assert: stream implements ReadableStream.- // 2. Assert: cloneForBranch2 is a boolean.-- // 3. If stream.[[controller]] implements ReadableByteStreamController, return ? ReadableByteStreamTee(stream).- if (stream.controller()->has<GC::Ref<Streams::ReadableByteStreamController>>())- return TRY(readable_byte_stream_tee(realm, stream));-- // 4. Return ? ReadableStreamDefaultTee(stream, cloneForBranch2).- return TRY(readable_stream_default_tee(realm, stream, clone_for_branch2));-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee-WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_default_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2)-{- // 1. Assert: stream implements ReadableStream.- // 2. Assert: cloneForBranch2 is a boolean.-- // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).- auto reader = TRY(acquire_readable_stream_default_reader(realm, stream));-- // 4. Let reading be false.- // 5. Let readAgain be false.- // 6. Let canceled1 be false.- // 7. Let canceled2 be false.- // 8. Let reason1 be undefined.- // 9. Let reason2 be undefined.- // 10. Let branch1 be undefined.- // 11. Let branch2 be undefined.- auto params = GC::Heap::the().allocate<Detail::ReadableStreamTeeParams>();-- // 12. Let cancelPromise be a new promise.- auto cancel_promise = WebIDL::create_promise(realm);-- // 13. Let pullAlgorithm be the following steps:- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&realm, &stream, reader, params, cancel_promise, clone_for_branch2]() {- // 1. If reading is true,- if (params->reading) {- // 1. Set readAgain to true.- params->read_again = true;-- // 2. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- }-- // 2. Set reading to true.- params->reading = true;-- // 3. Let readRequest be a read request with the following items:- auto read_request = GC::Heap::the().allocate<Detail::ReadableStreamTeeReadRequest>(stream, params, cancel_promise, clone_for_branch2);-- // 4. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).- readable_stream_default_reader_read(reader, read_request);-- // 5. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // AD-HOC: The read request within the pull algorithm must be able to re-invoke the pull algorithm, so cache it here.- params->pull_algorithm = pull_algorithm;-- // 14. Let cancel1Algorithm be the following steps, taking a reason argument:- auto cancel1_algorithm = GC::create_function(GC::Heap::the(), [&realm, &stream, params, cancel_promise](JS::Value reason) {- // 1. Set canceled1 to true.- params->canceled1 = true;-- // 2. Set reason1 to reason.- params->reason1 = reason;-- // 3. If canceled2 is true,- if (params->canceled2) {- // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).- auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });-- // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).- auto cancel_result = readable_stream_cancel(realm, stream, composite_reason);-- // 3. Resolve cancelPromise with cancelResult.- WebIDL::resolve_promise(cancel_promise, cancel_result->promise());- }-- // 4. Return cancelPromise.- return cancel_promise;- });-- // 15. Let cancel2Algorithm be the following steps, taking a reason argument:- auto cancel2_algorithm = GC::create_function(GC::Heap::the(), [&realm, &stream, params, cancel_promise](JS::Value reason) {- // 1. Set canceled2 to true.- params->canceled2 = true;-- // 2. Set reason2 to reason.- params->reason2 = reason;-- // 3. If canceled1 is true,- if (params->canceled1) {- // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).- auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });-- // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).- auto cancel_result = readable_stream_cancel(realm, stream, composite_reason);-- // 3. Resolve cancelPromise with cancelResult.- WebIDL::resolve_promise(cancel_promise, cancel_result->promise());- }-- // 4. Return cancelPromise.- return cancel_promise;- });-- // 16. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 17. Set branch1 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm).- params->branch1 = MUST(create_readable_stream(realm, start_algorithm, pull_algorithm, cancel1_algorithm));-- // 18. Set branch2 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm).- params->branch2 = MUST(create_readable_stream(realm, start_algorithm, pull_algorithm, cancel2_algorithm));-- // 19. Upon rejection of reader.[[closedPromise]] with reason r,- WebIDL::upon_rejection(*reader->closed_promise_capability(), GC::create_function(GC::Heap::the(), [params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- auto controller1 = params->branch1->controller()->get<GC::Ref<ReadableStreamDefaultController>>();- auto controller2 = params->branch2->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], r).- readable_stream_default_controller_error(controller1, reason);-- // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], r).- readable_stream_default_controller_error(controller2, reason);-- // 3. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.- if (!params->canceled1 || !params->canceled2) {- WebIDL::resolve_promise(cancel_promise);- }-- return JS::js_undefined();- }));-- // 20. Return « branch1, branch2 ».- return ReadableStreamPair { *params->branch1, *params->branch2 };-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamtee-WebIDL::ExceptionOr<ReadableStreamPair> readable_byte_stream_tee(JS::Realm& realm, ReadableStream& stream)-{- // 1. Assert: stream implements ReadableStream.- // 2. Assert: stream.[[controller]] implements ReadableByteStreamController.- VERIFY(stream.controller().has_value() && stream.controller()->has<GC::Ref<ReadableByteStreamController>>());-- // 3. Let reader be ? AcquireReadableStreamDefaultReader(stream).- auto reader = TRY(acquire_readable_stream_default_reader(realm, stream));-- // 4. Let reading be false.- // 5. Let readAgainForBranch1 be false.- // 6. Let readAgainForBranch2 be false.- // 7. Let canceled1 be false.- // 8. Let canceled2 be false.- // 9. Let reason1 be undefined.- // 10. Let reason2 be undefined.- // 11. Let branch1 be undefined.- // 12. Let branch2 be undefined.- auto params = GC::Heap::the().allocate<Detail::ReadableByteStreamTeeParams>(reader);-- // 13. Let cancelPromise be a new promise.- auto cancel_promise = WebIDL::create_promise(realm);-- // 14. Let forwardReaderError be the following steps, taking a thisReader argument:- auto forward_reader_error = GC::create_function(GC::Heap::the(), [params, cancel_promise](ReadableStreamReader const& this_reader) {- // 1. Upon rejection of thisReader.[[closedPromise]] with reason r,- auto closed_promise = this_reader.visit([](auto underlying_reader) { return underlying_reader->closed_promise_capability(); });-- WebIDL::upon_rejection(*closed_promise, GC::create_function(GC::Heap::the(), [this_reader, params, cancel_promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- auto controller1 = params->branch1->controller()->get<GC::Ref<ReadableByteStreamController>>();- auto controller2 = params->branch2->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. If thisReader is not reader, return.- if (this_reader != params->reader) {- return JS::js_undefined();- }-- // 2. Perform ! ReadableByteStreamControllerError(branch1.[[controller]], r).- readable_byte_stream_controller_error(controller1, reason);-- // 3. Perform ! ReadableByteStreamControllerError(branch2.[[controller]], r).- readable_byte_stream_controller_error(controller2, reason);-- // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.- if (!params->canceled1 || !params->canceled2) {- WebIDL::resolve_promise(cancel_promise);- }-- return JS::js_undefined();- }));- });-- // 15. Let pullWithDefaultReader be the following steps:- auto pull_with_default_reader = GC::create_function(GC::Heap::the(), [&realm, &stream, params, cancel_promise, forward_reader_error]() mutable {- // 1. If reader implements ReadableStreamBYOBReader,- if (auto const* byob_reader = params->reader.get_pointer<GC::Ref<ReadableStreamBYOBReader>>()) {- // 1. Assert: reader.[[readIntoRequests]] is empty.- VERIFY((*byob_reader)->read_into_requests().is_empty());-- // 2. Perform ! ReadableStreamBYOBReaderRelease(reader).- readable_stream_byob_reader_release(*byob_reader);-- // 3. Set reader to ! AcquireReadableStreamDefaultReader(stream).- params->reader = MUST(acquire_readable_stream_default_reader(realm, stream));-- // 4. Perform forwardReaderError, given reader.- forward_reader_error->function()(params->reader);- }-- // 2. Let readRequest be a read request with the following items:- auto read_request = GC::Heap::the().allocate<Detail::ReadableByteStreamTeeDefaultReadRequest>(stream, params, cancel_promise);-- // 3. Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).- readable_stream_default_reader_read(params->reader.get<GC::Ref<ReadableStreamDefaultReader>>(), read_request);- });-- // 16. Let pullWithBYOBReader be the following steps, given view and forBranch2:- auto pull_with_byob_reader = GC::create_function(GC::Heap::the(), [&realm, &stream, params, cancel_promise, forward_reader_error](GC::Ptr<JS::Uint8Array> view, bool for_branch2) mutable {- VERIFY(view);- WebIDL::ArrayBufferView array_buffer_view { WebIDL::ArrayBufferViewVariant { *view } };-- // 1. If reader implements ReadableStreamDefaultReader,- if (auto const* default_reader = params->reader.get_pointer<GC::Ref<ReadableStreamDefaultReader>>()) {- // 2. Assert: reader.[[readRequests]] is empty.- VERIFY((*default_reader)->read_requests().is_empty());-- // 3. Perform ! ReadableStreamDefaultReaderRelease(reader).- readable_stream_default_reader_release(*default_reader);-- // 4. Set reader to ! AcquireReadableStreamBYOBReader(stream).- params->reader = MUST(acquire_readable_stream_byob_reader(realm, stream));-- // 5. Perform forwardReaderError, given reader.- forward_reader_error->function()(params->reader);- };-- // 2. Let byobBranch be branch2 if forBranch2 is true, and branch1 otherwise.- auto byob_branch = for_branch2 ? params->branch2 : params->branch1;-- // 3. Let otherBranch be branch2 if forBranch2 is false, and branch1 otherwise.- auto other_branch = !for_branch2 ? params->branch2 : params->branch1;-- // 4. Let readIntoRequest be a read-into request with the following items:- auto read_into_request = GC::Heap::the().allocate<Detail::ReadableByteStreamTeeBYOBReadRequest>(stream, params, cancel_promise, *byob_branch, *other_branch, for_branch2);-- // 5. Perform ! ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest).- readable_stream_byob_reader_read(params->reader.get<GC::Ref<ReadableStreamBYOBReader>>(), array_buffer_view, 1, read_into_request);- });-- // 17. Let pull1Algorithm be the following steps:- auto pull1_algorithm = GC::create_function(GC::Heap::the(), [&realm, params, pull_with_default_reader, pull_with_byob_reader]() {- auto controller1 = params->branch1->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. If reading is true,- if (params->reading) {- // 1. Set readAgainForBranch1 to true.- params->read_again_for_branch1 = true;-- // 2. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- }-- // 2. Set reading to true.- params->reading = true;-- // 3. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(branch1.[[controller]]).- auto byob_request = readable_byte_stream_controller_get_byob_request(realm, controller1);-- // 4. If byobRequest is null, perform pullWithDefaultReader.- if (!byob_request)- pull_with_default_reader->function()();- // 5. Otherwise, perform pullWithBYOBReader, given byobRequest.[[view]] and false.- else- pull_with_byob_reader->function()(byob_request->view(), false);-- // 6. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 18. Let pull2Algorithm be the following steps:- auto pull2_algorithm = GC::create_function(GC::Heap::the(), [&realm, params, pull_with_default_reader, pull_with_byob_reader]() {- auto controller2 = params->branch2->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. If reading is true,- if (params->reading) {- // 1. Set readAgainForBranch2 to true.- params->read_again_for_branch2 = true;-- // 2. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- }-- // 2. Set reading to true.- params->reading = true;-- // 3. Let byobRequest be ! ReadableByteStreamControllerGetBYOBRequest(branch2.[[controller]]).- auto byob_request = readable_byte_stream_controller_get_byob_request(realm, controller2);-- // 4. If byobRequest is null, perform pullWithDefaultReader.- if (!byob_request)- pull_with_default_reader->function()();- // 5. Otherwise, perform pullWithBYOBReader, given byobRequest.[[view]] and true.- else- pull_with_byob_reader->function()(byob_request->view(), true);-- // 6. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // AD-HOC: The read requests within the pull algorithms must be able to re-invoke the pull algorithms, so cache them here.- params->pull1_algorithm = pull1_algorithm;- params->pull2_algorithm = pull2_algorithm;-- // 19. Let cancel1Algorithm be the following steps, taking a reason argument:- auto cancel1_algorithm = GC::create_function(GC::Heap::the(), [&realm, &stream, params, cancel_promise](JS::Value reason) {- // 1. Set canceled1 to true.- params->canceled1 = true;-- // 2. Set reason1 to reason.- params->reason1 = reason;-- // 3. If canceled2 is true,- if (params->canceled2) {- // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).- auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });-- // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).- auto cancel_result = readable_stream_cancel(realm, stream, composite_reason);-- // 3. Resolve cancelPromise with cancelResult.- WebIDL::resolve_promise(cancel_promise, cancel_result->promise());- }-- // 4. Return cancelPromise.- return cancel_promise;- });-- // 20. Let cancel2Algorithm be the following steps, taking a reason argument:- auto cancel2_algorithm = GC::create_function(GC::Heap::the(), [&realm, &stream, params, cancel_promise](JS::Value reason) {- // 1. Set canceled2 to true.- params->canceled2 = true;-- // 2. Set reason2 to reason.- params->reason2 = reason;-- // 3. If canceled1 is true,- if (params->canceled1) {- // 1. Let compositeReason be ! CreateArrayFromList(« reason1, reason2 »).- auto composite_reason = JS::Array::create_from(realm, AK::Array { params->reason1, params->reason2 });-- // 2. Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).- auto cancel_result = readable_stream_cancel(realm, stream, composite_reason);-- // 3. Resolve cancelPromise with cancelResult.- WebIDL::resolve_promise(cancel_promise, cancel_result->promise());- }-- // 4. Return cancelPromise.- return cancel_promise;- });-- // 21. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 22. Set branch1 to ! CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm).- params->branch1 = MUST(create_readable_byte_stream(realm, start_algorithm, pull1_algorithm, cancel1_algorithm));-- // 23. Set branch2 to ! CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm).- params->branch2 = MUST(create_readable_byte_stream(realm, start_algorithm, pull2_algorithm, cancel2_algorithm));-- // 24. Perform forwardReaderError, given reader.- forward_reader_error->function()(reader);-- // 25. Return « branch1, branch2 ».- return ReadableStreamPair { *params->branch1, *params->branch2 };-}--// https://streams.spec.whatwg.org/#readable-stream-add-read-into-request-void readable_stream_add_read_into_request(ReadableStream& stream, GC::Ref<ReadIntoRequest> read_into_request)-{- VERIFY(stream.reader().has_value());-- // 1. Assert: stream.[[reader]] implements ReadableStreamBYOBReader.- auto reader = stream.reader()->get<GC::Ref<ReadableStreamBYOBReader>>();-- // 2. Assert: stream.[[state]] is "readable" or "closed".- VERIFY(first_is_one_of(stream.state(), ReadableStream::State::Readable, ReadableStream::State::Closed));-- // 3. Append readRequest to stream.[[reader]].[[readIntoRequests]].- reader->read_into_requests().append(read_into_request);-}--// https://streams.spec.whatwg.org/#readable-stream-add-read-request-void readable_stream_add_read_request(ReadableStream& stream, GC::Ref<ReadRequest> read_request)-{- VERIFY(stream.reader().has_value());-- // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.- auto reader = stream.reader()->get<GC::Ref<ReadableStreamDefaultReader>>();-- // 2. Assert: stream.[[state]] is "readable".- VERIFY(stream.state() == ReadableStream::State::Readable);-- // 3. Append readRequest to stream.[[reader]].[[readRequests]].- reader->read_requests().append(read_request);-}--// https://streams.spec.whatwg.org/#readable-stream-cancel-GC::Ref<WebIDL::Promise> readable_stream_cancel(JS::Realm& realm, ReadableStream& stream, JS::Value reason)-{- // 1. Set stream.[[disturbed]] to true.- stream.set_disturbed(true);-- // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.- if (stream.state() == ReadableStream::State::Closed)- return WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].- if (stream.state() == ReadableStream::State::Errored)- return WebIDL::create_rejected_promise(realm, stream.stored_error());-- // 4. Perform ! ReadableStreamClose(stream).- readable_stream_close(stream);-- // 5. Let reader be stream.[[reader]].- auto reader = stream.reader();-- // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,- if (reader.has_value()) {- if (auto* byob_reader = reader->get_pointer<GC::Ref<ReadableStreamBYOBReader>>()) {- // 1. Let readIntoRequests be reader.[[readIntoRequests]].- // 2. Set reader.[[readIntoRequests]] to an empty list.- GC::RootVector read_into_requests { move((*byob_reader)->read_into_requests()) };-- // 3. For each readIntoRequest of readIntoRequests,- for (auto read_into_request : read_into_requests) {- // 1. Perform readIntoRequest’s close steps, given undefined.- read_into_request->on_close(JS::js_undefined());- }- }- }-- // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).- auto source_cancel_promise = stream.controller()->visit([&](auto controller) {- return controller->cancel_steps(reason);- });-- // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.- return WebIDL::upon_fulfillment(source_cancel_promise,- GC::create_function(GC::Heap::the(), [](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- }));-}--// https://streams.spec.whatwg.org/#readable-stream-close-void readable_stream_close(ReadableStream& stream)-{- // 1. Assert: stream.[[state]] is "readable".- VERIFY(stream.state() == ReadableStream::State::Readable);-- // 2. Set stream.[[state]] to "closed".- stream.set_state(ReadableStream::State::Closed);- complete_rendering_pending_stream(stream);-- // 3. Let reader be stream.[[reader]].- auto reader = stream.reader();-- // 4. If reader is undefined, return.- if (!reader.has_value())- return;-- // 5. Resolve reader.[[closedPromise]] with undefined.- auto closed_promise_capability = reader->visit([](auto reader) { return reader->closed_promise_capability(); });- WebIDL::resolve_promise(*closed_promise_capability);-- // 6. If reader implements ReadableStreamDefaultReader,- if (auto* default_reader = reader->get_pointer<GC::Ref<ReadableStreamDefaultReader>>()) {- // 1. Let readRequests be reader.[[readRequests]].- // 2. Set reader.[[readRequests]] to an empty list.- GC::RootVector<GC::Ref<ReadRequest>> read_requests;- for (auto read_request : (*default_reader)->read_requests())- read_requests.append(read_request);- (*default_reader)->read_requests().clear();-- // 3. For each readRequest of readRequests,- for (auto read_request : read_requests) {- // 1. Perform readRequest’s close steps.- read_request->on_close();- }- }-}--// https://streams.spec.whatwg.org/#readable-stream-error-void readable_stream_error(ReadableStream& stream, JS::Value error)-{- // 1. Assert: stream.[[state]] is "readable".- VERIFY(stream.state() == ReadableStream::State::Readable);-- // 2. Set stream.[[state]] to "errored".- stream.set_state(ReadableStream::State::Errored);- complete_rendering_pending_stream(stream);-- // 3. Set stream.[[storedError]] to e.- stream.set_stored_error(error);-- // 4. Let reader be stream.[[reader]].- auto reader = stream.reader();-- // 5. If reader is undefined, return.- if (!reader.has_value())- return;-- // 6. Reject reader.[[closedPromise]] with e.- auto closed_promise_capability = reader->visit([](auto reader) { return reader->closed_promise_capability(); });- WebIDL::reject_promise(*closed_promise_capability, error);-- // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*closed_promise_capability);-- reader->visit(- // 8. If reader implements ReadableStreamDefaultReader,- [&](GC::Ref<ReadableStreamDefaultReader> reader) {- // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).- readable_stream_default_reader_error_read_requests(reader, error);- },- // 9. Otherwise,- [&](GC::Ref<ReadableStreamBYOBReader> reader) {- // 1. Assert: reader implements ReadableStreamBYOBReader.- // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).- readable_stream_byob_reader_error_read_into_requests(reader, error);- });-}--// https://streams.spec.whatwg.org/#readable-stream-fulfill-read-into-request-void readable_stream_fulfill_read_into_request(ReadableStream& stream, JS::Value chunk, bool done)-{- // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.- VERIFY(readable_stream_has_byob_reader(stream));-- // 2. Let reader be stream.[[reader]].- auto reader = stream.reader()->get<GC::Ref<ReadableStreamBYOBReader>>();-- // 3. Assert: reader.[[readIntoRequests]] is not empty.- VERIFY(!reader->read_into_requests().is_empty());-- // 4. Let readIntoRequest be reader.[[readIntoRequests]][0].- // 5. Remove readIntoRequest from reader.[[readIntoRequests]].- auto read_into_request = reader->read_into_requests().take_first();-- // 6. If done is true, perform readIntoRequest’s close steps, given chunk.- if (done) {- read_into_request->on_close(chunk);- }- // 7. Otherwise, perform readIntoRequest’s chunk steps, given chunk.- else {- read_into_request->on_chunk(chunk);- }-}--// https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request-void readable_stream_fulfill_read_request(ReadableStream& stream, JS::Value chunk, bool done)-{- // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.- VERIFY(readable_stream_has_default_reader(stream));-- // 2. Let reader be stream.[[reader]].- auto reader = stream.reader()->get<GC::Ref<ReadableStreamDefaultReader>>();-- // 3. Assert: reader.[[readRequests]] is not empty.- VERIFY(!reader->read_requests().is_empty());-- // 4. Let readRequest be reader.[[readRequests]][0].- // 5. Remove readRequest from reader.[[readRequests]].- auto read_request = reader->read_requests().take_first();-- // 6. If done is true, perform readRequest’s close steps.- if (done) {- read_request->on_close();- }- // 7. Otherwise, perform readRequest’s chunk steps, given chunk.- else {- read_request->on_chunk(chunk);- }-}--// https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests-size_t readable_stream_get_num_read_into_requests(ReadableStream const& stream)-{- // 1. Assert: ! ReadableStreamHasBYOBReader(stream) is true.- VERIFY(readable_stream_has_byob_reader(stream));-- // 2. Return stream.[[reader]].[[readIntoRequests]]'s size.- return stream.reader()->get<GC::Ref<ReadableStreamBYOBReader>>()->read_into_requests().size();-}--// https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests-size_t readable_stream_get_num_read_requests(ReadableStream const& stream)-{- // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.- VERIFY(readable_stream_has_default_reader(stream));-- // 2. Return stream.[[reader]].[[readRequests]]'s size.- return stream.reader()->get<GC::Ref<ReadableStreamDefaultReader>>()->read_requests().size();-}--// https://streams.spec.whatwg.org/#readable-stream-has-byob-reader-bool readable_stream_has_byob_reader(ReadableStream const& stream)-{- // 1. Let reader be stream.[[reader]].- auto reader = stream.reader();-- // 2. If reader is undefined, return false.- if (!reader.has_value())- return false;-- // 3. If reader implements ReadableStreamBYOBReader, return true.- if (reader->has<GC::Ref<ReadableStreamBYOBReader>>())- return true;-- // 4. Return false.- return false;-}--// https://streams.spec.whatwg.org/#readable-stream-has-default-reader-bool readable_stream_has_default_reader(ReadableStream const& stream)-{- // 1. Let reader be stream.[[reader]].- auto reader = stream.reader();-- // 2. If reader is undefined, return false.- if (!reader.has_value())- return false;-- // 3. If reader implements ReadableStreamDefaultReader, return true.- if (reader->has<GC::Ref<ReadableStreamDefaultReader>>())- return true;-- // 4. Return false.- return false;-}--// https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel-GC::Ref<WebIDL::Promise> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin& reader, JS::Value reason)-{- // 1. Let stream be reader.[[stream]]- auto stream = reader.stream();-- // 2. Assert: stream is not undefined- VERIFY(stream);-- // 3. Return ! ReadableStreamCancel(stream, reason)- return readable_stream_cancel(reader.closed_promise_realm(), *stream, reason);-}--// https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize-void readable_stream_reader_generic_initialize(JS::Realm& realm, ReadableStreamReader const& reader, ReadableStream& stream)-{- auto& mixin = reader.visit([&](auto reader) -> ReadableStreamGenericReaderMixin& { return *reader; });-- // 1. Set reader.[[stream]] to stream.- mixin.set_stream(stream);-- // 2. Set stream.[[reader]] to reader.- stream.set_reader(reader);-- // 3. If stream.[[state]] is "readable",- if (auto state = stream.state(); state == ReadableStream::State::Readable) {- // 1. Set reader.[[closedPromise]] to a new promise.- mixin.set_closed_promise_capability(WebIDL::create_promise(realm));- }- // 4. Otherwise, if stream.[[state]] is "closed",- else if (state == ReadableStream::State::Closed) {- // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.- mixin.set_closed_promise_capability(WebIDL::create_resolved_promise(realm, JS::js_undefined()));- }- // 5. Otherwise,- else {- // 1. Assert: stream.[[state]] is "errored".- VERIFY(state == ReadableStream::State::Errored);-- // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].- mixin.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, stream.stored_error()));-- // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*mixin.closed_promise_capability());- }-}--// https://streams.spec.whatwg.org/#readable-stream-reader-generic-release-void readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin& reader)-{- // 1. Let stream be reader.[[stream]].- auto stream = reader.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Assert: stream.[[reader]] is reader.- VERIFY(stream->reader()->visit([](auto& reader) -> ReadableStreamGenericReaderMixin* { return reader.ptr(); }) == &reader);-- auto& realm = reader.closed_promise_realm();- auto exception = JS::TypeError::create(realm, "Reader has been released"sv);-- // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.- if (stream->state() == ReadableStream::State::Readable) {- WebIDL::reject_promise(*reader.closed_promise_capability(), exception);- }- // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.- else {- reader.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, exception));- }-- // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());-- // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().- stream->controller()->visit([](auto controller) { controller->release_steps(); });-- // 8. Set stream.[[reader]] to undefined.- stream->set_reader({});-- // 9. Set reader.[[stream]] to undefined.- reader.set_stream({});-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreadererrorreadintorequests-void readable_stream_byob_reader_error_read_into_requests(ReadableStreamBYOBReader& reader, JS::Value error)-{- // 1. Let readIntoRequests be reader.[[readIntoRequests]].- // 2. Set reader.[[readIntoRequests]] to a new empty list.- GC::RootVector read_into_requests { move(reader.read_into_requests()) };-- // 3. For each readIntoRequest of readIntoRequests,- for (auto read_into_request : read_into_requests) {- // 1. Perform readIntoRequest’s error steps, given e.- read_into_request->on_error(error);- }-}--// https://streams.spec.whatwg.org/#readable-stream-byob-reader-read-void readable_stream_byob_reader_read(ReadableStreamBYOBReader& reader, WebIDL::ArrayBufferView& view, u64 min, ReadIntoRequest& read_into_request)-{- auto& realm = reader.closed_promise_realm();-- // 1. Let stream be reader.[[stream]].- auto stream = reader.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Set stream.[[disturbed]] to true.- stream->set_disturbed(true);-- // 4. If stream.[[state]] is "errored", perform readIntoRequest’s error steps given stream.[[storedError]].- if (stream->state() == ReadableStream::State::Errored) {- read_into_request.on_error(stream->stored_error());- }- // 5. Otherwise, perform ! ReadableByteStreamControllerPullInto(stream.[[controller]], view, min, readIntoRequest).- else {- readable_byte_stream_controller_pull_into(realm, stream->controller()->get<GC::Ref<ReadableByteStreamController>>(), view, min, read_into_request);- }-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablestreambyobreaderrelease-void readable_stream_byob_reader_release(ReadableStreamBYOBReader& reader)-{- auto& realm = reader.closed_promise_realm();-- // 1. Perform ! ReadableStreamReaderGenericRelease(reader).- readable_stream_reader_generic_release(reader);-- // 2. Let e be a new TypeError exception.- auto exception = JS::TypeError::create(realm, "Reader has been released"_utf16);-- // 3. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).- readable_stream_byob_reader_error_read_into_requests(reader, exception);-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests-void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader& reader, JS::Value error)-{- // 1. Let readRequests be reader.[[readRequests]].- // 2. Set reader.[[readRequests]] to a new empty list.- GC::RootVector<GC::Ref<ReadRequest>> read_requests;- for (auto read_request : reader.read_requests())- read_requests.append(read_request);- reader.read_requests().clear();-- // 3. For each readRequest of readRequests,- for (auto read_request : read_requests) {- // 1. Perform readRequest’s error steps, given e.- read_request->on_error(error);- }-}--// https://streams.spec.whatwg.org/#readable-stream-default-reader-read-void readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)-{- // 1. Let stream be reader.[[stream]].- auto stream = reader.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Set stream.[[disturbed]] to true.- stream->set_disturbed(true);-- // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.- if (auto state = stream->state(); state == ReadableStream::State::Closed) {- read_request.on_close();- }- // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].- else if (state == ReadableStream::State::Errored) {- read_request.on_error(stream->stored_error());- }- // 6. Otherwise,- else {- // 1. Assert: stream.[[state]] is "readable".- VERIFY(state == ReadableStream::State::Readable);-- // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).- stream->controller()->visit(- [&](GC::Ref<ReadableStreamDefaultController> controller) {- controller->pull_steps(read_request);- },- [&](GC::Ref<ReadableByteStreamController> controller) {- controller->pull_steps(reader.closed_promise_realm(), read_request);- });- }-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease-void readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)-{- auto& realm = reader.closed_promise_realm();-- // 1. Perform ! ReadableStreamReaderGenericRelease(reader).- readable_stream_reader_generic_release(reader);-- // 2. Let e be a new TypeError exception.- auto exception = JS::TypeError::create(realm, "Reader has been released"_utf16);-- // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).- readable_stream_default_reader_error_read_requests(reader, exception);-}--// https://streams.spec.whatwg.org/#set-up-readable-stream-byob-reader-WebIDL::ExceptionOr<void> set_up_readable_stream_byob_reader(JS::Realm& realm, ReadableStreamBYOBReader& reader, ReadableStream& stream)-{- // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.- if (is_readable_stream_locked(stream))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"_utf16 };-- // 2. If stream.[[controller]] does not implement ReadableByteStreamController, throw a TypeError exception.- if (!stream.controller()->has<GC::Ref<ReadableByteStreamController>>())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "BYOB reader cannot set up reader from non-byte stream"_utf16 };-- // 3. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).- readable_stream_reader_generic_initialize(realm, { reader }, stream);-- // 4. Set reader.[[readIntoRequests]] to a new empty list.- reader.read_into_requests().clear();-- return {};-}--// https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader-WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(JS::Realm& realm, ReadableStreamDefaultReader& reader, ReadableStream& stream)-{- // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.- if (is_readable_stream_locked(stream))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"_utf16 };-- // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).- readable_stream_reader_generic_initialize(realm, { reader }, stream);-- // 3. Set reader.[[readRequests]] to a new empty list.- reader.read_requests().clear();-- return {};-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed-void readable_stream_default_controller_call_pull_if_needed(ReadableStreamDefaultController& controller)-{- // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).- auto should_pull = readable_stream_default_controller_should_call_pull(controller);-- // 2. If shouldPull is false, return.- if (!should_pull)- return;-- // 3. If controller.[[pulling]] is true,- if (controller.pulling()) {- // 1. Set controller.[[pullAgain]] to true.- controller.set_pull_again(true);-- // 2. Return.- return;- }-- // 4. Assert: controller.[[pullAgain]] is false.- VERIFY(!controller.pull_again());-- // 5. Set controller.[[pulling]] to true.- controller.set_pulling(true);-- // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].- auto pull_promise = controller.pull_algorithm()->function()();-- WebIDL::react_to_promise(pull_promise,- // 7. Upon fulfillment of pullPromise,- GC::create_function(GC::Heap::the(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Set controller.[[pulling]] to false.- controller.set_pulling(false);-- // 2. If controller.[[pullAgain]] is true,- if (controller.pull_again()) {- // 1. Set controller.[[pullAgain]] to false.- controller.set_pull_again(false);-- // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).- readable_stream_default_controller_call_pull_if_needed(controller);- }-- return JS::js_undefined();- }),-- // 8. Upon rejection of pullPromise with reason e,- GC::create_function(GC::Heap::the(), [&controller](JS::Value error) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).- readable_stream_default_controller_error(controller, error);-- return JS::js_undefined();- }));-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull-bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.- if (!readable_stream_default_controller_can_close_or_enqueue(controller))- return false;-- // 3. If controller.[[started]] is false, return false.- if (!controller.started())- return false;-- // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.- if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)- return true;-- // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).- auto desired_size = readable_stream_default_controller_get_desired_size(controller);-- // 6. Assert: desiredSize is not null.- VERIFY(desired_size.has_value());-- // 7. If desiredSize > 0, return true.- if (*desired_size > 0.0)- return true;-- // 8. Return false.- return false;-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms-void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)-{- // 1. Set controller.[[pullAlgorithm]] to undefined.- controller.set_pull_algorithm({});-- // 2. Set controller.[[cancelAlgorithm]] to undefined.- controller.set_cancel_algorithm({});-- // 3. Set controller.[[strategySizeAlgorithm]] to undefined.- controller.set_strategy_size_algorithm({});-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-close-void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)-{- // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.- if (!readable_stream_default_controller_can_close_or_enqueue(controller))- return;-- // 2. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 3. Set controller.[[closeRequested]] to true.- controller.set_close_requested(true);- complete_rendering_pending_stream(*stream);-- // 4. If controller.[[queue]] is empty,- if (controller.queue().is_empty()) {- // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).- readable_stream_default_controller_clear_algorithms(controller);-- // 2. Perform ! ReadableStreamClose(stream).- readable_stream_close(*stream);- }-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue-WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(JS::Realm& realm, ReadableStreamDefaultController& controller, JS::Value chunk)-{- auto& vm = realm.vm();-- // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.- if (!readable_stream_default_controller_can_close_or_enqueue(controller))- return {};-- // 2. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).- if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {- readable_stream_fulfill_read_request(*stream, chunk, false);- }- // 4. Otherwise,- else {- // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.- auto result = controller.strategy_size_algorithm()->function()(chunk);-- // 2. If result is an abrupt completion,- if (result.is_abrupt()) {- // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).- readable_stream_default_controller_error(controller, result.value());-- // 2. Return result.- return result;- }-- // 3. Let chunkSize be result.[[Value]].- auto chunk_size = result.release_value();-- // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).- auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);-- // 5. If enqueueResult is an abrupt completion,- if (enqueue_result.is_error()) {- auto throw_completion = WebIDL::exception_to_throw_completion(vm, realm, enqueue_result.exception());-- // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).- readable_stream_default_controller_error(controller, throw_completion.value());-- // 2. Return enqueueResult.- return throw_completion;- }- }-- // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).- readable_stream_default_controller_call_pull_if_needed(controller);-- return {};-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-error-void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If stream.[[state]] is not "readable", return.- if (stream->state() != ReadableStream::State::Readable)- return;-- // 3. Perform ! ResetQueue(controller).- reset_queue(controller);-- // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).- readable_stream_default_controller_clear_algorithms(controller);-- // 5. Perform ! ReadableStreamError(stream, e).- readable_stream_error(*stream, error);-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size-Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)-{- // 1. Let state be controller.[[stream]].[[state]].- auto state = controller.stream()->state();-- // 2. If state is "errored", return null.- if (state == ReadableStream::State::Errored)- return {};-- // 3. If state is "closed", return 0.- if (state == ReadableStream::State::Closed)- return 0.0;-- // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].- return controller.strategy_hwm() - controller.queue_total_size();-}--// https://streams.spec.whatwg.org/#rs-default-controller-has-backpressure-bool readable_stream_default_controller_has_backpressure(ReadableStreamDefaultController& controller)-{- // 1. If ! ReadableStreamDefaultControllerShouldCallPull(controller) is true, return false.- if (readable_stream_default_controller_should_call_pull(controller))- return false;-- // 2. Otherwise, return true.- return true;-}--// https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue-bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)-{- // 1. Let state be controller.[[stream]].[[state]].- auto state = controller.stream()->state();-- // 2. If controller.[[closeRequested]] is false and state is "readable", return true.- if (!controller.close_requested() && state == ReadableStream::State::Readable)- return true;-- // 3. Otherwise, return false.- return false;-}--// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller(JS::Realm& realm, ReadableStream& stream, ReadableStreamDefaultController& controller, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm)-{- // 1. Assert: stream.[[controller]] is undefined.- VERIFY(!stream.controller().has_value());-- // 2. Set controller.[[stream]] to stream.- controller.set_stream(stream);-- // 3. Perform ! ResetQueue(controller).- reset_queue(controller);-- // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.- controller.set_started(false);- controller.set_close_requested(false);- controller.set_pull_again(false);- controller.set_pulling(false);-- // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.- controller.set_strategy_size_algorithm(size_algorithm);- controller.set_strategy_hwm(high_water_mark);-- // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.- controller.set_pull_algorithm(pull_algorithm);-- // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.- controller.set_cancel_algorithm(cancel_algorithm);-- // 8. Set stream.[[controller]] to controller.- stream.set_controller(ReadableStreamController { controller });-- // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)- auto start_result = TRY(start_algorithm->function()());-- // 10. Let startPromise be a promise resolved with startResult.- auto start_promise = WebIDL::create_resolved_promise(realm, start_result);-- WebIDL::react_to_promise(start_promise,- // 11. Upon fulfillment of startPromise,- GC::create_function(GC::Heap::the(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Set controller.[[started]] to true.- controller.set_started(true);-- // 2. Assert: controller.[[pulling]] is false.- VERIFY(!controller.pulling());-- // 3. Assert: controller.[[pullAgain]] is false.- VERIFY(!controller.pull_again());-- // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).- readable_stream_default_controller_call_pull_if_needed(controller);-- return JS::js_undefined();- }),-- // 12. Upon rejection of startPromise with reason r,- GC::create_function(GC::Heap::the(), [&controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).- readable_stream_default_controller_error(controller, reason);-- return JS::js_undefined();- }));-- return {};-}--// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source-WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller_from_underlying_source(JS::Realm& realm, ReadableStream& stream, JS::Value underlying_source_value, UnderlyingSource underlying_source, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm)-{- // 1. Let controller be a new ReadableStreamDefaultController.- auto controller = GC::Heap::the().allocate<ReadableStreamDefaultController>();-- // 2. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&realm]() {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [&realm](JS::Value) {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of- // invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.- if (underlying_source.start) {- start_algorithm = GC::create_function(GC::Heap::the(), [controller, underlying_source_value, callback = underlying_source.start, realm = GC::Ref(realm)]() -> WebIDL::ExceptionOr<JS::Value> {- return Bindings::invoke_readable_stream_start_algorithm_callback(realm, *callback, underlying_source_value, controller);- });- }-- // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of- // invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.- if (underlying_source.pull) {- pull_algorithm = GC::create_function(GC::Heap::the(), [controller, underlying_source_value, callback = underlying_source.pull, realm = GC::Ref(realm)]() {- return Bindings::invoke_readable_stream_pull_algorithm_callback(realm, *callback, underlying_source_value, controller);- });- }-- // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument- // reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and- // callback this value underlyingSource.- if (underlying_source.cancel) {- cancel_algorithm = GC::create_function(GC::Heap::the(), [underlying_source_value, callback = underlying_source.cancel](JS::Value reason) {- return WebIDL::invoke_promise_callback(*callback, underlying_source_value, { { reason } });- });- }-- // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).- return set_up_readable_stream_default_controller(realm, stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, size_algorithm);-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed-void readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController& controller)-{- // 1. Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).- auto should_pull = readable_byte_stream_controller_should_call_pull(controller);-- // 2. If shouldPull is false, return.- if (!should_pull)- return;-- // 3. If controller.[[pulling]] is true,- if (controller.pulling()) {- // 1. Set controller.[[pullAgain]] to true.- controller.set_pull_again(true);-- // 2. Return.- return;- }-- // 4. Assert: controller.[[pullAgain]] is false.- VERIFY(!controller.pull_again());-- // 5. Set controller.[[pulling]] to true.- controller.set_pulling(true);-- // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].- auto pull_promise = controller.pull_algorithm()->function()();-- WebIDL::react_to_promise(pull_promise,- // 7. Upon fulfillment of pullPromise,- GC::create_function(GC::Heap::the(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Set controller.[[pulling]] to false.- controller.set_pulling(false);-- // 2. If controller.[[pullAgain]] is true,- if (controller.pull_again()) {- // 1. Set controller.[[pullAgain]] to false.- controller.set_pull_again(false);-- // 2. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).- readable_byte_stream_controller_call_pull_if_needed(controller);- }-- return JS::js_undefined();- }),-- // 8. Upon rejection of pullPromise with reason e,- GC::create_function(GC::Heap::the(), [&controller](JS::Value error) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! ReadableByteStreamControllerError(controller, e).- readable_byte_stream_controller_error(controller, error);-- return JS::js_undefined();- }));-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms-void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController& controller)-{- // 1. Set controller.[[pullAlgorithm]] to undefined.- controller.set_pull_algorithm({});-- // 2. Set controller.[[cancelAlgorithm]] to undefined.- controller.set_cancel_algorithm({});-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos-void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController& controller)-{- // 1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).- readable_byte_stream_controller_invalidate_byob_request(controller);-- // 2. Set controller.[[pendingPullIntos]] to a new empty list.- controller.pending_pull_intos().clear();-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-close-WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(JS::Realm& realm, ReadableByteStreamController& controller)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.- if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)- return {};-- complete_rendering_pending_stream(*stream);-- // 3. If controller.[[queueTotalSize]] > 0,- if (controller.queue_total_size() > 0.0) {- // 1. Set controller.[[closeRequested]] to true.- controller.set_close_requested(true);-- // 2. Return.- return {};- }-- // 4. If controller.[[pendingPullIntos]] is not empty,- if (!controller.pending_pull_intos().is_empty()) {- // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].- auto first_pending_pull_into = controller.pending_pull_intos().first();-- // 2. If the remainder after dividing firstPendingPullInto’s bytes filled by firstPendingPullInto’s element size is not 0,- if (first_pending_pull_into->bytes_filled % first_pending_pull_into->element_size != 0) {- // 1. Let e be a new TypeError exception.- auto error = JS::TypeError::create(realm, "Cannot close controller in the middle of processing a write request"_utf16);-- // 2. Perform ! ReadableByteStreamControllerError(controller, e).- readable_byte_stream_controller_error(controller, error);-- // 3. Throw e.- return JS::throw_completion(error);- }- }-- // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).- readable_byte_stream_controller_clear_algorithms(controller);-- // 6. Perform ! ReadableStreamClose(stream).- readable_stream_close(*stream);-- return {};-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor-void readable_byte_stream_controller_commit_pull_into_descriptor(JS::Realm& realm, ReadableStream& stream, PullIntoDescriptor const& pull_into_descriptor)-{- // 1. Assert: stream.[[state]] is not "errored".- VERIFY(stream.state() != ReadableStream::State::Errored);-- // 2. Assert: pullIntoDescriptor.reader type is not "none".- VERIFY(pull_into_descriptor.reader_type != ReaderType::None);-- // 3. Let done be false.- bool done = false;-- // 4. If stream.[[state]] is "closed",- if (stream.state() == ReadableStream::State::Closed) {- // 1. Assert: the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element size is 0.- VERIFY(pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size == 0);-- // 2. Set done to true.- done = true;- }-- // 5. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).- auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(realm, pull_into_descriptor);-- // 6. If pullIntoDescriptor’s reader type is "default",- if (pull_into_descriptor.reader_type == ReaderType::Default) {- // 1. Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).- readable_stream_fulfill_read_request(stream, filled_view, done);- }- // 7. Otherwise,- else {- // 1. Assert: pullIntoDescriptor’s reader type is "byob".- VERIFY(pull_into_descriptor.reader_type == ReaderType::Byob);-- // 2. Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).- readable_stream_fulfill_read_into_request(stream, filled_view, done);- }-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor-JS::Value readable_byte_stream_controller_convert_pull_into_descriptor(JS::Realm& realm, PullIntoDescriptor const& pull_into_descriptor)-{- auto& vm = realm.vm();-- // 1. Let bytesFilled be pullIntoDescriptor’s bytes filled.- auto bytes_filled = pull_into_descriptor.bytes_filled;-- // 2. Let elementSize be pullIntoDescriptor’s element size.- auto element_size = pull_into_descriptor.element_size;-- // 3. Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.- VERIFY(bytes_filled <= pull_into_descriptor.byte_length);-- // 4. Assert: the remainder after dividing bytesFilled by elementSize is 0.- VERIFY(bytes_filled % element_size == 0);-- // 5. Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).- auto buffer = MUST(transfer_array_buffer(realm, pull_into_descriptor.buffer));-- // 6. Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).- return MUST(JS::construct(vm, *pull_into_descriptor.view_constructor, buffer, JS::Value(pull_into_descriptor.byte_offset), JS::Value(bytes_filled / element_size)));-}--static WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_transferred_buffer(JS::Realm& realm, ReadableByteStreamController& controller, GC::Ref<JS::ArrayBuffer> transferred_buffer, u32 byte_offset, u32 byte_length)-{- auto& vm = realm.vm();- auto stream = controller.stream();-- // 8. If controller.[[pendingPullIntos]] is not empty,- if (!controller.pending_pull_intos().is_empty()) {- // 1. Let firstPendingPullInto be controller.[[pendingPullIntos]][0].- auto first_pending_pull_into = controller.pending_pull_intos().first();-- // 2. If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.- if (first_pending_pull_into->buffer->is_detached())- return vm.throw_completion<JS::TypeError>("Buffer is detached"_utf16);-- // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).- readable_byte_stream_controller_invalidate_byob_request(controller);-- // 4. Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).- first_pending_pull_into->buffer = MUST(transfer_array_buffer(realm, first_pending_pull_into->buffer));-- // 5. If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).- if (first_pending_pull_into->reader_type == ReaderType::None)- TRY(readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(realm, controller, first_pending_pull_into));- }-- // 9. If ! ReadableStreamHasDefaultReader(stream) is true,- if (readable_stream_has_default_reader(*stream)) {- // 1. Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).- readable_byte_stream_controller_process_read_requests_using_queue(realm, controller);-- // 2. If ! ReadableStreamGetNumReadRequests(stream) is 0,- if (readable_stream_get_num_read_requests(*stream) == 0) {- // 1. Assert: controller.[[pendingPullIntos]] is empty.- VERIFY(controller.pending_pull_intos().is_empty());-- // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).- readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);- }- // 3. Otherwise.- else {- // 1. Assert: controller.[[queue]] is empty.- VERIFY(controller.queue().is_empty());-- // 2. If controller.[[pendingPullIntos]] is not empty,- if (!controller.pending_pull_intos().is_empty()) {- // 1. Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".- VERIFY(controller.pending_pull_intos().first()->reader_type == ReaderType::Default);-- // 2. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).- readable_byte_stream_controller_shift_pending_pull_into(controller);- }-- // 3. Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).- auto transferred_view = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), transferred_buffer, JS::Value(byte_offset), JS::Value(byte_length)));-- // 4. Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).- readable_stream_fulfill_read_request(*stream, transferred_view, false);- }- }- // 10. Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,- else if (readable_stream_has_byob_reader(*stream)) {- // 1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).- readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);-- // 2. Let filledPullIntos be the result of performing ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).- auto filled_pull_intos = readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);-- // 3. For each filledPullInto of filledPullIntos,- for (auto& filled_pull_into : filled_pull_intos) {- // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, filledPullInto).- readable_byte_stream_controller_commit_pull_into_descriptor(realm, *stream, *filled_pull_into);- }- }- // 11. Otherwise,- else {- // 1. Assert: ! IsReadableStreamLocked(stream) is false.- VERIFY(!is_readable_stream_locked(*stream));-- // 2. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).- readable_byte_stream_controller_enqueue_chunk_to_queue(controller, transferred_buffer, byte_offset, byte_length);- }-- // 12. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).- readable_byte_stream_controller_call_pull_if_needed(controller);-- return {};-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(JS::Realm& realm, ReadableByteStreamController& controller, JS::Value chunk)-{- auto& vm = realm.vm();-- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.- if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)- return {};-- // 3. Let buffer be chunk.[[ViewedArrayBuffer]].- auto* typed_array = TRY(JS::typed_array_from(vm, chunk));- auto* buffer = typed_array->viewed_array_buffer();-- // 4. Let byteOffset be chunk.[[ByteOffset]].- auto byte_offset = typed_array->byte_offset();-- // 6. If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.- // FIXME: The streams spec has not been updated for resizable ArrayBuffer objects. We must perform step 6 before- // invoking TypedArrayByteLength in step 5. We also must check if the array is out-of-bounds, rather than- // just detached.- auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(*typed_array, JS::ArrayBuffer::Order::SeqCst);-- if (JS::is_typed_array_out_of_bounds(typed_array_record))- return vm.throw_completion<JS::TypeError>(JS::ErrorType::BufferOutOfBounds, "TypedArray"_utf16);-- // 5. Let byteLength be chunk.[[ByteLength]].- auto byte_length = JS::typed_array_byte_length(typed_array_record);-- // 7. Let transferredBuffer be ? TransferArrayBuffer(buffer).- auto transferred_buffer = TRY(transfer_array_buffer(realm, *buffer));-- return readable_byte_stream_controller_enqueue_transferred_buffer(realm, controller, transferred_buffer, byte_offset, byte_length);-}--WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_native_bytes(JS::Realm& realm, ReadableByteStreamController& controller, ByteBuffer bytes)-{- auto stream = controller.stream();- if (controller.close_requested() || stream->state() != ReadableStream::State::Readable)- return {};-- VERIFY(bytes.size() <= NumericLimits<u32>::max());- auto byte_length = static_cast<u32>(bytes.size());-- // OPTIMIZATION: Native byte producers have no observable chunk object to detach, so enter the enqueue algorithm after- // the TransferArrayBuffer step with an already-owned ArrayBuffer.- auto transferred_buffer = JS::ArrayBuffer::create(realm, move(bytes));- return readable_byte_stream_controller_enqueue_transferred_buffer(realm, controller, transferred_buffer, 0, byte_length);-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue-void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, GC::Ref<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length)-{- // 1. Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].- controller.queue().append(ReadableByteStreamQueueEntry {- .buffer = buffer,- .byte_offset = byte_offset,- .byte_length = byte_length,- });-- // 2. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.- controller.set_queue_total_size(controller.queue_total_size() + byte_length);-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(JS::Realm& realm, ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length)-{- auto& vm = realm.vm();-- // 1. Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).- auto clone_result = JS::clone_array_buffer(vm, buffer, byte_offset, byte_length);-- // 2. If cloneResult is an abrupt completion,- if (clone_result.is_throw_completion()) {- auto throw_completion = clone_result.throw_completion();-- // 1. Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).- readable_byte_stream_controller_error(controller, throw_completion.value());-- // 2. Return cloneResult.- return throw_completion;- }-- // 3. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).- readable_byte_stream_controller_enqueue_chunk_to_queue(controller, *clone_result.release_value(), 0, byte_length);-- return {};-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(JS::Realm& realm, ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)-{- // 1. Assert: pullIntoDescriptor’s reader type is "none".- VERIFY(pull_into_descriptor.reader_type == ReaderType::None);-- // 2. If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).- if (pull_into_descriptor.bytes_filled > 0)- TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(realm, controller, pull_into_descriptor.buffer, pull_into_descriptor.byte_offset, pull_into_descriptor.bytes_filled));-- // 3. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).- readable_byte_stream_controller_shift_pending_pull_into(controller);-- return {};-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-error-void readable_byte_stream_controller_error(ReadableByteStreamController& controller, JS::Value error)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If stream.[[state]] is not "readable", return.- if (stream->state() != ReadableStream::State::Readable)- return;-- // 3. Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).- readable_byte_stream_controller_clear_pending_pull_intos(controller);-- // 4. Perform ! ResetQueue(controller).- reset_queue(controller);-- // 5. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).- readable_byte_stream_controller_clear_algorithms(controller);-- // 6. Perform ! ReadableStreamError(stream, e).- readable_stream_error(*stream, error);-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-head-pull-into-descriptor-void readable_byte_stream_controller_fill_head_pull_into_descriptor(ReadableByteStreamController const& controller, u64 size, PullIntoDescriptor& pull_into_descriptor)-{- // 1. Assert: either controller.[[pendingPullIntos]] is empty, or controller.[[pendingPullIntos]][0] is pullIntoDescriptor.- VERIFY(controller.pending_pull_intos().is_empty() || controller.pending_pull_intos().first().ptr() == &pull_into_descriptor);-- // 2. Assert: controller.[[byobRequest]] is null.- VERIFY(!controller.raw_byob_request());-- // 3. Set pullIntoDescriptor’s bytes filled to bytes filled + size.- pull_into_descriptor.bytes_filled += size;-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-pull-into-descriptor-from-queue-bool readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor)-{- // 1. Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).- auto max_bytes_to_copy = min(controller.queue_total_size(), pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled);-- // 2. Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.- u64 max_bytes_filled = pull_into_descriptor.bytes_filled + max_bytes_to_copy;-- // 3. Let totalBytesToCopyRemaining be maxBytesToCopy.- auto total_bytes_to_copy_remaining = max_bytes_to_copy;-- // 4. Let ready be false.- bool ready = false;-- // 5. Assert: ! IsDetachedBuffer(pullIntoDescriptor’s buffer) is false.- VERIFY(!pull_into_descriptor.buffer->is_detached());-- // 6. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill.- VERIFY(pull_into_descriptor.bytes_filled < pull_into_descriptor.minimum_fill);-- // 7. Let remainderBytes be the remainder after dividing maxBytesFilled by pullIntoDescriptor’s element size.- auto remainder_bytes = max_bytes_filled % pull_into_descriptor.element_size;-- // 8. Let maxAlignedBytes be maxBytesFilled − remainderBytes.- auto max_aligned_bytes = max_bytes_filled - remainder_bytes;-- // 9. If maxAlignedBytes ≥ pullIntoDescriptor’s minimum fill,- if (max_aligned_bytes >= pull_into_descriptor.minimum_fill) {- // 1. Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.- total_bytes_to_copy_remaining = max_aligned_bytes - pull_into_descriptor.bytes_filled;-- // 2. Set ready to true.- ready = true;-- // NOTE: A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head- // of the queue, so the underlying source can keep filling it.- }-- // 10. Let queue be controller.[[queue]].- auto& queue = controller.queue();-- // 11. While totalBytesToCopyRemaining > 0,- while (total_bytes_to_copy_remaining > 0) {- // 1. Let headOfQueue be queue[0].- auto& head_of_queue = queue.first();-- // 2. Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).- auto bytes_to_copy = min(total_bytes_to_copy_remaining, head_of_queue.byte_length);-- // 3. Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.- auto dest_start = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;-- // 4. Let descriptorBuffer be pullIntoDescriptor’s buffer.- auto descriptor_buffer = pull_into_descriptor.buffer;-- // 5. Let queueBuffer be headOfQueue’s buffer.- auto queue_buffer = head_of_queue.buffer;-- // 6. Let queueByteOffset be headOfQueue’s byte offset.- auto queue_byte_offset = head_of_queue.byte_offset;-- // 7. Assert: ! CanCopyDataBlockBytes(descriptorBuffer, destStart, queueBuffer, queueByteOffset, bytesToCopy) is true.- VERIFY(can_copy_data_block_bytes_buffer(descriptor_buffer, dest_start, queue_buffer, queue_byte_offset, bytes_to_copy));-- // 8. Perform ! CopyDataBlockBytes(pullIntoDescriptor’s buffer.[[ArrayBufferData]], destStart, headOfQueue’s buffer.[[ArrayBufferData]], headOfQueue’s byte offset, bytesToCopy).- head_of_queue.buffer->copy_data_to(*descriptor_buffer, head_of_queue.byte_offset, dest_start, bytes_to_copy);-- // 9. If headOfQueue’s byte length is bytesToCopy,- if (head_of_queue.byte_length == bytes_to_copy) {- // 1. Remove queue[0].- queue.take_first();- }- // 10. Otherwise,- else {- // 1. Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.- head_of_queue.byte_offset += bytes_to_copy;-- // 2. Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.- head_of_queue.byte_length -= bytes_to_copy;- }-- // 11. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.- controller.set_queue_total_size(controller.queue_total_size() - bytes_to_copy);-- // 12, Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor).- readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_to_copy, pull_into_descriptor);-- // 13. Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.- total_bytes_to_copy_remaining -= bytes_to_copy;- }-- // 12. If ready is false,- if (!ready) {- // 1. Assert: controller.[[queueTotalSize]] is 0.- VERIFY(controller.queue_total_size() == 0);-- // 2. Assert: pullIntoDescriptor’s bytes filled > 0.- VERIFY(pull_into_descriptor.bytes_filled > 0);-- // 3. Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill.- VERIFY(pull_into_descriptor.bytes_filled < pull_into_descriptor.minimum_fill);- }-- // 13. Return ready.- return ready;-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue-void readable_byte_stream_controller_fill_read_request_from_queue(JS::Realm& realm, ReadableByteStreamController& controller, ReadRequest& read_request)-{- auto& vm = realm.vm();-- // 1. Assert: controller.[[queueTotalSize]] > 0.- VERIFY(controller.queue_total_size() > 0.0);-- // 2. Let entry be controller.[[queue]][0].- // 3. Remove entry from controller.[[queue]].- auto entry = controller.queue().take_first();-- // 4. Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.- controller.set_queue_total_size(controller.queue_total_size() - entry.byte_length);-- // 5. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).- readable_byte_stream_controller_handle_queue_drain(controller);-- // 6. Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).- auto view = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), entry.buffer, JS::Value(entry.byte_offset), JS::Value(entry.byte_length)));-- // 7. Perform readRequest’s chunk steps, given view.- read_request.on_chunk(view);-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollergetbyobrequest-GC::Ptr<ReadableStreamBYOBRequest> readable_byte_stream_controller_get_byob_request(JS::Realm& realm, ReadableByteStreamController& controller)-{- auto& vm = realm.vm();-- // 1. If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,- if (!controller.raw_byob_request() && !controller.pending_pull_intos().is_empty()) {- // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].- auto first_descriptor = controller.pending_pull_intos().first();-- // 2. Let view be ! Construct(%Uint8Array%, « firstDescriptor’s buffer, firstDescriptor’s byte offset + firstDescriptor’s bytes filled, firstDescriptor’s byte length − firstDescriptor’s bytes filled »).- auto view_object = MUST(JS::construct(vm, *realm.intrinsics().uint8_array_constructor(), first_descriptor->buffer, JS::Value(first_descriptor->byte_offset + first_descriptor->bytes_filled), JS::Value(first_descriptor->byte_length - first_descriptor->bytes_filled)));- auto& view = static_cast<JS::Uint8Array&>(*view_object);-- // 3. Let byobRequest be a new ReadableStreamBYOBRequest.- auto byob_request = GC::Heap::the().allocate<ReadableStreamBYOBRequest>();-- // 4. Set byobRequest.[[controller]] to controller.- byob_request->set_controller(controller);-- // 5. Set byobRequest.[[view]] to view.- byob_request->set_view(view);-- // 6. Set controller.[[byobRequest]] to byobRequest.- controller.set_byob_request(byob_request);- }-- // 2. Return controller.[[byobRequest]].- return controller.raw_byob_request();-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size-Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const& controller)-{- // 1. Let state be controller.[[stream]].[[state]].- auto state = controller.stream()->state();-- // 2. If state is "errored", return null.- if (state == ReadableStream::State::Errored)- return {};-- // 3. If state is "closed", return 0.- if (state == ReadableStream::State::Closed)- return 0.0;-- // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].- return controller.strategy_hwm() - controller.queue_total_size();-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain-void readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController& controller)-{- auto stream = controller.stream();-- // 1. Assert: controller.[[stream]].[[state]] is "readable".- VERIFY(stream->state() == ReadableStream::State::Readable);-- // 2. If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,- if (controller.queue_total_size() == 0.0 && controller.close_requested()) {- // 1. Perform ! ReadableByteStreamControllerClearAlgorithms(controller).- readable_byte_stream_controller_clear_algorithms(controller);-- // 2. Perform ! ReadableStreamClose(controller.[[stream]]).- readable_stream_close(*stream);- }- // 3. Otherwise,- else {- // 1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).- readable_byte_stream_controller_call_pull_if_needed(controller);- }-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request-void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController& controller)-{- // 1. If controller.[[byobRequest]] is null, return.- if (!controller.raw_byob_request())- return;-- // 2. Set controller.[[byobRequest]].[[controller]] to undefined.- controller.raw_byob_request()->set_controller({});-- // 3. Set controller.[[byobRequest]].[[view]] to null.- controller.raw_byob_request()->set_view({});-- // 4. Set controller.[[byobRequest]] to null.- controller.set_byob_request({});-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue-SinglyLinkedList<GC::Root<PullIntoDescriptor>> readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController& controller)-{- // 1. Assert: controller.[[closeRequested]] is false.- VERIFY(!controller.close_requested());-- // 2. Let filledPullIntos be a new empty list.- SinglyLinkedList<GC::Root<PullIntoDescriptor>> filled_pull_intos;-- // 3. While controller.[[pendingPullIntos]] is not empty,- while (!controller.pending_pull_intos().is_empty()) {- // 1. If controller.[[queueTotalSize]] is 0, then break.- if (controller.queue_total_size() == 0)- break;-- // 2. Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].- auto pull_into_descriptor = controller.pending_pull_intos().first();-- // 3. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,- if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {- // 1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).- readable_byte_stream_controller_shift_pending_pull_into(controller);-- // 2. Append pullIntoDescriptor to filledPullIntos.- filled_pull_intos.append(pull_into_descriptor);- }- }-- // 4. Return filledPullIntos.- return filled_pull_intos;-}--// https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue-void readable_byte_stream_controller_process_read_requests_using_queue(JS::Realm& realm, ReadableByteStreamController& controller)-{- // 1. Let reader be controller.[[stream]].[[reader]].- // 2. Assert: reader implements ReadableStreamDefaultReader.- auto reader = controller.stream()->reader()->get<GC::Ref<ReadableStreamDefaultReader>>();-- // 3. While reader.[[readRequests]] is not empty,- while (!reader->read_requests().is_empty()) {- // 1. If controller.[[queueTotalSize]] is 0, return.- if (controller.queue_total_size() == 0.0)- return;-- // 2. Let readRequest be reader.[[readRequests]][0].- // 3. Remove readRequest from reader.[[readRequests]].- auto read_request = reader->read_requests().take_first();-- // 4. Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).- readable_byte_stream_controller_fill_read_request_from_queue(realm, controller, read_request);- }-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into-void readable_byte_stream_controller_pull_into(JS::Realm& realm, ReadableByteStreamController& controller, WebIDL::ArrayBufferView& view, u64 min, ReadIntoRequest& read_into_request)-{- auto& vm = realm.vm();-- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. Let elementSize be 1.- size_t element_size = 1;-- // 3. Let ctor be %DataView%.- GC::Ref<JS::NativeFunction> ctor = realm.intrinsics().data_view_constructor();-- // 4. If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),- if (auto typed_array = view.typed_array_base()) {- // 1. Set elementSize to the element size specified in the typed array constructors table for view.[[TypedArrayName]].- element_size = typed_array->element_size();-- // 2. Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].- switch (typed_array->kind()) {-#define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \- case JS::TypedArrayBase::Kind::ClassName: \- ctor = realm.intrinsics().snake_name##_constructor(); \- break;- JS_ENUMERATE_TYPED_ARRAYS-#undef __JS_ENUMERATE- }- }-- // 5. Let minimumFill be min × elementSize.- u64 minimum_fill = min * element_size;-- // 6. Assert: minimumFill ≥ 0 and minimumFill ≤ view.[[ByteLength]].- VERIFY(minimum_fill <= view.byte_length());-- // 7. Assert: the remainder after dividing minimumFill by elementSize is 0.- VERIFY(minimum_fill % element_size == 0);-- // 8. Let byteOffset be view.[[ByteOffset]].- auto byte_offset = view.byte_offset();-- // 6. Let byteLength be view.[[ByteLength]].- auto byte_length = view.byte_length();-- // 7. Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).- auto buffer_result = transfer_array_buffer(realm, *view.viewed_array_buffer());-- // 8. If bufferResult is an abrupt completion,- if (buffer_result.is_exception()) {- // 1. Perform readIntoRequest’s error steps, given bufferResult.[[Value]].- auto throw_completion = WebIDL::exception_to_throw_completion(vm, realm, buffer_result.exception());- read_into_request.on_error(throw_completion.release_value());-- // 2. Return.- return;- }-- // 9. Let buffer be bufferResult.[[Value]].- auto buffer = buffer_result.value();-- // 10. Let pullIntoDescriptor be a new pull-into descriptor with- //- // buffer buffer- // buffer byte length buffer.[[ArrayBufferByteLength]]- // byte offset byteOffset- // byte length byteLength- // bytes filled 0- // minimum fill minimumFill- // element size elementSize- // view constructor ctor- // reader type "byob"- auto pull_into_descriptor = GC::Heap::the().allocate<PullIntoDescriptor>(- buffer,- buffer->byte_length(),- byte_offset,- byte_length,- 0,- minimum_fill,- element_size,- *ctor,- ReaderType::Byob);-- // 11. If controller.[[pendingPullIntos]] is not empty,- if (!controller.pending_pull_intos().is_empty()) {- // 1. Append pullIntoDescriptor to controller.[[pendingPullIntos]].- controller.pending_pull_intos().append(pull_into_descriptor);-- // 2. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).- readable_stream_add_read_into_request(*stream, read_into_request);-- // 3. Return.- return;- }-- // 12. If stream.[[state]] is "closed",- if (stream->state() == ReadableStream::State::Closed) {- // 1. Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).- auto empty_view = MUST(JS::construct(vm, *ctor, pull_into_descriptor->buffer, JS::Value(pull_into_descriptor->byte_offset), JS::Value(0)));-- // 2. Perform readIntoRequest’s close steps, given emptyView.- read_into_request.on_close(empty_view);-- // 3. Return.- return;- }-- // 13. If controller.[[queueTotalSize]] > 0,- if (controller.queue_total_size() > 0) {- // 1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,- if (readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(controller, pull_into_descriptor)) {- // 1. Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).- auto filled_view = readable_byte_stream_controller_convert_pull_into_descriptor(realm, pull_into_descriptor);-- // 2. Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).- readable_byte_stream_controller_handle_queue_drain(controller);-- // 3. Perform readIntoRequest’s chunk steps, given filledView.- read_into_request.on_chunk(filled_view);-- // 4. Return.- return;- }-- // 2. If controller.[[closeRequested]] is true,- if (controller.close_requested()) {- // 1. Let e be a TypeError exception.- auto error = JS::TypeError::create(realm, "Reader has been released"_utf16);-- // 2. Perform ! ReadableByteStreamControllerError(controller, e).- readable_byte_stream_controller_error(controller, error);-- // 3. Perform readIntoRequest’s error steps, given e.- read_into_request.on_error(error);-- // 4. Return.- return;- }- }-- // 14. Append pullIntoDescriptor to controller.[[pendingPullIntos]].- controller.pending_pull_intos().append(pull_into_descriptor);-- // 15. Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).- readable_stream_add_read_into_request(*stream, read_into_request);-- // 16. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).- readable_byte_stream_controller_call_pull_if_needed(controller);-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond(JS::Realm& realm, ReadableByteStreamController& controller, u64 bytes_written)-{- // 1. Assert: controller.[[pendingPullIntos]] is not empty.- VERIFY(!controller.pending_pull_intos().is_empty());-- // 2. Let firstDescriptor be controller.[[pendingPullIntos]][0].- auto first_descriptor = controller.pending_pull_intos().first();-- // 3. Let state be controller.[[stream]].[[state]].- auto state = controller.stream()->state();-- // 4. If state is "closed",- if (state == ReadableStream::State::Closed) {- // 1. If bytesWritten is not 0, throw a TypeError exception.- if (bytes_written != 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is not zero for closed stream"_utf16 };- }- // 5. Otherwise,- else {- // 1. Assert: state is "readable".- VERIFY(state == ReadableStream::State::Readable);-- // 2. If bytesWritten is 0, throw a TypeError exception.- if (bytes_written == 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Bytes written is zero for stream which is not closed"_utf16 };-- // 3. If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length, throw a RangeError exception.- if (first_descriptor->bytes_filled + bytes_written > first_descriptor->byte_length)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Bytes written is greater than the pull requests byte length"_utf16 };- }-- // 6. Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).- first_descriptor->buffer = MUST(transfer_array_buffer(realm, *first_descriptor->buffer));-- // 7. Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).- return readable_byte_stream_controller_respond_internal(realm, controller, bytes_written);-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-closed-state-void readable_byte_stream_controller_respond_in_closed_state(JS::Realm& realm, ReadableByteStreamController& controller, PullIntoDescriptor& first_descriptor)-{- // 1. Assert: the remainder after dividing firstDescriptor’s bytes filled by firstDescriptor’s element size is 0.- VERIFY(first_descriptor.bytes_filled % first_descriptor.element_size == 0);-- // 2. If firstDescriptor’s reader type is "none", perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).- if (first_descriptor.reader_type == ReaderType::None)- readable_byte_stream_controller_shift_pending_pull_into(controller);-- // 3. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 4. If ! ReadableStreamHasBYOBReader(stream) is true,- if (readable_stream_has_byob_reader(*stream)) {- // 1. Let filledPullIntos be a new empty list.- SinglyLinkedList<GC::Root<PullIntoDescriptor>> filled_pull_intos;-- // 2. While filledPullIntos’s size < ! ReadableStreamGetNumReadIntoRequests(stream),- while (filled_pull_intos.size() < readable_stream_get_num_read_into_requests(*stream)) {- // 1. Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).- auto pull_into_descriptor = readable_byte_stream_controller_shift_pending_pull_into(controller);-- // 2. Append pullIntoDescriptor to filledPullIntos.- filled_pull_intos.append(pull_into_descriptor);- }-- // 3. For each filledPullInto of filledPullIntos,- for (auto& filled_pull_into : filled_pull_intos) {- // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, filledPullInto).- readable_byte_stream_controller_commit_pull_into_descriptor(realm, *stream, *filled_pull_into);- }- }-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-readable-state-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_in_readable_state(JS::Realm& realm, ReadableByteStreamController& controller, u64 bytes_written, PullIntoDescriptor& pull_into_descriptor)-{- // 1. Assert: pullIntoDescriptor’s bytes filled + bytesWritten ≤ pullIntoDescriptor’s byte length.- VERIFY(pull_into_descriptor.bytes_filled + bytes_written <= pull_into_descriptor.byte_length);-- // 2. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor).- readable_byte_stream_controller_fill_head_pull_into_descriptor(controller, bytes_written, pull_into_descriptor);-- // 3. If pullIntoDescriptor’s reader type is "none",- if (pull_into_descriptor.reader_type == ReaderType::None) {- // 1. Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).- TRY(readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(realm, controller, pull_into_descriptor));-- // 2. Let filledPullIntos be the result of performing ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).- auto filled_pulled_intos = readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);-- // 3. For each filledPullInto of filledPullIntos,- for (auto& filled_pull_into : filled_pulled_intos) {- // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], filledPullInto).- readable_byte_stream_controller_commit_pull_into_descriptor(realm, *controller.stream(), *filled_pull_into);- }-- // 4. Return.- return {};- }-- // 4. If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.- if (pull_into_descriptor.bytes_filled < pull_into_descriptor.minimum_fill)- return {};-- // NOTE: A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head of- // the queue, so the underlying source can keep filling it.-- // 5. Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).- readable_byte_stream_controller_shift_pending_pull_into(controller);-- // 6. Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element size.- auto remainder_size = pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size;-- // 7. If remainderSize > 0,- if (remainder_size > 0) {- // 1. Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.- auto end = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;-- // 2. Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, end − remainderSize, remainderSize).- TRY(readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(realm, controller, *pull_into_descriptor.buffer, end - remainder_size, remainder_size));- }-- // 8. Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.- pull_into_descriptor.bytes_filled -= remainder_size;-- // 9. Let filledPullIntos be the result of performing ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).- auto filled_pulled_intos = readable_byte_stream_controller_process_pull_into_descriptors_using_queue(controller);-- // 10. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).- readable_byte_stream_controller_commit_pull_into_descriptor(realm, *controller.stream(), pull_into_descriptor);-- // 11. For each filledPullInto of filledPullIntos,- for (auto& filled_pull_into : filled_pulled_intos) {- // 1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], filledPullInto).- readable_byte_stream_controller_commit_pull_into_descriptor(realm, *controller.stream(), *filled_pull_into);- }-- return {};-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-internal-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_internal(JS::Realm& realm, ReadableByteStreamController& controller, u64 bytes_written)-{- // 1. Let firstDescriptor be controller.[[pendingPullIntos]][0].- auto first_descriptor = controller.pending_pull_intos().first();-- // 2. Assert: ! CanTransferArrayBuffer(firstDescriptor’s buffer) is true.- VERIFY(can_transfer_array_buffer(*first_descriptor->buffer));-- // 3. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).- readable_byte_stream_controller_invalidate_byob_request(controller);-- // 4. Let state be controller.[[stream]].[[state]].- auto state = controller.stream()->state();-- // 5. If state is "closed",- if (state == ReadableStream::State::Closed) {- // 1. Assert: bytesWritten is 0.- VERIFY(bytes_written == 0);-- // 2. Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).- readable_byte_stream_controller_respond_in_closed_state(realm, controller, first_descriptor);- }- // 6. Otherwise,- else {- // 1. Assert: state is "readable".- VERIFY(state == ReadableStream::State::Readable);-- // 2. Assert: bytesWritten > 0.- VERIFY(bytes_written > 0);-- // 3. Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).- TRY(readable_byte_stream_controller_respond_in_readable_state(realm, controller, bytes_written, first_descriptor));- }-- // 7. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).- readable_byte_stream_controller_call_pull_if_needed(controller);-- return {};-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-with-new-view-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_with_new_view(JS::Realm& realm, ReadableByteStreamController& controller, WebIDL::ArrayBufferView view)-{- // 1. Assert: controller.[[pendingPullIntos]] is not empty.- VERIFY(!controller.pending_pull_intos().is_empty());-- // 2. Assert: ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is false.- VERIFY(!view.viewed_array_buffer()->is_detached());-- // 3. Let firstDescriptor be controller.[[pendingPullIntos]][0].- auto first_descriptor = controller.pending_pull_intos().first();-- // 4. Let state be controller.[[stream]].[[state]].- auto state = controller.stream()->state();-- // 5. If state is "closed",- if (state == ReadableStream::State::Closed) {- // 1. If view.[[ByteLength]] is not 0, throw a TypeError exception.- if (view.byte_length() != 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Byte length is not zero for closed stream"_utf16 };- }- // 6. Otherwise,- else {- // 1. Assert: state is "readable".- VERIFY(state == ReadableStream::State::Readable);-- // 2. If view.[[ByteLength]] is 0, throw a TypeError exception.- if (view.byte_length() == 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Byte length is zero for stream which is not closed"_utf16 };- }-- // 7. If firstDescriptor’s byte offset + firstDescriptor’ bytes filled is not view.[[ByteOffset]], throw a RangeError exception.- if (first_descriptor->byte_offset + first_descriptor->bytes_filled != view.byte_offset())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Byte offset is not aligned with the pull request's byte offset"_utf16 };-- // 8. If firstDescriptor’s buffer byte length is not view.[[ViewedArrayBuffer]].[[ByteLength]], throw a RangeError exception.- if (first_descriptor->buffer_byte_length != view.viewed_array_buffer()->byte_length())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Buffer byte length is not aligned with the pull request's byte length"_utf16 };-- // 9. If firstDescriptor’s bytes filled + view.[[ByteLength]] > firstDescriptor’s byte length, throw a RangeError exception.- if (first_descriptor->bytes_filled + view.byte_length() > first_descriptor->byte_length)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Byte length is greater than the pull request's byte length"_utf16 };-- // 10. Let viewByteLength be view.[[ByteLength]].- auto view_byte_length = view.byte_length();-- // 11. Set firstDescriptor’s buffer to ? TransferArrayBuffer(view.[[ViewedArrayBuffer]]).- first_descriptor->buffer = TRY(transfer_array_buffer(realm, *view.viewed_array_buffer()));-- // 12. Perform ? ReadableByteStreamControllerRespondInternal(controller, viewByteLength).- TRY(readable_byte_stream_controller_respond_internal(realm, controller, view_byte_length));-- return {};-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into-GC::Ref<PullIntoDescriptor> readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller)-{- // 1. Assert: controller.[[byobRequest]] is null.- VERIFY(!controller.raw_byob_request());-- // 2. Let descriptor be controller.[[pendingPullIntos]][0].- // 3. Remove descriptor from controller.[[pendingPullIntos]].- auto descriptor = controller.pending_pull_intos().take_first();-- // 4. Return descriptor.- return descriptor;-}--// https://streams.spec.whatwg.org/#readable-byte-stream-controller-error-bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const& controller)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If stream.[[state]] is not "readable", return false.- if (stream->state() != ReadableStream::State::Readable)- return false;-- // 3. If controller.[[closeRequested]] is true, return false.- if (controller.close_requested())- return false;-- // 4. If controller.[[started]] is false, return false.- if (!controller.started())- return false;-- // 5. If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.- if (readable_stream_has_default_reader(*stream) && readable_stream_get_num_read_requests(*stream) > 0)- return true;-- // 6. If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.- if (readable_stream_has_byob_reader(*stream) && readable_stream_get_num_read_into_requests(*stream) > 0)- return true;-- // 7. Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).- auto desired_size = readable_byte_stream_controller_get_desired_size(controller);-- // 8. Assert: desiredSize is not null.- VERIFY(desired_size.has_value());-- // 9. If desiredSize > 0, return true.- if (*desired_size > 0.0)- return true;-- // 10. Return false.- return false;-}--// https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller(JS::Realm& realm, ReadableStream& stream, ReadableByteStreamController& controller, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm, double high_water_mark, JS::Value auto_allocate_chunk_size)-{- // 1. Assert: stream.[[controller]] is undefined.- VERIFY(!stream.controller().has_value());-- // 2. If autoAllocateChunkSize is not undefined,- if (!auto_allocate_chunk_size.is_undefined()) {- // 1. Assert: ! IsInteger(autoAllocateChunkSize) is true.- VERIFY(auto_allocate_chunk_size.is_integral_number());-- // 2. Assert: autoAllocateChunkSize is positive.- VERIFY(auto_allocate_chunk_size.as_double() > 0);- }-- // 3. Set controller.[[stream]] to stream.- controller.set_stream(stream);-- // 4. Set controller.[[pullAgain]] and controller.[[pulling]] to false.- controller.set_pull_again(false);- controller.set_pulling(false);-- // 5. Set controller.[[byobRequest]] to null.- controller.set_byob_request({});-- // 6. Perform ! ResetQueue(controller).- reset_queue(controller);-- // 7. Set controller.[[closeRequested]] and controller.[[started]] to false.- controller.set_close_requested(false);- controller.set_started(false);-- // 8. Set controller.[[strategyHWM]] to highWaterMark.- controller.set_strategy_hwm(high_water_mark);-- // 9. Set controller.[[pullAlgorithm]] to pullAlgorithm.- controller.set_pull_algorithm(pull_algorithm);-- // 10. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.- controller.set_cancel_algorithm(cancel_algorithm);-- // 11. Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.- if (auto_allocate_chunk_size.is_integral_number())- controller.set_auto_allocate_chunk_size(auto_allocate_chunk_size.as_double());-- // 12. Set controller.[[pendingPullIntos]] to a new empty list.- controller.pending_pull_intos().clear();-- // 13. Set stream.[[controller]] to controller.- stream.set_controller(ReadableStreamController { controller });-- // 14. Let startResult be the result of performing startAlgorithm.- auto start_result = TRY(start_algorithm->function()());-- // 15. Let startPromise be a promise resolved with startResult.- auto start_promise = WebIDL::create_resolved_promise(realm, start_result);-- WebIDL::react_to_promise(start_promise,- // 16. Upon fulfillment of startPromise,- GC::create_function(GC::Heap::the(), [&controller](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Set controller.[[started]] to true.- controller.set_started(true);-- // 2. Assert: controller.[[pulling]] is false.- VERIFY(!controller.pulling());-- // 3. Assert: controller.[[pullAgain]] is false.- VERIFY(!controller.pull_again());-- // 4. Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).- readable_byte_stream_controller_call_pull_if_needed(controller);-- return JS::js_undefined();- }),-- // 17. Upon rejection of startPromise with reason r,- GC::create_function(GC::Heap::the(), [&controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! ReadableByteStreamControllerError(controller, r).- readable_byte_stream_controller_error(controller, reason);-- return JS::js_undefined();- }));-- return {};-}--// https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source-WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller_from_underlying_source(JS::Realm& realm, ReadableStream& stream, JS::Value underlying_source, UnderlyingSource const& underlying_source_dict, double high_water_mark)-{- // 1. Let controller be a new ReadableByteStreamController.- auto controller = GC::Heap::the().allocate<ReadableByteStreamController>();-- // 2. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> {- return JS::js_undefined();- });-- // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&realm]() {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [&realm](JS::Value) {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of- // invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.- if (underlying_source_dict.start) {- start_algorithm = GC::create_function(GC::Heap::the(), [&realm, controller, underlying_source, callback = underlying_source_dict.start]() -> WebIDL::ExceptionOr<JS::Value> {- return Bindings::invoke_readable_byte_stream_start_algorithm_callback(realm, *callback, underlying_source, controller);- });- }-- // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of- // invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.- if (underlying_source_dict.pull) {- pull_algorithm = GC::create_function(GC::Heap::the(), [&realm, controller, underlying_source, callback = underlying_source_dict.pull]() {- return Bindings::invoke_readable_byte_stream_pull_algorithm_callback(realm, *callback, underlying_source, controller);- });- }-- // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument- // reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and- // callback this value underlyingSource.- if (underlying_source_dict.cancel) {- cancel_algorithm = GC::create_function(GC::Heap::the(), [underlying_source, callback = underlying_source_dict.cancel](JS::Value reason) {- return WebIDL::invoke_promise_callback(*callback, underlying_source, { { reason } });- });- }-- // 8. Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.- auto auto_allocate_chunk_size = underlying_source_dict.auto_allocate_chunk_size.has_value()- ? JS::Value(underlying_source_dict.auto_allocate_chunk_size.value())- : JS::js_undefined();-- // 9. If autoAllocateChunkSize is 0, then throw a TypeError exception.- if (auto_allocate_chunk_size.is_integral_number() && auto_allocate_chunk_size.as_double() == 0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot use an auto allocate chunk size of 0"_utf16 };-- // 10. Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).- return set_up_readable_byte_stream_controller(realm, stream, controller, start_algorithm, pull_algorithm, cancel_algorithm, high_water_mark, auto_allocate_chunk_size);-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamOperations.h b/Libraries/LibWeb/Streams/ReadableStreamOperations.hdeleted file mode 100644index 8ad304093ea..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamOperations.h+++ /dev/null@@ -1,113 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Forward.h>-#include <LibGC/Ptr.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--// 4.9.1. Working with readable streams, https://streams.spec.whatwg.org/#rs-abstract-ops-WebIDL::ExceptionOr<GC::Ref<ReadableStreamBYOBReader>> acquire_readable_stream_byob_reader(JS::Realm&, ReadableStream&);-WebIDL::ExceptionOr<GC::Ref<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(JS::Realm&, ReadableStream&);-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> create_readable_stream(JS::Realm& realm, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm, Optional<double> high_water_mark = {}, GC::Ptr<SizeAlgorithm> size_algorithm = {});-WebIDL::ExceptionOr<GC::Ref<ReadableStream>> create_readable_byte_stream(JS::Realm& realm, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<PullAlgorithm> pull_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm);-void initialize_readable_stream(ReadableStream&);-bool is_readable_stream_locked(ReadableStream const&);--WebIDL::ExceptionOr<GC::Ref<ReadableStream>> readable_stream_from_iterable(JS::Realm&, JS::Value async_iterable);-GC::Ref<WebIDL::Promise> readable_stream_pipe_to(JS::Realm&, ReadableStream& source, WritableStream& dest, bool prevent_close, bool prevent_abort, bool prevent_cancel, GC::Ptr<DOM::AbortSignal> signal = {});-WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_tee(JS::Realm&, ReadableStream&, bool clone_for_branch2);-WebIDL::ExceptionOr<ReadableStreamPair> readable_stream_default_tee(JS::Realm& realm, ReadableStream& stream, bool clone_for_branch2);-WebIDL::ExceptionOr<ReadableStreamPair> readable_byte_stream_tee(JS::Realm& realm, ReadableStream& stream);--// 4.9.2. Interfacing with controllers, https://streams.spec.whatwg.org/#rs-abstract-ops-used-by-controllers-void readable_stream_add_read_into_request(ReadableStream&, GC::Ref<ReadIntoRequest>);-void readable_stream_add_read_request(ReadableStream&, GC::Ref<ReadRequest>);-GC::Ref<WebIDL::Promise> readable_stream_cancel(JS::Realm&, ReadableStream&, JS::Value reason);-void readable_stream_close(ReadableStream&);-void readable_stream_error(ReadableStream&, JS::Value error);--void readable_stream_fulfill_read_into_request(ReadableStream&, JS::Value chunk, bool done);-void readable_stream_fulfill_read_request(ReadableStream&, JS::Value chunk, bool done);-size_t readable_stream_get_num_read_into_requests(ReadableStream const&);-size_t readable_stream_get_num_read_requests(ReadableStream const&);-bool readable_stream_has_byob_reader(ReadableStream const&);-bool readable_stream_has_default_reader(ReadableStream const&);--// 4.9.3. Readers, https://streams.spec.whatwg.org/#rs-reader-abstract-ops-GC::Ref<WebIDL::Promise> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin&, JS::Value reason);-void readable_stream_reader_generic_initialize(JS::Realm&, ReadableStreamReader const&, ReadableStream&);-void readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin&);--void readable_stream_byob_reader_error_read_into_requests(ReadableStreamBYOBReader&, JS::Value error);-void readable_stream_byob_reader_read(ReadableStreamBYOBReader&, WebIDL::ArrayBufferView&, u64 min, ReadIntoRequest&);-void readable_stream_byob_reader_release(ReadableStreamBYOBReader&);--void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader&, JS::Value error);-void readable_stream_default_reader_read(ReadableStreamDefaultReader&, ReadRequest&);-void readable_stream_default_reader_release(ReadableStreamDefaultReader&);--WebIDL::ExceptionOr<void> set_up_readable_stream_byob_reader(JS::Realm&, ReadableStreamBYOBReader&, ReadableStream&);-WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(JS::Realm&, ReadableStreamDefaultReader&, ReadableStream&);--// 4.9.4. Default controllers, https://streams.spec.whatwg.org/#rs-default-controller-abstract-ops-void readable_stream_default_controller_call_pull_if_needed(ReadableStreamDefaultController&);-bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController&);-void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController&);-void readable_stream_default_controller_close(ReadableStreamDefaultController&);-WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(JS::Realm&, ReadableStreamDefaultController&, JS::Value chunk);-void readable_stream_default_controller_error(ReadableStreamDefaultController&, JS::Value error);-Optional<double> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController&);-bool readable_stream_default_controller_has_backpressure(ReadableStreamDefaultController&);-bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController&);-WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller(JS::Realm&, ReadableStream&, ReadableStreamDefaultController&, GC::Ref<StartAlgorithm>, GC::Ref<PullAlgorithm>, GC::Ref<CancelAlgorithm>, double high_water_mark, GC::Ref<SizeAlgorithm>);-WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller_from_underlying_source(JS::Realm&, ReadableStream&, JS::Value underlying_source_value, UnderlyingSource, double high_water_mark, GC::Ref<SizeAlgorithm>);--// 4.9.5. Byte stream controllers, https://streams.spec.whatwg.org/#rbs-controller-abstract-ops-void readable_byte_stream_controller_call_pull_if_needed(ReadableByteStreamController&);-void readable_byte_stream_controller_clear_algorithms(ReadableByteStreamController&);-void readable_byte_stream_controller_clear_pending_pull_intos(ReadableByteStreamController&);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_close(JS::Realm&, ReadableByteStreamController&);-void readable_byte_stream_controller_commit_pull_into_descriptor(JS::Realm&, ReadableStream&, PullIntoDescriptor const&);-JS::Value readable_byte_stream_controller_convert_pull_into_descriptor(JS::Realm&, PullIntoDescriptor const&);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue(JS::Realm&, ReadableByteStreamController& controller, JS::Value chunk);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_native_bytes(JS::Realm&, ReadableByteStreamController& controller, ByteBuffer bytes);-void readable_byte_stream_controller_enqueue_chunk_to_queue(ReadableByteStreamController& controller, GC::Ref<JS::ArrayBuffer> buffer, u32 byte_offset, u32 byte_length);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(JS::Realm&, ReadableByteStreamController& controller, JS::ArrayBuffer& buffer, u64 byte_offset, u64 byte_length);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_enqueue_detached_pull_into_to_queue(JS::Realm&, ReadableByteStreamController& controller, PullIntoDescriptor& pull_into_descriptor);-void readable_byte_stream_controller_error(ReadableByteStreamController&, JS::Value error);-void readable_byte_stream_controller_fill_head_pull_into_descriptor(ReadableByteStreamController const&, u64 size, PullIntoDescriptor&);-bool readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(ReadableByteStreamController&, PullIntoDescriptor&);-void readable_byte_stream_controller_fill_read_request_from_queue(JS::Realm&, ReadableByteStreamController&, ReadRequest&);-GC::Ptr<ReadableStreamBYOBRequest> readable_byte_stream_controller_get_byob_request(JS::Realm&, ReadableByteStreamController&);-Optional<double> readable_byte_stream_controller_get_desired_size(ReadableByteStreamController const&);-void readable_byte_stream_controller_handle_queue_drain(ReadableByteStreamController&);-void readable_byte_stream_controller_invalidate_byob_request(ReadableByteStreamController&);-[[nodiscard]] SinglyLinkedList<GC::Root<PullIntoDescriptor>> readable_byte_stream_controller_process_pull_into_descriptors_using_queue(ReadableByteStreamController&);-void readable_byte_stream_controller_process_read_requests_using_queue(JS::Realm&, ReadableByteStreamController& controller);-void readable_byte_stream_controller_pull_into(JS::Realm&, ReadableByteStreamController&, WebIDL::ArrayBufferView&, u64 min, ReadIntoRequest&);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond(JS::Realm&, ReadableByteStreamController&, u64 bytes_written);-void readable_byte_stream_controller_respond_in_closed_state(JS::Realm&, ReadableByteStreamController&, PullIntoDescriptor&);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_in_readable_state(JS::Realm&, ReadableByteStreamController&, u64 bytes_written, PullIntoDescriptor&);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_internal(JS::Realm&, ReadableByteStreamController&, u64 bytes_written);-WebIDL::ExceptionOr<void> readable_byte_stream_controller_respond_with_new_view(JS::Realm&, ReadableByteStreamController&, WebIDL::ArrayBufferView);-GC::Ref<PullIntoDescriptor> readable_byte_stream_controller_shift_pending_pull_into(ReadableByteStreamController& controller);-bool readable_byte_stream_controller_should_call_pull(ReadableByteStreamController const&);-WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller(JS::Realm&, ReadableStream&, ReadableByteStreamController&, GC::Ref<StartAlgorithm>, GC::Ref<PullAlgorithm>, GC::Ref<CancelAlgorithm>, double high_water_mark, JS::Value auto_allocate_chunk_size);-WebIDL::ExceptionOr<void> set_up_readable_byte_stream_controller_from_underlying_source(JS::Realm&, ReadableStream&, JS::Value underlying_source, UnderlyingSource const& underlying_source_dict, double high_water_mark);--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamPipeTo.cpp b/Libraries/LibWeb/Streams/ReadableStreamPipeTo.cppdeleted file mode 100644index d77f5c17b71..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamPipeTo.cpp+++ /dev/null@@ -1,413 +0,0 @@-/*- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/ReadableStreamPipeTo.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultWriter.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams::Detail {--class ReadableStreamPipeToReadRequest final : public ReadRequest {- GC_CELL(ReadableStreamPipeToReadRequest, ReadRequest);- GC_DECLARE_ALLOCATOR(ReadableStreamPipeToReadRequest);-- using OnChunk = GC::Ref<GC::Function<void(JS::Value)>>;- using OnComplete = GC::Ref<GC::Function<void()>>;-- // This has a return value just for compatibility with WebIDL::react_to_promise.- using OnError = GC::Ref<GC::Function<WebIDL::ExceptionOr<JS::Value>(JS::Value)>>;--public:- virtual void on_chunk(JS::Value chunk) override- {- m_on_chunk->function()(chunk);- }-- virtual void on_close() override- {- m_on_complete->function()();- }-- virtual void on_error(JS::Value error) override- {- MUST(m_on_error->function()(error));- }--private:- ReadableStreamPipeToReadRequest(OnChunk on_chunk, OnComplete on_complete, OnError on_error)- : m_on_chunk(on_chunk)- , m_on_complete(on_complete)- , m_on_error(on_error)- {- }-- virtual void visit_edges(Visitor& visitor) override- {- Base::visit_edges(visitor);- visitor.visit(m_on_chunk);- visitor.visit(m_on_complete);- visitor.visit(m_on_error);- }-- OnChunk m_on_chunk;- OnComplete m_on_complete;- OnError m_on_error;-};--GC_DEFINE_ALLOCATOR(ReadableStreamPipeTo);-GC_DEFINE_ALLOCATOR(ReadableStreamPipeToReadRequest);--// https://streams.spec.whatwg.org/#ref-for-in-parallel-ReadableStreamPipeTo::ReadableStreamPipeTo(- GC::Ref<WebIDL::Promise> promise,- GC::Ref<ReadableStream> source,- GC::Ref<WritableStream> destination,- GC::Ref<ReadableStreamDefaultReader> reader,- GC::Ref<WritableStreamDefaultWriter> writer,- bool prevent_close,- bool prevent_abort,- bool prevent_cancel)- : m_promise(promise)- , m_source(source)- , m_destination(destination)- , m_reader(reader)- , m_writer(writer)- , m_on_shutdown(GC::create_function(GC::Heap::the(), [this](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- check_for_error_and_close_states();- return JS::js_undefined();- }))- , m_prevent_close(prevent_close)- , m_prevent_abort(prevent_abort)- , m_prevent_cancel(prevent_cancel)-{- m_reader->set_readable_stream_pipe_to_operation({}, this);-- if (auto reader_closed_promise = m_reader->closed())- WebIDL::react_to_promise(*reader_closed_promise, m_on_shutdown, m_on_shutdown);- if (auto writer_closed_promise = m_writer->closed())- WebIDL::react_to_promise(*writer_closed_promise, m_on_shutdown, m_on_shutdown);-}--void ReadableStreamPipeTo::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_promise);- visitor.visit(m_source);- visitor.visit(m_destination);- visitor.visit(m_reader);- visitor.visit(m_writer);- visitor.visit(m_signal);- visitor.visit(m_last_write_promise);- visitor.visit(m_unwritten_chunks);- visitor.visit(m_on_shutdown);-}--JS::Realm& ReadableStreamPipeTo::promise_realm() const-{- return WebIDL::promise_realm(m_promise);-}--void ReadableStreamPipeTo::process()-{- if (check_for_error_and_close_states())- return;-- auto ready_promise = m_writer->ready();-- if (ready_promise && WebIDL::is_promise_fulfilled(*ready_promise)) {- read_chunk();- return;- }-- auto when_ready = GC::create_function(GC::Heap::the(), [this](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- read_chunk();- return JS::js_undefined();- });-- if (ready_promise)- WebIDL::react_to_promise(*ready_promise, when_ready, m_on_shutdown);-}--void ReadableStreamPipeTo::set_abort_signal(GC::Ref<DOM::AbortSignal> signal, DOM::AbortSignal::AbortSignal::AbortAlgorithmID signal_id)-{- m_signal = signal;- m_signal_id = signal_id;-}--// https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-with-action-void ReadableStreamPipeTo::shutdown_with_action(GC::Ref<GC::Function<GC::Ref<WebIDL::Promise>()>> action, Optional<JS::Value> original_error)-{- // 1. If shuttingDown is true, abort these substeps.- if (m_shutting_down)- return;-- // 2. Set shuttingDown to true.- m_shutting_down = true;-- auto on_pending_writes_complete = [this, action, original_error = move(original_error)]() mutable {- HTML::TemporaryExecutionContext execution_context { promise_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 4. Let p be the result of performing action.- auto promise = action->function()();-- WebIDL::react_to_promise(promise,- // 5. Upon fulfillment of p, finalize, passing along originalError if it was given.- GC::create_function(GC::Heap::the(), [this, original_error = move(original_error)](JS::Value) mutable -> WebIDL::ExceptionOr<JS::Value> {- finish(move(original_error));- return JS::js_undefined();- }),-- // 6. Upon rejection of p with reason newError, finalize with newError.- GC::create_function(GC::Heap::the(), [this](JS::Value new_error) -> WebIDL::ExceptionOr<JS::Value> {- finish(new_error);- return JS::js_undefined();- }));- };-- // 3. If dest.[[state]] is "writable" and ! WritableStreamCloseQueuedOrInFlight(dest) is false,- if (m_destination->state() == WritableStream::State::Writable && !writable_stream_close_queued_or_in_flight(m_destination)) {- // 1. If any chunks have been read but not yet written, write them to dest.- write_unwritten_chunks();-- // 2. Wait until every chunk that has been read has been written (i.e. the corresponding promises have settled).- wait_for_pending_writes_to_complete(move(on_pending_writes_complete));- } else {- on_pending_writes_complete();- }-}--// https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-void ReadableStreamPipeTo::shutdown(Optional<JS::Value> error)-{- // 1. If shuttingDown is true, abort these substeps.- if (m_shutting_down)- return;-- // 2. Set shuttingDown to true.- m_shutting_down = true;-- auto on_pending_writes_complete = [this, error = move(error)]() mutable {- HTML::TemporaryExecutionContext execution_context { promise_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 4. Finalize, passing along error if it was given.- finish(move(error));- };-- // 3. If dest.[[state]] is "writable" and ! WritableStreamCloseQueuedOrInFlight(dest) is false,- if (m_destination->state() == WritableStream::State::Writable && !writable_stream_close_queued_or_in_flight(m_destination)) {- // 1. If any chunks have been read but not yet written, write them to dest.- write_unwritten_chunks();-- // 2. Wait until every chunk that has been read has been written (i.e. the corresponding promises have settled).- wait_for_pending_writes_to_complete(move(on_pending_writes_complete));- } else {- on_pending_writes_complete();- }-}--void ReadableStreamPipeTo::read_chunk()-{- // Shutdown must stop activity: if shuttingDown becomes true, the user agent must not initiate further reads from- // reader, and must only perform writes of already-read chunks, as described below. In particular, the user agent- // must check the below conditions before performing any reads or writes, since they might lead to immediate shutdown.- if (check_for_error_and_close_states())- return;-- auto on_chunk = GC::create_function(GC::Heap::the(), [this](JS::Value chunk) {- m_unwritten_chunks.append(chunk);-- if (check_for_error_and_close_states())- return;-- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [this]() {- HTML::TemporaryExecutionContext execution_context { promise_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- write_chunk();- process();- }));- });-- auto on_complete = GC::create_function(GC::Heap::the(), [this]() {- if (!check_for_error_and_close_states())- finish();- });-- auto read_request = GC::Heap::the().allocate<ReadableStreamPipeToReadRequest>(on_chunk, on_complete, *m_on_shutdown);- readable_stream_default_reader_read(m_reader, read_request);-}--void ReadableStreamPipeTo::write_chunk()-{- // Shutdown must stop activity: if shuttingDown becomes true, the user agent must not initiate further reads from- // reader, and must only perform writes of already-read chunks, as described below. In particular, the user agent- // must check the below conditions before performing any reads or writes, since they might lead to immediate shutdown.- if (!m_shutting_down && check_for_error_and_close_states())- return;-- auto promise = writable_stream_default_writer_write(m_writer, m_unwritten_chunks.take_first());- WebIDL::mark_promise_as_handled(promise);-- m_last_write_promise = promise;-}--void ReadableStreamPipeTo::write_unwritten_chunks()-{- while (!m_unwritten_chunks.is_empty())- write_chunk();-}--void ReadableStreamPipeTo::wait_for_pending_writes_to_complete(Function<void()> on_complete)-{- auto last_write_promise = m_last_write_promise;- m_last_write_promise = {};- if (!last_write_promise) {- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [on_complete = move(on_complete)]() {- on_complete();- }));- return;- }- auto run_complete_steps = GC::create_function(GC::Heap::the(), [on_complete = move(on_complete)](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- on_complete();- return JS::js_undefined();- });- WebIDL::react_to_promise(*last_write_promise, run_complete_steps, run_complete_steps);-}--// https://streams.spec.whatwg.org/#rs-pipeTo-finalize-// We call this `finish` instead of `finalize` to avoid conflicts with GC::Cell::finalize.-void ReadableStreamPipeTo::finish(Optional<JS::Value> error)-{- // 1. Perform ! WritableStreamDefaultWriterRelease(writer).- writable_stream_default_writer_release(m_writer);-- // 2. If reader implements ReadableStreamBYOBReader, perform ! ReadableStreamBYOBReaderRelease(reader).- // 3. Otherwise, perform ! ReadableStreamDefaultReaderRelease(reader).- readable_stream_default_reader_release(m_reader);-- // 4. If signal is not undefined, remove abortAlgorithm from signal.- if (m_signal)- m_signal->remove_abort_algorithm(m_signal_id);-- // 5. If error was given, reject promise with error.- if (error.has_value()) {- WebIDL::reject_promise(m_promise, *error);- }- // 6. Otherwise, resolve promise with undefined.- else {- WebIDL::resolve_promise(m_promise);- }-- m_reader->set_readable_stream_pipe_to_operation({}, nullptr);-}--bool ReadableStreamPipeTo::check_for_error_and_close_states()-{- // Error and close states must be propagated: the following conditions must be applied in order.- return m_shutting_down- || check_for_forward_errors()- || check_for_backward_errors()- || check_for_forward_close()- || check_for_backward_close();-}--bool ReadableStreamPipeTo::check_for_forward_errors()-{- // 1. Errors must be propagated forward: if source.[[state]] is or becomes "errored", then- if (m_source->state() == ReadableStream::State::Errored) {- // 1. If preventAbort is false, shutdown with an action of ! WritableStreamAbort(dest, source.[[storedError]])- // and with source.[[storedError]].- if (!m_prevent_abort) {- auto action = GC::create_function(GC::Heap::the(), [this]() {- return writable_stream_abort(promise_realm(), m_destination, m_source->stored_error());- });-- shutdown_with_action(action, m_source->stored_error());- }- // 2. Otherwise, shutdown with source.[[storedError]].- else {- shutdown(m_source->stored_error());- }- }-- return m_shutting_down;-}--bool ReadableStreamPipeTo::check_for_backward_errors()-{- // 2. Errors must be propagated backward: if dest.[[state]] is or becomes "errored", then- if (m_destination->state() == WritableStream::State::Errored) {- // 1. If preventCancel is false, shutdown with an action of ! ReadableStreamCancel(source, dest.[[storedError]])- // and with dest.[[storedError]].- if (!m_prevent_cancel) {- auto action = GC::create_function(GC::Heap::the(), [this]() {- return readable_stream_cancel(promise_realm(), m_source, m_destination->stored_error());- });-- shutdown_with_action(action, m_destination->stored_error());- }- // 2. Otherwise, shutdown with dest.[[storedError]].- else {- shutdown(m_destination->stored_error());- }- }-- return m_shutting_down;-}--bool ReadableStreamPipeTo::check_for_forward_close()-{- // 3. Closing must be propagated forward: if source.[[state]] is or becomes "closed", then- if (m_source->state() == ReadableStream::State::Closed) {- // 1. If preventClose is false, shutdown with an action of ! WritableStreamDefaultWriterCloseWithErrorPropagation(writer).- if (!m_prevent_close) {- auto action = GC::create_function(GC::Heap::the(), [this]() {- return writable_stream_default_writer_close_with_error_propagation(m_writer);- });-- shutdown_with_action(action);- }- // 2. Otherwise, shutdown.- else {- shutdown();- }- }-- return m_shutting_down;-}--bool ReadableStreamPipeTo::check_for_backward_close()-{- // 4. Closing must be propagated backward: if ! WritableStreamCloseQueuedOrInFlight(dest) is true or dest.[[state]] is "closed", then- if (writable_stream_close_queued_or_in_flight(m_destination) || m_destination->state() == WritableStream::State::Closed) {- // 1. Assert: no chunks have been read or written.-- // 2. Let destClosed be a new TypeError.- auto destination_closed = JS::TypeError::create(promise_realm(), "Destination stream was closed during piping operation"sv);-- // 3. If preventCancel is false, shutdown with an action of ! ReadableStreamCancel(source, destClosed) and with destClosed.- if (!m_prevent_cancel) {- auto action = GC::create_function(GC::Heap::the(), [this, destination_closed]() {- return readable_stream_cancel(promise_realm(), m_source, destination_closed);- });-- shutdown_with_action(action, destination_closed);- }- // 4. Otherwise, shutdown with destClosed.- else {- shutdown(destination_closed);- }- }-- return m_shutting_down;-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamPipeTo.h b/Libraries/LibWeb/Streams/ReadableStreamPipeTo.hdeleted file mode 100644index fff83ea9acf..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamPipeTo.h+++ /dev/null@@ -1,83 +0,0 @@-/*- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Vector.h>-#include <LibGC/Ptr.h>-#include <LibJS/Forward.h>-#include <LibJS/Heap/Cell.h>-#include <LibWeb/DOM/AbortSignal.h>-#include <LibWeb/Forward.h>--namespace Web::Streams::Detail {--// https://streams.spec.whatwg.org/#ref-for-in-parallel-class ReadableStreamPipeTo final : public JS::Cell {- GC_CELL(ReadableStreamPipeTo, JS::Cell);- GC_DECLARE_ALLOCATOR(ReadableStreamPipeTo);--public:- void process();-- void set_abort_signal(GC::Ref<DOM::AbortSignal>, DOM::AbortSignal::AbortSignal::AbortAlgorithmID);-- void shutdown_with_action(GC::Ref<GC::Function<GC::Ref<WebIDL::Promise>()>> action, Optional<JS::Value> original_error = {});- void shutdown(Optional<JS::Value> error = {});--private:- ReadableStreamPipeTo(- GC::Ref<WebIDL::Promise>,- GC::Ref<ReadableStream> source,- GC::Ref<WritableStream> destination,- GC::Ref<ReadableStreamDefaultReader> reader,- GC::Ref<WritableStreamDefaultWriter> writer,- bool prevent_close,- bool prevent_abort,- bool prevent_cancel);-- virtual void visit_edges(Cell::Visitor& visitor) override;-- JS::Realm& promise_realm() const;-- void read_chunk();- void write_chunk();-- void write_unwritten_chunks();- void wait_for_pending_writes_to_complete(Function<void()> on_complete);-- void finish(Optional<JS::Value> error = {});-- bool check_for_error_and_close_states();- bool check_for_forward_errors();- bool check_for_backward_errors();- bool check_for_forward_close();- bool check_for_backward_close();-- GC::Ref<WebIDL::Promise> m_promise;-- GC::Ref<ReadableStream> m_source;- GC::Ref<WritableStream> m_destination;-- GC::Ref<ReadableStreamDefaultReader> m_reader;- GC::Ref<WritableStreamDefaultWriter> m_writer;-- GC::Ptr<DOM::AbortSignal> m_signal;- DOM::AbortSignal::AbortAlgorithmID m_signal_id { 0 };-- GC::Ptr<WebIDL::Promise> m_last_write_promise;- Vector<JS::Value, 1> m_unwritten_chunks;-- GC::Ref<WebIDL::ReactionSteps> m_on_shutdown;-- bool m_prevent_close { false };- bool m_prevent_abort { false };- bool m_prevent_cancel { false };-- bool m_shutting_down { false };-};--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamTee.cpp b/Libraries/LibWeb/Streams/ReadableStreamTee.cppdeleted file mode 100644index c621a69ef18..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamTee.cpp+++ /dev/null@@ -1,495 +0,0 @@-/*- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/ReadableByteStreamController.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/ReadableStreamTee.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams::Detail {--GC_DEFINE_ALLOCATOR(ReadableStreamTeeParams);-GC_DEFINE_ALLOCATOR(ReadableStreamTeeReadRequest);--void ReadableStreamTeeParams::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(reason1);- visitor.visit(reason2);- visitor.visit(branch1);- visitor.visit(branch2);- visitor.visit(pull_algorithm);-}--// https://streams.spec.whatwg.org/#ref-for-read-request③-ReadableStreamTeeReadRequest::ReadableStreamTeeReadRequest(- GC::Ref<ReadableStream> stream,- GC::Ref<ReadableStreamTeeParams> params,- GC::Ref<WebIDL::Promise> cancel_promise,- bool clone_for_branch2)- : m_stream(stream)- , m_params(params)- , m_cancel_promise(cancel_promise)- , m_clone_for_branch2(clone_for_branch2)-{-}--JS::Realm& ReadableStreamTeeReadRequest::promise_realm() const-{- return WebIDL::promise_realm(m_cancel_promise);-}--void ReadableStreamTeeReadRequest::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_stream);- visitor.visit(m_params);- visitor.visit(m_cancel_promise);-}--// https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps③-void ReadableStreamTeeReadRequest::on_chunk(JS::Value chunk)-{- // 1. Queue a microtask to perform the following steps:- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [this, chunk]() {- HTML::TemporaryExecutionContext execution_context { promise_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- auto controller1 = m_params->branch1->controller()->get<GC::Ref<ReadableStreamDefaultController>>();- auto controller2 = m_params->branch2->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 1. Set readAgain to false.- m_params->read_again = false;-- // 2. Let chunk1 and chunk2 be chunk.- auto chunk1 = chunk;- auto chunk2 = chunk;-- // 3. If canceled2 is false and cloneForBranch2 is true,- if (!m_params->canceled2 && m_clone_for_branch2) {- // 1. Let cloneResult be StructuredClone(chunk2).- auto clone_result = structured_clone(promise_realm(), chunk2);-- // 2. If cloneResult is an abrupt completion,- if (clone_result.is_exception()) {- auto completion = WebIDL::exception_to_throw_completion(promise_realm().vm(), promise_realm(), clone_result.release_error());-- // 1. Perform ! ReadableStreamDefaultControllerError(branch1.[[controller]], cloneResult.[[Value]]).- readable_stream_default_controller_error(controller1, completion.value());-- // 2. Perform ! ReadableStreamDefaultControllerError(branch2.[[controller]], cloneResult.[[Value]]).- readable_stream_default_controller_error(controller2, completion.value());-- // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).- auto cancel_result = readable_stream_cancel(promise_realm(), m_stream, completion.value());-- // Note: We need to manually convert the result to an ECMAScript value here, by extracting its [[Promise]] slot.- WebIDL::resolve_promise(m_cancel_promise, cancel_result->promise());-- // 4. Return.- return;- }-- // 3. Otherwise, set chunk2 to cloneResult.[[Value]].- chunk2 = clone_result.release_value();- }-- // 4. If canceled1 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch1.[[controller]], chunk1).- if (!m_params->canceled1) {- MUST(readable_stream_default_controller_enqueue(promise_realm(), controller1, chunk1));- }-- // 5. If canceled2 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch2.[[controller]], chunk2).- if (!m_params->canceled2) {- MUST(readable_stream_default_controller_enqueue(promise_realm(), controller2, chunk2));- }-- // 6. Set reading to false.- m_params->reading = false;-- // 7. If readAgain is true, perform pullAlgorithm.- if (m_params->read_again) {- m_params->pull_algorithm->function()();- }- }));-- // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we- // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we- // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.-}--// https://streams.spec.whatwg.org/#ref-for-read-request-close-steps②-void ReadableStreamTeeReadRequest::on_close()-{- auto controller1 = m_params->branch1->controller()->get<GC::Ref<ReadableStreamDefaultController>>();- auto controller2 = m_params->branch2->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 1. Set reading to false.- m_params->reading = false;-- // 2. If canceled1 is false, perform ! ReadableStreamDefaultControllerClose(branch1.[[controller]]).- if (!m_params->canceled1) {- readable_stream_default_controller_close(controller1);- }-- // 3. If canceled2 is false, perform ! ReadableStreamDefaultControllerClose(branch2.[[controller]]).- if (!m_params->canceled2) {- readable_stream_default_controller_close(controller2);- }-- // 4. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.- if (!m_params->canceled1 || !m_params->canceled2) {- WebIDL::resolve_promise(m_cancel_promise);- }-}--// https://streams.spec.whatwg.org/#ref-for-read-request-error-steps③-void ReadableStreamTeeReadRequest::on_error(JS::Value)-{- // 1. Set reading to false.- m_params->reading = false;-}--GC_DEFINE_ALLOCATOR(ReadableByteStreamTeeParams);-GC_DEFINE_ALLOCATOR(ReadableByteStreamTeeDefaultReadRequest);-GC_DEFINE_ALLOCATOR(ReadableByteStreamTeeBYOBReadRequest);--ReadableByteStreamTeeParams::ReadableByteStreamTeeParams(ReadableStreamReader reader)- : reader(move(reader))-{-}--void ReadableByteStreamTeeParams::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(reason1);- visitor.visit(reason2);- visitor.visit(branch1);- visitor.visit(branch2);- visitor.visit(pull1_algorithm);- visitor.visit(pull2_algorithm);- visitor.visit(reader);-}--// https://streams.spec.whatwg.org/#ref-for-read-request④-ReadableByteStreamTeeDefaultReadRequest::ReadableByteStreamTeeDefaultReadRequest(- GC::Ref<ReadableStream> stream,- GC::Ref<ReadableByteStreamTeeParams> params,- GC::Ref<WebIDL::Promise> cancel_promise)- : m_stream(stream)- , m_params(params)- , m_cancel_promise(cancel_promise)-{-}--JS::Realm& ReadableByteStreamTeeDefaultReadRequest::promise_realm() const-{- return WebIDL::promise_realm(m_cancel_promise);-}--void ReadableByteStreamTeeDefaultReadRequest::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_stream);- visitor.visit(m_params);- visitor.visit(m_cancel_promise);-}--// https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps④-void ReadableByteStreamTeeDefaultReadRequest::on_chunk(JS::Value chunk)-{- // 1. Queue a microtask to perform the following steps:- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [this, chunk]() mutable {- HTML::TemporaryExecutionContext execution_context { promise_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- auto controller1 = m_params->branch1->controller()->get<GC::Ref<ReadableByteStreamController>>();- auto controller2 = m_params->branch2->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. Set readAgainForBranch1 to false.- m_params->read_again_for_branch1 = false;-- // 2. Set readAgainForBranch2 to false.- m_params->read_again_for_branch2 = false;-- // 3. Let chunk1 and chunk2 be chunk.- auto chunk1 = chunk;- auto chunk2 = chunk;-- // 4. If canceled1 is false and canceled2 is false,- if (!m_params->canceled1 && !m_params->canceled2) {- // 1. Let cloneResult be CloneAsUint8Array(chunk).- WebIDL::ArrayBufferView chunk_view { WebIDL::ArrayBufferView::from_object(chunk.as_object()) };- auto clone_result = clone_as_uint8_array(promise_realm(), chunk_view);-- // 2. If cloneResult is an abrupt completion,- if (clone_result.is_exception()) {- auto completion = WebIDL::exception_to_throw_completion(promise_realm().vm(), promise_realm(), clone_result.release_error());-- // 1. Perform ! ReadableByteStreamControllerError(branch1.[[controller]], cloneResult.[[Value]]).- readable_byte_stream_controller_error(controller1, completion.value());-- // 2. Perform ! ReadableByteStreamControllerError(branch2.[[controller]], cloneResult.[[Value]]).- readable_byte_stream_controller_error(controller2, completion.value());-- // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).- auto cancel_result = readable_stream_cancel(promise_realm(), m_stream, completion.value());-- WebIDL::resolve_promise(m_cancel_promise, cancel_result->promise());-- // 4. Return.- return;- }-- // 3. Otherwise, set chunk2 to cloneResult.[[Value]].- chunk2 = clone_result.release_value();- }-- // 5. If canceled1 is false, perform ! ReadableByteStreamControllerEnqueue(branch1.[[controller]], chunk1).- if (!m_params->canceled1) {- MUST(readable_byte_stream_controller_enqueue(promise_realm(), controller1, chunk1));- }-- // 6. If canceled2 is false, perform ! ReadableByteStreamControllerEnqueue(branch2.[[controller]], chunk2).- if (!m_params->canceled2) {- MUST(readable_byte_stream_controller_enqueue(promise_realm(), controller2, chunk2));- }-- // 7. Set reading to false.- m_params->reading = false;-- // 8. If readAgainForBranch1 is true, perform pull1Algorithm.- if (m_params->read_again_for_branch1) {- m_params->pull1_algorithm->function()();- }- // 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.- else if (m_params->read_again_for_branch2) {- m_params->pull2_algorithm->function()();- }- }));-- // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we- // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we- // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.-}--// https://streams.spec.whatwg.org/#ref-for-read-request-close-steps③-void ReadableByteStreamTeeDefaultReadRequest::on_close()-{- auto controller1 = m_params->branch1->controller()->get<GC::Ref<ReadableByteStreamController>>();- auto controller2 = m_params->branch2->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. Set reading to false.- m_params->reading = false;-- // 2. If canceled1 is false, perform ! ReadableByteStreamControllerClose(branch1.[[controller]]).- if (!m_params->canceled1) {- MUST(readable_byte_stream_controller_close(promise_realm(), controller1));- }-- // 3. If canceled2 is false, perform ! ReadableByteStreamControllerClose(branch2.[[controller]]).- if (!m_params->canceled2) {- MUST(readable_byte_stream_controller_close(promise_realm(), controller2));- }-- // 4. If branch1.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(branch1.[[controller]], 0).- if (!controller1->pending_pull_intos().is_empty()) {- MUST(readable_byte_stream_controller_respond(promise_realm(), controller1, 0));- }-- // 5. If branch2.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(branch2.[[controller]], 0).- if (!controller2->pending_pull_intos().is_empty()) {- MUST(readable_byte_stream_controller_respond(promise_realm(), controller2, 0));- }-- // 6. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.- if (!m_params->canceled1 || !m_params->canceled2) {- WebIDL::resolve_promise(m_cancel_promise);- }-}--// https://streams.spec.whatwg.org/#ref-for-read-request-error-steps④-void ReadableByteStreamTeeDefaultReadRequest::on_error(JS::Value)-{- // 1. Set reading to false.- m_params->reading = false;-}--// https://streams.spec.whatwg.org/#ref-for-read-into-request②-ReadableByteStreamTeeBYOBReadRequest::ReadableByteStreamTeeBYOBReadRequest(- GC::Ref<ReadableStream> stream,- GC::Ref<ReadableByteStreamTeeParams> params,- GC::Ref<WebIDL::Promise> cancel_promise,- GC::Ref<ReadableStream> byob_branch,- GC::Ref<ReadableStream> other_branch,- bool for_branch2)- : m_stream(stream)- , m_params(params)- , m_cancel_promise(cancel_promise)- , m_byob_branch(byob_branch)- , m_other_branch(other_branch)- , m_for_branch2(for_branch2)-{-}--JS::Realm& ReadableByteStreamTeeBYOBReadRequest::promise_realm() const-{- return WebIDL::promise_realm(m_cancel_promise);-}--void ReadableByteStreamTeeBYOBReadRequest::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_stream);- visitor.visit(m_params);- visitor.visit(m_cancel_promise);- visitor.visit(m_byob_branch);- visitor.visit(m_other_branch);-}--// https://streams.spec.whatwg.org/#ref-for-read-into-request-chunk-steps①-void ReadableByteStreamTeeBYOBReadRequest::on_chunk(JS::Value chunk)-{- WebIDL::ArrayBufferView chunk_view { WebIDL::ArrayBufferView::from_object(chunk.as_object()) };-- // 1. Queue a microtask to perform the following steps:- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [this, chunk = move(chunk_view)]() {- HTML::TemporaryExecutionContext execution_context { promise_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- auto byob_controller = m_byob_branch->controller()->get<GC::Ref<ReadableByteStreamController>>();- auto other_controller = m_other_branch->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. Set readAgainForBranch1 to false.- m_params->read_again_for_branch1 = false;-- // 2. Set readAgainForBranch2 to false.- m_params->read_again_for_branch2 = false;-- // 3. Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.- auto byob_cancelled = m_for_branch2 ? m_params->canceled2 : m_params->canceled1;-- // 4. Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.- auto other_cancelled = !m_for_branch2 ? m_params->canceled2 : m_params->canceled1;-- // 5. If otherCanceled is false,- if (!other_cancelled) {- // 1. Let cloneResult be CloneAsUint8Array(chunk).- auto clone_result = clone_as_uint8_array(promise_realm(), chunk);-- // 2. If cloneResult is an abrupt completion,- if (clone_result.is_exception()) {- auto completion = WebIDL::exception_to_throw_completion(promise_realm().vm(), promise_realm(), clone_result.release_error());-- // 1. Perform ! ReadableByteStreamControllerError(byobBranch.[[controller]], cloneResult.[[Value]]).- readable_byte_stream_controller_error(byob_controller, completion.value());-- // 2. Perform ! ReadableByteStreamControllerError(otherBranch.[[controller]], cloneResult.[[Value]]).- readable_byte_stream_controller_error(other_controller, completion.value());-- // 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).- auto cancel_result = readable_stream_cancel(promise_realm(), m_stream, completion.value());-- WebIDL::resolve_promise(m_cancel_promise, cancel_result->promise());-- // 4. Return.- return;- }-- // 3. Otherwise, let clonedChunk be cloneResult.[[Value]].- auto cloned_chunk = clone_result.release_value();-- // 4. If byobCanceled is false, perform ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).- if (!byob_cancelled) {- MUST(readable_byte_stream_controller_respond_with_new_view(promise_realm(), byob_controller, chunk));- }-- // 5. Perform ! ReadableByteStreamControllerEnqueue(otherBranch.[[controller]], clonedChunk).- MUST(readable_byte_stream_controller_enqueue(promise_realm(), other_controller, cloned_chunk));- }- // 6. Otherwise, if byobCanceled is false, perform ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).- else if (!byob_cancelled) {- MUST(readable_byte_stream_controller_respond_with_new_view(promise_realm(), byob_controller, chunk));- }-- // 7. Set reading to false.- m_params->reading = false;-- // 8. If readAgainForBranch1 is true, perform pull1Algorithm.- if (m_params->read_again_for_branch1) {- m_params->pull1_algorithm->function()();- }- // 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.- else if (m_params->read_again_for_branch2) {- m_params->pull2_algorithm->function()();- }- }));-- // NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we- // use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we- // cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.-}--// https://streams.spec.whatwg.org/#ref-for-read-into-request-close-steps②-void ReadableByteStreamTeeBYOBReadRequest::on_close(JS::Value chunk)-{- auto byob_controller = m_byob_branch->controller()->get<GC::Ref<ReadableByteStreamController>>();- auto other_controller = m_other_branch->controller()->get<GC::Ref<ReadableByteStreamController>>();-- // 1. Set reading to false.- m_params->reading = false;-- // 2. Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.- auto byob_cancelled = m_for_branch2 ? m_params->canceled2 : m_params->canceled1;-- // 3. Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.- auto other_cancelled = !m_for_branch2 ? m_params->canceled2 : m_params->canceled1;-- // 4. If byobCanceled is false, perform ! ReadableByteStreamControllerClose(byobBranch.[[controller]]).- if (!byob_cancelled) {- MUST(readable_byte_stream_controller_close(promise_realm(), byob_controller));- }-- // 5. If otherCanceled is false, perform ! ReadableByteStreamControllerClose(otherBranch.[[controller]]).- if (!other_cancelled) {- MUST(readable_byte_stream_controller_close(promise_realm(), other_controller));- }-- // 6. If chunk is not undefined,- if (!chunk.is_undefined()) {- // 1. Assert: chunk.[[ByteLength]] is 0.-- // 2. If byobCanceled is false, perform ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).- if (!byob_cancelled) {- WebIDL::ArrayBufferView array_buffer_view { WebIDL::ArrayBufferView::from_object(chunk.as_object()) };- MUST(readable_byte_stream_controller_respond_with_new_view(promise_realm(), byob_controller, array_buffer_view));- }-- // 3. If otherCanceled is false and otherBranch.[[controller]].[[pendingPullIntos]] is not empty,- // perform ! ReadableByteStreamControllerRespond(otherBranch.[[controller]], 0).- if (!other_cancelled && !other_controller->pending_pull_intos().is_empty()) {- MUST(readable_byte_stream_controller_respond(promise_realm(), other_controller, 0));- }- }-- // 7. If byobCanceled is false or otherCanceled is false, resolve cancelPromise with undefined.- if (!byob_cancelled || !other_cancelled) {- WebIDL::resolve_promise(m_cancel_promise);- }-}--// https://streams.spec.whatwg.org/#ref-for-read-into-request-error-steps①-void ReadableByteStreamTeeBYOBReadRequest::on_error(JS::Value)-{- // 1. Set reading to false.- m_params->reading = false;-}--}diff --git a/Libraries/LibWeb/Streams/ReadableStreamTee.h b/Libraries/LibWeb/Streams/ReadableStreamTee.hdeleted file mode 100644index 8f29aba000b..00000000000--- a/Libraries/LibWeb/Streams/ReadableStreamTee.h+++ /dev/null@@ -1,139 +0,0 @@-/*- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Ptr.h>-#include <LibJS/Forward.h>-#include <LibJS/Heap/Cell.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamBYOBReader.h>-#include <LibWeb/Streams/ReadableStreamDefaultReader.h>--namespace Web::Streams::Detail {--struct ReadableStreamTeeParams final : public JS::Cell {- GC_CELL(ReadableStreamTeeParams, JS::Cell);- GC_DECLARE_ALLOCATOR(ReadableStreamTeeParams);-- virtual void visit_edges(Visitor& visitor) override;-- bool reading { false };- bool read_again { false };- bool canceled1 { false };- bool canceled2 { false };- JS::Value reason1 { JS::js_undefined() };- JS::Value reason2 { JS::js_undefined() };- GC::Ptr<ReadableStream> branch1;- GC::Ptr<ReadableStream> branch2;- GC::Ptr<PullAlgorithm> pull_algorithm;-};--// https://streams.spec.whatwg.org/#ref-for-read-request③-class ReadableStreamTeeReadRequest final : public ReadRequest {- GC_CELL(ReadableStreamTeeReadRequest, ReadRequest);- GC_DECLARE_ALLOCATOR(ReadableStreamTeeReadRequest);--private:- ReadableStreamTeeReadRequest(- GC::Ref<ReadableStream> stream,- GC::Ref<ReadableStreamTeeParams> params,- GC::Ref<WebIDL::Promise> cancel_promise,- bool clone_for_branch2);-- [[nodiscard]] JS::Realm& promise_realm() const;-- virtual void visit_edges(Visitor& visitor) override;-- virtual void on_chunk(JS::Value chunk) override;- virtual void on_close() override;- virtual void on_error(JS::Value) override;-- GC::Ref<ReadableStream> m_stream;- GC::Ref<ReadableStreamTeeParams> m_params;- GC::Ref<WebIDL::Promise> m_cancel_promise;- bool m_clone_for_branch2 { false };-};--struct ReadableByteStreamTeeParams final : public JS::Cell {- GC_CELL(ReadableByteStreamTeeParams, JS::Cell);- GC_DECLARE_ALLOCATOR(ReadableByteStreamTeeParams);-- explicit ReadableByteStreamTeeParams(ReadableStreamReader reader);-- virtual void visit_edges(Visitor& visitor) override;-- bool reading { false };- bool read_again_for_branch1 { false };- bool read_again_for_branch2 { false };- bool canceled1 { false };- bool canceled2 { false };- JS::Value reason1 { JS::js_undefined() };- JS::Value reason2 { JS::js_undefined() };- GC::Ptr<ReadableStream> branch1;- GC::Ptr<ReadableStream> branch2;- GC::Ptr<PullAlgorithm> pull1_algorithm;- GC::Ptr<PullAlgorithm> pull2_algorithm;- ReadableStreamReader reader;-};--// https://streams.spec.whatwg.org/#ref-for-read-request④-class ReadableByteStreamTeeDefaultReadRequest final : public ReadRequest {- GC_CELL(ReadableByteStreamTeeDefaultReadRequest, ReadRequest);- GC_DECLARE_ALLOCATOR(ReadableByteStreamTeeDefaultReadRequest);--private:- ReadableByteStreamTeeDefaultReadRequest(- GC::Ref<ReadableStream> stream,- GC::Ref<ReadableByteStreamTeeParams> params,- GC::Ref<WebIDL::Promise> cancel_promise);-- [[nodiscard]] JS::Realm& promise_realm() const;-- virtual void visit_edges(Visitor& visitor) override;-- virtual void on_chunk(JS::Value chunk) override;- virtual void on_close() override;- virtual void on_error(JS::Value) override;-- GC::Ref<ReadableStream> m_stream;- GC::Ref<ReadableByteStreamTeeParams> m_params;- GC::Ref<WebIDL::Promise> m_cancel_promise;-};--// https://streams.spec.whatwg.org/#ref-for-read-into-request②-class ReadableByteStreamTeeBYOBReadRequest final : public ReadIntoRequest {- GC_CELL(ReadableByteStreamTeeBYOBReadRequest, ReadIntoRequest);- GC_DECLARE_ALLOCATOR(ReadableByteStreamTeeBYOBReadRequest);--private:- ReadableByteStreamTeeBYOBReadRequest(- GC::Ref<ReadableStream> stream,- GC::Ref<ReadableByteStreamTeeParams> params,- GC::Ref<WebIDL::Promise> cancel_promise,- GC::Ref<ReadableStream> byob_branch,- GC::Ref<ReadableStream> other_branch,- bool for_branch2);-- [[nodiscard]] JS::Realm& promise_realm() const;-- virtual void visit_edges(Visitor& visitor) override;-- virtual void on_chunk(JS::Value chunk) override;- virtual void on_close(JS::Value chunk) override;- virtual void on_error(JS::Value) override;-- GC::Ref<ReadableStream> m_stream;- GC::Ref<ReadableByteStreamTeeParams> m_params;- GC::Ref<WebIDL::Promise> m_cancel_promise;- GC::Ref<ReadableStream> m_byob_branch;- GC::Ref<ReadableStream> m_other_branch;- bool m_for_branch2 { false };-};--}diff --git a/Libraries/LibWeb/Streams/TransformStream.cpp b/Libraries/LibWeb/Streams/TransformStream.cppindex f104796a93c..2472f647c77 100644--- a/Libraries/LibWeb/Streams/TransformStream.cpp+++ b/Libraries/LibWeb/Streams/TransformStream.cpp@@ -4,261 +4,50 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibIPC/File.h>-#include <LibJS/Runtime/Promise.h>-#include <LibWeb/Bindings/ReadableStream.h>-#include <LibWeb/Bindings/Transformer.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Bindings/WritableStream.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/BindingsGlue.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/TransformStreamDefaultController.h>-#include <LibWeb/Streams/TransformStreamOperations.h>#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Streams {-GC_DEFINE_ALLOCATOR(TransformStream);+extern "C" {-WebIDL::ExceptionOr<GC::Ref<TransformStream>> TransformStream::create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<JS::Object> transformer_object, QueuingStrategy const& writable_strategy, QueuingStrategy const& readable_strategy)-{- auto& realm = HTML::relevant_realm(relevant_global_object);- auto transformer = transformer_object ? JS::Value { transformer_object } : JS::js_null();- auto transformer_dict = TRY(Bindings::convert_to_idl_value_for_transformer(realm.vm(), transformer));- if (transformer_dict.readable_type.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid use of reserved key 'readableType'"_utf16 };- if (transformer_dict.writable_type.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid use of reserved key 'writableType'"_utf16 };-- return create(realm, transformer_object, transformer_dict, writable_strategy, readable_strategy);+// Defined in Bindings/Rust/src/streams/exports.rs.+void* web_rust_transform_stream_create(JSVM*, void* realm);+void web_rust_transform_stream_set_up(JSVM*, void* realm, void* stream, TransformAlgorithm* transform_algorithm, FlushAlgorithm* flush_algorithm, CancelAlgorithm* cancel_algorithm);+JSCompletion web_rust_transform_stream_enqueue(JSVM*, void* stream, JSValue chunk);+void* web_rust_transform_stream_readable(void* stream);+void* web_rust_transform_stream_writable(void* stream);}-// https://streams.spec.whatwg.org/#ts-constructor-WebIDL::ExceptionOr<GC::Ref<TransformStream>> TransformStream::create(JS::Realm& realm, GC::Ptr<JS::Object> transformer_object, Transformer const& transformer_dict, QueuingStrategy const& writable_strategy, QueuingStrategy const& readable_strategy)-{- auto& vm = realm.vm();-- auto stream = GC::Heap::the().allocate<TransformStream>();-- // 1. If transformer is missing, set it to null.- auto transformer = transformer_object ? JS::Value { transformer_object } : JS::js_null();-- // 5. Let readableHighWaterMark be ? ExtractHighWaterMark(readableStrategy, 0).- auto readable_high_water_mark = TRY(extract_high_water_mark(readable_strategy, 0));-- // 6. Let readableSizeAlgorithm be ! ExtractSizeAlgorithm(readableStrategy).- auto readable_size_algorithm = extract_size_algorithm(vm, readable_strategy);-- // 7. Let writableHighWaterMark be ? ExtractHighWaterMark(writableStrategy, 1).- auto writable_high_water_mark = TRY(extract_high_water_mark(writable_strategy, 1));-- // 8. Let writableSizeAlgorithm be ! ExtractSizeAlgorithm(writableStrategy).- auto writable_size_algorithm = extract_size_algorithm(vm, writable_strategy);-- // 9. Let startPromise be a new promise.- auto start_promise = WebIDL::create_promise(realm);-- // 10. Perform ! InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm).- initialize_transform_stream(realm, *stream, start_promise, writable_high_water_mark, writable_size_algorithm, readable_high_water_mark, readable_size_algorithm);- Bindings::prepare_transform_stream_readable_writable_wrappers(realm, *stream);-- // 11. Perform ? SetUpTransformStreamDefaultControllerFromTransformer(this, transformer, transformerDict).- set_up_transform_stream_default_controller_from_transformer(realm, *stream, transformer, transformer_dict);-- // 12. If transformerDict["start"] exists, then resolve startPromise with the result of invoking- // transformerDict["start"] with argument list « this.[[controller]] » and callback this value transformer.- if (transformer_dict.start) {- auto result = TRY(Bindings::invoke_transform_stream_start_algorithm_callback(realm, *transformer_dict.start, transformer, *stream->controller()));- WebIDL::resolve_promise(start_promise, result);- }- // 13. Otherwise, resolve startPromise with undefined.- else {- WebIDL::resolve_promise(start_promise);- }-- return stream;-}--TransformStream::TransformStream()-{-}--TransformStream::~TransformStream() = default;--void TransformStream::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_backpressure_change_promise);- visitor.visit(m_controller);- visitor.visit(m_readable);- visitor.visit(m_writable);-}--}--namespace Web::Bindings {--void prepare_transform_stream_readable_writable_wrappers(JS::Realm& realm, Streams::TransformStream& stream)-{- (void)Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, stream.readable());- (void)Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, stream.writable());-}--}--namespace Web::Streams {--JS::Realm& TransformStream::backpressure_change_promise_realm() const+GC::Ref<TransformStream> TransformStream::create(JS::Realm& realm){- VERIFY(m_backpressure_change_promise);- return WebIDL::promise_realm(*m_backpressure_change_promise);+ return GC::Ref { *static_cast<TransformStream*>(web_rust_transform_stream_create(JS::HostABI::vm_to_abi(realm.vm()), &realm)) };}-// https://streams.spec.whatwg.org/#transformstream-enqueue-void TransformStream::enqueue(JS::Value chunk)-{- // To enqueue the JavaScript value chunk into a TransformStream stream, perform ! TransformStreamDefaultControllerEnqueue(stream.[[controller]], chunk).- MUST(Streams::transform_stream_default_controller_enqueue(*controller(), chunk));-}--// https://streams.spec.whatwg.org/#transformstream-set-upvoid TransformStream::set_up(JS::Realm& realm, GC::Ref<TransformAlgorithm> transform_algorithm, GC::Ptr<FlushAlgorithm> flush_algorithm, GC::Ptr<CancelAlgorithm> cancel_algorithm){- // 1. Let writableHighWaterMark be 1.- auto writable_high_water_mark = 1.0;-- // 2. Let writableSizeAlgorithm be an algorithm that returns 1.- auto writable_size_algorithm = GC::create_function(GC::Heap::the(), [](JS::Value) {- return JS::normal_completion(JS::Value { 1 });- });-- // 3. Let readableHighWaterMark be 0.- auto readable_high_water_mark = 0.0;-- // 4. Let readableSizeAlgorithm be an algorithm that returns 1.- auto readable_size_algorithm = GC::create_function(GC::Heap::the(), [](JS::Value) {- return JS::normal_completion(JS::Value { 1 });- });-- // 5. Let transformAlgorithmWrapper be an algorithm that runs these steps given a value chunk:- auto transform_algorithm_wrapper = GC::create_function(GC::Heap::the(), [&realm, transform_algorithm](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {- // 1. Let result be the result of running transformAlgorithm given chunk. If this throws an exception e, return a promise rejected with e.- GC::Ptr<JS::PromiseCapability> result = nullptr;- result = transform_algorithm->function()(chunk);-- // 2. If result is a Promise, then return result.- if (result)- return GC::Ref { *result };-- // 3. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 6. Let flushAlgorithmWrapper be an algorithm that runs these steps:- auto flush_algorithm_wrapper = GC::create_function(GC::Heap::the(), [&realm, flush_algorithm]() -> GC::Ref<WebIDL::Promise> {- // 1. Let result be the result of running flushAlgorithm, if flushAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.- GC::Ptr<JS::PromiseCapability> result = nullptr;- if (flush_algorithm)- result = flush_algorithm->function()();-- // 2. If result is a Promise, then return result.- if (result)- return GC::Ref { *result };-- // 3. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 7. Let cancelAlgorithmWrapper be an algorithm that runs these steps given a value reason:- auto cancel_algorithm_wrapper = GC::create_function(GC::Heap::the(), [&realm, cancel_algorithm](JS::Value reason) -> GC::Ref<WebIDL::Promise> {- // 1. Let result be the result of running cancelAlgorithm given reason, if cancelAlgorithm was given, or null otherwise. If this throws an exception e, return a promise rejected with e.- GC::Ptr<JS::PromiseCapability> result = nullptr;- if (cancel_algorithm)- result = cancel_algorithm->function()(reason);-- // 2. If result is a Promise, then return result.- if (result)- return GC::Ref { *result };-- // 3. Return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 8. Let startPromise be a promise resolved with undefined.- auto start_promise = WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // 9. Perform ! InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm).- initialize_transform_stream(realm, *this, start_promise, writable_high_water_mark, writable_size_algorithm, readable_high_water_mark, readable_size_algorithm);- Bindings::prepare_transform_stream_readable_writable_wrappers(realm, *this);-- // 10. Let controller be a new TransformStreamDefaultController.- auto controller = GC::Heap::the().allocate<TransformStreamDefaultController>();-- // 11. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithmWrapper, flushAlgorithmWrapper, cancelAlgorithmWrapper).- set_up_transform_stream_default_controller(*this, controller, transform_algorithm_wrapper, flush_algorithm_wrapper, cancel_algorithm_wrapper);+ web_rust_transform_stream_set_up(JS::HostABI::vm_to_abi(realm.vm()), &realm, this, transform_algorithm.ptr(), flush_algorithm.ptr(), cancel_algorithm.ptr());}-// https://streams.spec.whatwg.org/#ref-for-transfer-steps②-WebIDL::ExceptionOr<void> TransformStream::transfer_steps(JS::Realm& realm, HTML::TransferDataEncoder& data_holder)+WebIDL::ExceptionOr<void> TransformStream::enqueue(JS::Value chunk){- // 1. Let readable be value.[[readable]].- auto readable = this->readable();-- // 2. Let writable be value.[[writable]].- auto writable = this->writable();-- // 3. If ! IsReadableStreamLocked(readable) is true, throw a "DataCloneError" DOMException.- if (is_readable_stream_locked(readable))- return WebIDL::DataCloneError::create("Cannot transfer locked ReadableStream"_utf16);-- // 4. If ! IsWritableStreamLocked(writable) is true, throw a "DataCloneError" DOMException.- if (is_writable_stream_locked(writable))- return WebIDL::DataCloneError::create("Cannot transfer locked WritableStream"_utf16);-- // 5. Set dataHolder.[[readable]] to ! StructuredSerializeWithTransfer(readable, « readable »).- Bindings::serialize_readable_stream_with_transfer(realm, data_holder, readable);-- // 6. Set dataHolder.[[writable]] to ! StructuredSerializeWithTransfer(writable, « writable »).- Bindings::serialize_writable_stream_with_transfer(realm, data_holder, writable);-+ auto result = JS::HostABI::completion_from_abi<JS::Value>(web_rust_transform_stream_enqueue(JS::HostABI::vm_to_abi(JS::VM::the()), this, JS::HostABI::value_to_abi(chunk)));+ if (result.is_error())+ return result.release_error();return {};}-// https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps②-WebIDL::ExceptionOr<void> TransformStream::transfer_receiving_steps(JS::Realm& realm, HTML::TransferDataDecoder& data_holder)+GC::Ref<ReadableStream> TransformStream::readable(){- // 1. Let readableRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[readable]], the current Realm).- auto readable_record = MUST(HTML::structured_deserialize_with_transfer_internal(data_holder, realm));-- // 2. Let writableRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[writable]], the current Realm).- auto writeable_record = MUST(HTML::structured_deserialize_with_transfer_internal(data_holder, realm));-- // 3. Set value.[[readable]] to readableRecord.[[Deserialized]].- auto* readable = Bindings::readable_stream_from_object(readable_record.as_object());- VERIFY(readable);- set_readable(*readable);-- // 4. Set value.[[writable]] to writableRecord.[[Deserialized]].- auto* writable = Bindings::writable_stream_from_object(writeable_record.as_object());- VERIFY(writable);- set_writable(*writable);-- // 5. Set value.[[backpressure]], value.[[backpressureChangePromise]], and value.[[controller]] to undefined.- set_backpressure({});- set_backpressure_change_promise({});- set_controller({});+ return GC::Ref { *static_cast<ReadableStream*>(web_rust_transform_stream_readable(this)) };+}- return {};+GC::Ref<WritableStream> TransformStream::writable()+{+ return GC::Ref { *static_cast<WritableStream*>(web_rust_transform_stream_writable(this)) };}}diff --git a/Libraries/LibWeb/Streams/TransformStream.h b/Libraries/LibWeb/Streams/TransformStream.hindex 58c8e9a8c24..4a9ddc282a3 100644--- a/Libraries/LibWeb/Streams/TransformStream.h+++ b/Libraries/LibWeb/Streams/TransformStream.h@@ -7,79 +7,37 @@#pragma once#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Transferable.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/TransformStream.h>+#include <LibWeb/Export.h>#include <LibWeb/Forward.h>#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/Streams/QueuingStrategy.h>-#include <LibWeb/WebIDL/Promise.h>+#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Streams {-class TransformStream final- : public Bindings::GCAllocatedWrappable- , public Bindings::Transferable {- WEB_WRAPPABLE(TransformStream, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(TransformStream);+// https://streams.spec.whatwg.org/#transformstream+// The C++ side of a TransformStream, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/streams): what+// the specifications that LibWeb implements in C++ use to set up transform streams,+// https://streams.spec.whatwg.org/#other-specs-ts+class WEB_API TransformStream : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(TransformStream, transform_stream)public:- static constexpr size_t readable_offset() { return offsetof(TransformStream, m_readable); }- static constexpr size_t writable_offset() { return offsetof(TransformStream, m_writable); }- virtual ~TransformStream() override;-- static WebIDL::ExceptionOr<GC::Ref<TransformStream>> create_for_constructor(JS::Object&, GC::Ptr<JS::Object> transformer_object, QueuingStrategy const& writable_strategy = {}, QueuingStrategy const& readable_strategy = {});- static WebIDL::ExceptionOr<GC::Ref<TransformStream>> create(JS::Realm&, GC::Ptr<JS::Object> transformer_object, Transformer const&, QueuingStrategy const& writable_strategy = {}, QueuingStrategy const& readable_strategy = {});-- // https://streams.spec.whatwg.org/#ts-readable- GC::Ref<ReadableStream> readable() { return *m_readable; }- void set_readable(ReadableStream& readable) { m_readable = readable; }-- // https://streams.spec.whatwg.org/#ts-writable- GC::Ref<WritableStream> writable() { return *m_writable; }- void set_writable(WritableStream& writable) { m_writable = writable; }-- Optional<bool> backpressure() const { return m_backpressure; }- void set_backpressure(Optional<bool> value) { m_backpressure = move(value); }-- GC::Ptr<WebIDL::Promise> backpressure_change_promise() const { return m_backpressure_change_promise; }- void set_backpressure_change_promise(GC::Ptr<WebIDL::Promise> value) { m_backpressure_change_promise = value; }- JS::Realm& backpressure_change_promise_realm() const;-- GC::Ptr<TransformStreamDefaultController> controller() const { return m_controller; }- void set_controller(GC::Ptr<TransformStreamDefaultController> value) { m_controller = value; }+ // A new TransformStream in the realm, which set_up() then sets up.+ [[nodiscard]] static GC::Ref<TransformStream> create(JS::Realm&);+ // https://streams.spec.whatwg.org/#transformstream-set-upvoid set_up(JS::Realm&, GC::Ref<TransformAlgorithm>, GC::Ptr<FlushAlgorithm> = {}, GC::Ptr<CancelAlgorithm> = {});- void enqueue(JS::Value chunk);-- // ^Transferable- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) override;- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) override;- virtual HTML::TransferType primary_interface() const override { return HTML::TransferType::TransformStream; }--private:- TransformStream();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#transformstream-backpressure- // Whether there was backpressure on [[readable]] the last time it was observed- Optional<bool> m_backpressure { false };-- // https://streams.spec.whatwg.org/#transformstream-backpressurechangepromise- // A promise which is fulfilled and replaced every time the value of [[backpressure]] changes- GC::Ptr<WebIDL::Promise> m_backpressure_change_promise;- // https://streams.spec.whatwg.org/#transformstream-controller- // A TransformStreamDefaultController created with the ability to control [[readable]] and [[writable]]- GC::Ptr<TransformStreamDefaultController> m_controller;+ // https://streams.spec.whatwg.org/#transformstream-enqueue+ WebIDL::ExceptionOr<void> enqueue(JS::Value chunk);// https://streams.spec.whatwg.org/#transformstream-readable- // The ReadableStream instance controlled by this object- GC::Ptr<ReadableStream> m_readable;+ GC::Ref<ReadableStream> readable();// https://streams.spec.whatwg.org/#transformstream-writable- // The WritableStream instance controlled by this object- GC::Ptr<WritableStream> m_writable;+ GC::Ref<WritableStream> writable();};}diff --git a/Libraries/LibWeb/Streams/TransformStream.idl b/Libraries/LibWeb/Streams/TransformStream.idlindex 95595b9a0c4..16cf02e8dcf 100644--- a/Libraries/LibWeb/Streams/TransformStream.idl+++ b/Libraries/LibWeb/Streams/TransformStream.idl@@ -1,8 +1,8 @@// https://streams.spec.whatwg.org/#transformstream-[Exposed=*, Transferable]+[Exposed=*, Transferable, ImplementedIn=Rust]interface TransformStream {constructor(optional object transformer, optional QueuingStrategy writableStrategy = {}, optional QueuingStrategy readableStrategy = {});- [DirectGetter] readonly attribute ReadableStream readable;- [DirectGetter] readonly attribute WritableStream writable;+ [CachedAccessor] readonly attribute ReadableStream readable;+ [CachedAccessor] readonly attribute WritableStream writable;};diff --git a/Libraries/LibWeb/Streams/TransformStreamDefaultController.cpp b/Libraries/LibWeb/Streams/TransformStreamDefaultController.cppdeleted file mode 100644index 511c035a811..00000000000--- a/Libraries/LibWeb/Streams/TransformStreamDefaultController.cpp+++ /dev/null@@ -1,67 +0,0 @@-/*- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/TransformStreamDefaultController.h>-#include <LibWeb/Streams/TransformStreamOperations.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(TransformStreamDefaultController);--TransformStreamDefaultController::TransformStreamDefaultController()-{-}--TransformStreamDefaultController::~TransformStreamDefaultController() = default;--void TransformStreamDefaultController::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_stream);- visitor.visit(m_cancel_algorithm);- visitor.visit(m_finish_promise);- visitor.visit(m_flush_algorithm);- visitor.visit(m_transform_algorithm);-}--// https://streams.spec.whatwg.org/#ts-default-controller-desired-size-Optional<double> TransformStreamDefaultController::desired_size()-{- VERIFY(stream()->readable()->controller().has_value() && stream()->readable()->controller()->has<GC::Ref<ReadableStreamDefaultController>>());-- // 1. Let readableController be this.[[stream]].[[readable]].[[controller]].- auto readable_controller = stream()->readable()->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 2. Return ! ReadableStreamDefaultControllerGetDesiredSize(readableController).- return readable_stream_default_controller_get_desired_size(*readable_controller);-}--// https://streams.spec.whatwg.org/#ts-default-controller-enqueue-WebIDL::ExceptionOr<void> TransformStreamDefaultController::enqueue(Optional<JS::Value> chunk)-{- // 1. Perform ? TransformStreamDefaultControllerEnqueue(this, chunk).- TRY(transform_stream_default_controller_enqueue(*this, chunk.has_value() ? chunk.value() : JS::js_undefined()));-- return {};-}--// https://streams.spec.whatwg.org/#ts-default-controller-error-void TransformStreamDefaultController::error(Optional<JS::Value> reason)-{- // 1. Perform ? TransformStreamDefaultControllerError(this, e).- transform_stream_default_controller_error(*this, reason.has_value() ? reason.value() : JS::js_undefined());-}--// https://streams.spec.whatwg.org/#ts-default-controller-terminate-void TransformStreamDefaultController::terminate()-{- // 1. Perform ? TransformStreamDefaultControllerTerminate(this).- transform_stream_default_controller_terminate(*this);-}--}diff --git a/Libraries/LibWeb/Streams/TransformStreamDefaultController.h b/Libraries/LibWeb/Streams/TransformStreamDefaultController.hdeleted file mode 100644index b2960022b73..00000000000--- a/Libraries/LibWeb/Streams/TransformStreamDefaultController.h+++ /dev/null@@ -1,61 +0,0 @@-/*- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Streams/Algorithms.h>--namespace Web::Streams {--class TransformStreamDefaultController : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(TransformStreamDefaultController, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(TransformStreamDefaultController);--public:- TransformStreamDefaultController();- virtual ~TransformStreamDefaultController() override;-- Optional<double> desired_size();- WebIDL::ExceptionOr<void> enqueue(Optional<JS::Value> chunk);- void error(Optional<JS::Value> reason = {});- void terminate();-- GC::Ptr<CancelAlgorithm> cancel_algorithm() { return m_cancel_algorithm; }- void set_cancel_algorithm(GC::Ptr<CancelAlgorithm> value) { m_cancel_algorithm = value; }-- GC::Ptr<JS::PromiseCapability> finish_promise() { return m_finish_promise; }- void set_finish_promise(GC::Ptr<JS::PromiseCapability> value) { m_finish_promise = value; }-- GC::Ptr<FlushAlgorithm> flush_algorithm() { return m_flush_algorithm; }- void set_flush_algorithm(GC::Ptr<FlushAlgorithm>&& value) { m_flush_algorithm = move(value); }-- GC::Ptr<TransformAlgorithm> transform_algorithm() { return m_transform_algorithm; }- void set_transform_algorithm(GC::Ptr<TransformAlgorithm>&& value) { m_transform_algorithm = move(value); }-- GC::Ptr<TransformStream> stream() { return m_stream; }- void set_stream(GC::Ptr<TransformStream> stream) { m_stream = stream; }--private:- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-cancelalgorithm- GC::Ptr<CancelAlgorithm> m_cancel_algorithm;-- // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-finishpromise- GC::Ptr<JS::PromiseCapability> m_finish_promise;-- // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-flushalgorithm- GC::Ptr<FlushAlgorithm> m_flush_algorithm;-- // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-transformalgorithm- GC::Ptr<TransformAlgorithm> m_transform_algorithm;-- // https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-stream- GC::Ptr<TransformStream> m_stream;-};--}diff --git a/Libraries/LibWeb/Streams/TransformStreamDefaultController.idl b/Libraries/LibWeb/Streams/TransformStreamDefaultController.idlindex 8a8408abb2c..72392cf53e8 100644--- a/Libraries/LibWeb/Streams/TransformStreamDefaultController.idl+++ b/Libraries/LibWeb/Streams/TransformStreamDefaultController.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller-[Exposed=*]+[Exposed=*, ImplementedIn=Rust]interface TransformStreamDefaultController {readonly attribute unrestricted double? desiredSize;diff --git a/Libraries/LibWeb/Streams/TransformStreamOperations.cpp b/Libraries/LibWeb/Streams/TransformStreamOperations.cppdeleted file mode 100644index 02bbfaedf12..00000000000--- a/Libraries/LibWeb/Streams/TransformStreamOperations.cpp+++ /dev/null@@ -1,621 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Bindings/TransformStreamDefaultController.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Streams/BindingsGlue.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamDefaultController.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/TransformStream.h>-#include <LibWeb/Streams/TransformStreamDefaultController.h>-#include <LibWeb/Streams/TransformStreamOperations.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultController.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--static JS::Realm& promise_realm(WebIDL::Promise const& promise)-{- return WebIDL::promise_realm(promise);-}--}--namespace Web::Bindings {--WebIDL::ExceptionOr<JS::Value> invoke_transform_stream_start_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value transformer, GC::Ref<Streams::TransformStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return TRY(WebIDL::invoke_callback(callback, transformer, { { wrapped_controller } }));-}--GC::Ref<WebIDL::Promise> invoke_transform_stream_transform_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value transformer, JS::Value chunk, GC::Ref<Streams::TransformStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return WebIDL::invoke_promise_callback(callback, transformer, { { chunk, wrapped_controller } });-}--GC::Ref<WebIDL::Promise> invoke_transform_stream_flush_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value transformer, GC::Ref<Streams::TransformStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return WebIDL::invoke_promise_callback(callback, transformer, { { wrapped_controller } });-}--}--namespace Web::Streams {--// https://streams.spec.whatwg.org/#initialize-transform-stream-void initialize_transform_stream(TransformStream& stream, GC::Ref<WebIDL::Promise> start_promise, double writable_high_water_mark, GC::Ref<SizeAlgorithm> writable_size_algorithm, double readable_high_water_mark, GC::Ref<SizeAlgorithm> readable_size_algorithm)-{- initialize_transform_stream(promise_realm(start_promise), stream, start_promise, writable_high_water_mark, writable_size_algorithm, readable_high_water_mark, readable_size_algorithm);-}--void initialize_transform_stream(JS::Realm& realm, TransformStream& stream, GC::Ref<WebIDL::Promise> start_promise, double writable_high_water_mark, GC::Ref<SizeAlgorithm> writable_size_algorithm, double readable_high_water_mark, GC::Ref<SizeAlgorithm> readable_size_algorithm)-{- // 1. Let startAlgorithm be an algorithm that returns startPromise.- auto writable_start_algorithm = GC::create_function(GC::Heap::the(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {- return start_promise->promise();- });-- auto readable_start_algorithm = GC::create_function(GC::Heap::the(), [start_promise]() -> WebIDL::ExceptionOr<JS::Value> {- return start_promise->promise();- });-- // 2. Let writeAlgorithm be the following steps, taking a chunk argument:- auto write_algorithm = GC::create_function(GC::Heap::the(), [&stream](JS::Value chunk) {- // 1. Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).- return transform_stream_default_sink_write_algorithm(stream, chunk);- });-- // 3. Let abortAlgorithm be the following steps, taking a reason argument:- auto abort_algorithm = GC::create_function(GC::Heap::the(), [&stream](JS::Value reason) {- // 1. Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).- return transform_stream_default_sink_abort_algorithm(stream, reason);- });-- // 4. Let closeAlgorithm be the following steps:- auto close_algorithm = GC::create_function(GC::Heap::the(), [&stream]() {- // 1. Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).- return transform_stream_default_sink_close_algorithm(stream);- });-- // 5. Set stream.[[writable]] to ! CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm).- stream.set_writable(MUST(create_writable_stream(realm, writable_start_algorithm, write_algorithm, close_algorithm, abort_algorithm, writable_high_water_mark, writable_size_algorithm)));-- // 6. Let pullAlgorithm be the following steps:- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&stream]() {- // 1. Return ! TransformStreamDefaultSourcePullAlgorithm(stream).- return transform_stream_default_source_pull_algorithm(stream);- });-- // 7. Let cancelAlgorithm be the following steps, taking a reason argument:- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [&stream](JS::Value reason) {- // 1. Return ! TransformStreamDefaultSourceCancelAlgorithm(stream, reason).- return transform_stream_default_source_cancel_algorithm(stream, reason);- });-- // 8. Set stream.[[readable]] to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm).- stream.set_readable(MUST(create_readable_stream(realm, readable_start_algorithm, pull_algorithm, cancel_algorithm, readable_high_water_mark, readable_size_algorithm)));- stream.readable()->set_result_realm(realm);-- // 9. Set stream.[[backpressure]] and stream.[[backpressureChangePromise]] to undefined.- stream.set_backpressure({});- stream.set_backpressure_change_promise({});-- // 10. Perform ! TransformStreamSetBackpressure(stream, true).- transform_stream_set_backpressure(realm, stream, true);-- // 11. Set stream.[[controller]] to undefined.- stream.set_controller({});-}--// https://streams.spec.whatwg.org/#transform-stream-error-void transform_stream_error(TransformStream& stream, JS::Value error)-{- auto readable_controller = stream.readable()->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 1. Perform ! ReadableStreamDefaultControllerError(stream.[[readable]].[[controller]], e).- readable_stream_default_controller_error(readable_controller, error);-- // 2. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, e).- transform_stream_error_writable_and_unblock_write(stream, error);-}--// https://streams.spec.whatwg.org/#transform-stream-error-writable-and-unblock-write-void transform_stream_error_writable_and_unblock_write(TransformStream& stream, JS::Value error)-{- // 1. Perform ! TransformStreamDefaultControllerClearAlgorithms(stream.[[controller]]).- transform_stream_default_controller_clear_algorithms(*stream.controller());-- // 2. Perform ! WritableStreamDefaultControllerErrorIfNeeded(stream.[[writable]].[[controller]], e).- writable_stream_default_controller_error_if_needed(*stream.writable()->controller(), error);-- // 3. Perform ! TransformStreamUnblockWrite(stream).- transform_stream_unblock_write(stream);-}--// https://streams.spec.whatwg.org/#transform-stream-set-backpressure-void transform_stream_set_backpressure(TransformStream& stream, bool backpressure)-{- transform_stream_set_backpressure(stream.backpressure_change_promise_realm(), stream, backpressure);-}--void transform_stream_set_backpressure(JS::Realm& realm, TransformStream& stream, bool backpressure)-{- // 1. Assert: stream.[[backpressure]] is not backpressure.- VERIFY(stream.backpressure() != backpressure);-- // 2. If stream.[[backpressureChangePromise]] is not undefined, resolve stream.[[backpressureChangePromise]] with undefined.- if (auto backpressure_change_promise = stream.backpressure_change_promise())- WebIDL::resolve_promise(*backpressure_change_promise);-- // 3. Set stream.[[backpressureChangePromise]] to a new promise.- stream.set_backpressure_change_promise(WebIDL::create_promise(realm));-- // 4. Set stream.[[backpressure]] to backpressure.- stream.set_backpressure(backpressure);-}--// https://streams.spec.whatwg.org/#transform-stream-unblock-write-void transform_stream_unblock_write(TransformStream& stream)-{- // 1. If stream.[[backpressure]] is true, perform ! TransformStreamSetBackpressure(stream, false).- if (stream.backpressure() == true)- transform_stream_set_backpressure(stream, false);-}--// https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-void set_up_transform_stream_default_controller(TransformStream& stream, TransformStreamDefaultController& controller, GC::Ref<TransformAlgorithm> transform_algorithm, GC::Ref<FlushAlgorithm> flush_algorithm, GC::Ref<CancelAlgorithm> cancel_algorithm)-{- // 1. Assert: stream implements TransformStream.- // 2. Assert: stream.[[controller]] is undefined.- VERIFY(!stream.controller());-- // 3. Set controller.[[stream]] to stream.- controller.set_stream(stream);-- // 4. Set stream.[[controller]] to controller.- stream.set_controller(controller);-- // 5. Set controller.[[transformAlgorithm]] to transformAlgorithm.- controller.set_transform_algorithm(transform_algorithm);-- // 6. Set controller.[[flushAlgorithm]] to flushAlgorithm.- controller.set_flush_algorithm(flush_algorithm);-- // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.- controller.set_cancel_algorithm(cancel_algorithm);-}--// https://streams.spec.whatwg.org/#set-up-transform-stream-default-controller-from-transformer-void set_up_transform_stream_default_controller_from_transformer(TransformStream& stream, JS::Value transformer, Transformer const& transformer_dict)-{- set_up_transform_stream_default_controller_from_transformer(stream.backpressure_change_promise_realm(), stream, transformer, transformer_dict);-}--void set_up_transform_stream_default_controller_from_transformer(JS::Realm& realm, TransformStream& stream, JS::Value transformer, Transformer const& transformer_dict)-{- auto& vm = realm.vm();-- // 1. Let controller be a new TransformStreamDefaultController.- auto controller = GC::Heap::the().allocate<TransformStreamDefaultController>();-- // 2. Let transformAlgorithm be the following steps, taking a chunk argument:- auto transform_algorithm = GC::create_function(GC::Heap::the(), [&realm, &vm, controller](JS::Value chunk) {- // 1. Let result be TransformStreamDefaultControllerEnqueue(controller, chunk).- auto result = transform_stream_default_controller_enqueue(realm, controller, chunk);-- // 2. If result is an abrupt completion, return a promise rejected with result.[[Value]].- if (result.is_error()) {- auto throw_completion = WebIDL::exception_to_throw_completion(vm, realm, result.exception());- return WebIDL::create_rejected_promise(realm, throw_completion.release_value());- }-- // 3. Otherwise, return a promise resolved with undefined.- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 3. Let flushAlgorithm be an algorithm which returns a promise resolved with undefined.- auto flush_algorithm = GC::create_function(GC::Heap::the(), [&realm]() {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 4. Let cancelAlgorithm be an algorithm which returns a promise resolved with undefined.- auto cancel_algorithm = GC::create_function(GC::Heap::the(), [&realm](JS::Value) {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 5. If transformerDict["transform"] exists, set transformAlgorithm to an algorithm which takes an argument chunk- // and returns the result of invoking transformerDict["transform"] with argument list « chunk, controller » and- // callback this value transformer.- if (transformer_dict.transform) {- transform_algorithm = GC::create_function(GC::Heap::the(), [transformer, controller, callback = transformer_dict.transform, realm = GC::Ref(realm)](JS::Value chunk) {- return Bindings::invoke_transform_stream_transform_algorithm_callback(realm, *callback, transformer, chunk, controller);- });- }-- // 6. If transformerDict["flush"] exists, set flushAlgorithm to an algorithm which returns the result of invoking- // transformerDict["flush"] with argument list « controller » and callback this value transformer.- if (transformer_dict.flush) {- flush_algorithm = GC::create_function(GC::Heap::the(), [transformer, callback = transformer_dict.flush, controller, realm = GC::Ref(realm)]() {- return Bindings::invoke_transform_stream_flush_algorithm_callback(realm, *callback, transformer, controller);- });- }-- // 7. If transformerDict["cancel"] exists, set cancelAlgorithm to an algorithm which takes an argument reason and returns- // the result of invoking transformerDict["cancel"] with argument list « reason » and callback this value transformer.- if (transformer_dict.cancel) {- cancel_algorithm = GC::create_function(GC::Heap::the(), [transformer, callback = transformer_dict.cancel](JS::Value reason) {- return WebIDL::invoke_promise_callback(*callback, transformer, { { reason } });- });- }-- // 8. Perform ! SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm).- set_up_transform_stream_default_controller(stream, controller, transform_algorithm, flush_algorithm, cancel_algorithm);-}--// https://streams.spec.whatwg.org/#transform-stream-default-controller-clear-algorithms-void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController& controller)-{- // NOTE: This is observable using weak references. See tc39/proposal-weakrefs#31 for more detail.- // 1. Set controller.[[transformAlgorithm]] to undefined.- controller.set_transform_algorithm({});-- // 2. Set controller.[[flushAlgorithm]] to undefined.- controller.set_flush_algorithm({});-- // 3. Set controller.[[cancelAlgorithm]] to undefined.- controller.set_cancel_algorithm({});-}--// https://streams.spec.whatwg.org/#transform-stream-default-controller-enqueue-WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController& controller, JS::Value chunk)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();- return transform_stream_default_controller_enqueue(stream->backpressure_change_promise_realm(), controller, chunk);-}--WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(JS::Realm& realm, TransformStreamDefaultController& controller, JS::Value chunk)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();- auto& vm = realm.vm();-- // 2. Let readableController be stream.[[readable]].[[controller]].- auto readable_controller = stream->readable()->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 3. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController) is false, throw a TypeError exception.- if (!readable_stream_default_controller_can_close_or_enqueue(readable_controller))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "ReadableController is either closed or not readable."_utf16 };-- // 4. Let enqueueResult be ReadableStreamDefaultControllerEnqueue(readableController, chunk).- auto enqueue_result = readable_stream_default_controller_enqueue(realm, readable_controller, chunk);-- // 5. If enqueueResult is an abrupt completion,- if (enqueue_result.is_error()) {- auto throw_completion = WebIDL::exception_to_throw_completion(vm, realm, enqueue_result.exception());-- // 1. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, enqueueResult.[[Value]]).- transform_stream_error_writable_and_unblock_write(*stream, throw_completion.value());-- // 2. Throw stream.[[readable]].[[storedError]].- return JS::throw_completion(stream->readable()->stored_error());- }-- // 6. Let backpressure be ! ReadableStreamDefaultControllerHasBackpressure(readableController).- auto backpressure = readable_stream_default_controller_has_backpressure(readable_controller);-- // 7. If backpressure is not stream.[[backpressure]],- if (backpressure != stream->backpressure()) {- // 1. Assert: backpressure is true.- VERIFY(backpressure);-- // 2. Perform ! TransformStreamSetBackpressure(stream, true).- transform_stream_set_backpressure(*stream, true);- }-- return {};-}--// https://streams.spec.whatwg.org/#transform-stream-default-controller-error-void transform_stream_default_controller_error(TransformStreamDefaultController& controller, JS::Value error)-{- // 1. Perform ! TransformStreamError(controller.[[stream]], e).- transform_stream_error(*controller.stream(), error);-}--// https://streams.spec.whatwg.org/#transform-stream-default-controller-perform-transform-GC::Ref<WebIDL::Promise> transform_stream_default_controller_perform_transform(TransformStreamDefaultController& controller, JS::Value chunk)-{- // 1. Let transformPromise be the result of performing controller.[[transformAlgorithm]], passing chunk.- auto transform_promise = controller.transform_algorithm()->function()(chunk);-- // 2. Return the result of reacting to transformPromise with the following rejection steps given the argument r:- return WebIDL::upon_rejection(*transform_promise,- GC::create_function(GC::Heap::the(), [&controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! TransformStreamError(controller.[[stream]], r).- transform_stream_error(*controller.stream(), reason);-- // 2. Throw r.- return JS::throw_completion(reason);- }));-}--// https://streams.spec.whatwg.org/#transform-stream-default-controller-terminate-void transform_stream_default_controller_terminate(TransformStreamDefaultController& controller)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();- auto& realm = stream->backpressure_change_promise_realm();-- // 2. Let readableController be stream.[[readable]].[[controller]].- auto readable_controller = stream->readable()->controller()->get<GC::Ref<ReadableStreamDefaultController>>();-- // 3. Perform ! ReadableStreamDefaultControllerClose(readableController).- readable_stream_default_controller_close(readable_controller);-- // 4. Let error be a TypeError exception indicating that the stream has been terminated.- auto error = JS::TypeError::create(realm, "Stream has been terminated."_utf16);-- // 5. Perform ! TransformStreamErrorWritableAndUnblockWrite(stream, error).- transform_stream_error_writable_and_unblock_write(*stream, error);-}--// https://streams.spec.whatwg.org/#transform-stream-default-sink-write-algorithm-GC::Ref<WebIDL::Promise> transform_stream_default_sink_write_algorithm(TransformStream& stream, JS::Value chunk)-{- // 1. Assert: stream.[[writable]].[[state]] is "writable".- VERIFY(stream.writable()->state() == WritableStream::State::Writable);-- // 2. Let controller be stream.[[controller]].- auto controller = stream.controller();-- // 3. If stream.[[backpressure]] is true,- if (stream.backpressure() == true) {- // 1. Let backpressureChangePromise be stream.[[backpressureChangePromise]].- auto backpressure_change_promise = stream.backpressure_change_promise();-- // 2. Assert: backpressureChangePromise is not undefined.- VERIFY(backpressure_change_promise);-- // 3. Return the result of reacting to backpressureChangePromise with the following fulfillment steps:- return WebIDL::upon_fulfillment(*backpressure_change_promise,- GC::create_function(GC::Heap::the(), [&stream, controller, chunk](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Let writable be stream.[[writable]].- auto writable = stream.writable();-- // 2. Let state be writable.[[state]].- auto state = writable->state();-- // 3. If state is "erroring", throw writable.[[storedError]].- if (state == WritableStream::State::Erroring)- return JS::throw_completion(writable->stored_error());-- // 4. Assert: state is "writable".- VERIFY(state == WritableStream::State::Writable);-- // 5. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).- return transform_stream_default_controller_perform_transform(*controller, chunk)->promise();- }));- }-- // 4. Return ! TransformStreamDefaultControllerPerformTransform(controller, chunk).- return transform_stream_default_controller_perform_transform(*controller, chunk);-}--// https://streams.spec.whatwg.org/#transform-stream-default-sink-abort-algorithm-GC::Ref<WebIDL::Promise> transform_stream_default_sink_abort_algorithm(TransformStream& stream, JS::Value reason)-{- auto& realm = stream.backpressure_change_promise_realm();-- // 1. Let controller be stream.[[controller]].- auto controller = stream.controller();-- // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].- if (controller->finish_promise())- return *controller->finish_promise();-- // 3. Let readable be stream.[[readable]].- auto readable = stream.readable();-- // 4. Let controller.[[finishPromise]] be a new promise.- controller->set_finish_promise(WebIDL::create_promise(realm));-- // 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.- auto cancel_promise = controller->cancel_algorithm()->function()(reason);-- // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).- transform_stream_default_controller_clear_algorithms(*controller);-- // 7. React to cancelPromise:- WebIDL::react_to_promise(cancel_promise,- // 1. If cancelPromise was fulfilled, then:- GC::create_function(GC::Heap::the(), [readable, controller, reason](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If readable.[[state]] is "errored", reject controller.[[finishPromise]] with readable.[[storedError]].- if (readable->state() == ReadableStream::State::Errored) {- WebIDL::reject_promise(*controller->finish_promise(), readable->stored_error());- }- // 2. Otherwise:- else {- // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], reason).- readable_stream_default_controller_error(readable->controller()->get<GC::Ref<ReadableStreamDefaultController>>(), reason);-- // 2. Resolve controller.[[finishPromise]] with undefined.- WebIDL::resolve_promise(*controller->finish_promise());- }-- return JS::js_undefined();- }),-- // 2. If cancelPromise was rejected with reason r, then:- GC::create_function(GC::Heap::the(), [readable, controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], r).- readable_stream_default_controller_error(readable->controller()->get<GC::Ref<ReadableStreamDefaultController>>(), reason);-- // 2. Reject controller.[[finishPromise]] with r.- WebIDL::reject_promise(*controller->finish_promise(), reason);-- return JS::js_undefined();- }));-- // 8. Return controller.[[finishPromise]].- return *controller->finish_promise();-}--// https://streams.spec.whatwg.org/#transform-stream-default-sink-close-algorithm-GC::Ref<WebIDL::Promise> transform_stream_default_sink_close_algorithm(TransformStream& stream)-{- auto& realm = stream.backpressure_change_promise_realm();-- // 1. Let controller be stream.[[controller]].- auto controller = stream.controller();-- // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].- if (controller->finish_promise())- return *controller->finish_promise();-- // 3. Let readable be stream.[[readable]].- auto readable = stream.readable();-- // 4. Let controller.[[finishPromise]] be a new promise.- controller->set_finish_promise(WebIDL::create_promise(realm));-- // 5. Let flushPromise be the result of performing controller.[[flushAlgorithm]].- auto flush_promise = controller->flush_algorithm()->function()();-- // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).- transform_stream_default_controller_clear_algorithms(*controller);-- // 7. React to flushPromise:- WebIDL::react_to_promise(flush_promise,- // 1. If flushPromise was fulfilled, then:- GC::create_function(GC::Heap::the(), [controller, readable](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If readable.[[state]] is "errored", reject controller.[[finishPromise]] with readable.[[storedError]].- if (readable->state() == ReadableStream::State::Errored) {- WebIDL::reject_promise(*controller->finish_promise(), readable->stored_error());- }- // 2. Otherwise:- else {- // 1. Perform ! ReadableStreamDefaultControllerClose(readable.[[controller]]).- readable_stream_default_controller_close(readable->controller().value().get<GC::Ref<ReadableStreamDefaultController>>());-- // 2. Resolve controller.[[finishPromise]] with undefined.- WebIDL::resolve_promise(*controller->finish_promise());- }-- return JS::js_undefined();- }),-- // 2. If flushPromise was rejected with reason r, then:- GC::create_function(GC::Heap::the(), [controller, readable](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! ReadableStreamDefaultControllerError(readable.[[controller]], r).- readable_stream_default_controller_error(readable->controller().value().get<GC::Ref<ReadableStreamDefaultController>>(), reason);-- // 2. Reject controller.[[finishPromise]] with r.- WebIDL::reject_promise(*controller->finish_promise(), reason);-- return JS::js_undefined();- }));-- // 8. Return controller.[[finishPromise]].- return *controller->finish_promise();-}--// https://streams.spec.whatwg.org/#transform-stream-default-source-cancel-GC::Ref<WebIDL::Promise> transform_stream_default_source_cancel_algorithm(TransformStream& stream, JS::Value reason)-{- auto& realm = stream.backpressure_change_promise_realm();-- // 1. Let controller be stream.[[controller]].- auto controller = stream.controller();-- // 2. If controller.[[finishPromise]] is not undefined, return controller.[[finishPromise]].- if (controller->finish_promise())- return *controller->finish_promise();-- // 3. Let writable be stream.[[writable]].- auto writable = stream.writable();-- // 4. Let controller.[[finishPromise]] be a new promise.- controller->set_finish_promise(WebIDL::create_promise(realm));-- // 5. Let cancelPromise be the result of performing controller.[[cancelAlgorithm]], passing reason.- auto cancel_promise = controller->cancel_algorithm()->function()(reason);-- // 6. Perform ! TransformStreamDefaultControllerClearAlgorithms(controller).- transform_stream_default_controller_clear_algorithms(*controller);-- // 7. React to cancelPromise:- WebIDL::react_to_promise(cancel_promise,- // 1. If cancelPromise was fulfilled, then:- GC::create_function(GC::Heap::the(), [&stream, writable, controller, reason](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If writable.[[state]] is "errored", reject controller.[[finishPromise]] with writable.[[storedError]].- if (writable->state() == WritableStream::State::Errored) {- WebIDL::reject_promise(*controller->finish_promise(), writable->stored_error());- }- // 2. Otherwise:- else {- // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(writable.[[controller]], reason).- writable_stream_default_controller_error_if_needed(*writable->controller(), reason);-- // 2. Perform ! TransformStreamUnblockWrite(stream).- transform_stream_unblock_write(stream);-- // 3. Resolve controller.[[finishPromise]] with undefined.- WebIDL::resolve_promise(*controller->finish_promise());- }-- return JS::js_undefined();- }),-- // 2. If cancelPromise was rejected with reason r, then:- GC::create_function(GC::Heap::the(), [&stream, writable, controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(writable.[[controller]], r).- writable_stream_default_controller_error_if_needed(*writable->controller(), reason);-- // 2. Perform ! TransformStreamUnblockWrite(stream).- transform_stream_unblock_write(stream);-- // 3. Reject controller.[[finishPromise]] with r.- WebIDL::reject_promise(*controller->finish_promise(), reason);-- return JS::js_undefined();- }));-- // 8. Return controller.[[finishPromise]].- return *controller->finish_promise();-}--// https://streams.spec.whatwg.org/#transform-stream-default-source-pull-GC::Ref<WebIDL::Promise> transform_stream_default_source_pull_algorithm(TransformStream& stream)-{- // 1. Assert: stream.[[backpressure]] is true.- VERIFY(stream.backpressure() == true);-- // 2. Assert: stream.[[backpressureChangePromise]] is not undefined.- VERIFY(stream.backpressure_change_promise());-- // 3. Perform ! TransformStreamSetBackpressure(stream, false).- transform_stream_set_backpressure(stream, false);-- // 4. Return stream.[[backpressureChangePromise]].- return *stream.backpressure_change_promise();-}--}diff --git a/Libraries/LibWeb/Streams/TransformStreamOperations.h b/Libraries/LibWeb/Streams/TransformStreamOperations.hdeleted file mode 100644index 70791622cd9..00000000000--- a/Libraries/LibWeb/Streams/TransformStreamOperations.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Ptr.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--// 6.4.1. Working with transform streams, https://streams.spec.whatwg.org/#ts-abstract-ops-void initialize_transform_stream(TransformStream&, GC::Ref<WebIDL::Promise> start_promise, double writable_high_water_mark, GC::Ref<SizeAlgorithm> writable_size_algorithm, double readable_high_water_mark, GC::Ref<SizeAlgorithm> readable_size_algorithm);-void initialize_transform_stream(JS::Realm&, TransformStream&, GC::Ref<WebIDL::Promise> start_promise, double writable_high_water_mark, GC::Ref<SizeAlgorithm> writable_size_algorithm, double readable_high_water_mark, GC::Ref<SizeAlgorithm> readable_size_algorithm);-void transform_stream_error(TransformStream&, JS::Value error);-void transform_stream_error_writable_and_unblock_write(TransformStream&, JS::Value error);-void transform_stream_set_backpressure(TransformStream&, bool backpressure);-void transform_stream_set_backpressure(JS::Realm&, TransformStream&, bool backpressure);-void transform_stream_unblock_write(TransformStream&);--// 6.4.2. Default controllers, https://streams.spec.whatwg.org/#ts-default-controller-abstract-ops-void set_up_transform_stream_default_controller(TransformStream&, TransformStreamDefaultController&, GC::Ref<TransformAlgorithm>, GC::Ref<FlushAlgorithm>, GC::Ref<CancelAlgorithm>);-void set_up_transform_stream_default_controller_from_transformer(TransformStream&, JS::Value transformer, Transformer const&);-void set_up_transform_stream_default_controller_from_transformer(JS::Realm&, TransformStream&, JS::Value transformer, Transformer const&);-void transform_stream_default_controller_clear_algorithms(TransformStreamDefaultController&);-WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(TransformStreamDefaultController&, JS::Value chunk);-WebIDL::ExceptionOr<void> transform_stream_default_controller_enqueue(JS::Realm&, TransformStreamDefaultController&, JS::Value chunk);-void transform_stream_default_controller_error(TransformStreamDefaultController&, JS::Value error);-GC::Ref<WebIDL::Promise> transform_stream_default_controller_perform_transform(TransformStreamDefaultController&, JS::Value chunk);-void transform_stream_default_controller_terminate(TransformStreamDefaultController&);--// 6.4.3. Default sinks, https://streams.spec.whatwg.org/#ts-default-sink-abstract-ops-GC::Ref<WebIDL::Promise> transform_stream_default_sink_write_algorithm(TransformStream&, JS::Value chunk);-GC::Ref<WebIDL::Promise> transform_stream_default_sink_abort_algorithm(TransformStream&, JS::Value reason);-GC::Ref<WebIDL::Promise> transform_stream_default_sink_close_algorithm(TransformStream&);--// 6.4.4. Default sources, https://streams.spec.whatwg.org/#ts-default-source-abstract-ops-GC::Ref<WebIDL::Promise> transform_stream_default_source_cancel_algorithm(TransformStream&, JS::Value reason);-GC::Ref<WebIDL::Promise> transform_stream_default_source_pull_algorithm(TransformStream&);--}diff --git a/Libraries/LibWeb/Streams/Transformer.idl b/Libraries/LibWeb/Streams/Transformer.idlindex dbd40a9eb05..2184b466e2e 100644--- a/Libraries/LibWeb/Streams/Transformer.idl+++ b/Libraries/LibWeb/Streams/Transformer.idl@@ -1,4 +1,5 @@// https://streams.spec.whatwg.org/#dictdef-transformer+[ImplementedIn=Rust]dictionary Transformer {TransformerStartCallback start;TransformerTransformCallback transform;diff --git a/Libraries/LibWeb/Streams/UnderlyingSink.idl b/Libraries/LibWeb/Streams/UnderlyingSink.idlindex b66bbbfd632..058adf11572 100644--- a/Libraries/LibWeb/Streams/UnderlyingSink.idl+++ b/Libraries/LibWeb/Streams/UnderlyingSink.idl@@ -1,4 +1,5 @@// https://streams.spec.whatwg.org/#dictdef-underlyingsink+[ImplementedIn=Rust]dictionary UnderlyingSink {UnderlyingSinkStartCallback start;UnderlyingSinkWriteCallback write;diff --git a/Libraries/LibWeb/Streams/UnderlyingSource.idl b/Libraries/LibWeb/Streams/UnderlyingSource.idlindex bc6aebf67f1..9099f0df260 100644--- a/Libraries/LibWeb/Streams/UnderlyingSource.idl+++ b/Libraries/LibWeb/Streams/UnderlyingSource.idl@@ -1,4 +1,5 @@// https://streams.spec.whatwg.org/#dictdef-underlyingsource+[ImplementedIn=Rust]dictionary UnderlyingSource {UnderlyingSourceStartCallback start;UnderlyingSourcePullCallback pull;diff --git a/Libraries/LibWeb/Streams/WritableStream.cpp b/Libraries/LibWeb/Streams/WritableStream.cppdeleted file mode 100644index 17f07e105a9..00000000000--- a/Libraries/LibWeb/Streams/WritableStream.cpp+++ /dev/null@@ -1,212 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibWeb/Bindings/UnderlyingSink.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Bindings/WritableStream.h>-#include <LibWeb/HTML/MessagePort.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/BindingsGlue.h>-#include <LibWeb/Streams/ReadableStream.h>-#include <LibWeb/Streams/ReadableStreamOperations.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultController.h>-#include <LibWeb/Streams/WritableStreamDefaultWriter.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(WritableStream);--WebIDL::ExceptionOr<GC::Ref<WritableStream>> WritableStream::create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<JS::Object> underlying_sink_object, QueuingStrategy const& strategy)-{- auto& realm = HTML::relevant_realm(relevant_global_object);- auto underlying_sink = underlying_sink_object ? JS::Value { underlying_sink_object } : JS::js_null();- auto underlying_sink_dict = TRY(Bindings::convert_to_idl_value_for_underlying_sink(realm.vm(), underlying_sink));- if (underlying_sink_dict.type.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Invalid use of reserved key 'type'"_utf16 };-- return create(realm, underlying_sink_object, underlying_sink_dict, strategy);-}--// https://streams.spec.whatwg.org/#ws-constructor-WebIDL::ExceptionOr<GC::Ref<WritableStream>> WritableStream::create(JS::Realm& realm, GC::Ptr<JS::Object> underlying_sink_object, UnderlyingSink const& underlying_sink_dict, QueuingStrategy const& strategy)-{- auto& vm = realm.vm();-- auto writable_stream = GC::Heap::the().allocate<WritableStream>();-- // 1. If underlyingSink is missing, set it to null.- auto underlying_sink = underlying_sink_object ? JS::Value(underlying_sink_object) : JS::js_null();-- // 4. Perform ! InitializeWritableStream(this).- // Note: This AO configures slot values which are already specified in the class's field initializers.-- // 5. Let sizeAlgorithm be ! ExtractSizeAlgorithm(strategy).- auto size_algorithm = extract_size_algorithm(vm, strategy);-- // 6. Let highWaterMark be ? ExtractHighWaterMark(strategy, 1).- auto high_water_mark = TRY(extract_high_water_mark(strategy, 1));-- // 7. Perform ? SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, underlyingSinkDict, highWaterMark, sizeAlgorithm).- TRY(set_up_writable_stream_default_controller_from_underlying_sink(realm, *writable_stream, underlying_sink, underlying_sink_dict, high_water_mark, size_algorithm));-- return writable_stream;-}--WritableStream::WritableStream()-{-}--}--namespace Web::Bindings {--Streams::WritableStream* writable_stream_from_object(JS::Object& object)-{- return Bindings::impl_from<Streams::WritableStream>(&object);-}--void serialize_writable_stream_with_transfer(JS::Realm& realm, HTML::TransferDataEncoder& data_holder, GC::Ref<Streams::WritableStream> stream)-{- JS::Value wrapped_stream = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, stream);- auto result = MUST(HTML::structured_serialize_with_transfer(realm, wrapped_stream, { { wrapped_stream.as_object() } }));- data_holder.extend(move(result.transfer_data_holders));-}--}--namespace Web::Streams {--void WritableStream::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_close_request);- visitor.visit(m_controller);- visitor.visit(m_in_flight_write_request);- visitor.visit(m_in_flight_close_request);- if (m_pending_abort_request.has_value()) {- visitor.visit(m_pending_abort_request->promise);- visitor.visit(m_pending_abort_request->reason);- }- visitor.visit(m_stored_error);- visitor.visit(m_writer);- for (auto& write_request : m_write_requests)- visitor.visit(write_request);-}--// https://streams.spec.whatwg.org/#ws-locked-bool WritableStream::locked() const-{- // 1. Return ! IsWritableStreamLocked(this).- return is_writable_stream_locked(*this);-}--// https://streams.spec.whatwg.org/#ws-close-GC::Ref<WebIDL::Promise> WritableStream::close(JS::Realm& realm)-{- // 1. If ! IsWritableStreamLocked(this) is true, return a promise rejected with a TypeError exception.- if (is_writable_stream_locked(*this)) {- auto exception = JS::TypeError::create(realm, "Cannot close a locked stream"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 2. If ! WritableStreamCloseQueuedOrInFlight(this) is true, return a promise rejected with a TypeError exception.- if (writable_stream_close_queued_or_in_flight(*this)) {- auto exception = JS::TypeError::create(realm, "Cannot close a stream that is already closed or errored"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 3. Return ! WritableStreamClose(this).- return writable_stream_close(realm, *this);-}--// https://streams.spec.whatwg.org/#ws-abort-GC::Ref<WebIDL::Promise> WritableStream::abort(JS::Realm& realm, Optional<JS::Value> reason)-{- // 1. If ! IsWritableStreamLocked(this) is true, return a promise rejected with a TypeError exception.- if (is_writable_stream_locked(*this)) {- auto exception = JS::TypeError::create(realm, "Cannot abort a locked stream"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 2. Return ! WritableStreamAbort(this, reason).- return writable_stream_abort(realm, *this, reason.value_or(JS::js_undefined()));-}--// https://streams.spec.whatwg.org/#ws-get-writer-WebIDL::ExceptionOr<GC::Ref<WritableStreamDefaultWriter>> WritableStream::get_writer(JS::Realm& realm)-{- // 1. Return ? AcquireWritableStreamDefaultWriter(this).- return acquire_writable_stream_default_writer(realm, *this);-}--// https://streams.spec.whatwg.org/#ref-for-transfer-steps①-WebIDL::ExceptionOr<void> WritableStream::transfer_steps(JS::Realm& realm, HTML::TransferDataEncoder& data_holder)-{- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 1. If ! IsWritableStreamLocked(value) is true, throw a "DataCloneError" DOMException.- if (is_writable_stream_locked(*this))- return WebIDL::DataCloneError::create("Cannot transfer locked WritableStream"_utf16);-- // 2. Let port1 be a new MessagePort in the current Realm.- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(realm.global_object());- VERIFY(global_scope);- auto port1 = HTML::MessagePort::create(global_scope->this_impl());-- // 3. Let port2 be a new MessagePort in the current Realm.- auto port2 = HTML::MessagePort::create(global_scope->this_impl());-- // 4. Entangle port1 and port2.- port1->entangle_with(port2);-- // 5. Let readable be a new ReadableStream in the current Realm.- auto readable = GC::Heap::the().allocate<ReadableStream>();- readable->set_realm(realm);-- // 6. Perform ! SetUpCrossRealmTransformReadable(readable, port1).- set_up_cross_realm_transform_readable(realm, readable, port1);-- // 7. Let promise be ! ReadableStreamPipeTo(readable, value, false, false, false).- auto promise = readable_stream_pipe_to(realm, readable, *this, false, false, false);-- // 8. Set promise.[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(promise);-- // 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).- Bindings::serialize_message_port_with_transfer(realm, data_holder, port2);-- return {};-}--// https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps①-WebIDL::ExceptionOr<void> WritableStream::transfer_receiving_steps(JS::Realm& realm, HTML::TransferDataDecoder& data_holder)-{- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- // 1. Let deserializedRecord be ! StructuredDeserializeWithTransfer(dataHolder.[[port]], the current Realm).- auto deserialized_record = MUST(HTML::structured_deserialize_with_transfer_internal(data_holder, realm));-- // 2. Let port be deserializedRecord.[[Deserialized]].- auto* port = Bindings::message_port_from_object(deserialized_record.as_object());- VERIFY(port);-- // 3. Perform ! SetUpCrossRealmTransformWritable(value, port).- set_up_cross_realm_transform_writable(realm, *this, *port);-- return {};-}--}diff --git a/Libraries/LibWeb/Streams/WritableStream.h b/Libraries/LibWeb/Streams/WritableStream.hindex 7312456cd2a..592e7c76bd5 100644--- a/Libraries/LibWeb/Streams/WritableStream.h+++ b/Libraries/LibWeb/Streams/WritableStream.h@@ -6,139 +6,16 @@#pragma once-#include <AK/Forward.h>-#include <AK/SinglyLinkedList.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Transferable.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/Streams/QueuingStrategy.h>-#include <LibWeb/WebIDL/Promise.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/WritableStream.h>+#include <LibWeb/Export.h>namespace Web::Streams {-// https://streams.spec.whatwg.org/#pending-abort-request-struct PendingAbortRequest {- // https://streams.spec.whatwg.org/#pending-abort-request-promise- // A promise returned from WritableStreamAbort- GC::Ref<WebIDL::Promise> promise;-- // https://streams.spec.whatwg.org/#pending-abort-request-reason- // A JavaScript value that was passed as the abort reason to WritableStreamAbort- JS::Value reason;-- // https://streams.spec.whatwg.org/#pending-abort-request-was-already-erroring- // A boolean indicating whether or not the stream was in the "erroring" state when WritableStreamAbort was called, which impacts the outcome of the abort request- bool was_already_erroring;-};-// https://streams.spec.whatwg.org/#writablestream-class WritableStream final- : public Bindings::GCAllocatedWrappable- , public Bindings::Transferable {- WEB_WRAPPABLE(WritableStream, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(WritableStream);--public:- enum class State {- Writable,- Closed,- Erroring,- Errored,- };-- static WebIDL::ExceptionOr<GC::Ref<WritableStream>> create_for_constructor(JS::Object&, GC::Ptr<JS::Object> underlying_sink_object, QueuingStrategy const& = {});- static WebIDL::ExceptionOr<GC::Ref<WritableStream>> create(JS::Realm&, GC::Ptr<JS::Object> underlying_sink_object, UnderlyingSink const&, QueuingStrategy const& = {});-- virtual ~WritableStream() = default;-- bool locked() const;- GC::Ref<WebIDL::Promise> abort(JS::Realm&, Optional<JS::Value> reason);- GC::Ref<WebIDL::Promise> close(JS::Realm&);- WebIDL::ExceptionOr<GC::Ref<WritableStreamDefaultWriter>> get_writer(JS::Realm&);-- bool backpressure() const { return m_backpressure; }- void set_backpressure(bool value) { m_backpressure = value; }-- GC::Ptr<WebIDL::Promise const> close_request() const { return m_close_request; }- GC::Ptr<WebIDL::Promise> close_request() { return m_close_request; }- void set_close_request(GC::Ptr<WebIDL::Promise> value) { m_close_request = value; }-- GC::Ptr<WritableStreamDefaultController const> controller() const { return m_controller; }- GC::Ptr<WritableStreamDefaultController> controller() { return m_controller; }- void set_controller(GC::Ptr<WritableStreamDefaultController> value) { m_controller = value; }-- GC::Ptr<WebIDL::Promise const> in_flight_write_request() const { return m_in_flight_write_request; }- void set_in_flight_write_request(GC::Ptr<WebIDL::Promise> value) { m_in_flight_write_request = value; }-- GC::Ptr<WebIDL::Promise const> in_flight_close_request() const { return m_in_flight_close_request; }- void set_in_flight_close_request(GC::Ptr<WebIDL::Promise> value) { m_in_flight_close_request = value; }-- Optional<PendingAbortRequest>& pending_abort_request() { return m_pending_abort_request; }- void set_pending_abort_request(Optional<PendingAbortRequest>&& value) { m_pending_abort_request = move(value); }-- State state() const { return m_state; }- void set_state(State value) { m_state = value; }-- JS::Value stored_error() const { return m_stored_error; }- void set_stored_error(JS::Value value) { m_stored_error = value; }-- GC::Ptr<WritableStreamDefaultWriter const> writer() const { return m_writer; }- GC::Ptr<WritableStreamDefaultWriter> writer() { return m_writer; }- void set_writer(GC::Ptr<WritableStreamDefaultWriter> value) { m_writer = value; }-- SinglyLinkedList<GC::Ref<WebIDL::Promise>>& write_requests() { return m_write_requests; }-- // ^Transferable- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) override;- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) override;- virtual HTML::TransferType primary_interface() const override { return HTML::TransferType::WritableStream; }--private:- WritableStream();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#writablestream-backpressure- // A boolean indicating the backpressure signal set by the controller- bool m_backpressure { false };-- // https://streams.spec.whatwg.org/#writablestream-closerequest- // The promise returned from the writer’s close() method- GC::Ptr<WebIDL::Promise> m_close_request;-- // https://streams.spec.whatwg.org/#writablestream-controller- // A WritableStreamDefaultController created with the ability to control the state and queue of this stream- GC::Ptr<WritableStreamDefaultController> m_controller;-- // https://streams.spec.whatwg.org/#writablestream-inflightwriterequest- // A slot set to the promise for the current in-flight write operation while the underlying sink's write algorithm is executing and has not yet fulfilled, used to prevent reentrant calls- GC::Ptr<WebIDL::Promise> m_in_flight_write_request;-- // https://streams.spec.whatwg.org/#writablestream-inflightcloserequest- // A slot set to the promise for the current in-flight close operation while the underlying sink's close algorithm is executing and has not yet fulfilled, used to prevent the abort() method from interrupting close- GC::Ptr<WebIDL::Promise> m_in_flight_close_request;-- // https://streams.spec.whatwg.org/#writablestream-pendingabortrequest- // A pending abort request- Optional<PendingAbortRequest> m_pending_abort_request;-- // https://streams.spec.whatwg.org/#writablestream-state- // A string containing the stream’s current state, used internally; one of "writable", "closed", "erroring", or "errored"- State m_state { State::Writable };-- // https://streams.spec.whatwg.org/#writablestream-storederror- // A value indicating how the stream failed, to be given as a failure reason or exception when trying to operate on the stream while in the "errored" state- JS::Value m_stored_error { JS::js_undefined() };-- // https://streams.spec.whatwg.org/#writablestream-writer- // A WritableStreamDefaultWriter instance, if the stream is locked to a writer, or undefined if it is not- GC::Ptr<WritableStreamDefaultWriter> m_writer;-- // https://streams.spec.whatwg.org/#writablestream-writerequests- // A list of promises representing the stream’s internal queue of write requests not yet processed by the underlying sink- SinglyLinkedList<GC::Ref<WebIDL::Promise>> m_write_requests;+// The C++ side of a WritableStream, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/streams).+class WEB_API WritableStream : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(WritableStream, writable_stream)};}diff --git a/Libraries/LibWeb/Streams/WritableStream.idl b/Libraries/LibWeb/Streams/WritableStream.idlindex b860a6a46ca..be0b61f0707 100644--- a/Libraries/LibWeb/Streams/WritableStream.idl+++ b/Libraries/LibWeb/Streams/WritableStream.idl@@ -1,6 +1,5 @@// https://streams.spec.whatwg.org/#writablestream- [Exposed=*,- Transferable]+ [Exposed=*, Transferable, ImplementedIn=Rust]interface WritableStream {constructor(optional object underlyingSink, optional QueuingStrategy strategy = {});diff --git a/Libraries/LibWeb/Streams/WritableStreamDefaultController.cpp b/Libraries/LibWeb/Streams/WritableStreamDefaultController.cppdeleted file mode 100644index 457a10431ec..00000000000--- a/Libraries/LibWeb/Streams/WritableStreamDefaultController.cpp+++ /dev/null@@ -1,67 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/DOM/AbortSignal.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultController.h>-#include <LibWeb/Streams/WritableStreamOperations.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(WritableStreamDefaultController);--void WritableStreamDefaultController::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_signal);- for (auto& value : m_queue)- visitor.visit(value.value);- visitor.visit(m_stream);- visitor.visit(m_abort_algorithm);- visitor.visit(m_close_algorithm);- visitor.visit(m_strategy_size_algorithm);- visitor.visit(m_write_algorithm);-}--// https://streams.spec.whatwg.org/#ws-default-controller-error-void WritableStreamDefaultController::error(Optional<JS::Value> error)-{- // 1. Let state be this.[[stream]].[[state]].- auto state = m_stream->state();-- // 2. If state is not "writable", return.- if (state != WritableStream::State::Writable)- return;-- // 3. Perform ! WritableStreamDefaultControllerError(this, e).- writable_stream_default_controller_error(*this, error.value_or(JS::js_undefined()));-}--// https://streams.spec.whatwg.org/#ws-default-controller-private-abort-GC::Ref<WebIDL::Promise> WritableStreamDefaultController::abort_steps(JS::Value reason)-{- // 1. Let result be the result of performing this.[[abortAlgorithm]], passing reason.- auto result = m_abort_algorithm->function()(reason);-- // 2. Perform ! WritableStreamDefaultControllerClearAlgorithms(this).- writable_stream_default_controller_clear_algorithms(*this);-- // 3. Return result.- return result;-}--// https://streams.spec.whatwg.org/#ws-default-controller-private-error-void WritableStreamDefaultController::error_steps()-{- // 1. Perform ! ResetQueue(this).- reset_queue(*this);-}--WritableStreamDefaultController::WritableStreamDefaultController()-{-}--}diff --git a/Libraries/LibWeb/Streams/WritableStreamDefaultController.h b/Libraries/LibWeb/Streams/WritableStreamDefaultController.hdeleted file mode 100644index 9c2b34770ff..00000000000--- a/Libraries/LibWeb/Streams/WritableStreamDefaultController.h+++ /dev/null@@ -1,103 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/SinglyLinkedList.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Streams/AbstractOperations.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-class WritableStreamDefaultController final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(WritableStreamDefaultController, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(WritableStreamDefaultController);--public:- static constexpr size_t signal_offset() { return offsetof(WritableStreamDefaultController, m_signal); }- virtual ~WritableStreamDefaultController() override = default;-- void error(Optional<JS::Value> error);- GC::Ref<DOM::AbortSignal> signal() { return *m_signal; }- void set_signal(GC::Ref<DOM::AbortSignal> value) { m_signal = value; }-- GC::Ptr<AbortAlgorithm> abort_algorithm() { return m_abort_algorithm; }- void set_abort_algorithm(GC::Ptr<AbortAlgorithm> value) { m_abort_algorithm = value; }-- GC::Ptr<CloseAlgorithm> close_algorithm() { return m_close_algorithm; }- void set_close_algorithm(GC::Ptr<CloseAlgorithm> value) { m_close_algorithm = value; }-- SinglyLinkedList<ValueWithSize>& queue() { return m_queue; }-- double queue_total_size() const { return m_queue_total_size; }- void set_queue_total_size(double value) { m_queue_total_size = value; }-- bool started() const { return m_started; }- void set_started(bool value) { m_started = value; }-- double strategy_hwm() const { return m_strategy_hwm; }- void set_strategy_hwm(double value) { m_strategy_hwm = value; }-- GC::Ptr<SizeAlgorithm> strategy_size_algorithm() { return m_strategy_size_algorithm; }- void set_strategy_size_algorithm(GC::Ptr<SizeAlgorithm> value) { m_strategy_size_algorithm = value; }-- GC::Ref<WritableStream> stream() { return *m_stream; }- void set_stream(GC::Ref<WritableStream> value) { m_stream = value; }-- GC::Ptr<WriteAlgorithm> write_algorithm() { return m_write_algorithm; }- void set_write_algorithm(GC::Ptr<WriteAlgorithm> value) { m_write_algorithm = value; }-- GC::Ref<WebIDL::Promise> abort_steps(JS::Value reason);- void error_steps();--private:- WritableStreamDefaultController();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-abortalgorithm- // A promise-returning algorithm, taking one argument (the abort reason), which communicates a requested abort to the underlying sink- GC::Ptr<AbortAlgorithm> m_abort_algorithm;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-closealgorithm- // A promise-returning algorithm which communicates a requested close to the underlying sink- GC::Ptr<CloseAlgorithm> m_close_algorithm;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-queue- // A list representing the stream’s internal queue of chunks- SinglyLinkedList<ValueWithSize> m_queue;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-queuetotalsize- // The total size of all the chunks stored in [[queue]]- double m_queue_total_size { 0 };-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-signal- // An AbortSignal that can be used to abort the pending write or close operation when the stream is aborted.- GC::Ptr<DOM::AbortSignal> m_signal;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-started- // A boolean flag indicating whether the underlying sink has finished starting- bool m_started { false };-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-strategyhwm- // A number supplied by the creator of the stream as part of the stream’s queuing strategy, indicating the point at which the stream will apply backpressure to its underlying sink- double m_strategy_hwm { 0 };-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-strategysizealgorithm- // An algorithm to calculate the size of enqueued chunks, as part of the stream’s queuing strategy- GC::Ptr<SizeAlgorithm> m_strategy_size_algorithm;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-stream- // The WritableStream instance controlled- GC::Ptr<WritableStream> m_stream;-- // https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-writealgorithm- // A promise-returning algorithm, taking one argument (the chunk to write), which writes data to the underlying sink- GC::Ptr<WriteAlgorithm> m_write_algorithm;-};--}diff --git a/Libraries/LibWeb/Streams/WritableStreamDefaultController.idl b/Libraries/LibWeb/Streams/WritableStreamDefaultController.idlindex d7de5788d25..12ad802fc61 100644--- a/Libraries/LibWeb/Streams/WritableStreamDefaultController.idl+++ b/Libraries/LibWeb/Streams/WritableStreamDefaultController.idl@@ -1,6 +1,6 @@// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-[Exposed=*]+[Exposed=*, ImplementedIn=Rust]interface WritableStreamDefaultController {- [DirectGetter] readonly attribute AbortSignal signal;+ [CachedAccessor] readonly attribute AbortSignal signal;undefined error(optional any e);};diff --git a/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cpp b/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cppdeleted file mode 100644index ea57cb184e6..00000000000--- a/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.cpp+++ /dev/null@@ -1,147 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/Promise.h>-#include <LibJS/Runtime/PromiseCapability.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultWriter.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--GC_DEFINE_ALLOCATOR(WritableStreamDefaultWriter);--WebIDL::ExceptionOr<GC::Ref<WritableStreamDefaultWriter>> WritableStreamDefaultWriter::create(JS::Realm& realm, GC::Ref<WritableStream> stream)-{- auto writer = GC::Heap::the().allocate<WritableStreamDefaultWriter>();-- // 1. Perform ? SetUpWritableStreamDefaultWriter(this, stream).- TRY(set_up_writable_stream_default_writer(realm, *writer, stream));-- return writer;-}--// https://streams.spec.whatwg.org/#default-writer-closed-GC::Ptr<WebIDL::Promise> WritableStreamDefaultWriter::closed()-{- // 1. Return this.[[closedPromise]].- return m_closed_promise;-}--// https://streams.spec.whatwg.org/#default-writer-desired-size-WebIDL::ExceptionOr<Optional<double>> WritableStreamDefaultWriter::desired_size() const-{- // 1. If this.[[stream]] is undefined, throw a TypeError exception.- if (!m_stream)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot get desired size of writer that has no locked stream"_utf16 };-- // 2. Return ! WritableStreamDefaultWriterGetDesiredSize(this).- return writable_stream_default_writer_get_desired_size(*this);-}--// https://streams.spec.whatwg.org/#default-writer-ready-GC::Ptr<WebIDL::Promise> WritableStreamDefaultWriter::ready()-{- // 1. Return this.[[readyPromise]].- return m_ready_promise;-}--// https://streams.spec.whatwg.org/#default-writer-abort-GC::Ref<WebIDL::Promise> WritableStreamDefaultWriter::abort(Optional<JS::Value> reason)-{- auto& realm = closed_promise_realm();-- // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.- if (!m_stream) {- auto exception = JS::TypeError::create(realm, "Cannot abort a writer that has no locked stream"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 2. Return ! WritableStreamDefaultWriterAbort(this, reason).- return writable_stream_default_writer_abort(*this, reason.value_or(JS::js_undefined()));-}--// https://streams.spec.whatwg.org/#default-writer-close-GC::Ref<WebIDL::Promise> WritableStreamDefaultWriter::close()-{- auto& realm = closed_promise_realm();-- // 1. Let stream be this.[[stream]].-- // 2. If stream is undefined, return a promise rejected with a TypeError exception.- if (!m_stream) {- auto exception = JS::TypeError::create(realm, "Cannot close a writer that has no locked stream"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 3. If ! WritableStreamCloseQueuedOrInFlight(stream) is true, return a promise rejected with a TypeError exception.- if (writable_stream_close_queued_or_in_flight(*m_stream)) {- auto exception = JS::TypeError::create(realm, "Cannot close a stream that is already closed or errored"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 4. Return ! WritableStreamDefaultWriterClose(this).- return writable_stream_default_writer_close(*this);-}--// https://streams.spec.whatwg.org/#default-writer-release-lock-void WritableStreamDefaultWriter::release_lock()-{- // 1. Let stream be this.[[stream]].-- // 2. If stream is undefined, return.- if (!m_stream)- return;-- // 3. Assert: stream.[[writer]] is not undefined.- VERIFY(m_stream->writer());-- // 4. Perform ! WritableStreamDefaultWriterRelease(this).- writable_stream_default_writer_release(*this);-}--// https://streams.spec.whatwg.org/#default-writer-write-GC::Ref<WebIDL::Promise> WritableStreamDefaultWriter::write(Optional<JS::Value> chunk)-{- auto& realm = ready_promise_realm();-- // 1. If this.[[stream]] is undefined, return a promise rejected with a TypeError exception.- if (!m_stream) {- auto exception = JS::TypeError::create(realm, "Cannot write to a writer that has no locked stream"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 2. Return ! WritableStreamDefaultWriterWrite(this, chunk).- return writable_stream_default_writer_write(*this, chunk.value_or(JS::js_undefined()));-}--WritableStreamDefaultWriter::WritableStreamDefaultWriter()-{-}--JS::Realm& WritableStreamDefaultWriter::closed_promise_realm() const-{- VERIFY(m_closed_promise);- return WebIDL::promise_realm(*m_closed_promise);-}--JS::Realm& WritableStreamDefaultWriter::ready_promise_realm() const-{- VERIFY(m_ready_promise);- return WebIDL::promise_realm(*m_ready_promise);-}--void WritableStreamDefaultWriter::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_closed_promise);- visitor.visit(m_ready_promise);- visitor.visit(m_stream);-}--}diff --git a/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.h b/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.hdeleted file mode 100644index 25e2eaaf8ed..00000000000--- a/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.h+++ /dev/null@@ -1,66 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Function.h>-#include <AK/SinglyLinkedList.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#writablestreamdefaultwriter-class WritableStreamDefaultWriter final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(WritableStreamDefaultWriter, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(WritableStreamDefaultWriter);--public:- static WebIDL::ExceptionOr<GC::Ref<WritableStreamDefaultWriter>> create(JS::Realm&, GC::Ref<WritableStream>);-- virtual ~WritableStreamDefaultWriter() override = default;-- GC::Ptr<WebIDL::Promise> closed();- WebIDL::ExceptionOr<Optional<double>> desired_size() const;- GC::Ptr<WebIDL::Promise> ready();- GC::Ref<WebIDL::Promise> abort(Optional<JS::Value> reason);- GC::Ref<WebIDL::Promise> close();- void release_lock();- GC::Ref<WebIDL::Promise> write(Optional<JS::Value> chunk);-- GC::Ptr<WebIDL::Promise> closed_promise() { return m_closed_promise; }- void set_closed_promise(GC::Ptr<WebIDL::Promise> value) { m_closed_promise = value; }- JS::Realm& closed_promise_realm() const;-- GC::Ptr<WebIDL::Promise> ready_promise() { return m_ready_promise; }- void set_ready_promise(GC::Ptr<WebIDL::Promise> value) { m_ready_promise = value; }- JS::Realm& ready_promise_realm() const;-- GC::Ptr<WritableStream const> stream() const { return m_stream; }- GC::Ptr<WritableStream> stream() { return m_stream; }- void set_stream(GC::Ptr<WritableStream> value) { m_stream = value; }--private:- WritableStreamDefaultWriter();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://streams.spec.whatwg.org/#writablestreamdefaultwriter-closedpromise- // A promise returned by the writer’s closed getter- GC::Ptr<WebIDL::Promise> m_closed_promise;-- // https://streams.spec.whatwg.org/#writablestreamdefaultwriter-readypromise- // A promise returned by the writer’s ready getter- GC::Ptr<WebIDL::Promise> m_ready_promise;-- // https://streams.spec.whatwg.org/#writablestreamdefaultwriter-stream- // A WritableStream instance that owns this reader- GC::Ptr<WritableStream> m_stream;-};--}diff --git a/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl b/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idlindex 0ea73259fc1..79ee6fbfa0f 100644--- a/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl+++ b/Libraries/LibWeb/Streams/WritableStreamDefaultWriter.idl@@ -1,5 +1,5 @@// https://streams.spec.whatwg.org/#writablestreamdefaultwriter- [Exposed=*]+ [Exposed=*, ImplementedIn=Rust]interface WritableStreamDefaultWriter {constructor(WritableStream stream);diff --git a/Libraries/LibWeb/Streams/WritableStreamOperations.cpp b/Libraries/LibWeb/Streams/WritableStreamOperations.cppdeleted file mode 100644index 62adfa505fe..00000000000--- a/Libraries/LibWeb/Streams/WritableStreamOperations.cpp+++ /dev/null@@ -1,1294 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/GenericShorthands.h>-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Bindings/WritableStreamDefaultController.h>-#include <LibWeb/DOM/AbortSignal.h>-#include <LibWeb/Streams/AbstractOperations.h>-#include <LibWeb/Streams/BindingsGlue.h>-#include <LibWeb/Streams/WritableStream.h>-#include <LibWeb/Streams/WritableStreamDefaultController.h>-#include <LibWeb/Streams/WritableStreamDefaultWriter.h>-#include <LibWeb/Streams/WritableStreamOperations.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Streams {--// https://streams.spec.whatwg.org/#close-sentinel-static JS::Value create_close_sentinel()-{- // The close sentinel is a unique value enqueued into [[queue]], in lieu of a chunk, to signal that the stream is- // closed. It is only used internally, and is never exposed to web developers.- return JS::js_special_empty_value();-}--// https://streams.spec.whatwg.org/#close-sentinel-static bool is_close_sentinel(JS::Value value)-{- return value.is_special_empty_value();-}--}--namespace Web::Bindings {--WebIDL::ExceptionOr<JS::Value> invoke_writable_stream_start_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value underlying_sink, GC::Ref<Streams::WritableStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return TRY(WebIDL::invoke_callback(callback, underlying_sink, WebIDL::ExceptionBehavior::Rethrow, { { wrapped_controller } }));-}--GC::Ref<WebIDL::Promise> invoke_writable_stream_write_algorithm_callback(JS::Realm& realm, WebIDL::CallbackType& callback, JS::Value underlying_sink, JS::Value chunk, GC::Ref<Streams::WritableStreamDefaultController> controller)-{- JS::Value wrapped_controller = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, controller);- return WebIDL::invoke_promise_callback(callback, underlying_sink, { { chunk, wrapped_controller } });-}--}--namespace Web::Streams {--// https://streams.spec.whatwg.org/#acquire-writable-stream-default-writer-WebIDL::ExceptionOr<GC::Ref<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(JS::Realm& realm, WritableStream& stream)-{- // 1. Let writer be a new WritableStreamDefaultWriter.- auto writer = GC::Heap::the().allocate<WritableStreamDefaultWriter>();-- // 2. Perform ? SetUpWritableStreamDefaultWriter(writer, stream).- TRY(set_up_writable_stream_default_writer(realm, writer, stream));-- // 3. Return writer.- return writer;-}--// https://streams.spec.whatwg.org/#create-writable-stream-WebIDL::ExceptionOr<GC::Ref<WritableStream>> create_writable_stream(JS::Realm& realm, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<WriteAlgorithm> write_algorithm, GC::Ref<CloseAlgorithm> close_algorithm, GC::Ref<AbortAlgorithm> abort_algorithm, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm)-{- // 1. Assert: ! IsNonNegativeNumber(highWaterMark) is true.- VERIFY(is_non_negative_number(JS::Value { high_water_mark }));-- // 2. Let stream be a new WritableStream.- auto stream = GC::Heap::the().allocate<WritableStream>();-- // 3. Perform ! InitializeWritableStream(stream).- initialize_writable_stream(stream);-- // 4. Let controller be a new WritableStreamDefaultController.- auto controller = GC::Heap::the().allocate<WritableStreamDefaultController>();-- // 5. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).- TRY(set_up_writable_stream_default_controller(realm, stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, high_water_mark, size_algorithm));-- // 6. Return stream.- return stream;-}--// https://streams.spec.whatwg.org/#initialize-writable-stream-void initialize_writable_stream(WritableStream& stream)-{- // 1. Set stream.[[state]] to "writable".- stream.set_state(WritableStream::State::Writable);-- // 2. Set stream.[[storedError]], stream.[[writer]], stream.[[controller]], stream.[[inFlightWriteRequest]],- // stream.[[closeRequest]], stream.[[inFlightCloseRequest]], and stream.[[pendingAbortRequest]] to undefined.- stream.set_stored_error(JS::js_undefined());- stream.set_writer({});- stream.set_controller({});- stream.set_in_flight_write_request({});- stream.set_close_request({});- stream.set_in_flight_close_request({});- stream.set_pending_abort_request({});-- // 3. Set stream.[[writeRequests]] to a new empty list.- stream.write_requests().clear();-- // 4. Set stream.[[backpressure]] to false.- stream.set_backpressure(false);-}--// https://streams.spec.whatwg.org/#is-writable-stream-locked-bool is_writable_stream_locked(WritableStream const& stream)-{- // 1. If stream.[[writer]] is undefined, return false.- if (!stream.writer())- return false;-- // 2. Return true.- return true;-}--// https://streams.spec.whatwg.org/#set-up-writable-stream-default-writer-WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(JS::Realm& realm, WritableStreamDefaultWriter& writer, WritableStream& stream)-{- // 1. If ! IsWritableStreamLocked(stream) is true, throw a TypeError exception.- if (is_writable_stream_locked(stream))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Stream is locked"_utf16 };-- // 2. Set writer.[[stream]] to stream.- writer.set_stream(stream);-- // 3. Set stream.[[writer]] to writer.- stream.set_writer(writer);-- // 4. Let state be stream.[[state]].- auto state = stream.state();-- // 5. If state is "writable",- if (state == WritableStream::State::Writable) {- // 1. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[backpressure]] is true, set- // writer.[[readyPromise]] to a new promise.- if (!writable_stream_close_queued_or_in_flight(stream) && stream.backpressure()) {- writer.set_ready_promise(WebIDL::create_promise(realm));- }- // 2. Otherwise, set writer.[[readyPromise]] to a promise resolved with undefined.- else {- writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));- }-- // 3. Set writer.[[closedPromise]] to a new promise.- writer.set_closed_promise(WebIDL::create_promise(realm));- }- // 6. Otherwise, if state is "erroring",- else if (state == WritableStream::State::Erroring) {- // 1. Set writer.[[readyPromise]] to a promise rejected with stream.[[storedError]].- writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stream.stored_error()));-- // 2. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*writer.ready_promise());-- // 3. Set writer.[[closedPromise]] to a new promise.- writer.set_closed_promise(WebIDL::create_promise(realm));- }- // 7. Otherwise, if state is "closed",- else if (state == WritableStream::State::Closed) {- // 1. Set writer.[[readyPromise]] to a promise resolved with undefined.- writer.set_ready_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));-- // 2. Set writer.[[closedPromise]] to a promise resolved with undefined.- writer.set_closed_promise(WebIDL::create_resolved_promise(realm, JS::js_undefined()));- }- // 8. Otherwise,- else {- // 1. Assert: state is "errored".- VERIFY(state == WritableStream::State::Errored);-- // 2. Let storedError be stream.[[storedError]].- auto stored_error = stream.stored_error();-- // 3. Set writer.[[readyPromise]] to a promise rejected with storedError.- writer.set_ready_promise(WebIDL::create_rejected_promise(realm, stored_error));-- // 4. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*writer.ready_promise());-- // 5. Set writer.[[closedPromise]] to a promise rejected with storedError.- writer.set_closed_promise(WebIDL::create_rejected_promise(realm, stored_error));-- // 6. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*writer.closed_promise());- }-- return {};-}--// https://streams.spec.whatwg.org/#writable-stream-abort-GC::Ref<WebIDL::Promise> writable_stream_abort(JS::Realm& realm, WritableStream& stream, JS::Value reason)-{- // 1. If stream.[[state]] is "closed" or "errored", return a promise resolved with undefined.- if (first_is_one_of(stream.state(), WritableStream::State::Closed, WritableStream::State::Errored))- return WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // 2. Signal abort on stream.[[controller]].[[signal]] with reason.- auto signal_abort_reason = reason;- if (signal_abort_reason.is_undefined())- signal_abort_reason = throw_completion(realm, WebIDL::AbortError::create("Aborted without reason"_utf16)).value();- stream.controller()->signal()->signal_abort(signal_abort_reason, realm.global_object());-- // 3. Let state be stream.[[state]].- auto state = stream.state();-- // 4. If state is "closed" or "errored", return a promise resolved with undefined.- if (state == WritableStream::State::Closed || state == WritableStream::State::Errored)- return WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // 5. If stream.[[pendingAbortRequest]] is not undefined, return stream.[[pendingAbortRequest]]'s promise.- if (stream.pending_abort_request().has_value())- return stream.pending_abort_request()->promise;-- // 6. Assert: state is "writable" or "erroring".- VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);-- // 7. Let wasAlreadyErroring be false.- auto was_already_erroring = false;-- // 8. If state is "erroring",- if (state == WritableStream::State::Erroring) {- // 1. Set wasAlreadyErroring to true.- was_already_erroring = true;-- // 2. Set reason to undefined.- reason = JS::js_undefined();- }-- // 9. Let promise be a new promise.- auto promise = WebIDL::create_promise(realm);-- // 10. Set stream.[[pendingAbortRequest]] to a new pending abort request whose promise is promise, reason is reason,- // and was already erroring is wasAlreadyErroring.- stream.set_pending_abort_request(PendingAbortRequest { promise, reason, was_already_erroring });-- // 11. If wasAlreadyErroring is false, perform ! WritableStreamStartErroring(stream, reason).- if (!was_already_erroring)- writable_stream_start_erroring(stream, reason);-- // 12. Return promise.- return promise;-}--// https://streams.spec.whatwg.org/#writable-stream-close-GC::Ref<WebIDL::Promise> writable_stream_close(JS::Realm& realm, WritableStream& stream)-{- // 1. Let state be stream.[[state]].- auto state = stream.state();-- // 2. If state is "closed" or "errored", return a promise rejected with a TypeError exception.- if (state == WritableStream::State::Closed || state == WritableStream::State::Errored) {- auto message = state == WritableStream::State::Closed ? "Cannot close a closed stream"_utf16 : "Cannot close an errored stream"_utf16;- auto exception = JS::TypeError::create(realm, message);-- return WebIDL::create_rejected_promise(realm, exception);- }-- // 3. Assert: state is "writable" or "erroring".- VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);-- // 4. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.- VERIFY(!writable_stream_close_queued_or_in_flight(stream));-- // 5. Let promise be a new promise.- auto promise = WebIDL::create_promise(realm);-- // 6. Set stream.[[closeRequest]] to promise.- stream.set_close_request(promise);-- // 7. Let writer be stream.[[writer]].- auto writer = stream.writer();-- // 8. If writer is not undefined, and stream.[[backpressure]] is true, and state is "writable", resolve- // writer.[[readyPromise]] with undefined.- if (writer && stream.backpressure() && state == WritableStream::State::Writable)- WebIDL::resolve_promise(*writer->ready_promise());-- // 9. Perform ! WritableStreamDefaultControllerClose(stream.[[controller]]).- writable_stream_default_controller_close(*stream.controller());-- // 10. Return promise.- return promise;-}--// https://streams.spec.whatwg.org/#writable-stream-add-write-request-GC::Ref<WebIDL::Promise> writable_stream_add_write_request(JS::Realm& realm, WritableStream& stream)-{- // 1. Assert: ! IsWritableStreamLocked(stream) is true.- VERIFY(is_writable_stream_locked(stream));-- // 2. Assert: stream.[[state]] is "writable".- VERIFY(stream.state() == WritableStream::State::Writable);-- // 3. Let promise be a new promise.- auto promise = WebIDL::create_promise(realm);-- // 4. Append promise to stream.[[writeRequests]].- stream.write_requests().append(promise);-- // 5. Return promise.- return promise;-}--// https://streams.spec.whatwg.org/#writable-stream-close-queued-or-in-flight-bool writable_stream_close_queued_or_in_flight(WritableStream const& stream)-{- // 1. If stream.[[closeRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.- if (!stream.close_request() && !stream.in_flight_close_request())- return false;-- // 2. Return true.- return true;-}--// https://streams.spec.whatwg.org/#writable-stream-deal-with-rejection-void writable_stream_deal_with_rejection(WritableStream& stream, JS::Value error)-{- // 1. Let state be stream.[[state]].- auto state = stream.state();-- // 2. If state is "writable",- if (state == WritableStream::State::Writable) {- // 1. Perform ! WritableStreamStartErroring(stream, error).- writable_stream_start_erroring(stream, error);-- // 2. Return.- return;- }-- // 3. Assert: state is "erroring".- VERIFY(state == WritableStream::State::Erroring);-- // 4. Perform ! WritableStreamFinishErroring(stream).- writable_stream_finish_erroring(stream);-}--// https://streams.spec.whatwg.org/#writable-stream-finish-erroring-void writable_stream_finish_erroring(WritableStream& stream)-{- // 1. Assert: stream.[[state]] is "erroring".- VERIFY(stream.state() == WritableStream::State::Erroring);-- // 2. Assert: ! WritableStreamHasOperationMarkedInFlight(stream) is false.- VERIFY(!writable_stream_has_operation_marked_in_flight(stream));-- // 3. Set stream.[[state]] to "errored".- stream.set_state(WritableStream::State::Errored);-- // 4. Perform ! stream.[[controller]].[[ErrorSteps]]().- stream.controller()->error_steps();-- // 5. Let storedError be stream.[[storedError]].- auto stored_error = stream.stored_error();-- // 6. For each writeRequest of stream.[[writeRequests]]:- for (auto write_request : stream.write_requests()) {- // 1. Reject writeRequest with storedError.- WebIDL::reject_promise(*write_request, stored_error);- }-- // 7. Set stream.[[writeRequests]] to an empty list.- stream.write_requests().clear();-- // 8. If stream.[[pendingAbortRequest]] is undefined,- if (!stream.pending_abort_request().has_value()) {- // 1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).- writable_stream_reject_close_and_closed_promise_if_needed(stream);-- // 2. Return.- return;- }-- // 9. Let abortRequest be stream.[[pendingAbortRequest]].- // 10. Set stream.[[pendingAbortRequest]] to undefined.- auto abort_request = stream.pending_abort_request().release_value();-- // 11. If abortRequest’s was already erroring is true,- if (abort_request.was_already_erroring) {- // 1. Reject abortRequest’s promise with storedError.- WebIDL::reject_promise(abort_request.promise, stored_error);-- // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).- writable_stream_reject_close_and_closed_promise_if_needed(stream);-- // 3. Return.- return;- }-- // 12. Let promise be ! stream.[[controller]].[[AbortSteps]](abortRequest’s reason).- auto promise = stream.controller()->abort_steps(abort_request.reason);-- WebIDL::react_to_promise(promise,- // 13. Upon fulfillment of promise,- GC::create_function(GC::Heap::the(), [&stream, abort_promise = abort_request.promise](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Resolve abortRequest’s promise with undefined.- WebIDL::resolve_promise(abort_promise);-- // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).- writable_stream_reject_close_and_closed_promise_if_needed(stream);-- return JS::js_undefined();- }),-- // 14. Upon rejection of promise with reason reason,- GC::create_function(GC::Heap::the(), [&stream, abort_promise = abort_request.promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Reject abortRequest’s promise with reason.- WebIDL::reject_promise(abort_promise, reason);-- // 2. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream).- writable_stream_reject_close_and_closed_promise_if_needed(stream);-- return JS::js_undefined();- }));-}--// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-void writable_stream_finish_in_flight_close(WritableStream& stream)-{- // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.- VERIFY(stream.in_flight_close_request());-- // 2. Resolve stream.[[inFlightCloseRequest]] with undefined.- WebIDL::resolve_promise(*stream.in_flight_close_request());-- // 3. Set stream.[[inFlightCloseRequest]] to undefined.- stream.set_in_flight_close_request({});-- // 4. Let state be stream.[[state]].- auto state = stream.state();-- // 5. Assert: stream.[[state]] is "writable" or "erroring".- VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);-- // 6. If state is "erroring",- if (state == WritableStream::State::Erroring) {- // 1. Set stream.[[storedError]] to undefined.- stream.set_stored_error(JS::js_undefined());-- // 2. If stream.[[pendingAbortRequest]] is not undefined,- if (stream.pending_abort_request().has_value()) {- // 1. Resolve stream.[[pendingAbortRequest]]'s promise with undefined.- // 2. Set stream.[[pendingAbortRequest]] to undefined.- auto abort_promise = stream.pending_abort_request().release_value().promise;- WebIDL::resolve_promise(abort_promise);- }- }-- // 7. Set stream.[[state]] to "closed".- stream.set_state(WritableStream::State::Closed);-- // 8. Let writer be stream.[[writer]].- auto writer = stream.writer();-- // 9. If writer is not undefined, resolve writer.[[closedPromise]] with undefined.- if (writer)- WebIDL::resolve_promise(*writer->closed_promise());-- // 10. Assert: stream.[[pendingAbortRequest]] is undefined.- VERIFY(!stream.pending_abort_request().has_value());-- // 11. Assert: stream.[[storedError]] is undefined.- VERIFY(stream.stored_error().is_undefined());-}--// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-close-with-error-void writable_stream_finish_in_flight_close_with_error(WritableStream& stream, JS::Value error)-{- // 1. Assert: stream.[[inFlightCloseRequest]] is not undefined.- VERIFY(stream.in_flight_close_request());-- // 2. Reject stream.[[inFlightCloseRequest]] with error.- WebIDL::reject_promise(*stream.in_flight_close_request(), error);-- // 3. Set stream.[[inFlightCloseRequest]] to undefined.- stream.set_in_flight_close_request({});-- // 4. Assert: stream.[[state]] is "writable" or "erroring".- VERIFY(first_is_one_of(stream.state(), WritableStream::State::Writable, WritableStream::State::Erroring));-- // 5. If stream.[[pendingAbortRequest]] is not undefined,- if (stream.pending_abort_request().has_value()) {- // 1. Reject stream.[[pendingAbortRequest]]'s promise with error.- // 2. Set stream.[[pendingAbortRequest]] to undefined.- auto abort_promise = stream.pending_abort_request().release_value().promise;- WebIDL::reject_promise(abort_promise, error);- }-- // 6. Perform ! WritableStreamDealWithRejection(stream, error).- writable_stream_deal_with_rejection(stream, error);-}--// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-void writable_stream_finish_in_flight_write(WritableStream& stream)-{- // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.- VERIFY(stream.in_flight_write_request());-- // 2. Resolve stream.[[inFlightWriteRequest]] with undefined.- WebIDL::resolve_promise(*stream.in_flight_write_request());-- // 3. Set stream.[[inFlightWriteRequest]] to undefined.- stream.set_in_flight_write_request({});-}--// https://streams.spec.whatwg.org/#writable-stream-finish-in-flight-write-with-error-void writable_stream_finish_in_flight_write_with_error(WritableStream& stream, JS::Value error)-{- // 1. Assert: stream.[[inFlightWriteRequest]] is not undefined.- VERIFY(stream.in_flight_write_request());-- // 2. Reject stream.[[inFlightWriteRequest]] with error.- WebIDL::reject_promise(*stream.in_flight_write_request(), error);-- // 3. Set stream.[[inFlightWriteRequest]] to undefined.- stream.set_in_flight_write_request({});-- // 4. Assert: stream.[[state]] is "writable" or "erroring".- VERIFY(first_is_one_of(stream.state(), WritableStream::State::Writable, WritableStream::State::Erroring));-- // 5. Perform ! WritableStreamDealWithRejection(stream, error).- writable_stream_deal_with_rejection(stream, error);-}--// https://streams.spec.whatwg.org/#writable-stream-has-operation-marked-in-flight-bool writable_stream_has_operation_marked_in_flight(WritableStream const& stream)-{- // 1. If stream.[[inFlightWriteRequest]] is undefined and stream.[[inFlightCloseRequest]] is undefined, return false.- if (!stream.in_flight_write_request() && !stream.in_flight_close_request())- return false;-- // 2. Return true.- return true;-}--// https://streams.spec.whatwg.org/#writable-stream-mark-close-request-in-flight-void writable_stream_mark_close_request_in_flight(WritableStream& stream)-{- // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.- VERIFY(!stream.in_flight_close_request());-- // 2. Assert: stream.[[closeRequest]] is not undefined.- VERIFY(stream.close_request());-- // 3. Set stream.[[inFlightCloseRequest]] to stream.[[closeRequest]].- stream.set_in_flight_close_request(stream.close_request());-- // 4. Set stream.[[closeRequest]] to undefined.- stream.set_close_request({});-}--// https://streams.spec.whatwg.org/#writable-stream-mark-first-write-request-in-flight-void writable_stream_mark_first_write_request_in_flight(WritableStream& stream)-{- // 1. Assert: stream.[[inFlightWriteRequest]] is undefined.- VERIFY(!stream.in_flight_write_request());-- // 2. Assert: stream.[[writeRequests]] is not empty.- VERIFY(!stream.write_requests().is_empty());-- // 3. Let writeRequest be stream.[[writeRequests]][0].- // 4. Remove writeRequest from stream.[[writeRequests]].- auto write_request = stream.write_requests().take_first();-- // 5. Set stream.[[inFlightWriteRequest]] to writeRequest.- stream.set_in_flight_write_request(write_request);-}--// https://streams.spec.whatwg.org/#writable-stream-reject-close-and-closed-promise-if-needed-void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream& stream)-{- // 1. Assert: stream.[[state]] is "errored".- VERIFY(stream.state() == WritableStream::State::Errored);-- // 2. If stream.[[closeRequest]] is not undefined,- if (stream.close_request()) {- // 1. Assert: stream.[[inFlightCloseRequest]] is undefined.- VERIFY(!stream.in_flight_close_request());-- // 2. Reject stream.[[closeRequest]] with stream.[[storedError]].- WebIDL::reject_promise(*stream.close_request(), stream.stored_error());-- // 3. Set stream.[[closeRequest]] to undefined.- stream.set_close_request({});- }-- // 3. Let writer be stream.[[writer]].- auto writer = stream.writer();-- // 4. If writer is not undefined,- if (writer) {- // 1. Reject writer.[[closedPromise]] with stream.[[storedError]].- WebIDL::reject_promise(*writer->closed_promise(), stream.stored_error());-- // 2. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*writer->closed_promise());- }-}--// https://streams.spec.whatwg.org/#writable-stream-start-erroring-void writable_stream_start_erroring(WritableStream& stream, JS::Value reason)-{- // 1. Assert: stream.[[storedError]] is undefined.- VERIFY(stream.stored_error().is_undefined());-- // 2. Assert: stream.[[state]] is "writable".- VERIFY(stream.state() == WritableStream::State::Writable);-- // 3. Let controller be stream.[[controller]].- auto controller = stream.controller();-- // 4. Assert: controller is not undefined.- VERIFY(controller);-- // 5. Set stream.[[state]] to "erroring".- stream.set_state(WritableStream::State::Erroring);-- // 6. Set stream.[[storedError]] to reason.- stream.set_stored_error(reason);-- // 7. Let writer be stream.[[writer]].- auto writer = stream.writer();-- // 8. If writer is not undefined, perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason).- if (writer)- writable_stream_default_writer_ensure_ready_promise_rejected(*writer, reason);-- // 9. If ! WritableStreamHasOperationMarkedInFlight(stream) is false and controller.[[started]] is true,- // perform ! WritableStreamFinishErroring(stream).- if (!writable_stream_has_operation_marked_in_flight(stream) && controller->started())- writable_stream_finish_erroring(stream);-}--// https://streams.spec.whatwg.org/#writable-stream-update-backpressure-void writable_stream_update_backpressure(WritableStream& stream, bool backpressure)-{- // 1. Assert: stream.[[state]] is "writable".- VERIFY(stream.state() == WritableStream::State::Writable);-- // 2. Assert: ! WritableStreamCloseQueuedOrInFlight(stream) is false.- VERIFY(!writable_stream_close_queued_or_in_flight(stream));-- // 3. Let writer be stream.[[writer]].- auto writer = stream.writer();-- // 4. If writer is not undefined and backpressure is not stream.[[backpressure]],- if (writer && backpressure != stream.backpressure()) {- auto& realm = writer->ready_promise_realm();-- // 1. If backpressure is true, set writer.[[readyPromise]] to a new promise.- if (backpressure) {- writer->set_ready_promise(WebIDL::create_promise(realm));- }- // 2. Otherwise,- else {- // 1. Assert: backpressure is false.-- // 2. Resolve writer.[[readyPromise]] with undefined.- WebIDL::resolve_promise(*writer->ready_promise());- }- }-- // 5. Set stream.[[backpressure]] to backpressure.- stream.set_backpressure(backpressure);-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-abort-GC::Ref<WebIDL::Promise> writable_stream_default_writer_abort(WritableStreamDefaultWriter& writer, JS::Value reason)-{- // 1. Let stream be writer.[[stream]].- auto stream = writer.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Return ! WritableStreamAbort(stream, reason).- return writable_stream_abort(writer.closed_promise_realm(), *stream, reason);-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-close-GC::Ref<WebIDL::Promise> writable_stream_default_writer_close(WritableStreamDefaultWriter& writer)-{- // 1. Let stream be writer.[[stream]].- auto stream = writer.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Return ! WritableStreamClose(stream).- return writable_stream_close(writer.closed_promise_realm(), *stream);-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-close-with-error-propagation-GC::Ref<WebIDL::Promise> writable_stream_default_writer_close_with_error_propagation(WritableStreamDefaultWriter& writer)-{- auto& realm = writer.closed_promise_realm();-- // 1. Let stream be writer.[[stream]].- auto stream = writer.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Let state be stream.[[state]].- auto state = stream->state();-- // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is true or state is "closed", return a promise resolved with undefined.- if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed)- return WebIDL::create_resolved_promise(realm, JS::js_undefined());-- // 5. If state is "errored", return a promise rejected with stream.[[storedError]].- if (state == WritableStream::State::Errored)- return WebIDL::create_rejected_promise(realm, stream->stored_error());-- // 6. Assert: state is "writable" or "erroring".- VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);-- // 7. Return ! WritableStreamDefaultWriterClose(writer).- return writable_stream_default_writer_close(writer);-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-closed-promise-rejected-void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)-{- auto& realm = writer.closed_promise_realm();-- // 1. If writer.[[closedPromise]].[[PromiseState]] is "pending", reject writer.[[closedPromise]] with error.- if (as<JS::Promise>(*writer.closed_promise()->promise()).state() == JS::Promise::State::Pending) {- WebIDL::reject_promise(*writer.closed_promise(), error);- }- // 2. Otherwise, set writer.[[closedPromise]] to a promise rejected with error.- else {- writer.set_closed_promise(WebIDL::create_rejected_promise(realm, error));- }-- // 3. Set writer.[[closedPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*writer.closed_promise());-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-ensure-ready-promise-rejected-void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter& writer, JS::Value error)-{- auto& realm = writer.ready_promise_realm();-- // 1. If writer.[[readyPromise]].[[PromiseState]] is "pending", reject writer.[[readyPromise]] with error.- if (as<JS::Promise>(*writer.ready_promise()->promise()).state() == JS::Promise::State::Pending) {- WebIDL::reject_promise(*writer.ready_promise(), error);- }- // 2. Otherwise, set writer.[[readyPromise]] to a promise rejected with error.- else {- writer.set_ready_promise(WebIDL::create_rejected_promise(realm, error));- }-- // 3. Set writer.[[readyPromise]].[[PromiseIsHandled]] to true.- WebIDL::mark_promise_as_handled(*writer.ready_promise());-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-get-desired-size-Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const& writer)-{- // 1. Let stream be writer.[[stream]].- auto stream = writer.stream();-- // 2. Let state be stream.[[state]].- auto state = stream->state();-- // 3. If state is "errored" or "erroring", return null.- if (state == WritableStream::State::Errored || state == WritableStream::State::Erroring)- return {};-- // 4. If state is "closed", return 0.- if (state == WritableStream::State::Closed)- return 0.0;-- // 5. Return ! WritableStreamDefaultControllerGetDesiredSize(stream.[[controller]]).- return writable_stream_default_controller_get_desired_size(*stream->controller());-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-release-void writable_stream_default_writer_release(WritableStreamDefaultWriter& writer)-{- auto& realm = writer.closed_promise_realm();-- // 1. Let stream be writer.[[stream]].- auto stream = writer.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Assert: stream.[[writer]] is writer.- VERIFY(stream->writer().ptr() == &writer);-- // 4. Let releasedError be a new TypeError.- auto released_error = JS::TypeError::create(realm, "Writer's stream lock has been released"_utf16);-- // 5. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError).- writable_stream_default_writer_ensure_ready_promise_rejected(writer, released_error);-- // 6. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError).- writable_stream_default_writer_ensure_closed_promise_rejected(writer, released_error);-- // 7. Set stream.[[writer]] to undefined.- stream->set_writer({});-- // 8. Set writer.[[stream]] to undefined.- writer.set_stream({});-}--// https://streams.spec.whatwg.org/#writable-stream-default-writer-write-GC::Ref<WebIDL::Promise> writable_stream_default_writer_write(WritableStreamDefaultWriter& writer, JS::Value chunk)-{- auto& realm = writer.ready_promise_realm();-- // 1. Let stream be writer.[[stream]].- auto stream = writer.stream();-- // 2. Assert: stream is not undefined.- VERIFY(stream);-- // 3. Let controller be stream.[[controller]].- auto controller = stream->controller();-- // 4. Let chunkSize be ! WritableStreamDefaultControllerGetChunkSize(controller, chunk).- auto chunk_size = writable_stream_default_controller_get_chunk_size(*controller, chunk);-- // 5. If stream is not equal to writer.[[stream]], return a promise rejected with a TypeError exception.- if (stream.ptr() != writer.stream().ptr()) {- auto exception = JS::TypeError::create(realm, "Writer's locked stream changed during write"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 6. Let state be stream.[[state]].- auto state = stream->state();-- // 7. If state is "errored", return a promise rejected with stream.[[storedError]].- if (state == WritableStream::State::Errored)- return WebIDL::create_rejected_promise(realm, stream->stored_error());-- // 8. If ! WritableStreamCloseQueuedOrInFlight(stream) is true or state is "closed", return a promise rejected with a TypeError exception indicating that the stream is closing or closed.- if (writable_stream_close_queued_or_in_flight(*stream) || state == WritableStream::State::Closed) {- auto exception = JS::TypeError::create(realm, "Cannot write to a writer whose stream is closing or already closed"_utf16);- return WebIDL::create_rejected_promise(realm, exception);- }-- // 9. If state is "erroring", return a promise rejected with stream.[[storedError]].- if (state == WritableStream::State::Erroring)- return WebIDL::create_rejected_promise(realm, stream->stored_error());-- // 10. Assert: state is "writable".- VERIFY(state == WritableStream::State::Writable);-- // 11. Let promise be ! WritableStreamAddWriteRequest(stream).- auto promise = writable_stream_add_write_request(realm, *stream);-- // 12. Perform ! WritableStreamDefaultControllerWrite(controller, chunk, chunkSize).- writable_stream_default_controller_write(realm, *controller, chunk, chunk_size);-- // 13. Return promise.- return promise;-}--// https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller(JS::Realm& realm, WritableStream& stream, WritableStreamDefaultController& controller, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<WriteAlgorithm> write_algorithm, GC::Ref<CloseAlgorithm> close_algorithm, GC::Ref<AbortAlgorithm> abort_algorithm, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm)-{- // 1. Assert: stream implements WritableStream.-- // 2. Assert: stream.[[controller]] is undefined.- VERIFY(!stream.controller());-- // 3. Set controller.[[stream]] to stream.- controller.set_stream(stream);-- // 4. Set stream.[[controller]] to controller.- stream.set_controller(controller);-- // 5. Perform ! ResetQueue(controller).- reset_queue(controller);-- // 6. Set controller.[[signal]] to a new AbortSignal.- controller.set_signal(DOM::AbortSignal::create());-- // 7. Set controller.[[started]] to false.- controller.set_started(false);-- // 8. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.- controller.set_strategy_size_algorithm(size_algorithm);-- // 9. Set controller.[[strategyHWM]] to highWaterMark.- controller.set_strategy_hwm(high_water_mark);-- // 10. Set controller.[[writeAlgorithm]] to writeAlgorithm.- controller.set_write_algorithm(write_algorithm);-- // 11. Set controller.[[closeAlgorithm]] to closeAlgorithm.- controller.set_close_algorithm(close_algorithm);-- // 12. Set controller.[[abortAlgorithm]] to abortAlgorithm.- controller.set_abort_algorithm(abort_algorithm);-- // 13. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).- auto backpressure = writable_stream_default_controller_get_backpressure(controller);-- // 14. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).- writable_stream_update_backpressure(stream, backpressure);-- // 15. Let startResult be the result of performing startAlgorithm. (This may throw an exception.)- auto start_result = TRY(start_algorithm->function()());-- // 16. Let startPromise be a promise resolved with startResult.- auto start_promise = WebIDL::create_resolved_promise(realm, start_result);-- WebIDL::react_to_promise(start_promise,- // 17. Upon fulfillment of startPromise,- GC::create_function(GC::Heap::the(), [&controller, &stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Assert: stream.[[state]] is "writable" or "erroring".- VERIFY(first_is_one_of(stream.state(), WritableStream::State::Writable, WritableStream::State::Erroring));-- // 2. Set controller.[[started]] to true.- controller.set_started(true);-- // 3. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).- writable_stream_default_controller_advance_queue_if_needed(controller);-- return JS::js_undefined();- }),-- // 18. Upon rejection of startPromise with reason r,- GC::create_function(GC::Heap::the(), [&stream, &controller](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Assert: stream.[[state]] is "writable" or "erroring".- VERIFY(first_is_one_of(stream.state(), WritableStream::State::Writable, WritableStream::State::Erroring));-- // 2. Set controller.[[started]] to true.- controller.set_started(true);-- // 3. Perform ! WritableStreamDealWithRejection(stream, r).- writable_stream_deal_with_rejection(stream, reason);-- return JS::js_undefined();- }));-- return {};-}--// https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink-WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller_from_underlying_sink(JS::Realm& realm, WritableStream& stream, JS::Value underlying_sink_value, UnderlyingSink const& underlying_sink, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm)-{- // 1. Let controller be a new WritableStreamDefaultController.- auto controller = GC::Heap::the().allocate<WritableStreamDefaultController>();-- // 2. Let startAlgorithm be an algorithm that returns undefined.- auto start_algorithm = GC::create_function(GC::Heap::the(), []() -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); });-- // 3. Let writeAlgorithm be an algorithm that returns a promise resolved with undefined.- auto write_algorithm = GC::create_function(GC::Heap::the(), [&realm](JS::Value) {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 4. Let closeAlgorithm be an algorithm that returns a promise resolved with undefined.- auto close_algorithm = GC::create_function(GC::Heap::the(), [&realm]() {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 5. Let abortAlgorithm be an algorithm that returns a promise resolved with undefined.- auto abort_algorithm = GC::create_function(GC::Heap::the(), [&realm](JS::Value) {- return WebIDL::create_resolved_promise(realm, JS::js_undefined());- });-- // 6. If underlyingSinkDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of- // invoking underlyingSinkDict["start"] with argument list « controller », exception behavior "rethrow", and- // callback this value underlyingSink.- if (underlying_sink.start) {- start_algorithm = GC::create_function(GC::Heap::the(), [controller, underlying_sink_value, callback = underlying_sink.start, realm = GC::Ref(realm)]() -> WebIDL::ExceptionOr<JS::Value> {- return Bindings::invoke_writable_stream_start_algorithm_callback(realm, *callback, underlying_sink_value, controller);- });- }-- // 7. If underlyingSinkDict["write"] exists, then set writeAlgorithm to an algorithm which takes an argument chunk- // and returns the result of invoking underlyingSinkDict["write"] with argument list « chunk, controller » and- // callback this value underlyingSink.- if (underlying_sink.write) {- write_algorithm = GC::create_function(GC::Heap::the(), [controller, underlying_sink_value, callback = underlying_sink.write, realm = GC::Ref(realm)](JS::Value chunk) {- return Bindings::invoke_writable_stream_write_algorithm_callback(realm, *callback, underlying_sink_value, chunk, controller);- });- }-- // 8. If underlyingSinkDict["close"] exists, then set closeAlgorithm to an algorithm which returns the result of- // invoking underlyingSinkDict["close"] with argument list «» and callback this value underlyingSink.- if (underlying_sink.close) {- close_algorithm = GC::create_function(GC::Heap::the(), [underlying_sink_value, callback = underlying_sink.close]() {- return WebIDL::invoke_promise_callback(*callback, underlying_sink_value, {});- });- }-- // 9. If underlyingSinkDict["abort"] exists, then set abortAlgorithm to an algorithm which takes an argument reason- // and returns the result of invoking underlyingSinkDict["abort"] with argument list « reason » and callback this- // value underlyingSink.- if (underlying_sink.abort) {- abort_algorithm = GC::create_function(GC::Heap::the(), [underlying_sink_value, callback = underlying_sink.abort](JS::Value reason) {- return WebIDL::invoke_promise_callback(*callback, underlying_sink_value, { { reason } });- });- }-- // 10. Perform ? SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm).- TRY(set_up_writable_stream_default_controller(realm, stream, controller, start_algorithm, write_algorithm, close_algorithm, abort_algorithm, high_water_mark, size_algorithm));-- return {};-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed-void writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController& controller)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. If controller.[[started]] is false, return.- if (!controller.started())- return;-- // 3. If stream.[[inFlightWriteRequest]] is not undefined, return.- if (stream->in_flight_write_request())- return;-- // 4. Let state be stream.[[state]].- auto state = stream->state();-- // 5. Assert: state is not "closed" or "errored".- VERIFY(state != WritableStream::State::Closed && state != WritableStream::State::Errored);-- // 6. If state is "erroring",- if (state == WritableStream::State::Erroring) {- // 1. Perform ! WritableStreamFinishErroring(stream).- writable_stream_finish_erroring(stream);-- // 2. Return.- return;- }-- // 7. If controller.[[queue]] is empty, return.- if (controller.queue().is_empty())- return;-- // 8. Let value be ! PeekQueueValue(controller).- auto value = peek_queue_value(controller);-- // 9. If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).- if (is_close_sentinel(value)) {- writable_stream_default_controller_process_close(controller);- }- // 10. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).- else {- writable_stream_default_controller_process_write(controller, value);- }-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms-void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController& controller)-{- // 1. Set controller.[[writeAlgorithm]] to undefined.- controller.set_write_algorithm({});-- // 2. Set controller.[[closeAlgorithm]] to undefined.- controller.set_close_algorithm({});-- // 3. Set controller.[[abortAlgorithm]] to undefined.- controller.set_abort_algorithm({});-- // 4. Set controller.[[strategySizeAlgorithm]] to undefined.- controller.set_strategy_size_algorithm({});-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-close-void writable_stream_default_controller_close(WritableStreamDefaultController& controller)-{- // 1. Perform ! EnqueueValueWithSize(controller, close sentinel, 0).- MUST(enqueue_value_with_size(controller, create_close_sentinel(), JS::Value(0.0)));-- // 2. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).- writable_stream_default_controller_advance_queue_if_needed(controller);-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-error-void writable_stream_default_controller_error(WritableStreamDefaultController& controller, JS::Value error)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. Assert: stream.[[state]] is "writable".- VERIFY(stream->state() == WritableStream::State::Writable);-- // 3. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).- writable_stream_default_controller_clear_algorithms(controller);-- // 4. Perform ! WritableStreamStartErroring(stream, error).- writable_stream_start_erroring(stream, error);-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed-void writable_stream_default_controller_error_if_needed(WritableStreamDefaultController& controller, JS::Value error)-{- // 1. If controller.[[stream]].[[state]] is "writable", perform ! WritableStreamDefaultControllerError(controller, error).- if (controller.stream()->state() == WritableStream::State::Writable)- writable_stream_default_controller_error(controller, error);-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure-bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const& controller)-{- // 1. Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).- auto desired_size = writable_stream_default_controller_get_desired_size(controller);-- // 2. Return true if desiredSize ≤ 0, or false otherwise.- return desired_size <= 0.0;-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size-JS::Value writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController& controller, JS::Value chunk)-{- // 1. If controller.[[strategySizeAlgorithm]] is undefined, then:- if (!controller.strategy_size_algorithm()) {- // 1. Assert: controller.[[stream]].[[state]] is not "writable".- VERIFY(controller.stream()->state() != WritableStream::State::Writable);-- // 2. Return 1.- return JS::Value { 1.0 };- }-- // 2. Let returnValue be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.- auto return_value = controller.strategy_size_algorithm()->function()(chunk);-- // 3. If returnValue is an abrupt completion,- if (return_value.is_abrupt()) {- // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).- writable_stream_default_controller_error_if_needed(controller, return_value.release_value());-- // 2. Return 1.- return JS::Value { 1.0 };- }-- // 4. Return returnValue.[[Value]].- return return_value.release_value();-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size-double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const& controller)-{- // 1. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].- return controller.strategy_hwm() - controller.queue_total_size();-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close-void writable_stream_default_controller_process_close(WritableStreamDefaultController& controller)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. Perform ! WritableStreamMarkCloseRequestInFlight(stream).- writable_stream_mark_close_request_in_flight(stream);-- // 3. Perform ! DequeueValue(controller).- dequeue_value(controller);-- // 4. Assert: controller.[[queue]] is empty.- VERIFY(controller.queue().is_empty());-- // 5. Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].- auto sink_close_promise = controller.close_algorithm()->function()();-- // 6. Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).- writable_stream_default_controller_clear_algorithms(controller);-- WebIDL::react_to_promise(sink_close_promise,- // 7. Upon fulfillment of sinkClosePromise,- GC::create_function(GC::Heap::the(), [stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! WritableStreamFinishInFlightClose(stream).- writable_stream_finish_in_flight_close(stream);-- return JS::js_undefined();- }),-- // 8. Upon rejection of sinkClosePromise with reason reason,- GC::create_function(GC::Heap::the(), [stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).- writable_stream_finish_in_flight_close_with_error(stream, reason);-- return JS::js_undefined();- }));-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write-void writable_stream_default_controller_process_write(WritableStreamDefaultController& controller, JS::Value chunk)-{- // 1. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 2. Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).- writable_stream_mark_first_write_request_in_flight(stream);-- // 3. Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.- auto sink_write_promise = controller.write_algorithm()->function()(chunk);-- WebIDL::react_to_promise(sink_write_promise,- // 4. Upon fulfillment of sinkWritePromise,- GC::create_function(GC::Heap::the(), [&controller, stream](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- // 1. Perform ! WritableStreamFinishInFlightWrite(stream).- writable_stream_finish_in_flight_write(stream);-- // 2. Let state be stream.[[state]].- auto state = stream->state();-- // 3. Assert: state is "writable" or "erroring".- VERIFY(state == WritableStream::State::Writable || state == WritableStream::State::Erroring);-- // 4. Perform ! DequeueValue(controller).- dequeue_value(controller);-- // 5. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",- if (!writable_stream_close_queued_or_in_flight(stream) && state == WritableStream::State::Writable) {- // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).- auto backpressure = writable_stream_default_controller_get_backpressure(controller);-- // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).- writable_stream_update_backpressure(stream, backpressure);- }-- // 6 .Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).- writable_stream_default_controller_advance_queue_if_needed(controller);-- return JS::js_undefined();- }),-- // 5. Upon rejection of sinkWritePromise with reason,- GC::create_function(GC::Heap::the(), [&controller, stream](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {- // 1. If stream.[[state]] is "writable", perform ! WritableStreamDefaultControllerClearAlgorithms(controller).- if (stream->state() == WritableStream::State::Writable)- writable_stream_default_controller_clear_algorithms(controller);-- // 2. Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).- writable_stream_finish_in_flight_write_with_error(stream, reason);-- return JS::js_undefined();- }));-}--// https://streams.spec.whatwg.org/#writable-stream-default-controller-write-void writable_stream_default_controller_write(JS::Realm& realm, WritableStreamDefaultController& controller, JS::Value chunk, JS::Value chunk_size)-{- auto& vm = realm.vm();-- // 1. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).- auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);-- // 2. If enqueueResult is an abrupt completion,- if (enqueue_result.is_exception()) {- auto throw_completion = WebIDL::exception_to_throw_completion(vm, realm, enqueue_result.exception());-- // 1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).- writable_stream_default_controller_error_if_needed(controller, throw_completion.release_value());-- // 2. Return.- return;- }-- // 3. Let stream be controller.[[stream]].- auto stream = controller.stream();-- // 4. If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",- if (!writable_stream_close_queued_or_in_flight(stream) && stream->state() == WritableStream::State::Writable) {- // 1. Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).- auto backpressure = writable_stream_default_controller_get_backpressure(controller);-- // 2. Perform ! WritableStreamUpdateBackpressure(stream, backpressure).- writable_stream_update_backpressure(stream, backpressure);- }-- // 5. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).- writable_stream_default_controller_advance_queue_if_needed(controller);-}--}diff --git a/Libraries/LibWeb/Streams/WritableStreamOperations.h b/Libraries/LibWeb/Streams/WritableStreamOperations.hdeleted file mode 100644index 8e17bb93577..00000000000--- a/Libraries/LibWeb/Streams/WritableStreamOperations.h+++ /dev/null@@ -1,70 +0,0 @@-/*- * Copyright (c) 2022, Linus Groh <[email protected]>- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2023-2025, Shannon Booth <[email protected]>- * Copyright (c) 2023-2024, Kenneth Myhra <[email protected]>- * Copyright (c) 2025, Tim Flynn <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Ptr.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Streams/Algorithms.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Streams {--// 5.5.1. Working with writable streams, https://streams.spec.whatwg.org/#ws-abstract-ops-WebIDL::ExceptionOr<GC::Ref<WritableStreamDefaultWriter>> acquire_writable_stream_default_writer(JS::Realm&, WritableStream&);-WebIDL::ExceptionOr<GC::Ref<WritableStream>> create_writable_stream(JS::Realm& realm, GC::Ref<StartAlgorithm> start_algorithm, GC::Ref<WriteAlgorithm> write_algorithm, GC::Ref<CloseAlgorithm> close_algorithm, GC::Ref<AbortAlgorithm> abort_algorithm, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm);-void initialize_writable_stream(WritableStream&);-bool is_writable_stream_locked(WritableStream const&);-WebIDL::ExceptionOr<void> set_up_writable_stream_default_writer(JS::Realm&, WritableStreamDefaultWriter&, WritableStream&);-GC::Ref<WebIDL::Promise> writable_stream_abort(JS::Realm&, WritableStream&, JS::Value reason);-GC::Ref<WebIDL::Promise> writable_stream_close(JS::Realm&, WritableStream&);--// 5.5.2. Interfacing with controllers, https://streams.spec.whatwg.org/#ws-abstract-ops-used-by-controllers-GC::Ref<WebIDL::Promise> writable_stream_add_write_request(JS::Realm&, WritableStream&);-bool writable_stream_close_queued_or_in_flight(WritableStream const&);-void writable_stream_deal_with_rejection(WritableStream&, JS::Value error);-void writable_stream_finish_erroring(WritableStream&);-void writable_stream_finish_in_flight_close(WritableStream&);-void writable_stream_finish_in_flight_close_with_error(WritableStream&, JS::Value error);-void writable_stream_finish_in_flight_write(WritableStream&);-void writable_stream_finish_in_flight_write_with_error(WritableStream&, JS::Value error);-bool writable_stream_has_operation_marked_in_flight(WritableStream const&);-void writable_stream_mark_close_request_in_flight(WritableStream&);-void writable_stream_mark_first_write_request_in_flight(WritableStream&);-void writable_stream_reject_close_and_closed_promise_if_needed(WritableStream&);-void writable_stream_start_erroring(WritableStream&, JS::Value reason);-void writable_stream_update_backpressure(WritableStream&, bool backpressure);--// 5.5.3. Writers, https://streams.spec.whatwg.org/#ws-writer-abstract-ops-GC::Ref<WebIDL::Promise> writable_stream_default_writer_abort(WritableStreamDefaultWriter&, JS::Value reason);-GC::Ref<WebIDL::Promise> writable_stream_default_writer_close(WritableStreamDefaultWriter&);-GC::Ref<WebIDL::Promise> writable_stream_default_writer_close_with_error_propagation(WritableStreamDefaultWriter&);-void writable_stream_default_writer_ensure_closed_promise_rejected(WritableStreamDefaultWriter&, JS::Value error);-void writable_stream_default_writer_ensure_ready_promise_rejected(WritableStreamDefaultWriter&, JS::Value error);-Optional<double> writable_stream_default_writer_get_desired_size(WritableStreamDefaultWriter const&);-void writable_stream_default_writer_release(WritableStreamDefaultWriter&);-GC::Ref<WebIDL::Promise> writable_stream_default_writer_write(WritableStreamDefaultWriter&, JS::Value chunk);--// 5.5.4. Default controllers, https://streams.spec.whatwg.org/#ws-default-controller-abstract-ops-WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller(JS::Realm&, WritableStream&, WritableStreamDefaultController&, GC::Ref<StartAlgorithm>, GC::Ref<WriteAlgorithm>, GC::Ref<CloseAlgorithm>, GC::Ref<AbortAlgorithm>, double high_water_mark, GC::Ref<SizeAlgorithm>);-WebIDL::ExceptionOr<void> set_up_writable_stream_default_controller_from_underlying_sink(JS::Realm&, WritableStream&, JS::Value underlying_sink_value, UnderlyingSink const&, double high_water_mark, GC::Ref<SizeAlgorithm> size_algorithm);-void writable_stream_default_controller_advance_queue_if_needed(WritableStreamDefaultController&);-void writable_stream_default_controller_clear_algorithms(WritableStreamDefaultController&);-void writable_stream_default_controller_close(WritableStreamDefaultController&);-void writable_stream_default_controller_error(WritableStreamDefaultController&, JS::Value error);-void writable_stream_default_controller_error_if_needed(WritableStreamDefaultController&, JS::Value error);-bool writable_stream_default_controller_get_backpressure(WritableStreamDefaultController const&);-JS::Value writable_stream_default_controller_get_chunk_size(WritableStreamDefaultController&, JS::Value chunk);-double writable_stream_default_controller_get_desired_size(WritableStreamDefaultController const&);-void writable_stream_default_controller_process_close(WritableStreamDefaultController&);-void writable_stream_default_controller_process_write(WritableStreamDefaultController&, JS::Value chunk);-void writable_stream_default_controller_write(JS::Realm&, WritableStreamDefaultController&, JS::Value chunk, JS::Value chunk_size);--}diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.pyindex 540c1dfd9c4..76ac9bf942c 100644--- a/Meta/Generators/libweb_bindings/glue_headers.py+++ b/Meta/Generators/libweb_bindings/glue_headers.py@@ -16,7 +16,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_n"CSS": "LibWeb/CSS/BindingsGlue.h","CookieStore": "LibWeb/CookieStore/BindingsGlue.h","IndexedDB": "LibWeb/IndexedDB/BindingsGlue.h",- "Streams": "LibWeb/Streams/BindingsGlue.h","TrustedTypes": "LibWeb/TrustedTypes/BindingsGlue.h","WebAssembly": "LibWeb/WebAssembly/BindingsGlue.h","WebAudio": "LibWeb/WebAudio/BindingsGlue.h",diff --git a/Meta/Generators/libweb_bindings/intrinsics.py b/Meta/Generators/libweb_bindings/intrinsics.pyindex e603567aa68..73f3478b644 100644--- a/Meta/Generators/libweb_bindings/intrinsics.py+++ b/Meta/Generators/libweb_bindings/intrinsics.py@@ -752,7 +752,6 @@ def write_wrapper_factory_implementation(out: TextIO, interface_sets: InterfaceS#include <LibWeb/DOM/BindingsGlue.h>#include <LibWeb/Fetch/BindingsGlue.h>#include <LibWeb/HTML/BindingsGlue.h>-#include <LibWeb/Streams/BindingsGlue.h>#include <LibWeb/WebAssembly/BindingsGlue.h>#include <LibWeb/Bindings/PlatformObject.h>#include <LibWeb/Bindings/Wrappable.h>diff --git a/Meta/Generators/libweb_bindings/structured_serialize.py b/Meta/Generators/libweb_bindings/structured_serialize.pyindex a1537908292..e099adffca8 100644--- a/Meta/Generators/libweb_bindings/structured_serialize.py+++ b/Meta/Generators/libweb_bindings/structured_serialize.py@@ -317,10 +317,6 @@ WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> create_transferred_platform_object(VERIFY(global_scope);auto transferable = HTML::OffscreenCanvas::create(global_scope->this_impl(), 0, 0);""")- elif interface.name in ("ReadableStream", "TransformStream", "WritableStream"):- out.write(- f" auto transferable = GC::Heap::the().allocate<{fully_qualified_name_for_interface(interface)}>();\n"- )else:out.write(f" auto transferable = {fully_qualified_name_for_interface(interface)}::create();\n")out.write(""" TRY(transferable->transfer_receiving_steps(target_realm, decoder));diff --git a/Meta/Linters/check_libjs_includes.py b/Meta/Linters/check_libjs_includes.pyindex 0e3ce55474d..83ffde0ceae 100755--- a/Meta/Linters/check_libjs_includes.py+++ b/Meta/Linters/check_libjs_includes.py@@ -41,7 +41,6 @@ ALLOWED_HEADERS = {"LibJS/Runtime/Completion.h","LibJS/Runtime/ConsoleObject.h","LibJS/Runtime/DataView.h",- "LibJS/Runtime/DataViewConstructor.h","LibJS/Runtime/Date.h","LibJS/Runtime/DeclarativeEnvironment.h","LibJS/Runtime/Environment.h",diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex bad102459f7..415c4eb9aa7 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -66,12 +66,7 @@ ALLOWED_REALM_MENTIONS = {41,"service worker jobs, caches, and container promises still materialize results in selected realms",),- "Streams": (- 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",- ),+ "Streams": (5, 14, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),"WebAssembly": (15,