


export function pipeStreamToHttpResponse(stream, response) {
  if (!stream?.pipe || !response?.once) {
    throw new TypeError("Wymagany jest czytelny strumień i odpowiedź HTTP.");
  }

  return new Promise((resolve, reject) => {
    let settled = false;

    const cleanup = () => {
      stream.off("error", onStreamError);
      response.off("error", onResponseError);
      response.off("finish", onFinish);
      response.off("close", onClose);
    };
    const settle = (error = null) => {
      if (settled) return;
      settled = true;
      cleanup();
      if (error) reject(error);
      else resolve();
    };
    const abortStream = () => {
      if (!stream.destroyed) stream.destroy();
    };
    const abortResponse = () => {
      if (!response.destroyed && !response.writableFinished) response.destroy();
    };
    const onStreamError = (error) => {
      abortResponse();
      settle(error);
    };
    const onResponseError = (error) => {
      abortStream();
      settle(error);
    };
    const onFinish = () => settle();
    const onClose = () => {
      if (settled) return;
      abortStream();
      const error = new Error("Klient przerwał pobieranie pliku.");
      error.code = "RESPONSE_ABORTED";
      settle(error);
    };

    stream.once("error", onStreamError);
    response.once("error", onResponseError);
    response.once("finish", onFinish);
    response.once("close", onClose);
    stream.pipe(response);
  });
}
