Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ option(JSRUNTIMEHOST_POLYFILL_FILE "Include JsRuntimeHost Polyfill File and File
option(JSRUNTIMEHOST_POLYFILL_PERFORMANCE "Include JsRuntimeHost Polyfill Performance." ON)
option(JSRUNTIMEHOST_POLYFILL_TEXTDECODER "Include JsRuntimeHost Polyfill TextDecoder." ON)
option(JSRUNTIMEHOST_POLYFILL_TEXTENCODER "Include JsRuntimeHost Polyfill TextEncoder." ON)
option(JSRUNTIMEHOST_POLYFILL_STREAMS "Include JsRuntimeHost Polyfill Web Streams." ON)

# Sanitizers
option(ENABLE_SANITIZERS "Enable AddressSanitizer and UBSan" OFF)
Expand Down
6 changes: 5 additions & 1 deletion Polyfills/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,8 @@ endif()

if(JSRUNTIMEHOST_POLYFILL_TEXTENCODER)
add_subdirectory(TextEncoder)
endif()
endif()

if(JSRUNTIMEHOST_POLYFILL_STREAMS)
add_subdirectory(Streams)
endif()
30 changes: 30 additions & 0 deletions Polyfills/Streams/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
set(WEB_STREAMS_POLYFILL_FILE
"${CMAKE_CURRENT_SOURCE_DIR}/ThirdParty/web-streams-polyfill/ponyfill.es5.js")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${WEB_STREAMS_POLYFILL_FILE}")
file(READ "${WEB_STREAMS_POLYFILL_FILE}" WEB_STREAMS_POLYFILL_SOURCE)
string(SUBSTRING "${WEB_STREAMS_POLYFILL_SOURCE}" 0 60000 WEB_STREAMS_POLYFILL_SOURCE_1)
string(SUBSTRING "${WEB_STREAMS_POLYFILL_SOURCE}" 60000 -1 WEB_STREAMS_POLYFILL_SOURCE_2)
configure_file(
"Source/StreamsScripts.h.in"
"${CMAKE_CURRENT_BINARY_DIR}/Generated/StreamsScripts.h"
@ONLY)

set(SOURCES
"Include/Babylon/Polyfills/Streams.h"
"Source/Streams.cpp"
"Source/StreamsScripts.h.in"
"ThirdParty/web-streams-polyfill/LICENSE"
"ThirdParty/web-streams-polyfill/ponyfill.es5.js")

add_library(Streams ${SOURCES})
warnings_as_errors(Streams)

target_include_directories(Streams
PUBLIC "Include"
PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/Generated")

target_link_libraries(Streams PUBLIC JsRuntime)

set_property(TARGET Streams PROPERTY FOLDER Polyfills)
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})
11 changes: 11 additions & 0 deletions Polyfills/Streams/Include/Babylon/Polyfills/Streams.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once

#include <Babylon/Api.h>
#include <napi/env.h>

namespace Babylon::Polyfills::Streams
{
// Installs the WHATWG Streams constructors that are not already supplied
// by the JavaScript engine.
void BABYLON_API Initialize(Napi::Env env);
}
14 changes: 14 additions & 0 deletions Polyfills/Streams/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Web Streams

Installs the standard `ReadableStream`, `WritableStream`, `TransformStream`,
reader, writer, controller, and queuing-strategy globals when the selected
JavaScript engine does not provide them.

The implementation is the ES5 ponyfill bundle from
[`web-streams-polyfill` 4.3.0](https://github.com/MattiasBuelens/web-streams-polyfill/tree/add69059ed08eae6a18559aba49575a280d1529e),
which is based on the WHATWG reference implementation. The vendored project
tests this release against the Streams portion of WPT at revision
[`c05b4473`](https://github.com/web-platform-tests/wpt/tree/c05b447326585237713013c66341eab2cdf967b6/streams).

`Initialize` preserves any Streams constructors already supplied by the host
engine and fills only missing globals.
53 changes: 53 additions & 0 deletions Polyfills/Streams/Source/Streams.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <Babylon/Polyfills/Streams.h>

#include "StreamsScripts.h"

#include <array>
#include <string_view>

namespace Babylon::Polyfills::Streams
{
void BABYLON_API Initialize(Napi::Env env)
{
Napi::HandleScope scope{env};
auto global = env.Global();

static constexpr std::array<std::string_view, 13> constructorNames{
"ReadableStream",
"ReadableStreamDefaultController",
"ReadableByteStreamController",
"ReadableStreamBYOBRequest",
"ReadableStreamDefaultReader",
"ReadableStreamBYOBReader",
"WritableStream",
"WritableStreamDefaultController",
"WritableStreamDefaultWriter",
"ByteLengthQueuingStrategy",
"CountQueuingStrategy",
"TransformStream",
"TransformStreamDefaultController",
};

bool needsPonyfill{};
for (const auto name : constructorNames)
{
const auto constructor = global.Get(name.data());
if (constructor.IsUndefined() || constructor.IsNull())
{
needsPonyfill = true;
break;
}
}

if (!needsPonyfill)
{
return;
}

const auto exports = Napi::Eval(env, Internal::StreamsScripts::Ponyfill.data(), "jsruntimehost://web-streams-polyfill.js").As<Napi::Object>();
for (const auto name : constructorNames)
{
global.Set(name.data(), exports.Get(name.data()));
}
Comment thread
matthargett marked this conversation as resolved.
}
}
36 changes: 36 additions & 0 deletions Polyfills/Streams/Source/StreamsScripts.h.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#pragma once

#include <array>
#include <cstddef>

namespace Babylon::Polyfills::Internal::StreamsScripts
{
inline constexpr char PonyfillPart1[] = R"JSRHSTREAM(
(function() {
var exports = {};
var module = { exports: exports };
@WEB_STREAMS_POLYFILL_SOURCE_1@
)JSRHSTREAM";

inline constexpr char PonyfillPart2[] = R"JSRHSTREAM(@WEB_STREAMS_POLYFILL_SOURCE_2@
return module.exports;
})()
)JSRHSTREAM";

template<std::size_t Part1Size, std::size_t Part2Size>
consteval auto Join(const char (&part1)[Part1Size], const char (&part2)[Part2Size])
{
std::array<char, Part1Size + Part2Size - 1> result{};
for (std::size_t index{}; index < Part1Size - 1; ++index)
{
result[index] = part1[index];
}
for (std::size_t index{}; index < Part2Size; ++index)
{
result[Part1Size - 1 + index] = part2[index];
}
return result;
}

inline constexpr auto Ponyfill = Join(PonyfillPart1, PonyfillPart2);
}
22 changes: 22 additions & 0 deletions Polyfills/Streams/ThirdParty/web-streams-polyfill/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2026 Mattias Buelens
Copyright (c) 2016 Diwank Singh Tomer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Tests/UnitTests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ target_link_libraries(UnitTests
PRIVATE Performance
PRIVATE TextDecoder
PRIVATE TextEncoder
PRIVATE Streams
${ADDITIONAL_LIBRARIES})

# See https://gitlab.kitware.com/cmake/cmake/-/issues/23543
Expand Down
156 changes: 156 additions & 0 deletions Tests/UnitTests/Scripts/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1371,6 +1371,162 @@ describe("Console", function () {
});
});

describe("Web Streams", function () {
// Focused ports from the WHATWG Streams WPT suites at c05b4473:
// readable-streams/general.any.js and tee.any.js,
// writable-streams/write.any.js, and transform-streams/general.any.js.
it("installs the standard stream constructors", function () {
expect(ReadableStream).to.be.a("function");
expect(WritableStream).to.be.a("function");
expect(TransformStream).to.be.a("function");
expect(ByteLengthQueuingStrategy).to.be.a("function");
expect(CountQueuingStrategy).to.be.a("function");
});

it("delivers queued chunks in order and closes the reader", async function () {
const stream = new ReadableStream({
start(controller) {
controller.enqueue("a");
controller.enqueue("b");
controller.close();
}
});
const reader = stream.getReader();

expect(await reader.read()).to.deep.equal({ value: "a", done: false });
expect(await reader.read()).to.deep.equal({ value: "b", done: false });
expect(await reader.read()).to.deep.equal({ value: undefined, done: true });
await reader.closed;
});

it("propagates a rejected pull to read and closed", async function () {
const failure = new Error("pull failed");
const reader = new ReadableStream({
pull() {
return Promise.reject(failure);
}
}).getReader();

let readFailure: unknown;
let closedFailure: unknown;
try { await reader.read(); } catch (error) { readFailure = error; }
try { await reader.closed; } catch (error) { closedFailure = error; }
expect(readFailure).to.equal(failure);
expect(closedFailure).to.equal(failure);
});

it("tees without one branch consuming the other", async function () {
const [first, second] = new ReadableStream({
start(controller) {
controller.enqueue("a");
controller.enqueue("b");
controller.close();
}
}).tee();
const firstReader = first.getReader();
const secondReader = second.getReader();

expect(await firstReader.read()).to.deep.equal({ value: "a", done: false });
expect(await firstReader.read()).to.deep.equal({ value: "b", done: false });
expect(await firstReader.read()).to.deep.equal({ value: undefined, done: true });
expect(await secondReader.read()).to.deep.equal({ value: "a", done: false });
});

it("waits for asynchronous writes before closing", async function () {
const stored: number[] = [];
const writable = new WritableStream({
write(chunk) {
return Promise.resolve().then(() => stored.push(chunk));
}
});
const writer = writable.getWriter();

writer.write(1);
writer.write(2);
await writer.close();
expect(stored).to.deep.equal([1, 2]);
});

it("applies transform output and backpressure", async function () {
const transform = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
}
});
const writer = transform.writable.getWriter();
const reader = transform.readable.getReader();
const write = writer.write("native");

expect(await reader.read()).to.deep.equal({ value: "NATIVE", done: false });
await write;
await writer.close();
expect(await reader.read()).to.deep.equal({ value: undefined, done: true });
});

it("supports BYOB reads from byte streams", async function () {
let sent = false;
const stream = new ReadableStream({
type: "bytes",
pull(controller) {
if (!sent) {
sent = true;
controller.enqueue(new Uint8Array([8, 241, 48, 123, 151]));
controller.close();
}
}
} as any);
const reader = stream.getReader({ mode: "byob" });
const result = await reader.read(new Uint8Array(8));

expect(result.done).to.equal(false);
expect(Array.from(result.value!)).to.deep.equal([8, 241, 48, 123, 151]);
expect((await reader.read(new Uint8Array(8))).done).to.equal(true);
});

// Ported from Firefox's dom/streams/test/xpcshell/subclassing.js.
it("supports subclassed streams, readers, and queuing strategies", async function () {
class SubclassedStream extends ReadableStream {}
class SubclassedStrategy extends CountQueuingStrategy {}
const stream = new SubclassedStream({
start(controller) {
controller.enqueue("first");
controller.close();
}
});
const Reader = stream.getReader().constructor as typeof ReadableStreamDefaultReader;
class SubclassedReader extends Reader {}

expect(stream).to.be.instanceOf(ReadableStream);
expect(new SubclassedStrategy({ highWaterMark: 4 }).highWaterMark).to.equal(4);

const secondStream = new ReadableStream({
start(controller) {
controller.enqueue("second");
controller.close();
}
});
const reader = new SubclassedReader(secondStream);
expect(await reader.read()).to.deep.equal({ value: "second", done: false });
});

// Ported from Chromium's http/tests/streams/chromium/transform-stream-enqueue.html.
it("rejects enqueues after a transform is terminated or errored", function () {
expect(() => new TransformStream({
start(controller) {
controller.terminate();
controller.enqueue("late");
}
})).to.throw(TypeError);

expect(() => new TransformStream({
start(controller) {
controller.error(new Error("failed"));
controller.enqueue("late");
}
})).to.throw(TypeError);
});
});

describe("Blob", function () {
let emptyBlobs: Blob[], helloBlobs: Blob[], stringBlob: Blob, typedArrayBlob: Blob, arrayBufferBlob: Blob, blobBlob: Blob;

Expand Down
Loading