Skip to content

Truly independent web browser

LibWeb: Implement fetch body `textStream()`

Callum Lawa920f5d96b61
diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch.rs
new file mode 100644
index 00000000000..0803b509e52
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch.rs
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+
+use crate::bindings::interface::{cell_from_abi, cell_into_abi, realm_arguments};
+use crate::bindings::{CallContext, MustNotThrow};
+use crate::encoding::text_decoder_stream::TextDecoderStream;
+use crate::streams::algorithms::{CancelAlgorithm, PullAlgorithm, StartAlgorithm};
+use crate::streams::readable_stream::{ReadableStream, create_readable_stream, readable_stream_close};
+
+/// https://fetch.spec.whatwg.org/#dom-body-textstream
+///
+/// # Safety
+///
+/// The pointers must be the live VM, the receiver's realm, and null or the body's live, usable ReadableStream.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_body_text_stream(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ stream: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and the receiver's realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let cx = CallContext::new(vm, realm);
+
+ // 1. If this is unusable, then throw a TypeError.
+ // AD-HOC: This is implemented in the C++ caller
+
+ // 2. If this's body is null:
+ if stream.is_null() {
+ // 1. Let emptyStream be a new ReadableStream in this's relevant realm.
+ // 2. Set up emptyStream.
+ let empty_stream = create_readable_stream(
+ &cx,
+ StartAlgorithm::ReturnsUndefined,
+ PullAlgorithm::ReturnsResolvedUndefined,
+ CancelAlgorithm::ReturnsResolvedUndefined,
+ None,
+ None,
+ )
+ .must();
+
+ // 3. Close emptyStream.
+ readable_stream_close(vm, empty_stream);
+
+ // 4. Return emptyStream.
+ return cell_into_abi(empty_stream);
+ }
+
+ // 3. Let stream be this's body's stream.
+ // SAFETY: The caller passes the body's live ReadableStream.
+ let stream = unsafe { cell_from_abi::<ReadableStream>(stream) };
+
+ // 4. Let decoder be a new TextDecoderStream object in this's relevant realm.
+ // 5. Set up decoder with UTF-8.
+ let decoder = TextDecoderStream::set_up(&cx, encoding_rs::UTF_8, false, false);
+
+ // 6. Return the result of stream, piped through decoder.
+ cell_into_abi(ReadableStream::piped_through(
+ stream,
+ vm,
+ decoder.transform(),
+ false,
+ false,
+ false,
+ None,
+ ))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index c4b13aa254a..491d7636c1b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -86,6 +86,8 @@ pub(crate) mod domurl;
allow(dead_code, reason = "only the generated bindings use the interfaces")
)]
pub(crate) mod encoding;
+#[cfg(not(test))]
+pub(crate) mod fetch;
#[cfg_attr(
not(web_idl_bindings),
allow(dead_code, reason = "only the generated bindings use the interfaces")
diff --git a/Libraries/LibWeb/Fetch/Body.cpp b/Libraries/LibWeb/Fetch/Body.cpp
index bc970168015..0d9b580b93b 100644
--- a/Libraries/LibWeb/Fetch/Body.cpp
+++ b/Libraries/LibWeb/Fetch/Body.cpp
@@ -9,6 +9,7 @@
#include <AK/TypeCasts.h>
#include <LibHTTP/HTTP.h>
#include <LibHTTP/HeaderList.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/TypedArray.h>
@@ -31,6 +32,8 @@
namespace Web::Fetch {
+extern "C" void* web_rust_body_text_stream(JSVM*, void* realm, void* stream);
+
// convertBytesToJSValue is an algorithm that takes a byte sequence and returns a JavaScript value or throws an exception
using ConvertBytesToJSValueCallback = GC::Ref<GC::Function<WebIDL::ExceptionOr<JS::Value>(ByteBuffer bytes)>>;
@@ -219,6 +222,16 @@ void BodyMixin::text(GC::Ref<WebIDL::Promise> promise) const
}));
}
+// https://fetch.spec.whatwg.org/#dom-body-textstream
+WebIDL::ExceptionOr<GC::Ref<Streams::ReadableStream>> BodyMixin::text_stream(JS::Realm& realm) const
+{
+ // 1. If this is unusable, then throw a TypeError.
+ if (is_unusable())
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Body is unusable"_utf16 };
+
+ return GC::Ref { *static_cast<Streams::ReadableStream*>(web_rust_body_text_stream(JS::HostABI::vm_to_abi(realm.vm()), &realm, body().ptr())) };
+}
+
// https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name
static MultipartParsingErrorOr<String> parse_multipart_form_data_name(GenericLexer& lexer)
{
diff --git a/Libraries/LibWeb/Fetch/Body.h b/Libraries/LibWeb/Fetch/Body.h
index 236887f3ac5..f2692ee00df 100644
--- a/Libraries/LibWeb/Fetch/Body.h
+++ b/Libraries/LibWeb/Fetch/Body.h
@@ -53,6 +53,7 @@ public:
void form_data(GC::Ref<WebIDL::Promise>) const;
void json(GC::Ref<WebIDL::Promise>) const;
void text(GC::Ref<WebIDL::Promise>) const;
+ WebIDL::ExceptionOr<GC::Ref<Streams::ReadableStream>> text_stream(JS::Realm&) const;
};
[[nodiscard]] MultipartParsingErrorOr<GC::ConservativeVector<XHR::FormDataEntry>> parse_multipart_form_data(StringView input, MimeSniff::MimeType const& mime_type);
diff --git a/Libraries/LibWeb/Fetch/Body.idl b/Libraries/LibWeb/Fetch/Body.idl
index 3da2791962f..fbd68ee591f 100644
--- a/Libraries/LibWeb/Fetch/Body.idl
+++ b/Libraries/LibWeb/Fetch/Body.idl
@@ -8,4 +8,5 @@ interface mixin Body {
[CreatesPromise, NeedsCallerRealm, NewObject] Promise<FormData> formData();
[CreatesPromise, NeedsCallerRealm, NewObject] Promise<any> json();
[CreatesPromise, NeedsCallerRealm, NewObject] Promise<USVString> text();
+ [NewObject] ReadableStream textStream();
};
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index a579a10dab2..a69de404302 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -56,11 +56,11 @@ ALLOWED_REALM_MENTIONS = {
"DOM abort plumbing, including the Rust AbortSignal adapter, and node helpers use callback/materialization realms",
),
"Fetch": (
- 20,
- 60,
+ 22,
+ 62,
"Fetch bodies, headers, requests, responses, response views, and controllers still materialize JS values/streams; "
"BodyStreamPullSource creates body streams and materializes their pulls and errors on the consumer side, each in "
- "its stream's realm",
+ "its stream's realm; Body.textStream() creates its empty stream or streaming decoder in the receiver's realm",
),
"FileAPI": (2, 9, "Blob glue still creates streams and buffers in selected realms"),
"HTML": (
diff --git a/Tests/LibWeb/Text/expected/Fetch/body-text-stream.txt b/Tests/LibWeb/Text/expected/Fetch/body-text-stream.txt
new file mode 100644
index 00000000000..4cfb2eaf575
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/body-text-stream.txt
@@ -0,0 +1,11 @@
+Before close: {"value":"€","done":false}
+After close: {"value":"�","done":false}
+Closed: {"done":true}
+Disturbed body: TypeError
+Null body BYOB reader: TypeError
+Source error: Error: source failed; unchanged: true
+Cancellation: stop
+Invalid chunk: TypeError
+Cancellation error unchanged: true
+Receiver realm (null): true
+Receiver realm (text): true
diff --git a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.txt b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.txt
index d054d79dfe0..8bcae64f237 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.txt
@@ -2,19 +2,18 @@ Harness status: OK
Found 14 tests
-4 Pass
-10 Fail
-Fail textStream method existence
-Fail Response.textStream() basic functionality
-Fail Request.textStream() basic functionality
-Fail textStream() handles chunked byte stream input
+14 Pass
+Pass textStream method existence
+Pass Response.textStream() basic functionality
+Pass Request.textStream() basic functionality
+Pass textStream() handles chunked byte stream input
Pass Response.textStream() on consumed body throws TypeError
Pass Request.textStream() on consumed body throws TypeError
Pass Response.textStream() on locked body throws TypeError
Pass Request.textStream() on locked body throws TypeError
-Fail Response.textStream() with null body
-Fail Request.textStream() with null body
-Fail Response.textStream() with empty body
-Fail Response.textStream() ignores Content-Type charset (UTF-16LE)
-Fail Request.textStream() ignores Content-Type charset (UTF-16LE)
-Fail Response.textStream() ignores invalid Content-Type charset (invalid-charset)
\ No newline at end of file
+Pass Response.textStream() with null body
+Pass Request.textStream() with null body
+Pass Response.textStream() with empty body
+Pass Response.textStream() ignores Content-Type charset (UTF-16LE)
+Pass Request.textStream() ignores Content-Type charset (UTF-16LE)
+Pass Response.textStream() ignores invalid Content-Type charset (invalid-charset)
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.worker.txt
index d054d79dfe0..8bcae64f237 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.worker.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/fetch/api/body/textstream.any.worker.txt
@@ -2,19 +2,18 @@ Harness status: OK
Found 14 tests
-4 Pass
-10 Fail
-Fail textStream method existence
-Fail Response.textStream() basic functionality
-Fail Request.textStream() basic functionality
-Fail textStream() handles chunked byte stream input
+14 Pass
+Pass textStream method existence
+Pass Response.textStream() basic functionality
+Pass Request.textStream() basic functionality
+Pass textStream() handles chunked byte stream input
Pass Response.textStream() on consumed body throws TypeError
Pass Request.textStream() on consumed body throws TypeError
Pass Response.textStream() on locked body throws TypeError
Pass Request.textStream() on locked body throws TypeError
-Fail Response.textStream() with null body
-Fail Request.textStream() with null body
-Fail Response.textStream() with empty body
-Fail Response.textStream() ignores Content-Type charset (UTF-16LE)
-Fail Request.textStream() ignores Content-Type charset (UTF-16LE)
-Fail Response.textStream() ignores invalid Content-Type charset (invalid-charset)
\ No newline at end of file
+Pass Response.textStream() with null body
+Pass Request.textStream() with null body
+Pass Response.textStream() with empty body
+Pass Response.textStream() ignores Content-Type charset (UTF-16LE)
+Pass Request.textStream() ignores Content-Type charset (UTF-16LE)
+Pass Response.textStream() ignores invalid Content-Type charset (invalid-charset)
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/Fetch/body-text-stream.html b/Tests/LibWeb/Text/input/Fetch/body-text-stream.html
new file mode 100644
index 00000000000..da874d95030
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/body-text-stream.html
@@ -0,0 +1,84 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ const decode = source => new Response(new ReadableStream(source)).textStream();
+
+ function errorName(callback) {
+ try {
+ callback();
+ } catch (error) {
+ return error.name;
+ }
+ }
+
+ asyncTest(async done => {
+ let controller;
+ const reader = decode({
+ start(value) {
+ controller = value;
+ },
+ }).getReader();
+ for (const bytes of [[0xef], [0xbb, 0xbf, 0xe2], [0x82], [0xac]]) controller.enqueue(new Uint8Array(bytes));
+ println(`Before close: ${JSON.stringify(await reader.read())}`);
+ controller.enqueue(new Uint8Array([0xe2, 0x82]));
+ controller.close();
+ println(`After close: ${JSON.stringify(await reader.read())}`);
+ println(`Closed: ${JSON.stringify(await reader.read())}`);
+
+ const disturbed = new Response("text");
+ const bodyReader = disturbed.body.getReader();
+ await bodyReader.read();
+ bodyReader.releaseLock();
+ println(`Disturbed body: ${errorName(() => disturbed.textStream())}`);
+
+ const empty = new Response().textStream();
+ println(`Null body BYOB reader: ${errorName(() => empty.getReader({ mode: "byob" }))}`);
+
+ const sourceError = new Error("source failed");
+ const failed = decode({
+ start(value) {
+ value.error(sourceError);
+ },
+ });
+ const readError = await failed
+ .getReader()
+ .read()
+ .catch(error => error);
+ println(`Source error: ${readError}; unchanged: ${readError === sourceError}`);
+
+ const canceled = Promise.withResolvers();
+ const cancelStream = decode({
+ cancel(reason) {
+ println(`Cancellation: ${reason}`);
+ canceled.resolve();
+ },
+ });
+ await cancelStream.cancel("stop");
+ await canceled.promise;
+
+ const invalidCanceled = Promise.withResolvers();
+ const invalid = decode({
+ start(value) {
+ value.enqueue("not bytes");
+ },
+ cancel: invalidCanceled.resolve,
+ });
+ const decodingError = await invalid
+ .getReader()
+ .read()
+ .catch(error => error);
+ println(`Invalid chunk: ${decodingError.name}`);
+ println(`Cancellation error unchanged: ${(await invalidCanceled.promise) === decodingError}`);
+
+ const frame = document.createElement("iframe");
+ document.body.append(frame);
+ const other = frame.contentWindow;
+ for (const body of [null, "text"]) {
+ const stream = Response.prototype.textStream.call(new other.Response(body));
+ println(`Receiver realm (${body}): ${stream instanceof other.ReadableStream}`);
+ await stream.cancel();
+ }
+ frame.remove();
+ done();
+ });
+</script>