Files

33 lines
2.1 KiB
JavaScript

import { ReadableStream, WritableStream, TextEncoderStream, TextDecoderStream, TransformStream } from "node:stream/web";
import { out, result, sameError, launch } from "./helpers.js";
export function reportEncoding() { launch(async () => {
const encode = async (values) => {
const got = [];
await ReadableStream.from(values).pipeThrough(new TextEncoderStream()).pipeTo(new WritableStream({ write(v) { got.push([...v].join(",")); } }));
return got.join(" | ");
};
const encoder = new TextEncoderStream();
out("encoder", TextEncoderStream === globalThis.TextEncoderStream, encoder.encoding, encoder.readable instanceof ReadableStream, encoder.writable instanceof WritableStream, encoder instanceof TransformStream, Object.prototype.toString.call(encoder), Object.keys(TextEncoderStream.prototype).join(","));
await encoder.writable.close();
out("ascii", await encode(["hello", "", " world"]));
out("surrogate", await encode(["A\ud83d", "", "\ude00B", "\ud800", "x\udc00", "\udbff"]));
out("surrogate-pairs", await encode(["\ud800", "\ud801", "\udc00", "\udc01"]));
out("empty", await encode(["", ""]));
out("coercion", await encode([undefined, null, false, 42, 3n, Symbol("x"), { toString() { return "object"; } }]));
{
const got = [];
await ReadableStream.from(["Hello ", "\ud83d", "\ude00", "!"]).pipeThrough(new TextEncoderStream()).pipeThrough(new TextDecoderStream()).pipeTo(new WritableStream({ write(v) { got.push(v); } }));
out("roundtrip", got.join(""));
}
{
const reason = new Error("coercion"), t = new TextEncoderStream(), w = t.writable.getWriter(), r = t.readable.getReader();
const read = sameError(r.read(), reason), write = sameError(w.write({ toString() { throw reason; } }), reason);
out("encoding-error", await write, await read, await sameError(w.closed, reason), await sameError(r.closed, reason));
}
for (const name of ["encoding", "readable", "writable"]) {
try { Object.getOwnPropertyDescriptor(TextEncoderStream.prototype, name).get.call({}); out("brand", name, false); }
catch (e) { out("brand", name, e instanceof TypeError); }
}
}); }