/**
 * Stream Utilities
 *
 * Small, cross-platform helpers built on top of the platform stream
 * implementation selected by `./streams` (Node.js or browser).
 */
import { createReadableFromArray, createTransform } from "./streams.js";
import { stringToUint8Array as _stringToUint8Array, uint8ArrayToString as _uint8ArrayToString } from "./shared.js";
// =============================================================================
// High-Level Stream Consumers
// =============================================================================
export async function collect(stream) {
    const result = [];
    for await (const chunk of stream) {
        result.push(chunk);
    }
    return result;
}
export async function text(stream) {
    const chunks = [];
    let totalLength = 0;
    for await (const chunk of stream) {
        chunks.push(chunk);
        totalLength += chunk.length;
    }
    if (chunks.length === 1) {
        return _uint8ArrayToString(chunks[0]);
    }
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (let i = 0, len = chunks.length; i < len; i++) {
        const c = chunks[i];
        result.set(c, offset);
        offset += c.length;
    }
    return _uint8ArrayToString(result);
}
export async function json(stream) {
    const str = await text(stream);
    return JSON.parse(str);
}
export async function bytes(stream) {
    const chunks = [];
    let totalLength = 0;
    for await (const chunk of stream) {
        chunks.push(chunk);
        totalLength += chunk.length;
    }
    if (chunks.length === 1) {
        return chunks[0];
    }
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (let i = 0, len = chunks.length; i < len; i++) {
        const c = chunks[i];
        result.set(c, offset);
        offset += c.length;
    }
    return result;
}
// =============================================================================
// Stream Factory Helpers
// =============================================================================
export function fromString(str) {
    return createReadableFromArray([_stringToUint8Array(str)], {
        objectMode: false
    });
}
export function fromJSON(data) {
    return fromString(JSON.stringify(data));
}
export function fromBytes(data) {
    return createReadableFromArray([data], { objectMode: false });
}
export function transform(fn) {
    return createTransform(fn);
}
export function filter(predicate) {
    return createTransform(async (chunk) => {
        if (await predicate(chunk)) {
            return chunk;
        }
        return undefined;
    }, { objectMode: true });
}
