// ets_tracing: off
import * as CS from "../../../../Cause";
import * as T from "../../../../Effect";
import * as E from "../../../../Either";
import { pipe } from "../../../../Function";
import * as M from "../../../../Managed";
import * as O from "../../../../Option";
import * as Q from "../../../../Queue";
import * as CH from "../../Channel";
import * as TK from "../../Take";
import * as C from "../core";
import { toEmit } from "./_internal/Emit";
/**
 * Creates a stream from an asynchronous callback that can be called multiple times
 * The registration of the callback itself returns an effect. The optionality of the
 * error type `E` can be used to signal the end of the stream, by setting it to `None`.
 */

export function asyncEffect(register, outputBuffer = 16) {
  return new C.Stream(CH.unwrapManaged(M.map_(M.tap_(M.bind_(M.bind_(M.do, "output", () => T.toManagedRelease_(Q.makeBounded(outputBuffer), Q.shutdown)), "runtime", () => M.runtime()), ({
    output,
    runtime
  }) => T.toManaged(register(toEmit(k => {
    try {
      runtime.run(T.chain_(TK.fromPull(k), _ => Q.offer_(output, _)));
    } catch (e) {
      if (CS.isFiberFailure(e)) {
        if (!CS.interrupted(e.cause)) {
          throw e;
        }
      }
    }
  })))), ({
    output
  }) => {
    const loop = CH.unwrap(T.foldCauseM_(T.chain_(Q.take(output), _ => TK.done(_)), maybeError => {
      return T.as_(Q.shutdown(output), E.fold_(CS.failureOrCause(maybeError), l => O.fold_(l, () => CH.end(undefined), failure => CH.fail(failure)), cause => CH.failCause(cause)));
    }, a => T.succeed(CH.zipRight_(CH.write(a), loop))));
    return loop;
  })));
}
//# sourceMappingURL=asyncEffect.js.map