// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

const textDecoder = new TextDecoder();

/**
 * Converts a {@linkcode ReadableSteam} of strings or {@linkcode Uint8Array}s
 * to a single string. Works the same as {@linkcode Response.text}.
 *
 * @param readableStream A `ReadableStream` to convert into a `string`.
 * @returns A `Promise` that resolves to the `string`.
 *
 * @example Basic usage
 * ```ts
 * import { toText } from "@std/streams/to-text";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const stream = ReadableStream.from(["Hello, ", "world!"]);
 * assertEquals(await toText(stream), "Hello, world!");
 * ```
 */
export async function toText(
  readableStream: ReadableStream,
): Promise<string> {
  const reader = readableStream.getReader();
  let result = "";

  while (true) {
    const { done, value } = await reader.read();

    if (done) {
      break;
    }

    result += typeof value === "string" ? value : textDecoder.decode(value);
  }

  return result;
}

// denoCacheMetadata={"headers":{"cache-control":"public, max-age=31536000, immutable","access-control-expose-headers":"*","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","date":"Tue, 28 Jul 2026 12:31:15 GMT","set-cookie":"__cf_bm=ATXm_08QHx1Fwfk5kaHiqFG7zE9zfcAsxGTGlcsFDl0-1785241875.1909785-1.0.1.1-EK6UngLsqfh5k7yR1UzEjw8SX3GX_wyvljlezAcai4mTWozvV4geUfcd6daCe179ogE18a4fgxuhr_QuZ90Ipqu664z__VvEm3HDrDeC56Q5P6Nh_tZdMl4rlYrdBrNf; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cf-ray":"a223e657eaec7db6-LAX","access-control-allow-origin":"*","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=oI59sLgK%2BSw%2BIKqv2uFMLnDHM3o8K4oc5TEbZLycOqDoz8Ft8tQ5JYR1taXcdMNCumc7KRXtn5QaJ0Z7%2F2mMpjTwuS1rWTM8ayj%2Fynry7%2Bvqb33exH9ub34%3D\"}]}","etag":"\"e9f9789801e22c99896ed9ed57d4e870\"","cross-origin-resource-policy":"cross-origin","x-jsr-backend":"modules","content-type":"text/typescript","x-robots-tag":"noindex","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","server":"cloudflare","x-content-type-options":"nosniff","alt-svc":"h3=\":443\"; ma=86400","content-length":"1067","vary":"Origin"},"url":"https://jsr.io/@std/streams/0.224.5/to_text.ts","time":1785241875}