// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

/**
 * Merge multiple streams into a single one, not taking order into account.
 * If a stream ends before other ones, the other will continue adding data,
 * and the finished one will not add any more data.
 *
 * @typeparam T The type of the chunks in the input/output streams.
 * @param streams An iterable of `ReadableStream`s to merge.
 * @returns A `ReadableStream` that will emit the merged chunks.
 *
 * @example Merge 2 streams
 * ```ts
 * import { mergeReadableStreams } from "@std/streams/merge-readable-streams";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const stream1 = ReadableStream.from([1, 2]);
 * const stream2 = ReadableStream.from([3, 4, 5]);
 *
 * const mergedStream = mergeReadableStreams(stream1, stream2);
 * const merged = await Array.fromAsync(mergedStream);
 * assertEquals(merged.toSorted(), [1, 2, 3, 4, 5]);
 * ```
 *
 * @example Merge 3 streams
 * ```ts
 * import { mergeReadableStreams } from "@std/streams/merge-readable-streams";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const stream1 = ReadableStream.from([1, 2]);
 * const stream2 = ReadableStream.from([3, 4, 5]);
 * const stream3 = ReadableStream.from([6]);
 *
 * const mergedStream = mergeReadableStreams(stream1, stream2, stream3);
 * const merged = await Array.fromAsync(mergedStream);
 * assertEquals(merged.toSorted(), [1, 2, 3, 4, 5, 6]);
 * ```
 */
export function mergeReadableStreams<T>(
  ...streams: ReadableStream<T>[]
): ReadableStream<T> {
  const resolvePromises = streams.map(() => Promise.withResolvers<void>());
  return new ReadableStream<T>({
    start(controller) {
      let mustClose = false;
      Promise.all(resolvePromises.map(({ promise }) => promise))
        .then(() => {
          controller.close();
        })
        .catch((error) => {
          mustClose = true;
          controller.error(error);
        });
      for (const [index, stream] of streams.entries()) {
        (async () => {
          try {
            for await (const data of stream) {
              if (mustClose) {
                break;
              }
              controller.enqueue(data);
            }
            resolvePromises[index]!.resolve();
          } catch (error) {
            resolvePromises[index]!.reject(error);
          }
        })();
      }
    },
  });
}

// denoCacheMetadata={"headers":{"alt-svc":"h3=\":443\"; ma=86400","access-control-allow-origin":"*","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';","content-type":"text/typescript","content-length":"2403","cf-ray":"a223e657dab87db6-LAX","etag":"\"a43a12bf3870632581adaab830543001\"","x-content-type-options":"nosniff","vary":"Origin","date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","access-control-expose-headers":"*","age":"112265","x-jsr-backend":"modules","cache-control":"public, max-age=31536000, immutable","set-cookie":"__cf_bm=XnUz9BnhfZAaKDJ8UaMvig0twgN9rOn1uTWqVK2bJgU-1785241875.1806555-1.0.1.1-APM10G4rFrQEP5FJzjxHG9HujQPKJAlZY8fAmHD4TZ3kltrtrdl6yOCJug5S3kAJ9ZIuadImhB6KgRbQ8I8rMTrIusB8GP7g8ej7JwZKVPttHO1tGiwQ4yo691k6U03j; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cf-cache-status":"HIT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=b%2BG6B9BP2iXK763i%2BSSrTk0CJ1mGAUd2AENnOIbyXue5TTxKALJzv7V3i9ELRqK%2BpmdX0N7mNi2jjIriekpwbxqxPOHHKhGOIIe4u6Q8%2Fwcc1gwherpOcuA%3D\"}]}","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","server":"cloudflare","x-robots-tag":"noindex","accept-ranges":"bytes"},"url":"https://jsr.io/@std/streams/0.224.5/merge_readable_streams.ts","time":1785241875}