Skip to content

Truly independent web browser

LibWeb: Implement TextEncoderStream and TextDecoderStream in Rust

Shannon Booth365fbf050242
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index cccec1b3a3a..a08993bb203 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -647,6 +647,20 @@ unsafe fn borrowed_or_copied_bytes_of_buffer(buffer: &ArrayBuffer, bytes: Range<
Some(Cow::Borrowed(unsafe { ak::slice_from_raw_parts(data, bytes.len()) }))
}
+/// The value as a BufferSource, if it is an ArrayBuffer, a DataView or a typed array, without the checks of a
+/// conversion to the type.
+pub(crate) fn buffer_source_type_of(value: Value) -> Option<BufferSource> {
+ if !value.is_object() {
+ return None;
+ }
+ let object = value.as_object();
+ object
+ .downcast::<ArrayBuffer>()
+ .map(BufferSource::ArrayBuffer)
+ .or_else(|| object.downcast::<DataView>().map(BufferSource::DataView))
+ .or_else(|| object.downcast::<TypedArrayBase>().map(BufferSource::TypedArray))
+}
+
/// https://webidl.spec.whatwg.org/#arraybufferview-create, for a Uint8Array in the realm of the call context.
pub(crate) fn create_uint8_array(cx: &CallContext, bytes: &[u8]) -> WebIdlResult<Gc<Object>> {
let length = u32::try_from(bytes.len())
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index d5477186e33..b1d214f6c56 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -33,6 +33,7 @@ use crate::bindings::realm_data::wrapper_world_of;
use crate::bindings::services::{
web_bindings_ensure_web_constructor, web_bindings_ensure_web_prototype, web_bindings_realm_is_window,
web_bindings_rejected_promise, web_bindings_rust_wrapper_for, web_bindings_set_rust_wrapper,
+ web_bindings_with_temporary_execution_context,
};
/// What an implementation can tell the bindings about its objects, as a C++ implementation object does by overriding
@@ -317,6 +318,27 @@ pub(crate) fn realm_is_window(realm: Gc<Realm>) -> bool {
unsafe { web_bindings_realm_is_window(realm.as_ptr().cast()) }
}
+/// Runs the steps while an execution context of the realm is on the stack, for steps that can run script but that do not
+/// run on behalf of script, as an HTML::TemporaryExecutionContext does for C++.
+pub(crate) fn with_temporary_execution_context<F: FnOnce() -> R, R>(realm: Gc<Realm>, steps: F) -> R {
+ unsafe extern "C" fn run_steps<F: FnOnce() -> R, R>(context: *mut c_void) {
+ // SAFETY: The context is the steps and the slot for their result, which outlive the call.
+ let (steps, result) = unsafe { &mut *context.cast::<(Option<F>, Option<R>)>() };
+ *result = Some(steps.take().expect("LibWeb runs the steps once")());
+ }
+
+ let mut context = (Some(steps), None);
+ // SAFETY: The realm is live, and the context outlives the call, which runs the steps once.
+ unsafe {
+ web_bindings_with_temporary_execution_context(
+ realm.as_ptr().cast(),
+ (&raw mut context).cast(),
+ run_steps::<F, R>,
+ );
+ }
+ context.1.expect("LibWeb runs the steps")
+}
+
/// What an operation that returns a promise type returns in place of throwing: a promise rejected with what its
/// steps threw, https://webidl.spec.whatwg.org/#dfn-create-operation-function
pub(crate) fn rejected_promise(vm: &Vm, throw: Throw) -> Value {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
index febf24d3ad6..8ef31f3dea7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/services.rs
@@ -35,6 +35,14 @@ unsafe extern "C" {
/// Whether the global object of the realm is a Window.
pub(crate) fn web_bindings_realm_is_window(realm: *mut c_void) -> bool;
+ /// Runs the steps with the context while an execution context of the realm is on the stack, as an
+ /// HTML::TemporaryExecutionContext puts it there.
+ pub(crate) fn web_bindings_with_temporary_execution_context(
+ realm: *mut c_void,
+ context: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void),
+ );
+
/// Whether the object is a wrapper of an object that implements the interface, a Web::Bindings::InterfaceName of
/// an interface that LibWeb implements in C++.
pub(crate) fn web_bindings_object_implements_interface(object: *mut c_void, interface_name: u16) -> bool;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs
index 0c8bb9fd0bc..cdbad90e743 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/mod.rs
@@ -9,5 +9,9 @@
#[cfg(not(test))]
pub(crate) mod text_decoder;
#[cfg(not(test))]
+pub(crate) mod text_decoder_stream;
+#[cfg(not(test))]
pub(crate) mod text_encoder;
+#[cfg(not(test))]
+pub(crate) mod text_encoder_stream;
pub(crate) mod utf8;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs
new file mode 100644
index 00000000000..faa2d339570
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_decoder_stream.rs
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! TextDecoderStream, https://encoding.spec.whatwg.org/#interface-textdecoderstream
+
+use core::cell::RefCell;
+
+use ak::Utf16String;
+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::interface::Wrappable;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::encoding::text_decoder::TextDecoderOptions;
+use crate::streams::generic_transform_stream::{TransformSteps, TransformStream};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct TextDecoderStream {
+ // https://encoding.spec.whatwg.org/#textdecoder-encoding
+ #[gc(untraced)]
+ encoding: &'static Encoding,
+ // https://encoding.spec.whatwg.org/#textdecoder-error-mode
+ fatal: bool,
+ // https://encoding.spec.whatwg.org/#textdecoder-ignore-bom-flag
+ ignore_bom: bool,
+ // https://streams.spec.whatwg.org/#generictransformstream-transform
+ transform: TransformStream,
+}
+
+impl Wrappable for TextDecoderStream {}
+
+#[expect(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"
+)]
+impl TextDecoderStream {
+ // https://encoding.spec.whatwg.org/#dom-textdecoderstream
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ label: Utf16String,
+ options: TextDecoderOptions,
+ ) -> WebIdlResult<Self> {
+ // 1. Let encoding be the result of getting an encoding from label.
+ // 2. If encoding is failure or replacement, then throw a RangeError.
+ let encoding = encoding_for_label(label.as_units())
+ .filter(|&encoding| encoding != encoding_rs::REPLACEMENT)
+ .ok_or_else(|| Exception::RangeError(Utf16String::from_ascii(b"Invalid encoding")))?;
+
+ // 3. Let errorMode be "fatal" if options["fatal"] is true; otherwise "replacement".
+ // 4. Set up a text decoder stream with this, encoding, errorMode, and options["ignoreBOM"].
+ Ok(Self::set_up(cx, encoding, options.fatal, options.ignore_bom))
+ }
+
+ // https://encoding.spec.whatwg.org/#set-up-a-text-decoder-stream
+ fn set_up(cx: &CallContext, encoding: &'static Encoding, fatal: bool, ignore_bom: bool) -> Self {
+ // 1. Assert: encoding is not replacement.
+ assert!(
+ encoding != encoding_rs::REPLACEMENT,
+ "a text decoder stream has an encoding with a decoder"
+ );
+
+ // 2. Set stream's encoding to encoding.
+ // 3. Set stream's error mode to errorMode.
+ // 4. Set stream's ignore BOM to ignoreBOM.
+ // 5. Set stream's decoder to a new instance of encoding's decoder.
+ // 6. Set stream's I/O queue to a new I/O queue.
+ // NB: The decoder holds the I/O queue, and whether the BOM was seen.
+ let decoder = Decoder {
+ decoder: RefCell::new(StreamingDecoder::new(encoding, fatal, ignore_bom)),
+ };
+
+ // 7. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the decode and enqueue a
+ // chunk algorithm with stream and chunk.
+ // 8. Let flushAlgorithm be an algorithm which takes no arguments and runs the flush and enqueue algorithm with
+ // stream.
+ // 9. Let transformStream be a new TransformStream.
+ // 10. Set up transformStream with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to
+ // flushAlgorithm.
+ // 11. Set stream's transform to transformStream.
+ Self {
+ encoding,
+ fatal,
+ ignore_bom,
+ transform: TransformStream::create_and_set_up(cx, decoder),
+ }
+ }
+
+ // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding
+ pub(crate) fn encoding(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The encoding getter steps are to return this's encoding's name, ASCII lowercased.
+ let name = self.encoding.name().to_ascii_lowercase();
+ Ok(Utf16String::from_ascii(name.as_bytes()))
+ }
+
+ // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal
+ pub(crate) fn fatal(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ // The fatal getter steps are to return true if this's error mode is "fatal", otherwise false.
+ Ok(self.fatal)
+ }
+
+ // https://encoding.spec.whatwg.org/#dom-textdecoder-ignorebom
+ pub(crate) fn ignore_bom(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ // The ignoreBOM getter steps are to return this's ignore BOM.
+ Ok(self.ignore_bom)
+ }
+
+ // https://streams.spec.whatwg.org/#dom-generictransformstream-readable
+ pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // The readable getter steps are to return this's transform.[[readable]].
+ Ok(self.transform.readable(cx))
+ }
+
+ // https://streams.spec.whatwg.org/#dom-generictransformstream-writable
+ pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // The writable getter steps are to return this's transform.[[writable]].
+ Ok(self.transform.writable(cx))
+ }
+}
+
+/// The decoder of a TextDecoderStream, with its I/O queue, which the algorithms of the stream's transform run on.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct Decoder {
+ #[gc(untraced)]
+ decoder: RefCell<StreamingDecoder>,
+}
+
+static DECODER_CLASS: EmbedderClass<Decoder> = EmbedderClass::new("TextDecoderStreamDecoder");
+
+impl EmbedderValue for Decoder {
+ const CLASS: &'static EmbedderClass<Self> = &DECODER_CLASS;
+}
+
+/// 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]) {
+ 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)));
+ }
+}
+
+fn decoding_failed(_: DecodingFailed) -> Exception {
+ Exception::TypeError(Utf16String::from_ascii(b"Decoding failed"))
+}
+
+impl TransformSteps for Decoder {
+ // https://encoding.spec.whatwg.org/#decode-and-enqueue-a-chunk
+ fn transform(&self, cx: &CallContext, transform: &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(
+ b"Chunk is not a BufferSource",
+ )));
+ };
+
+ // 2. Push a copy of bufferSource to decoder's I/O queue.
+ // 3. Let output be the I/O queue of scalar values « end-of-queue ».
+ // 4. While true:
+ // 1. Let item be the result of reading from decoder's I/O queue.
+ // 2. If item is end-of-queue:
+ // 1. Let outputChunk be the result of running serialize I/O queue with decoder and output.
+ // 2. If outputChunk is not the empty string, then enqueue outputChunk in decoder's transform.
+ // 3. Return.
+ // 3. Let result be the result of processing an item with item, decoder's decoder, decoder's I/O queue,
+ // output, and decoder's error mode.
+ // 4. If result is error, then throw a TypeError.
+ // NB: The decoder decodes the bytes as more input to follow, and keeps what it cannot decode yet.
+ let mut decoder = self.decoder.borrow_mut();
+ // SAFETY: Decoding runs no script and allocates no cell, so nothing detaches, resizes or frees the buffer of
+ // the chunk while its bytes are read.
+ let output =
+ unsafe { buffer_source.with_bytes(|bytes| decoder.decode(bytes, true)) }.map_err(decoding_failed)?;
+ enqueue_output_chunk(cx, transform, &output);
+ Ok(())
+ }
+
+ // https://encoding.spec.whatwg.org/#flush-and-enqueue
+ fn flush(&self, cx: &CallContext, transform: &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.
+ // 2. Let result be the result of processing an item with item, decoder's decoder, decoder's I/O queue,
+ // output, and decoder's error mode.
+ // 3. If result is finished:
+ // 1. Let outputChunk be the result of running serialize I/O queue with decoder and output.
+ // 2. If outputChunk is not the empty string, then enqueue outputChunk in decoder's transform.
+ // 3. Return.
+ // 4. Otherwise, if result is error, throw a TypeError.
+ // NB: The decoder's I/O queue holds no more bytes, so the decoder decodes the end of the input.
+ let output = self.decoder.borrow_mut().decode(&[], false).map_err(decoding_failed)?;
+ enqueue_output_chunk(cx, transform, &output);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs
new file mode 100644
index 00000000000..08309d0eaf6
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/encoding/text_encoder_stream.rs
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2025, Luke Wilde <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! TextEncoderStream, https://encoding.spec.whatwg.org/#interface-textencoderstream
+
+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::interface::{Wrappable, with_temporary_execution_context};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::streams::generic_transform_stream::{TransformSteps, TransformStream};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct TextEncoderStream {
+ // https://streams.spec.whatwg.org/#generictransformstream-transform
+ transform: TransformStream,
+}
+
+impl Wrappable for TextEncoderStream {}
+
+#[expect(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every method of an implementation for its WebIDL result, whether or not it can fail"
+)]
+impl TextEncoderStream {
+ // https://encoding.spec.whatwg.org/#dom-textencoderstream
+ pub(crate) fn construct(cx: &mut CallContext) -> WebIdlResult<Self> {
+ // 1. Set this's encoder to an instance of the UTF-8 encoder.
+ let encoder = Encoder {
+ leading_surrogate: Cell::new(None),
+ };
+
+ // 2. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the encode and enqueue a
+ // chunk algorithm with this and chunk.
+ // 3. Let flushAlgorithm be an algorithm which runs the encode and flush algorithm with this.
+ // 4. Let transformStream be a new TransformStream.
+ // 5. Set up transformStream with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to
+ // flushAlgorithm.
+ // 6. Set this's transform to transformStream.
+ Ok(Self {
+ transform: TransformStream::create_and_set_up(cx, encoder),
+ })
+ }
+
+ // https://encoding.spec.whatwg.org/#dom-textencoder-encoding
+ pub(crate) fn encoding(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The encoding getter steps are to return "utf-8".
+ Ok(Utf16String::from_ascii(b"utf-8"))
+ }
+
+ // https://streams.spec.whatwg.org/#dom-generictransformstream-readable
+ pub(crate) fn readable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // The readable getter steps are to return this's transform.[[readable]].
+ Ok(self.transform.readable(cx))
+ }
+
+ // https://streams.spec.whatwg.org/#dom-generictransformstream-writable
+ pub(crate) fn writable(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // The writable getter steps are to return this's transform.[[writable]].
+ Ok(self.transform.writable(cx))
+ }
+}
+
+/// The UTF-8 encoder of a TextEncoderStream, with its leading surrogate, which the algorithms of the stream's
+/// transform run on.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct Encoder {
+ // https://encoding.spec.whatwg.org/#textencoderstream-pending-high-surrogate
+ leading_surrogate: Cell<Option<u16>>,
+}
+
+static ENCODER_CLASS: EmbedderClass<Encoder> = EmbedderClass::new("TextEncoderStreamEncoder");
+
+impl EmbedderValue for Encoder {
+ const CLASS: &'static EmbedderClass<Self> = &ENCODER_CLASS;
+}
+
+/// The bytes of U+FFFD (�) in UTF-8.
+const REPLACEMENT_CHARACTER_UTF8_BYTES: [u8; 3] = [0xEF, 0xBF, 0xBD];
+
+impl Encoder {
+ // https://encoding.spec.whatwg.org/#convert-code-unit-to-scalar-value
+ fn convert_code_unit_to_scalar_value(&self, item: u16, input_position: &mut usize) -> Option<char> {
+ // 1. If encoder's leading surrogate is non-null:
+ if let Some(leading_surrogate) = self.leading_surrogate.get() {
+ // 1. Let leadingSurrogate be encoder's leading surrogate.
+ // 2. Set encoder's leading surrogate to null.
+ self.leading_surrogate.set(None);
+
+ // 3. If item is a trailing surrogate, then return a scalar value from surrogates given leadingSurrogate
+ // and item.
+ if is_trailing_surrogate(item) {
+ return Some(scalar_value_from_surrogates(leading_surrogate, item));
+ }
+
+ // 4. Restore item to input.
+ *input_position -= 1;
+
+ // 5. Return U+FFFD (�).
+ return Some(char::REPLACEMENT_CHARACTER);
+ }
+
+ // 2. If item is a leading surrogate, then set encoder's leading surrogate to item and return continue.
+ if is_leading_surrogate(item) {
+ self.leading_surrogate.set(Some(item));
+ return None;
+ }
+
+ // 3. If item is a trailing surrogate, then return U+FFFD (�).
+ if is_trailing_surrogate(item) {
+ return Some(char::REPLACEMENT_CHARACTER);
+ }
+
+ // 4. Return item.
+ Some(char::from_u32(u32::from(item)).expect("a code unit that is not a surrogate is a scalar value"))
+ }
+}
+
+fn is_leading_surrogate(code_unit: u16) -> bool {
+ (0xD800..=0xDBFF).contains(&code_unit)
+}
+
+fn is_trailing_surrogate(code_unit: u16) -> bool {
+ (0xDC00..=0xDFFF).contains(&code_unit)
+}
+
+// https://encoding.spec.whatwg.org/#scalar-value-from-surrogates
+fn scalar_value_from_surrogates(leading: u16, trailing: u16) -> char {
+ // To obtain a scalar value from surrogates, given a leading surrogate leading and a trailing surrogate trailing,
+ // return 0x10000 + ((leading − 0xD800) << 10) + (trailing − 0xDC00).
+ let scalar_value = 0x10000 + ((u32::from(leading) - 0xD800) << 10) + (u32::from(trailing) - 0xDC00);
+ char::from_u32(scalar_value).expect("surrogates make a scalar value")
+}
+
+impl TransformSteps for Encoder {
+ // https://encoding.spec.whatwg.org/#encode-and-enqueue-a-chunk
+ fn transform(&self, cx: &CallContext, transform: &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))?;
+
+ // 2. Convert input to an I/O queue of code units.
+ let input = input.to_utf16();
+ let mut input_position = 0;
+
+ // 3. Let output be the I/O queue of bytes « end-of-queue ».
+ let mut output = Vec::new();
+
+ // 4. While true:
+ loop {
+ // 1. Let item be the result of reading from input.
+ let Some(&item) = input.get(input_position) else {
+ // 2. If item is end-of-queue:
+ // 1. Convert output into a byte sequence.
+ // 2. If output is not empty:
+ if !output.is_empty() {
+ // 1. Let chunk be the result of creating a Uint8Array object given output and encoder's relevant
+ // realm.
+ let chunk = create_uint8_array(cx, &output)?;
+
+ // 2. Enqueue chunk into encoder's transform.
+ transform.enqueue(Value::from_object(chunk));
+ }
+
+ // 3. Return.
+ return Ok(());
+ };
+ input_position += 1;
+
+ // 3. Let result be the result of executing the convert code unit to scalar value algorithm with encoder,
+ // item and input.
+ // 4. If result is not continue, then process an item with result, encoder's encoder, input, output, and
+ // "fatal".
+ if let Some(result) = self.convert_code_unit_to_scalar_value(item, &mut input_position) {
+ let mut bytes = [0; 4];
+ output.extend_from_slice(result.encode_utf8(&mut bytes).as_bytes());
+ }
+ }
+ }
+
+ // https://encoding.spec.whatwg.org/#encode-and-flush
+ fn flush(&self, cx: &CallContext, transform: &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
+ // relevant realm.
+ // NB: This is U+FFFD (�) in UTF-8 bytes.
+ let chunk = create_uint8_array(cx, &REPLACEMENT_CHARACTER_UTF8_BYTES)?;
+
+ // 2. Enqueue chunk into encoder's transform.
+ transform.enqueue(Value::from_object(chunk));
+ }
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 6918b4661bc..e9f9c2aa940 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowProxy.h>
@@ -87,6 +88,7 @@ JSObject* web_bindings_rust_wrapper_for(void* realm, void* cell);
void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper);
JSObject* web_bindings_rejected_promise(void* current_realm, JSValue this_value, JSValue reason);
bool web_bindings_realm_is_window(void* realm);
+void web_bindings_with_temporary_execution_context(void* realm, void* context, void (*steps)(void*));
bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);
JSObject* web_bindings_create_dom_exception(void* realm, ReadonlyBytes name, FlatPtr message);
bool web_bindings_extract_an_origin(JSObject* object, void* ctx, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));
@@ -131,6 +133,12 @@ bool web_bindings_realm_is_window(void* realm)
return HTML::window_from_global_object(static_cast<JS::Realm*>(realm)->global_object());
}
+void web_bindings_with_temporary_execution_context(void* realm, void* context, void (*steps)(void*))
+{
+ HTML::TemporaryExecutionContext execution_context { *static_cast<JS::Realm*>(realm) };
+ steps(context);
+}
+
bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name)
{
auto* wrappable = wrappable_impl_from(JS::HostABI::object_from_abi(object));
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 8f0cb725155..6a8b7c07218 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -357,10 +357,6 @@ set(SOURCES
Editing/StyledMarkupSerializer.cpp
Editing/VisiblePosition.cpp
Editing/ReplaceSelection.cpp
- Encoding/TextDecoderCommon.cpp
- Encoding/TextDecoderStream.cpp
- Encoding/TextEncoderCommon.cpp
- Encoding/TextEncoderStream.cpp
EncryptedMediaExtensions/Algorithms.cpp
EncryptedMediaExtensions/MediaKeySystemAccess.cpp
EntriesAPI/FileSystemEntry.cpp
diff --git a/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp b/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp
deleted file mode 100644
index fc65bc18eb3..00000000000
--- a/Libraries/LibWeb/Encoding/TextDecoderCommon.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Encoding/TextDecoderCommon.h>
-#include <LibWeb/WebIDL/ExceptionOrUtils.h>
-
-namespace Web::Encoding {
-
-void TextDecoderOutputQueue::push(Utf16String output)
-{
- if (output.is_empty())
- return;
-
- if (m_has_builder) {
- m_builder.append(output);
- return;
- }
-
- if (!m_single_output.has_value()) {
- m_single_output = move(output);
- return;
- }
-
- m_has_builder = true;
- m_builder.append(m_single_output.release_value());
- m_builder.append(output);
-}
-
-Utf16String TextDecoderOutputQueue::serialize()
-{
- if (m_has_builder)
- return m_builder.to_string();
- if (m_single_output.has_value())
- return m_single_output.release_value();
- return {};
-}
-
-TextDecoderCommonMixin::TextDecoderCommonMixin(FlyString encoding, TextCodec::ErrorMode error_mode, bool ignore_bom)
- : m_encoding(move(encoding))
- , m_encoding_for_bindings(Utf16FlyString::from_fly_string(m_encoding))
- , m_error_mode(error_mode)
- , m_ignore_bom(ignore_bom)
-{
-}
-
-void TextDecoderCommonMixin::set_decoder_to_new_instance_of_encoding_decoder() const
-{
- m_decoder = make<TextCodec::StreamingDecoder>(m_encoding, m_ignore_bom ? TextCodec::IgnoreBOM::Yes : TextCodec::IgnoreBOM::No, m_error_mode);
-}
-
-static WebIDL::ExceptionOr<void> append_decoded_output(TextDecoderOutputQueue& output, ErrorOr<Utf16String> decoded_or_error)
-{
- if (decoded_or_error.is_error())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Decoding failed"_utf16 };
-
- output.push(decoded_or_error.release_value());
- return {};
-}
-
-WebIDL::ExceptionOr<void> TextDecoderCommonMixin::process_an_item(ReadonlyBytes item, TextDecoderOutputQueue& output)
-{
- VERIFY(m_decoder);
- return append_decoded_output(output, m_decoder->decode(item));
-}
-
-WebIDL::ExceptionOr<void> TextDecoderCommonMixin::process_an_item(EndOfQueue, TextDecoderOutputQueue& output)
-{
- VERIFY(m_decoder);
- return append_decoded_output(output, m_decoder->decode({}, TextCodec::Flush::Yes));
-}
-
-Utf16String TextDecoderCommonMixin::serialize_io_queue(TextDecoderOutputQueue& output)
-{
- return output.serialize();
-}
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextDecoderCommon.h b/Libraries/LibWeb/Encoding/TextDecoderCommon.h
deleted file mode 100644
index c2f568e50c8..00000000000
--- a/Libraries/LibWeb/Encoding/TextDecoderCommon.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/FlyString.h>
-#include <AK/OwnPtr.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16StringBuilder.h>
-#include <LibJS/Forward.h>
-#include <LibTextCodec/Decoder.h>
-#include <LibWeb/Bindings/TextDecoder.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::Encoding {
-
-using TextDecoderOptions = Bindings::TextDecoderOptions;
-
-struct EndOfQueue {
-};
-
-class TextDecoderOutputQueue {
-public:
- void push(Utf16String);
- Utf16String serialize();
-
-private:
- Optional<Utf16String> m_single_output;
- Utf16StringBuilder m_builder;
- bool m_has_builder { false };
-};
-
-// https://encoding.spec.whatwg.org/#textdecodercommon
-class TextDecoderCommonMixin {
-public:
- // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding
- Utf16FlyString const& encoding() const { return m_encoding_for_bindings; }
-
- // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal
- bool fatal() const { return m_error_mode == TextCodec::ErrorMode::Fatal; }
-
- // https://encoding.spec.whatwg.org/#dom-textdecoder-ignorebom
- bool ignore_bom() const { return m_ignore_bom; }
-
-protected:
- TextDecoderCommonMixin(FlyString encoding, TextCodec::ErrorMode error_mode, bool ignore_bom);
-
- void set_decoder_to_new_instance_of_encoding_decoder() const;
- WebIDL::ExceptionOr<void> process_an_item(ReadonlyBytes item, TextDecoderOutputQueue& output);
- WebIDL::ExceptionOr<void> process_an_item(EndOfQueue, TextDecoderOutputQueue& output);
- Utf16String serialize_io_queue(TextDecoderOutputQueue& output);
-
- // https://encoding.spec.whatwg.org/#textdecodercommon-decoder
- mutable OwnPtr<TextCodec::StreamingDecoder> m_decoder;
-
- // https://encoding.spec.whatwg.org/#textdecoder-encoding
- FlyString m_encoding;
- Utf16FlyString m_encoding_for_bindings;
-
- // https://encoding.spec.whatwg.org/#textdecoder-error-mode
- TextCodec::ErrorMode m_error_mode { TextCodec::ErrorMode::Replacement };
-
- // https://encoding.spec.whatwg.org/#textdecoder-ignore-bom-flag
- bool m_ignore_bom { false };
-};
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextDecoderStream.cpp b/Libraries/LibWeb/Encoding/TextDecoderStream.cpp
deleted file mode 100644
index 5fa1e1e8df4..00000000000
--- a/Libraries/LibWeb/Encoding/TextDecoderStream.cpp
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/DataView.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibTextCodec/Decoder.h>
-#include <LibWeb/Encoding/TextDecoderStream.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/Streams/ReadableStream.h>
-#include <LibWeb/Streams/TransformStream.h>
-#include <LibWeb/Streams/TransformStreamOperations.h>
-#include <LibWeb/Streams/WritableStream.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/Promise.h>
-
-namespace Web::Encoding {
-
-GC_DEFINE_ALLOCATOR(TextDecoderStream);
-
-WebIDL::ExceptionOr<GC::Ref<TextDecoderStream>> TextDecoderStream::create_for_constructor(JS::Object& relevant_global_object, Utf16String const& label, TextDecoderOptions const& options)
-{
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto label_fly_string = Utf16FlyString::from_utf16(label.utf16_view());
-
- // 1. Let encoding be the result of getting an encoding from label.
- auto encoding = TextCodec::get_standardized_encoding(label_fly_string.view());
-
- // 2. If encoding is failure or replacement, then throw a RangeError.
- if (!encoding.has_value() || encoding->equals_ignoring_ascii_case("replacement"sv))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, Utf16String::formatted("Invalid encoding {}", label_fly_string.to_utf16_string()) };
-
- // 3. Set this’s encoding to encoding.
- auto lowercase_encoding_name = encoding.value().to_ascii_lowercase_string();
-
- // 4. If options["fatal"] is true, then set this’s error mode to "fatal".
- auto error_mode = options.fatal ? TextCodec::ErrorMode::Fatal : TextCodec::ErrorMode::Replacement;
-
- // 5. Set this’s ignore BOM to options["ignoreBOM"].
- auto ignore_bom = options.ignore_bom;
-
- // NB: Steps 7-11 — we create the TransformStream and the TextDecoderStream first so that we can refer to the
- // stream from the transform/flush algorithms.
-
- // 9. Let transformStream be a new TransformStream.
- auto transform_stream = GC::Heap::the().allocate<Streams::TransformStream>();
-
- auto stream = GC::Heap::the().allocate<TextDecoderStream>(transform_stream, lowercase_encoding_name, error_mode, ignore_bom);
-
- // 7. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the decode and enqueue a chunk
- // algorithm with this and chunk.
- auto transform_algorithm = GC::create_function(GC::Heap::the(), [stream, realm = GC::Ref(realm)](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {
- if (auto result = stream->decode_and_enqueue_chunk(realm->vm(), chunk); result.is_error())
- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
-
- // 8. Let flushAlgorithm be an algorithm which takes no arguments and runs the flush and enqueue algorithm with this.
- auto flush_algorithm = GC::create_function(GC::Heap::the(), [stream, realm = GC::Ref(realm)]() -> GC::Ref<WebIDL::Promise> {
- if (auto result = stream->flush_and_enqueue(realm->vm()); result.is_error())
- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
-
- // 10. Set up transformStream with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.
- transform_stream->set_up(realm, transform_algorithm, flush_algorithm);
-
- // 11. Set this’s transform to transformStream.
- // NB: Done via the GenericTransformStreamMixin constructor above.
-
- return stream;
-}
-
-TextDecoderStream::TextDecoderStream(GC::Ref<Streams::TransformStream> transform, FlyString encoding, TextCodec::ErrorMode error_mode, bool ignore_bom)
- : Streams::GenericTransformStreamMixin(transform)
- , TextDecoderCommonMixin(move(encoding), error_mode, ignore_bom)
-{
- set_decoder_to_new_instance_of_encoding_decoder();
-}
-
-TextDecoderStream::~TextDecoderStream() = default;
-
-void TextDecoderStream::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- Streams::GenericTransformStreamMixin::visit_edges(visitor);
-}
-
-// https://encoding.spec.whatwg.org/#decode-and-enqueue-a-chunk
-WebIDL::ExceptionOr<void> TextDecoderStream::decode_and_enqueue_chunk(JS::VM& vm, JS::Value chunk)
-{
- // 1. Let bufferSource be the result of converting chunk to an AllowSharedBufferSource.
- if (!WebIDL::is_buffer_source_type(chunk))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Chunk is not a BufferSource"_utf16 };
-
- // 2. Push a copy of bufferSource to decoder's I/O queue.
- // WARNING: See the warning for SharedArrayBuffer objects above.
- auto buffer_or_error = WebIDL::get_buffer_source_copy(chunk.as_object());
- if (buffer_or_error.is_error())
- return WebIDL::OperationError::create("Failed to copy bytes from BufferSource"_utf16);
- auto input_copy = buffer_or_error.release_value();
-
- // Decode this chunk while preserving the streaming decoder's pending state.
- TextDecoderOutputQueue output;
- TRY(process_an_item(input_copy.bytes(), output));
- auto decoded = serialize_io_queue(output);
- return enqueue_decoded_output(vm, decoded);
-}
-
-// https://encoding.spec.whatwg.org/#flush-and-enqueue
-WebIDL::ExceptionOr<void> TextDecoderStream::flush_and_enqueue(JS::VM& vm)
-{
- // 1. Let output be the I/O queue of scalar values « end-of-queue ».
- TextDecoderOutputQueue output;
-
- // 2. While true:
- // NB: TextCodec::StreamingDecoder keeps any cross-chunk decoder state internally. Since flushing reads only
- // end-of-queue from the decoder's I/O queue, we write out that single read instead of materializing a queue and
- // looping over it.
- // 1. Let item be the result of reading from this’s I/O queue.
- auto item = EndOfQueue {};
-
- // 2. Let result be the result of processing an item with item, this’s decoder, decoder’s I/O queue, output, and decoder’s
- // error mode.
- auto result = process_an_item(item, output);
-
- // 3. If result is finished:
- // 1. Let outputChunk be the result of running serialize I/O queue with decoder and output.
- // 2. If outputChunk is not the empty string, then enqueue outputChunk in decoder’s transform.
- // 3. Return.
- if (!result.is_error()) {
- auto output_chunk = serialize_io_queue(output);
- TRY(enqueue_decoded_output(vm, output_chunk));
- return {};
- }
-
- return result.release_error();
-}
-
-WebIDL::ExceptionOr<void> TextDecoderStream::enqueue_decoded_output(JS::VM& vm, Utf16String const& decoded)
-{
- if (decoded.is_empty())
- return {};
-
- auto js_string = JS::PrimitiveString::create(vm, decoded);
- return Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), js_string);
-}
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextDecoderStream.h b/Libraries/LibWeb/Encoding/TextDecoderStream.h
deleted file mode 100644
index 88dd19f4ba2..00000000000
--- a/Libraries/LibWeb/Encoding/TextDecoderStream.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Encoding/TextDecoderCommon.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/Streams/GenericTransformStream.h>
-
-namespace Web::Encoding {
-
-// https://encoding.spec.whatwg.org/#textdecoderstream
-class TextDecoderStream final
- : public Bindings::GCAllocatedWrappable
- , public Streams::GenericTransformStreamMixin
- , public TextDecoderCommonMixin {
- WEB_WRAPPABLE(TextDecoderStream, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(TextDecoderStream);
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<TextDecoderStream>> create_for_constructor(JS::Object&, Utf16String const& label, TextDecoderOptions const&);
- virtual ~TextDecoderStream() override;
-
-private:
- TextDecoderStream(GC::Ref<Streams::TransformStream>, FlyString encoding, TextCodec::ErrorMode, bool ignore_bom);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- WebIDL::ExceptionOr<void> decode_and_enqueue_chunk(JS::VM&, JS::Value);
- WebIDL::ExceptionOr<void> flush_and_enqueue(JS::VM&);
-
- WebIDL::ExceptionOr<void> enqueue_decoded_output(JS::VM&, Utf16String const&);
-
- // https://encoding.spec.whatwg.org/#textdecodercommon-i-o-queue
- // NB: We accumulate input bytes that have been pushed to the I/O queue but not yet decoded, so that a multi-byte
- // sequence which is split across chunks can be reassembled.
-};
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextDecoderStream.idl b/Libraries/LibWeb/Encoding/TextDecoderStream.idl
index 705b9d8837a..609446a4128 100644
--- a/Libraries/LibWeb/Encoding/TextDecoderStream.idl
+++ b/Libraries/LibWeb/Encoding/TextDecoderStream.idl
@@ -1,5 +1,5 @@
// https://encoding.spec.whatwg.org/#textdecoderstream
-[Exposed=*]
+[Exposed=*, ImplementedIn=Rust]
interface TextDecoderStream {
constructor(optional DOMString label = "utf-8", optional TextDecoderOptions options = {});
};
diff --git a/Libraries/LibWeb/Encoding/TextEncoderCommon.cpp b/Libraries/LibWeb/Encoding/TextEncoderCommon.cpp
deleted file mode 100644
index 0a24a881e77..00000000000
--- a/Libraries/LibWeb/Encoding/TextEncoderCommon.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Encoding/TextEncoderCommon.h>
-
-namespace Web::Encoding {
-
-TextEncoderCommonMixin::TextEncoderCommonMixin() = default;
-TextEncoderCommonMixin::~TextEncoderCommonMixin() = default;
-
-// https://encoding.spec.whatwg.org/#dom-textencoder-encoding
-Utf16FlyString const& TextEncoderCommonMixin::encoding() const
-{
- // The encoding getter steps are to return "utf-8".
- static Utf16FlyString const encoding = "utf-8"_utf16_fly_string;
- return encoding;
-}
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextEncoderCommon.h b/Libraries/LibWeb/Encoding/TextEncoderCommon.h
deleted file mode 100644
index 0bd605cd31f..00000000000
--- a/Libraries/LibWeb/Encoding/TextEncoderCommon.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-
-namespace Web::Encoding {
-
-class TextEncoderCommonMixin {
-public:
- virtual ~TextEncoderCommonMixin();
-
- // https://encoding.spec.whatwg.org/#dom-textencoder-encoding
- Utf16FlyString const& encoding() const;
-
-protected:
- TextEncoderCommonMixin();
-};
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextEncoderStream.cpp b/Libraries/LibWeb/Encoding/TextEncoderStream.cpp
deleted file mode 100644
index a3f025e48a1..00000000000
--- a/Libraries/LibWeb/Encoding/TextEncoderStream.cpp
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/UnicodeUtils.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/Encoding/TextEncoderStream.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/Streams/ReadableStream.h>
-#include <LibWeb/Streams/TransformStream.h>
-#include <LibWeb/Streams/TransformStreamOperations.h>
-#include <LibWeb/Streams/WritableStream.h>
-#include <LibWeb/WebIDL/Promise.h>
-
-namespace Web::Encoding {
-
-GC_DEFINE_ALLOCATOR(TextEncoderStream);
-
-// https://encoding.spec.whatwg.org/#dom-textencoderstream
-WebIDL::ExceptionOr<GC::Ref<TextEncoderStream>> TextEncoderStream::create_for_constructor(JS::Object& relevant_global_object)
-{
- auto& realm = HTML::relevant_realm(relevant_global_object);
-
- // 1. Set this’s encoder to an instance of the UTF-8 encoder.
- // NOTE: No-op, as AK::String is already in UTF-8 format.
-
- // NOTE: We do these steps first so that we may store it as nonnull in the GenericTransformStream.
- // 4. Let transformStream be a new TransformStream.
- auto transform_stream = GC::Heap::the().allocate<Streams::TransformStream>();
-
- // 6. Set this's transform to a new TransformStream.
- auto stream = GC::Heap::the().allocate<TextEncoderStream>(transform_stream);
-
- // 2. Let transformAlgorithm be an algorithm which takes a chunk argument and runs the encode and enqueue a chunk
- // algorithm with this and chunk.
- auto transform_algorithm = GC::create_function(GC::Heap::the(), [stream, relevant_global_object = GC::Ref(relevant_global_object), realm = GC::Ref(realm)](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {
- if (auto result = stream->encode_and_enqueue_chunk(*relevant_global_object, chunk); result.is_error())
- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());
-
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
-
- // 3. Let flushAlgorithm be an algorithm which runs the encode and flush algorithm with this.
- auto flush_algorithm = GC::create_function(GC::Heap::the(), [stream, relevant_global_object = GC::Ref(relevant_global_object), realm = GC::Ref(realm)]() -> GC::Ref<WebIDL::Promise> {
- if (auto result = stream->encode_and_flush(*relevant_global_object); result.is_error())
- return WebIDL::create_rejected_promise_from_exception(realm, result.release_error());
-
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
-
- // 5. Set up transformStream with transformAlgorithm set to transformAlgorithm and flushAlgorithm set to flushAlgorithm.
- transform_stream->set_up(realm, transform_algorithm, flush_algorithm);
-
- auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
- (void)Bindings::wrap(wrapper_world, realm, stream->readable());
- (void)Bindings::wrap(wrapper_world, realm, stream->writable());
-
- return stream;
-}
-
-TextEncoderStream::TextEncoderStream(GC::Ref<Streams::TransformStream> transform)
- : Streams::GenericTransformStreamMixin(transform)
-{
-}
-
-TextEncoderStream::~TextEncoderStream() = default;
-
-void TextEncoderStream::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- Streams::GenericTransformStreamMixin::visit_edges(visitor);
-}
-
-// https://encoding.spec.whatwg.org/#encode-and-enqueue-a-chunk
-WebIDL::ExceptionOr<void> TextEncoderStream::encode_and_enqueue_chunk(JS::Object& relevant_global_object, JS::Value chunk)
-{
- // Spec Note: This is equivalent to the "convert a string into a scalar value string" algorithm from the Infra
- // Standard, but allows for surrogate pairs that are split between strings. [INFRA]
-
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto& vm = realm.vm();
-
- // 1. Let input be the result of converting chunk to a DOMString.
- Utf16String input;
- {
- HTML::TemporaryExecutionContext execution_context { realm };
- input = TRY(chunk.to_utf16_string(vm));
- }
-
- // 2. Convert input to an I/O queue of code units.
- // Spec Note: DOMString, as well as an I/O queue of code units rather than scalar values, are used here so that a
- // surrogate pair that is split between chunks can be reassembled into the appropriate scalar value.
- // The behavior is otherwise identical to USVString. In particular, lone surrogates will be replaced
- // with U+FFFD.
- size_t code_unit_index = 0;
-
- // 3. Let output be the I/O queue of bytes « end-of-queue ».
- ByteBuffer output;
-
- // 4. While true:
- while (true) {
- // 2. If item is end-of-queue, then:
- // NOTE: This is done out-of-order so that we're not dereferencing a code point iterator that points to the end.
- if (code_unit_index >= input.length_in_code_units()) {
- // 1. Convert output into a byte sequence.
- // Note: No-op.
-
- // 2. If output is non-empty, then:
- if (!output.is_empty()) {
- // 1. Let chunk be a Uint8Array object wrapping an ArrayBuffer containing output.
- auto array_buffer = JS::ArrayBuffer::create(realm, move(output));
- auto array = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);
-
- // 2. Enqueue chunk into encoder’s transform.
- TRY(Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), array));
- }
-
- // 3. Return.
- return {};
- }
-
- // 1. Let item be the result of reading from input.
- auto item = input.code_unit_at(code_unit_index);
-
- // 3. Let result be the result of executing the convert code unit to scalar value algorithm with encoder, item and input.
- auto result = convert_code_unit_to_scalar_value(item, code_unit_index);
-
- // 4. If result is not continue, then process an item with result, encoder’s encoder, input, output, and "fatal".
- if (result.has_value()) {
- (void)AK::UnicodeUtils::code_point_to_utf8(result.value(), [&output](char utf8_byte) {
- output.append(static_cast<u8>(utf8_byte));
- });
- }
- }
-}
-
-// https://encoding.spec.whatwg.org/#encode-and-flush
-WebIDL::ExceptionOr<void> TextEncoderStream::encode_and_flush(JS::Object& relevant_global_object)
-{
- auto& realm = HTML::relevant_realm(relevant_global_object);
-
- // 1. If encoder’s leading surrogate is non-null, then:
- if (m_leading_surrogate.has_value()) {
- // 1. Let chunk be a Uint8Array object wrapping an ArrayBuffer containing 0xEF 0xBF 0xBD.
- // Spec Note: This is U+FFFD (�) in UTF-8 bytes.
- constexpr static u8 replacement_character_utf8_bytes[3] = { 0xEF, 0xBF, 0xBD };
- auto bytes = MUST(ByteBuffer::copy(replacement_character_utf8_bytes, sizeof(replacement_character_utf8_bytes)));
- auto array_buffer = JS::ArrayBuffer::create(realm, bytes);
- auto chunk = JS::Uint8Array::create(realm, array_buffer->byte_length(), *array_buffer);
-
- // 2. Enqueue chunk into encoder’s transform.
- TRY(Streams::transform_stream_default_controller_enqueue(*m_transform->controller(), chunk));
- }
-
- return {};
-}
-
-// https://encoding.spec.whatwg.org/#convert-code-unit-to-scalar-value
-Optional<u32> TextEncoderStream::convert_code_unit_to_scalar_value(u32 item, size_t& code_unit_index)
-{
- ArmedScopeGuard move_to_next_code_point_guard = [&] {
- ++code_unit_index;
- };
-
- // 1. If encoder’s leading surrogate is non-null, then:
- if (m_leading_surrogate.has_value()) {
- // 1. Let leadingSurrogate be encoder’s leading surrogate.
- auto leading_surrogate = m_leading_surrogate.value();
-
- // 2. Set encoder’s leading surrogate to null.
- m_leading_surrogate.clear();
-
- // 3. If item is a trailing surrogate, then return a scalar value from surrogates given leadingSurrogate
- // and item.
- if (AK::UnicodeUtils::is_utf16_low_surrogate(item)) {
- // https://encoding.spec.whatwg.org/#scalar-value-from-surrogates
- // To obtain a scalar value from surrogates, given a leading surrogate leading and a trailing surrogate
- // trailing, return 0x10000 + ((leading − 0xD800) << 10) + (trailing − 0xDC00).
- return AK::UnicodeUtils::decode_utf16_surrogate_pair(leading_surrogate, item);
- }
-
- // 4. Restore item to input.
- move_to_next_code_point_guard.disarm();
-
- // 5. Return U+FFFD.
- return 0xFFFD;
- }
-
- // 2. If item is a leading surrogate, then set encoder’s leading surrogate to item and return continue.
- if (AK::UnicodeUtils::is_utf16_high_surrogate(item)) {
- m_leading_surrogate = item;
- return OptionalNone {};
- }
-
- // 3. If item is a trailing surrogate, then return U+FFFD.
- if (AK::UnicodeUtils::is_utf16_low_surrogate(item))
- return 0xFFFD;
-
- // 4. Return item.
- return item;
-}
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextEncoderStream.h b/Libraries/LibWeb/Encoding/TextEncoderStream.h
deleted file mode 100644
index ffb33f748d7..00000000000
--- a/Libraries/LibWeb/Encoding/TextEncoderStream.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Encoding/TextEncoderCommon.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/Streams/GenericTransformStream.h>
-
-namespace Web::Encoding {
-
-class TextEncoderStream final
- : public Bindings::GCAllocatedWrappable
- , public Streams::GenericTransformStreamMixin
- , public TextEncoderCommonMixin {
- WEB_WRAPPABLE(TextEncoderStream, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(TextEncoderStream);
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<TextEncoderStream>> create_for_constructor(JS::Object&);
- virtual ~TextEncoderStream() override;
-
-private:
- TextEncoderStream(GC::Ref<Streams::TransformStream>);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- WebIDL::ExceptionOr<void> encode_and_enqueue_chunk(JS::Object&, JS::Value);
- WebIDL::ExceptionOr<void> encode_and_flush(JS::Object&);
-
- Optional<u32> convert_code_unit_to_scalar_value(u32 item, size_t& code_unit_index);
-
- // https://encoding.spec.whatwg.org/#textencoderstream-pending-high-surrogate
- Optional<u32> m_leading_surrogate;
-};
-
-}
diff --git a/Libraries/LibWeb/Encoding/TextEncoderStream.idl b/Libraries/LibWeb/Encoding/TextEncoderStream.idl
index 153e9b138e3..514e7ab532d 100644
--- a/Libraries/LibWeb/Encoding/TextEncoderStream.idl
+++ b/Libraries/LibWeb/Encoding/TextEncoderStream.idl
@@ -1,5 +1,5 @@
// https://encoding.spec.whatwg.org/#textencoderstream
-[Exposed=*]
+[Exposed=*, ImplementedIn=Rust]
interface TextEncoderStream {
constructor();
};
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index fb68338386b..bdd927a8f1f 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -551,12 +551,6 @@ enum class HistoryAction : u8;
}
-namespace Web::Encoding {
-
-class TextEncoderStream;
-
-}
-
namespace Web::EncryptedMediaExtensions {
class MediaKeySystemAccess;
diff --git a/Libraries/LibWeb/Streams/GenericTransformStream.cpp b/Libraries/LibWeb/Streams/GenericTransformStream.cpp
index 6f10bfa4668..b686b7cbcef 100644
--- a/Libraries/LibWeb/Streams/GenericTransformStream.cpp
+++ b/Libraries/LibWeb/Streams/GenericTransformStream.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -9,7 +9,6 @@
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/Streams/GenericTransformStream.h>
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/Streams/TransformStream.h>
#include <LibWeb/Streams/WritableStream.h>
@@ -32,32 +31,6 @@ void web_transform_stream_enqueue(TransformStream*, JSValue chunk);
void* web_transform_stream_side(TransformStream*, JS::Realm*, TransformStreamSide);
}
-GenericTransformStreamMixin::GenericTransformStreamMixin(GC::Ref<TransformStream> transform)
- : m_transform(transform)
-{
-}
-
-GenericTransformStreamMixin::~GenericTransformStreamMixin() = default;
-
-void GenericTransformStreamMixin::visit_edges(GC::Cell::Visitor& visitor)
-{
- visitor.visit(m_transform);
-}
-
-// https://streams.spec.whatwg.org/#dom-generictransformstream-readable
-GC::Ref<ReadableStream> GenericTransformStreamMixin::readable()
-{
- // The readable getter steps are to return this's transform.[[readable]].
- return m_transform->readable();
-}
-
-// https://streams.spec.whatwg.org/#dom-generictransformstream-writable
-GC::Ref<WritableStream> GenericTransformStreamMixin::writable()
-{
- // The writable getter steps are to return this's transform.[[writable]].
- return m_transform->writable();
-}
-
static GC::Ref<WebIDL::Promise> promise_for(JS::Realm& realm, JSCompletion completion)
{
auto result = JS::HostABI::completion_from_abi<JS::Value>(completion);
diff --git a/Libraries/LibWeb/Streams/GenericTransformStream.h b/Libraries/LibWeb/Streams/GenericTransformStream.h
deleted file mode 100644
index cb7ae5f1d6d..00000000000
--- a/Libraries/LibWeb/Streams/GenericTransformStream.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibGC/Cell.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::Streams {
-
-class GenericTransformStreamMixin {
-public:
- virtual ~GenericTransformStreamMixin();
-
- GC::Ref<ReadableStream> readable();
- GC::Ref<WritableStream> writable();
-
-protected:
- explicit GenericTransformStreamMixin(GC::Ref<TransformStream>);
- void visit_edges(GC::Cell::Visitor&);
-
- // https://streams.spec.whatwg.org/#generictransformstream-transform
- GC::Ref<TransformStream> m_transform;
-};
-
-}
diff --git a/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-attributes.any.txt b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-attributes.any.txt
new file mode 100644
index 00000000000..d065a896506
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-attributes.any.txt
@@ -0,0 +1,33 @@
+Harness status: OK
+
+Found 28 tests
+
+28 Pass
+Pass encoding attribute should have correct value for 'unicode-1-1-utf-8'
+Pass encoding attribute should have correct value for 'iso-8859-2'
+Pass encoding attribute should have correct value for 'ascii'
+Pass encoding attribute should have correct value for 'utf-16'
+Pass setting fatal to 'false' should set the attribute to false
+Pass setting ignoreBOM to 'false' should set the attribute to false
+Pass setting fatal to '0' should set the attribute to false
+Pass setting ignoreBOM to '0' should set the attribute to false
+Pass setting fatal to '' should set the attribute to false
+Pass setting ignoreBOM to '' should set the attribute to false
+Pass setting fatal to 'undefined' should set the attribute to false
+Pass setting ignoreBOM to 'undefined' should set the attribute to false
+Pass setting fatal to 'null' should set the attribute to false
+Pass setting ignoreBOM to 'null' should set the attribute to false
+Pass setting fatal to 'true' should set the attribute to true
+Pass setting ignoreBOM to 'true' should set the attribute to true
+Pass setting fatal to '1' should set the attribute to true
+Pass setting ignoreBOM to '1' should set the attribute to true
+Pass setting fatal to '[object Object]' should set the attribute to true
+Pass setting ignoreBOM to '[object Object]' should set the attribute to true
+Pass setting fatal to '' should set the attribute to true
+Pass setting ignoreBOM to '' should set the attribute to true
+Pass setting fatal to 'yes' should set the attribute to true
+Pass setting ignoreBOM to 'yes' should set the attribute to true
+Pass constructing with an invalid encoding should throw
+Pass constructing with a non-stringifiable encoding should throw
+Pass a throwing fatal member should cause the constructor to throw
+Pass a throwing ignoreBOM member should cause the constructor to throw
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-bad-chunks.any.txt b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-bad-chunks.any.txt
new file mode 100644
index 00000000000..70ee18b55f7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-bad-chunks.any.txt
@@ -0,0 +1,10 @@
+Harness status: OK
+
+Found 5 tests
+
+5 Pass
+Pass chunk of type undefined should error the stream
+Pass chunk of type null should error the stream
+Pass chunk of type numeric should error the stream
+Pass chunk of type object, not BufferSource should error the stream
+Pass chunk of type array should error the stream
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-incomplete-input.any.txt b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-incomplete-input.any.txt
new file mode 100644
index 00000000000..2803b0576c0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-incomplete-input.any.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass incomplete input with error mode "replacement" should end with a replacement character
+Pass incomplete input with error mode "fatal" should error the stream
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-non-utf8.any.txt b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-non-utf8.any.txt
new file mode 100644
index 00000000000..1c1d7561b08
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-non-utf8.any.txt
@@ -0,0 +1,18 @@
+Harness status: OK
+
+Found 13 tests
+
+13 Pass
+Pass TextDecoderStream should be able to decode UTF-16BE
+Pass TextDecoderStream should be able to decode invalid sequences in UTF-16BE
+Pass TextDecoderStream should be able to reject invalid sequences in UTF-16BE
+Pass TextDecoderStream should be able to decode UTF-16LE
+Pass TextDecoderStream should be able to decode invalid sequences in UTF-16LE
+Pass TextDecoderStream should be able to reject invalid sequences in UTF-16LE
+Pass TextDecoderStream should be able to decode Shift_JIS
+Pass TextDecoderStream should be able to decode invalid sequences in Shift_JIS
+Pass TextDecoderStream should be able to reject invalid sequences in Shift_JIS
+Pass TextDecoderStream should be able to decode ISO-2022-JP
+Pass TextDecoderStream should be able to decode invalid sequences in ISO-2022-JP
+Pass TextDecoderStream should be able to reject invalid sequences in ISO-2022-JP
+Pass TextDecoderStream should be able to decode ISO-8859-14
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-split-character.any.txt b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-split-character.any.txt
new file mode 100644
index 00000000000..571cec215fb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-split-character.any.txt
@@ -0,0 +1,16 @@
+Harness status: OK
+
+Found 11 tests
+
+11 Pass
+Pass a code point split between chunks should not be emitted until all bytes are available; split point = 2
+Pass a code point split between chunks should not be emitted until all bytes are available; split point = 3
+Pass a code point split between chunks should not be emitted until all bytes are available; split point = 4
+Pass a code point split between chunks should not be emitted until all bytes are available; split point = 5
+Pass a code point should be emitted as soon as all bytes are available
+Pass an empty chunk inside a code point split between chunks should not change the output; split point = 1
+Pass an empty chunk inside a code point split between chunks should not change the output; split point = 2
+Pass an empty chunk inside a code point split between chunks should not change the output; split point = 3
+Pass an empty chunk inside a code point split between chunks should not change the output; split point = 4
+Pass an empty chunk inside a code point split between chunks should not change the output; split point = 5
+Pass an empty chunk inside a code point split between chunks should not change the output; split point = 6
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-utf8.any.txt b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-utf8.any.txt
new file mode 100644
index 00000000000..47ab6075ba3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/encoding/streams/decode-utf8.any.txt
@@ -0,0 +1,17 @@
+Harness status: OK
+
+Found 12 tests
+
+12 Pass
+Pass decoding one UTF-8 chunk should give one output string - ArrayBuffer
+Pass decoding an empty chunk should give no output chunks - ArrayBuffer
+Pass an initial empty chunk should be ignored - ArrayBuffer
+Pass a trailing empty chunk should be ignored - ArrayBuffer
+Pass UTF-8 EOF handling - ArrayBuffer
+Pass decoding one UTF-8 chunk should give one output string - SharedArrayBuffer
+Pass decoding an empty chunk should give no output chunks - SharedArrayBuffer
+Pass an initial empty chunk should be ignored - SharedArrayBuffer
+Pass a trailing empty chunk should be ignored - SharedArrayBuffer
+Pass UTF-8 EOF handling - SharedArrayBuffer
+Pass decoding a transferred Uint8Array chunk should give no output
+Pass decoding a transferred ArrayBuffer chunk should give no output
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-attributes.any.html b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-attributes.any.html
new file mode 100644
index 00000000000..f7ff54cfeb6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-attributes.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../encoding/streams/decode-attributes.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-attributes.any.js b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-attributes.any.js
new file mode 100644
index 00000000000..0843cc665fd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-attributes.any.js
@@ -0,0 +1,71 @@
+// META: global=window,worker
+
+'use strict';
+
+// Verify that constructor arguments are correctly reflected in the attributes.
+
+// Mapping of the first argument to TextDecoderStream to the expected value of
+// the encoding attribute. We assume that if this subset works correctly, the
+// rest probably work too.
+const labelToName = {
+ 'unicode-1-1-utf-8': 'utf-8',
+ 'iso-8859-2': 'iso-8859-2',
+ 'ascii': 'windows-1252',
+ 'utf-16': 'utf-16le'
+};
+
+for (const label of Object.keys(labelToName)) {
+ test(() => {
+ const stream = new TextDecoderStream(label);
+ assert_equals(stream.encoding, labelToName[label], 'encoding should match');
+ }, `encoding attribute should have correct value for '${label}'`);
+}
+
+for (const falseValue of [false, 0, '', undefined, null]) {
+ test(() => {
+ const stream = new TextDecoderStream('utf-8', { fatal: falseValue });
+ assert_false(stream.fatal, 'fatal should be false');
+ }, `setting fatal to '${falseValue}' should set the attribute to false`);
+
+ test(() => {
+ const stream = new TextDecoderStream('utf-8', { ignoreBOM: falseValue });
+ assert_false(stream.ignoreBOM, 'ignoreBOM should be false');
+ }, `setting ignoreBOM to '${falseValue}' should set the attribute to false`);
+}
+
+for (const trueValue of [true, 1, {}, [], 'yes']) {
+ test(() => {
+ const stream = new TextDecoderStream('utf-8', { fatal: trueValue });
+ assert_true(stream.fatal, 'fatal should be true');
+ }, `setting fatal to '${trueValue}' should set the attribute to true`);
+
+ test(() => {
+ const stream = new TextDecoderStream('utf-8', { ignoreBOM: trueValue });
+ assert_true(stream.ignoreBOM, 'ignoreBOM should be true');
+ }, `setting ignoreBOM to '${trueValue}' should set the attribute to true`);
+}
+
+test(() => {
+ assert_throws_js(RangeError, () => new TextDecoderStream(''),
+ 'the constructor should throw');
+}, 'constructing with an invalid encoding should throw');
+
+test(() => {
+ assert_throws_js(TypeError, () => new TextDecoderStream({
+ toString() { return {}; }
+ }), 'the constructor should throw');
+}, 'constructing with a non-stringifiable encoding should throw');
+
+test(() => {
+ assert_throws_js(Error,
+ () => new TextDecoderStream('utf-8', {
+ get fatal() { throw new Error(); }
+ }), 'the constructor should throw');
+}, 'a throwing fatal member should cause the constructor to throw');
+
+test(() => {
+ assert_throws_js(Error,
+ () => new TextDecoderStream('utf-8', {
+ get ignoreBOM() { throw new Error(); }
+ }), 'the constructor should throw');
+}, 'a throwing ignoreBOM member should cause the constructor to throw');
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-bad-chunks.any.html b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-bad-chunks.any.html
new file mode 100644
index 00000000000..402b23f001d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-bad-chunks.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../encoding/streams/decode-bad-chunks.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-bad-chunks.any.js b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-bad-chunks.any.js
new file mode 100644
index 00000000000..b7b2dd58459
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-bad-chunks.any.js
@@ -0,0 +1,38 @@
+// META: global=window,worker
+
+'use strict';
+
+const badChunks = [
+ {
+ name: 'undefined',
+ value: undefined
+ },
+ {
+ name: 'null',
+ value: null
+ },
+ {
+ name: 'numeric',
+ value: 3.14
+ },
+ {
+ name: 'object, not BufferSource',
+ value: {}
+ },
+ {
+ name: 'array',
+ value: [65]
+ }
+];
+
+for (const chunk of badChunks) {
+ promise_test(async t => {
+ const tds = new TextDecoderStream();
+ const reader = tds.readable.getReader();
+ const writer = tds.writable.getWriter();
+ const writePromise = writer.write(chunk.value);
+ const readPromise = reader.read();
+ await promise_rejects_js(t, TypeError, writePromise, 'write should reject');
+ await promise_rejects_js(t, TypeError, readPromise, 'read should reject');
+ }, `chunk of type ${chunk.name} should error the stream`);
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-incomplete-input.any.html b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-incomplete-input.any.html
new file mode 100644
index 00000000000..9635fca9f8d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-incomplete-input.any.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="resources/readable-stream-from-array.js"></script>
+<script src="resources/readable-stream-to-array.js"></script>
+<div id=log></div>
+<script src="../../encoding/streams/decode-incomplete-input.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-incomplete-input.any.js b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-incomplete-input.any.js
new file mode 100644
index 00000000000..3add74336df
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-incomplete-input.any.js
@@ -0,0 +1,24 @@
+// META: global=window,worker
+// META: script=resources/readable-stream-from-array.js
+// META: script=resources/readable-stream-to-array.js
+
+'use strict';
+
+const inputBytes = [229];
+
+promise_test(async () => {
+ const input = readableStreamFromArray([new Uint8Array(inputBytes)]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, ['\uFFFD'], 'array should have one element');
+}, 'incomplete input with error mode "replacement" should end with a ' +
+ 'replacement character');
+
+promise_test(async t => {
+ const input = readableStreamFromArray([new Uint8Array(inputBytes)]);
+ const output = input.pipeThrough(new TextDecoderStream(
+ 'utf-8', {fatal: true}));
+ const reader = output.getReader();
+ await promise_rejects_js(t, TypeError, reader.read(),
+ 'read should reject');
+}, 'incomplete input with error mode "fatal" should error the stream');
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-non-utf8.any.html b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-non-utf8.any.html
new file mode 100644
index 00000000000..ad08bd4984a
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-non-utf8.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../encoding/streams/decode-non-utf8.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-non-utf8.any.js b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-non-utf8.any.js
new file mode 100644
index 00000000000..2950a9e58ed
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-non-utf8.any.js
@@ -0,0 +1,83 @@
+// META: global=window,worker
+
+'use strict';
+
+// The browser is assumed to use the same implementation as for TextDecoder, so
+// this file don't replicate the exhaustive checks it has. It is just a smoke
+// test that non-UTF-8 encodings work at all.
+
+const encodings = [
+ {
+ name: 'UTF-16BE',
+ value: [108, 52],
+ expected: "\u{6c34}",
+ invalid: [0xD8, 0x00]
+ },
+ {
+ name: 'UTF-16LE',
+ value: [52, 108],
+ expected: "\u{6c34}",
+ invalid: [0x00, 0xD8]
+ },
+ {
+ name: 'Shift_JIS',
+ value: [144, 133],
+ expected: "\u{6c34}",
+ invalid: [255]
+ },
+ {
+ name: 'ISO-2022-JP',
+ value: [65, 66, 67, 0x1B, 65, 66, 67],
+ expected: "ABC\u{fffd}ABC",
+ invalid: [0x0E]
+ },
+ {
+ name: 'ISO-8859-14',
+ value: [100, 240, 114],
+ expected: "d\u{0175}r",
+ invalid: undefined // all bytes are treated as valid
+ }
+];
+
+for (const encoding of encodings) {
+ promise_test(async () => {
+ const stream = new TextDecoderStream(encoding.name);
+ const reader = stream.readable.getReader();
+ const writer = stream.writable.getWriter();
+ const writePromise = writer.write(new Uint8Array(encoding.value));
+ const {value, done} = await reader.read();
+ assert_false(done, 'readable should not be closed');
+ assert_equals(value, encoding.expected, 'chunk should match expected');
+ await writePromise;
+ }, `TextDecoderStream should be able to decode ${encoding.name}`);
+
+ if (!encoding.invalid)
+ continue;
+
+ promise_test(async t => {
+ const stream = new TextDecoderStream(encoding.name);
+ const reader = stream.readable.getReader();
+ const writer = stream.writable.getWriter();
+ const writePromise = writer.write(new Uint8Array(encoding.invalid));
+ const closePromise = writer.close();
+ const {value, done} = await reader.read();
+ assert_false(done, 'readable should not be closed');
+ assert_equals(value, '\u{FFFD}', 'output should be replacement character');
+ await Promise.all([writePromise, closePromise]);
+ }, `TextDecoderStream should be able to decode invalid sequences in ` +
+ `${encoding.name}`);
+
+ promise_test(async t => {
+ const stream = new TextDecoderStream(encoding.name, {fatal: true});
+ const reader = stream.readable.getReader();
+ const writer = stream.writable.getWriter();
+ const writePromise = writer.write(new Uint8Array(encoding.invalid));
+ const closePromise = writer.close();
+ await promise_rejects_js(t, TypeError, reader.read(),
+ 'readable should be errored');
+ await promise_rejects_js(t, TypeError,
+ Promise.all([writePromise, closePromise]),
+ 'writable should be errored');
+ }, `TextDecoderStream should be able to reject invalid sequences in ` +
+ `${encoding.name}`);
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-split-character.any.html b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-split-character.any.html
new file mode 100644
index 00000000000..82c4aa81924
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-split-character.any.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="resources/readable-stream-from-array.js"></script>
+<script src="resources/readable-stream-to-array.js"></script>
+<div id=log></div>
+<script src="../../encoding/streams/decode-split-character.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-split-character.any.js b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-split-character.any.js
new file mode 100644
index 00000000000..d589694fce9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-split-character.any.js
@@ -0,0 +1,50 @@
+// META: global=window,worker
+// META: script=resources/readable-stream-from-array.js
+// META: script=resources/readable-stream-to-array.js
+
+'use strict';
+
+const inputBytes = [73, 32, 240, 159, 146, 153, 32, 115, 116, 114, 101,
+ 97, 109, 115];
+for (const splitPoint of [2, 3, 4, 5]) {
+ promise_test(async () => {
+ const input = readableStreamFromArray(
+ [new Uint8Array(inputBytes.slice(0, splitPoint)),
+ new Uint8Array(inputBytes.slice(splitPoint))]);
+ const expectedOutput = ['I ', '\u{1F499} streams'];
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, expectedOutput,
+ 'the split code point should be in the second chunk ' +
+ 'of the output');
+ }, 'a code point split between chunks should not be emitted until all ' +
+ 'bytes are available; split point = ' + splitPoint);
+}
+
+promise_test(async () => {
+ const splitPoint = 6;
+ const input = readableStreamFromArray(
+ [new Uint8Array(inputBytes.slice(0, splitPoint)),
+ new Uint8Array(inputBytes.slice(splitPoint))]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, ['I \u{1F499}', ' streams'],
+ 'the multibyte character should be in the first chunk ' +
+ 'of the output');
+}, 'a code point should be emitted as soon as all bytes are available');
+
+for (let splitPoint = 1; splitPoint < 7; ++splitPoint) {
+ promise_test(async () => {
+ const input = readableStreamFromArray(
+ [new Uint8Array(inputBytes.slice(0, splitPoint)),
+ new Uint8Array([]),
+ new Uint8Array(inputBytes.slice(splitPoint))]);
+ const concatenatedOutput = 'I \u{1F499} streams';
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_equals(array.length, 2, 'two chunks should be output');
+ assert_equals(array[0].concat(array[1]), concatenatedOutput,
+ 'output should be unchanged by the empty chunk');
+ }, 'an empty chunk inside a code point split between chunks should not ' +
+ 'change the output; split point = ' + splitPoint);
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.html b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.html
new file mode 100644
index 00000000000..291b1e6f3c1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="resources/readable-stream-from-array.js"></script>
+<script src="resources/readable-stream-to-array.js"></script>
+<script src="../../common/sab.js"></script>
+<div id=log></div>
+<script src="../../encoding/streams/decode-utf8.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.js b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.js
new file mode 100644
index 00000000000..f6fceb299bd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.js
@@ -0,0 +1,76 @@
+// META: global=window,worker
+// META: script=resources/readable-stream-from-array.js
+// META: script=resources/readable-stream-to-array.js
+// META: script=/common/sab.js
+'use strict';
+
+["ArrayBuffer", "SharedArrayBuffer"].forEach((arrayBufferOrSharedArrayBuffer) => {
+ const inputChunkData = [73, 32, 240, 159, 146, 153, 32, 115, 116, 114, 101, 97, 109, 115];
+
+ const emptyChunk = new Uint8Array(createBuffer(arrayBufferOrSharedArrayBuffer, 0));
+ const inputChunk = new Uint8Array(createBuffer(arrayBufferOrSharedArrayBuffer, inputChunkData.length));
+
+ inputChunk.set(inputChunkData);
+
+ const expectedOutputString = 'I \u{1F499} streams';
+
+ promise_test(async () => {
+ const input = readableStreamFromArray([inputChunk]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, [expectedOutputString],
+ 'the output should be in one chunk');
+ }, 'decoding one UTF-8 chunk should give one output string - ' + arrayBufferOrSharedArrayBuffer);
+
+ promise_test(async () => {
+ const input = readableStreamFromArray([emptyChunk]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, [], 'no chunks should be output');
+ }, 'decoding an empty chunk should give no output chunks - ' + arrayBufferOrSharedArrayBuffer);
+
+ promise_test(async () => {
+ const input = readableStreamFromArray([emptyChunk, inputChunk]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, [expectedOutputString],
+ 'the output should be in one chunk');
+ }, 'an initial empty chunk should be ignored - ' + arrayBufferOrSharedArrayBuffer);
+
+ promise_test(async () => {
+ const input = readableStreamFromArray([inputChunk, emptyChunk]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, [expectedOutputString],
+ 'the output should be in one chunk');
+ }, 'a trailing empty chunk should be ignored - ' + arrayBufferOrSharedArrayBuffer);
+
+ promise_test(async () => {
+ const chunk = new Uint8Array(createBuffer(arrayBufferOrSharedArrayBuffer, 3));
+ chunk.set([0xF0, 0x9F, 0x92]);
+ const input = readableStreamFromArray([chunk]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, ['\uFFFD']);
+ }, 'UTF-8 EOF handling - ' + arrayBufferOrSharedArrayBuffer);
+});
+
+promise_test(async () => {
+ const buffer = new ArrayBuffer(3);
+ const view = new Uint8Array(buffer, 1, 1);
+ view[0] = 65;
+ new MessageChannel().port1.postMessage(buffer, [buffer]);
+ const input = readableStreamFromArray([view]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, [], 'no chunks should be output');
+}, 'decoding a transferred Uint8Array chunk should give no output');
+
+promise_test(async () => {
+ const buffer = new ArrayBuffer(1);
+ new MessageChannel().port1.postMessage(buffer, [buffer]);
+ const input = readableStreamFromArray([buffer]);
+ const output = input.pipeThrough(new TextDecoderStream());
+ const array = await readableStreamToArray(output);
+ assert_array_equals(array, [], 'no chunks should be output');
+}, 'decoding a transferred ArrayBuffer chunk should give no output');
diff --git a/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.js.headers b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.js.headers
new file mode 100644
index 00000000000..4fff9d9fba4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/encoding/streams/decode-utf8.any.js.headers
@@ -0,0 +1,2 @@
+Cross-Origin-Opener-Policy: same-origin
+Cross-Origin-Embedder-Policy: require-corp
\ No newline at end of file