var _a, _b, _c;
import * as Duration from "@effect/data/Duration";
import * as Either from "@effect/data/Either";
import * as Equal from "@effect/data/Equal";
import { dual } from "@effect/data/Function";
import * as Hash from "@effect/data/Hash";
import * as MutableHashMap from "@effect/data/MutableHashMap";
import * as Option from "@effect/data/Option";
import { pipeArguments } from "@effect/data/Pipeable";
import * as Predicate from "@effect/data/Predicate";
import * as Exit from "@effect/io/Exit";
import * as FiberId from "@effect/io/Fiber/Id";
import * as internalCause from "@effect/io/internal/cause";
import * as core from "@effect/io/internal/core";
import * as effect from "@effect/io/internal/effect";
import * as executionStrategy from "@effect/io/internal/executionStrategy";
import * as internalFiber from "@effect/io/internal/fiber";
import * as fiberRuntime from "@effect/io/internal/fiberRuntime";
import { globalScope } from "@effect/io/internal/fiberScope";
import * as internalRef from "@effect/io/internal/ref";
import * as _schedule from "@effect/io/internal/schedule";
import * as supervisor from "@effect/io/internal/supervisor";
/** @internal */
class Semaphore {
  constructor(permits) {
    this.permits = permits;
    this.waiters = new Array();
    this.taken = 0;
    this.take = n => core.asyncEither(resume => {
      if (this.free < n) {
        const observer = () => {
          if (this.free >= n) {
            const observerIndex = this.waiters.findIndex(cb => cb === observer);
            if (observerIndex !== -1) {
              this.waiters.splice(observerIndex, 1);
            }
            this.taken += n;
            resume(core.succeed(n));
          }
        };
        this.waiters.push(observer);
        return Either.left(core.sync(() => {
          const observerIndex = this.waiters.findIndex(cb => cb === observer);
          if (observerIndex !== -1) {
            this.waiters.splice(observerIndex, 1);
          }
        }));
      }
      this.taken += n;
      return Either.right(core.succeed(n));
    });
    this.release = n => core.withFiberRuntime(fiber => {
      this.taken -= n;
      fiber.getFiberRef(core.currentScheduler).scheduleTask(() => {
        this.waiters.forEach(wake => wake());
      }, fiber.getFiberRef(core.currentSchedulingPriority));
      return core.unit;
    });
    this.withPermits = n => self => core.uninterruptibleMask(restore => core.flatMap(restore(this.take(n)), permits => fiberRuntime.ensuring(restore(self), this.release(permits))));
  }
  get free() {
    return this.permits - this.taken;
  }
}
/** @internal */
export const unsafeMakeSemaphore = leases => {
  return new Semaphore(leases);
};
/** @internal */
export const makeSemaphore = permits => core.sync(() => unsafeMakeSemaphore(permits));
/** @internal */
export const awaitAllChildren = self => ensuringChildren(self, fiberRuntime.fiberAwaitAll);
/** @internal */
export const cached = /*#__PURE__*/dual(2, (self, timeToLive) => core.map(cachedInvalidate(self, timeToLive), tuple => tuple[0]));
/** @internal */
export const cachedInvalidate = /*#__PURE__*/dual(2, (self, timeToLive) => {
  const duration = Duration.decode(timeToLive);
  return core.flatMap(core.context(), env => core.map(makeSynchronized(Option.none()), cache => [core.provideContext(getCachedValue(self, duration, cache), env), invalidateCache(cache)]));
});
/** @internal */
const computeCachedValue = (self, timeToLive, start) => {
  const timeToLiveMillis = Duration.toMillis(Duration.decode(timeToLive));
  return core.map(deferred => Option.some([start + timeToLiveMillis, deferred]))(core.tap(deferred => core.intoDeferred(self, deferred))(core.deferredMake()));
};
/** @internal */
const getCachedValue = (self, timeToLive, cache) => core.uninterruptibleMask(restore => core.flatMap(option => Option.isNone(option) ? core.dieMessage("BUG: Effect.cachedInvalidate - please report an issue at https://github.com/Effect-TS/io/issues") : restore(core.deferredAwait(option.value[1])))(core.flatMap(time => updateSomeAndGetEffectSynchronized(cache, option => {
  switch (option._tag) {
    case "None":
      {
        return Option.some(computeCachedValue(self, timeToLive, time));
      }
    case "Some":
      {
        const [end] = option.value;
        return end - time <= 0 ? Option.some(computeCachedValue(self, timeToLive, time)) : Option.none();
      }
  }
}))(effect.clockWith(clock => clock.currentTimeMillis))));
/** @internal */
const invalidateCache = cache => internalRef.set(cache, Option.none());
/** @internal */
export const ensuringChild = /*#__PURE__*/dual(2, (self, f) => ensuringChildren(self, children => f(fiberRuntime.fiberAll(children))));
/** @internal */
export const ensuringChildren = /*#__PURE__*/dual(2, (self, children) => core.flatMap(supervisor.track, supervisor => fiberRuntime.ensuring(core.flatMap(supervisor.value(), children))(supervised(self, supervisor))));
/** @internal */
// @ts-expect-error
export const forkAll = /*#__PURE__*/dual(args => Predicate.isIterable(args[0]), (effects, options) => options?.discard ? core.forEachSequentialDiscard(effects, fiberRuntime.fork) : core.map(core.forEachSequential(effects, fiberRuntime.fork), fiberRuntime.fiberAll));
/** @internal */
export const forkIn = /*#__PURE__*/dual(2, (self, scope) => core.uninterruptibleMask(restore => core.flatMap(scope.fork(executionStrategy.sequential), child => core.tap(fiber => child.addFinalizer(() => core.fiberIdWith(fiberId => Equal.equals(fiberId, fiber.id()) ? core.unit : core.asUnit(core.interruptFiber(fiber)))))(fiberRuntime.forkDaemon(core.onExit(exit => child.close(exit))(restore(self)))))));
/** @internal */
export const forkScoped = self => fiberRuntime.scopeWith(scope => forkIn(self, scope));
/** @internal */
export const fromFiber = fiber => internalFiber.join(fiber);
/** @internal */
export const fromFiberEffect = fiber => core.suspend(() => core.flatMap(fiber, internalFiber.join));
const memoKeySymbol = /*#__PURE__*/Symbol.for("@effect/io/Effect/memoizeFunction.key");
class Key {
  constructor(a, eq) {
    this.a = a;
    this.eq = eq;
    this[_a] = memoKeySymbol;
  }
  [(_a = memoKeySymbol, Equal.symbol)](that) {
    if (typeof that === "object" && that !== null && memoKeySymbol in that) {
      if (this.eq) {
        return this.eq(this.a, that.a);
      } else {
        return Equal.equals(this.a, that.a);
      }
    }
    return false;
  }
  [Hash.symbol]() {
    return this.eq ? 0 : Hash.hash(this.a);
  }
}
/** @internal */
export const memoizeFunction = (f, eq) => {
  return core.map(ref => a => core.flatMap(([patch, b]) => core.as(b)(effect.patchFiberRefs(patch)))(core.flatMap(core.deferredAwait)(ref.modifyEffect(map => {
    const result = MutableHashMap.get(new Key(a, eq))(map);
    if (Option.isNone(result)) {
      return core.map(deferred => [deferred, MutableHashMap.set(new Key(a, eq), deferred)(map)])(core.tap(deferred => fiberRuntime.fork(core.intoDeferred(deferred)(effect.diffFiberRefs(f(a)))))(core.deferredMake()));
    }
    return core.succeed([result.value, map]);
  }))))(core.flatMap(makeSynchronized)(core.sync(() => MutableHashMap.empty())));
};
/** @internal */
export const raceFirst = /*#__PURE__*/dual(2, (self, that) => (effect => core.flatten(effect))(fiberRuntime.race(core.exit(that))(core.exit(self))));
/** @internal */
export const scheduleForked = /*#__PURE__*/dual(2, (self, schedule) => forkScoped(_schedule.schedule_Effect(schedule)(self)));
/** @internal */
export const supervised = /*#__PURE__*/dual(2, (self, supervisor) => {
  const supervise = core.fiberRefLocallyWith(fiberRuntime.currentSupervisor, s => s.zip(supervisor));
  return supervise(self);
});
/** @internal */
export const timeout = /*#__PURE__*/dual(2, (self, duration) => timeoutTo(self, {
  onTimeout: Option.none,
  onSuccess: Option.some,
  duration
}));
/** @internal */
export const timeoutFail = /*#__PURE__*/dual(2, (self, {
  duration,
  onTimeout
}) => core.flatten(timeoutTo(self, {
  onTimeout: () => core.failSync(onTimeout),
  onSuccess: core.succeed,
  duration
})));
/** @internal */
export const timeoutFailCause = /*#__PURE__*/dual(2, (self, {
  duration,
  onTimeout
}) => core.flatten(timeoutTo(self, {
  onTimeout: () => core.failCauseSync(onTimeout),
  onSuccess: core.succeed,
  duration
})));
/** @internal */
export const timeoutTo = /*#__PURE__*/dual(2, (self, {
  duration,
  onSuccess,
  onTimeout
}) => core.fiberIdWith(parentFiberId => fiberRuntime.raceFibersWith(self, core.interruptible(effect.sleep(duration)), {
  onSelfWin: (winner, loser) => core.flatMap(winner.await(), exit => {
    if (exit._tag === "Success") {
      return core.flatMap(winner.inheritAll(), () => core.as(core.interruptAsFiber(loser, parentFiberId), onSuccess(exit.value)));
    } else {
      return core.flatMap(core.interruptAsFiber(loser, parentFiberId), () => core.exitFailCause(exit.cause));
    }
  }),
  onOtherWin: (winner, loser) => core.flatMap(winner.await(), exit => {
    if (exit._tag === "Success") {
      return core.flatMap(winner.inheritAll(), () => core.as(core.interruptAsFiber(loser, parentFiberId), onTimeout()));
    } else {
      return core.flatMap(core.interruptAsFiber(loser, parentFiberId), () => core.exitFailCause(exit.cause));
    }
  }),
  otherScope: globalScope
})));
// circular with Synchronized
/** @internal */
const SynchronizedSymbolKey = "@effect/io/Ref/Synchronized";
/** @internal */
export const SynchronizedTypeId = /*#__PURE__*/Symbol.for(SynchronizedSymbolKey);
/** @internal */
export const synchronizedVariance = {
  _A: _ => _
};
/** @internal */
class SynchronizedImpl {
  constructor(ref, withLock) {
    this.ref = ref;
    this.withLock = withLock;
    this[_b] = synchronizedVariance;
    this[_c] = internalRef.refVariance;
  }
  modify(f) {
    return this.modifyEffect(a => core.succeed(f(a)));
  }
  modifyEffect(f) {
    return this.withLock(core.flatMap(([b, a]) => core.as(internalRef.set(this.ref, a), b))(core.flatMap(internalRef.get(this.ref), f)));
  }
  pipe() {
    return pipeArguments(this, arguments);
  }
}
_b = SynchronizedTypeId, _c = internalRef.RefTypeId;
/** @internal */
export const makeSynchronized = value => core.sync(() => unsafeMakeSynchronized(value));
/** @internal */
export const unsafeMakeSynchronized = value => {
  const ref = internalRef.unsafeMake(value);
  const sem = unsafeMakeSemaphore(1);
  return new SynchronizedImpl(ref, sem.withPermits(1));
};
/** @internal */
export const updateSomeAndGetEffectSynchronized = /*#__PURE__*/dual(2, (self, pf) => self.modifyEffect(value => {
  const result = pf(value);
  switch (result._tag) {
    case "None":
      {
        return core.succeed([value, value]);
      }
    case "Some":
      {
        return core.map(result.value, a => [a, a]);
      }
  }
}));
// circular with Fiber
/** @internal */
export const zipFiber = /*#__PURE__*/dual(2, (self, that) => zipWithFiber(self, that, (a, b) => [a, b]));
/** @internal */
export const zipLeftFiber = /*#__PURE__*/dual(2, (self, that) => zipWithFiber(self, that, (a, _) => a));
/** @internal */
export const zipRightFiber = /*#__PURE__*/dual(2, (self, that) => zipWithFiber(self, that, (_, b) => b));
/** @internal */
export const zipWithFiber = /*#__PURE__*/dual(3, (self, that, f) => ({
  [internalFiber.FiberTypeId]: internalFiber.fiberVariance,
  id: () => FiberId.getOrElse(that.id())(self.id()),
  await: () => core.exit(fiberRuntime.zipWithOptions(core.flatten(that.await()), f, {
    concurrent: true
  })(core.flatten(self.await()))),
  children: () => self.children(),
  inheritAll: () => core.zipRight(that.inheritAll(), self.inheritAll()),
  poll: () => core.zipWith(self.poll(), that.poll(), (optionA, optionB) => Option.flatMap(exitA => Option.map(exitB => Exit.zipWith(exitA, exitB, {
    onSuccess: f,
    onFailure: internalCause.parallel
  }))(optionB))(optionA)),
  interruptAsFork: id => core.zipRight(self.interruptAsFork(id), that.interruptAsFork(id)),
  pipe() {
    return pipeArguments(this, arguments);
  }
}));
//# sourceMappingURL=circular.mjs.map