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

import { DEFAULT_CHUNK_SIZE } from "./_constants.ts";
import { isCloser } from "./_common.ts";
import type { Closer, Reader } from "./types.ts";

/** Options for {@linkcode toReadableStream}. */
export interface ToReadableStreamOptions {
  /** If the `reader` is also a `Closer`, automatically close the `reader`
   * when `EOF` is encountered, or a read error occurs.
   *
   * @default {true}
   */
  autoClose?: boolean;

  /**
   * The size of chunks to allocate to read.
   *
   * @default {16640}
   */
  chunkSize?: number;

  /** The queuing strategy to create the {@linkcode ReadableStream} with. */
  strategy?: QueuingStrategy<Uint8Array>;
}

/**
 * Create a {@linkcode ReadableStream} of {@linkcode Uint8Array}s from a
 * {@linkcode Reader}.
 *
 * When the pull algorithm is called on the stream, a chunk from the reader
 * will be read.  When `null` is returned from the reader, the stream will be
 * closed along with the reader (if it is also a `Closer`).
 *
 * @example Usage
 * ```ts no-assert
 * import { toReadableStream } from "@std/io/to-readable-stream";
 *
 * const file = await Deno.open("./README.md", { read: true });
 * const fileStream = toReadableStream(file);
 * ```
 *
 * @param reader The reader to read from
 * @param options The options
 * @returns The readable stream
 */
export function toReadableStream(
  reader: Reader | (Reader & Closer),
  options?: ToReadableStreamOptions,
): ReadableStream<Uint8Array> {
  const {
    autoClose = true,
    chunkSize = DEFAULT_CHUNK_SIZE,
    strategy,
  } = options ?? {};

  return new ReadableStream({
    async pull(controller) {
      const chunk = new Uint8Array(chunkSize);
      try {
        const read = await reader.read(chunk);
        if (read === null) {
          if (isCloser(reader) && autoClose) {
            reader.close();
          }
          controller.close();
          return;
        }
        controller.enqueue(chunk.subarray(0, read));
      } catch (e) {
        controller.error(e);
        if (isCloser(reader)) {
          reader.close();
        }
      }
    },
    cancel() {
      if (isCloser(reader) && autoClose) {
        reader.close();
      }
    },
  }, strategy);
}

// denoCacheMetadata={"headers":{"content-type":"text/typescript","date":"Tue, 28 Jul 2026 12:31:15 GMT","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';","alt-svc":"h3=\":443\"; ma=86400","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cross-origin-resource-policy":"cross-origin","access-control-expose-headers":"*","cache-control":"public, max-age=31536000, immutable","x-robots-tag":"noindex","cf-ray":"a223e65728e77db6-LAX","access-control-allow-origin":"*","etag":"\"3f69ecf253558b1a6140568af2aa3231\"","vary":"Origin","x-content-type-options":"nosniff","content-length":"2305","server":"cloudflare","x-jsr-backend":"modules","set-cookie":"__cf_bm=jVftc.ErJLPhjRDf1xIF.5gT6TuOtgC_VpfVaOG6x9k-1785241875.065511-1.0.1.1-.fhsy6vyfpTtPUdU3aGlabONJfG4JaAjwD9j0DJExA69bPcF1jbo20TnXWH9dLtxdxRPF.I.t24dIAB4hPpE8NrxXfyjOnmwC.JVdm9yg0cfGqthYQZ94kFLCemXupvF; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=aDb%2BJGHtTcXjgnOAOO60nuRS0TlHKrMlEMfSIQ7SgbJQAY1vR%2BAfTUBRUmQNnbeqQSs6ZCvNSBvEwz4bMizspf2Hxqb6VujzEvVpy3f2v8aiUzRgOfNwwbk%3D\"}]}"},"url":"https://jsr.io/@std/io/0.224.8/to_readable_stream.ts","time":1785241875}