"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.exitZipWith = exports.exitZipRight = exports.exitZipParRight = exports.exitZipParLeft = exports.exitZipPar = exports.exitZipLeft = exports.exitZip = exports.exitUnit = exports.exitUnannotate = exports.exitSucceed = exports.exitMatchEffect = exports.exitMatch = exports.exitMapErrorCause = exports.exitMapError = exports.exitMapBoth = exports.exitMap = exports.exitIsSuccess = exports.exitIsInterrupted = exports.exitIsFailure = exports.exitIsExit = exports.exitInterrupt = exports.exitGetOrElse = exports.exitFromOption = exports.exitFromEither = exports.exitForEachEffect = exports.exitFlatten = exports.exitFlatMapEffect = exports.exitFlatMap = exports.exitFailCause = exports.exitFail = exports.exitExists = exports.exitDie = exports.exitCollectAll = exports.exitCauseOption = exports.exitAsUnit = exports.exitAs = exports.exit = exports.either = exports.dieSync = exports.dieMessage = exports.die = exports.deferredUnsafeMake = exports.deferredUnsafeDone = exports.deferredSync = exports.deferredSucceed = exports.deferredPoll = exports.deferredMakeAs = exports.deferredMake = exports.deferredIsDone = exports.deferredInterruptWith = exports.deferredInterrupt = exports.deferredFailSync = exports.deferredFailCauseSync = exports.deferredFailCause = exports.deferredFail = exports.deferredDone = exports.deferredDieSync = exports.deferredDie = exports.deferredCompleteWith = exports.deferredComplete = exports.deferredAwait = exports.currentUnhandledErrorLogLevel = exports.currentTracerTimingEnabled = exports.currentTracerSpanLinks = exports.currentTracerSpanAnnotations = exports.currentTracerSpan = exports.currentSchedulingPriority = exports.currentScheduler = exports.currentRequestBatching = exports.currentMetricLabels = exports.currentMaxFiberOps = exports.currentLogSpan = exports.currentLogLevel = exports.currentLogAnnotations = exports.currentInterruptedCause = exports.currentForkScopeOverride = exports.currentContext = exports.currentConcurrency = exports.contextWithEffect = exports.context = exports.checkInterruptible = exports.catchSome = exports.catchAllCause = exports.catchAll = exports.blocked = exports.attemptOrElse = exports.asyncEither = exports.async = exports.asUnit = exports.as = exports.allLogLevels = exports.acquireUseRelease = exports.ScopeTypeId = exports.RevertFlags = exports.RequestResolverTypeId = exports.RequestResolverImpl = exports.FiberRefTypeId = exports.EffectTypeId = exports.EffectErrorTypeId = exports.CloseableScopeTypeId = void 0;
exports.withConcurrency = exports.whileLoop = exports.whenEffect = exports.updateRuntimeFlags = exports.unit = exports.uninterruptibleMask = exports.uninterruptible = exports.unified = exports.transplant = exports.tap = exports.sync = exports.suspend = exports.succeed = exports.step = exports.scopeFork = exports.scopeClose = exports.scopeAddFinalizerExit = exports.scopeAddFinalizer = exports.runtimeFlags = exports.runRequestBlock = exports.resolverLocally = exports.requestBlockLocally = exports.releaseMapReplace = exports.releaseMapRemove = exports.releaseMapRelease = exports.releaseMapMake = exports.releaseMapGet = exports.releaseMapAddIfOpen = exports.releaseMapAdd = exports.provideSomeContext = exports.provideContext = exports.partitionMap = exports.orElse = exports.orDieWith = exports.orDie = exports.onInterrupt = exports.onExit = exports.onError = exports.never = exports.metricLabels = exports.matchEffect = exports.matchCauseEffect = exports.matchCause = exports.mapInputContext = exports.mapError = exports.mapBoth = exports.map = exports.makeEffectError = exports.logLevelWarning = exports.logLevelTrace = exports.logLevelNone = exports.logLevelInfo = exports.logLevelFatal = exports.logLevelError = exports.logLevelDebug = exports.logLevelAll = exports.isRequestResolver = exports.isEffectError = exports.isEffect = exports.intoDeferred = exports.interruptibleMask = exports.interruptible = exports.interruptWith = exports.interruptFiber = exports.interruptAsFiber = exports.interrupt = exports.if_ = exports.forEachSequentialDiscard = exports.forEachSequential = exports.flip = exports.flatten = exports.flatMapStep = exports.flatMap = exports.fiberRefUpdateSomeAndGet = exports.fiberRefUpdateSome = exports.fiberRefUpdateAndGet = exports.fiberRefUpdate = exports.fiberRefUnsafeMakeRuntimeFlags = exports.fiberRefUnsafeMakePatch = exports.fiberRefUnsafeMakeHashSet = exports.fiberRefUnsafeMakeContext = exports.fiberRefUnsafeMake = exports.fiberRefSet = exports.fiberRefReset = exports.fiberRefModifySome = exports.fiberRefModify = exports.fiberRefLocallyWith = exports.fiberRefLocally = exports.fiberRefGetWith = exports.fiberRefGetAndUpdateSome = exports.fiberRefGetAndUpdate = exports.fiberRefGetAndSet = exports.fiberRefGet = exports.fiberRefDelete = exports.fiberIdWith = exports.fiberId = exports.failSync = exports.failCauseSync = exports.failCause = exports.fail = void 0;
exports.zipWith = exports.zipRight = exports.zipLeft = exports.zipFlatten = exports.zip = exports.yieldNow = exports.withUnhandledErrorLogLevel = exports.withTracerTiming = exports.withSchedulingPriority = exports.withScheduler = exports.withRuntimeFlags = exports.withRequestBatching = exports.withMaxFiberOps = exports.withFiberRuntime = void 0;
var Chunk = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Chunk"));
var Context = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Context"));
var Differ = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Differ"));
var ContextPatch = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Differ/ContextPatch"));
var HashSetPatch = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Differ/HashSetPatch"));
var Either = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Either"));
var Equal = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Equal"));
var _Function = /*#__PURE__*/require("@effect/data/Function");
var _Global = /*#__PURE__*/require("@effect/data/Global");
var Hash = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Hash"));
var HashMap = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/HashMap"));
var HashSet = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/HashSet"));
var List = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/List"));
var MutableRef = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/MutableRef"));
var Option = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Option"));
var _Pipeable = /*#__PURE__*/require("@effect/data/Pipeable");
var ReadonlyArray = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/ReadonlyArray"));
var Cause = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Cause"));
var FiberId = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Fiber/Id"));
var RuntimeFlagsPatch = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Fiber/Runtime/Flags/Patch"));
var _blockedRequests = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/blockedRequests"));
var internalCause = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/cause"));
var deferred = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/deferred"));
var DeferredOpCodes = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/opCodes/deferred"));
var OpCodes = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/opCodes/effect"));
var _runtimeFlags = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/runtimeFlags"));
var scheduler = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Scheduler"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _a, _b, _c, _d;
// -----------------------------------------------------------------------------
// Effect
// -----------------------------------------------------------------------------
/** @internal */
const EffectErrorSymbolKey = "@effect/io/Effect/Error";
/** @internal */
const EffectErrorTypeId = /*#__PURE__*/Symbol.for(EffectErrorSymbolKey);
/** @internal */
exports.EffectErrorTypeId = EffectErrorTypeId;
const isEffectError = u => typeof u === "object" && u != null && EffectErrorTypeId in u;
/** @internal */
exports.isEffectError = isEffectError;
const makeEffectError = cause => ({
  [EffectErrorTypeId]: EffectErrorTypeId,
  _tag: "EffectError",
  cause
});
/**
 * @internal
 */
exports.makeEffectError = makeEffectError;
const blocked = (blockedRequests, _continue) => {
  const effect = new EffectPrimitive("Blocked");
  effect.i0 = blockedRequests;
  effect.i1 = _continue;
  return effect;
};
/**
 * @internal
 */
exports.blocked = blocked;
const runRequestBlock = blockedRequests => {
  const effect = new EffectPrimitive("RunBlocked");
  effect.i0 = blockedRequests;
  return effect;
};
/** @internal */
exports.runRequestBlock = runRequestBlock;
const EffectTypeId = /*#__PURE__*/Symbol.for("@effect/io/Effect");
/** @internal */
exports.EffectTypeId = EffectTypeId;
class RevertFlags {
  constructor(patch, op) {
    this.patch = patch;
    this.op = op;
    this._tag = OpCodes.OP_REVERT_FLAGS;
  }
}
/** @internal */
exports.RevertFlags = RevertFlags;
class EffectPrimitive {
  constructor(_tag) {
    this._tag = _tag;
    this.i0 = undefined;
    this.i1 = undefined;
    this.i2 = undefined;
    this.trace = undefined;
    this[_a] = effectVariance;
  }
  [(_a = EffectTypeId, Equal.symbol)](that) {
    return this === that;
  }
  [Hash.symbol]() {
    return Hash.random(this);
  }
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
}
/** @internal */
class EffectPrimitiveFailure {
  constructor(_tag) {
    this._tag = _tag;
    this.i0 = undefined;
    this.i1 = undefined;
    this.i2 = undefined;
    this.trace = undefined;
    this[_b] = effectVariance;
  }
  [(_b = EffectTypeId, Equal.symbol)](that) {
    return this === that;
  }
  [Hash.symbol]() {
    return Hash.random(this);
  }
  get cause() {
    return this.i0;
  }
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
  toJSON() {
    return {
      _tag: this._tag,
      cause: this.cause.toJSON()
    };
  }
  toString() {
    return Cause.pretty(this.cause);
  }
  [Symbol.for("nodejs.util.inspect.custom")]() {
    return this.toJSON();
  }
}
/** @internal */
class EffectPrimitiveSuccess {
  constructor(_tag) {
    this._tag = _tag;
    this.i0 = undefined;
    this.i1 = undefined;
    this.i2 = undefined;
    this.trace = undefined;
    this[_c] = effectVariance;
  }
  [(_c = EffectTypeId, Equal.symbol)](that) {
    return this === that;
  }
  [Hash.symbol]() {
    return Hash.random(this);
  }
  get value() {
    return this.i0;
  }
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
  toJSON() {
    return {
      _tag: this._tag,
      value: this.value
    };
  }
  toString() {
    return `Success: ${String(this.value)}`;
  }
  [Symbol.for("nodejs.util.inspect.custom")]() {
    return this.toJSON();
  }
}
/** @internal */
const effectVariance = {
  _R: _ => _,
  _E: _ => _,
  _A: _ => _
};
/** @internal */
const isEffect = u => typeof u === "object" && u != null && EffectTypeId in u;
/* @internal */
exports.isEffect = isEffect;
const withFiberRuntime = withRuntime => {
  const effect = new EffectPrimitive(OpCodes.OP_WITH_RUNTIME);
  effect.i0 = withRuntime;
  return effect;
};
/* @internal */
exports.withFiberRuntime = withFiberRuntime;
const acquireUseRelease = /*#__PURE__*/(0, _Function.dual)(3, (acquire, use, release) => uninterruptibleMask(restore => flatMap(acquire, a => flatMap(exit(suspend(() => restore(use(a)))), exit => suspend(() => release(a, exit)).pipe(matchCauseEffect({
  onFailure: cause => {
    switch (exit._tag) {
      case OpCodes.OP_FAILURE:
        {
          return failCause(internalCause.parallel(exit.i0, cause));
        }
      case OpCodes.OP_SUCCESS:
        {
          return failCause(cause);
        }
    }
  },
  onSuccess: () => exit
}))))));
/* @internal */
exports.acquireUseRelease = acquireUseRelease;
const as = /*#__PURE__*/(0, _Function.dual)(2, (self, value) => flatMap(self, () => succeed(value)));
/* @internal */
exports.as = as;
const asUnit = self => as(self, void 0);
/* @internal */
exports.asUnit = asUnit;
const async = (register, blockingOn = FiberId.none) => suspend(() => {
  let cancelerRef = undefined;
  let controllerRef = undefined;
  const effect = new EffectPrimitive(OpCodes.OP_ASYNC);
  if (register.length !== 1) {
    const controller = new AbortController();
    controllerRef = controller;
    effect.i0 = resume => {
      cancelerRef = register(resume, controller.signal);
    };
  } else {
    effect.i0 = resume => {
      // @ts-expect-error
      cancelerRef = register(resume);
    };
  }
  effect.i1 = blockingOn;
  return onInterrupt(effect, () => {
    if (controllerRef) {
      controllerRef.abort();
    }
    return cancelerRef ?? unit;
  });
});
/* @internal */
exports.async = async;
const asyncEither = (register, blockingOn = FiberId.none) => async(resume => {
  const result = register(resume);
  if (Either.isRight(result)) {
    resume(result.right);
  } else {
    return result.left;
  }
}, blockingOn);
/* @internal */
exports.asyncEither = asyncEither;
const catchAllCause = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  const effect = new EffectPrimitive(OpCodes.OP_ON_FAILURE);
  effect.i0 = self;
  effect.i1 = f;
  return effect;
});
/* @internal */
exports.catchAllCause = catchAllCause;
const catchAll = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => matchEffect(self, {
  onFailure: f,
  onSuccess: succeed
}));
/**
 * @macro identity
 * @internal
 */
exports.catchAll = catchAll;
const unified = f => (...args) => f(...args);
/* @internal */
exports.unified = unified;
const catchSome = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => matchCauseEffect(self, {
  onFailure: unified(cause => {
    const either = internalCause.failureOrCause(cause);
    switch (either._tag) {
      case "Left":
        {
          return Option.getOrElse(() => failCause(cause))(pf(either.left));
        }
      case "Right":
        {
          return failCause(either.right);
        }
    }
  }),
  onSuccess: succeed
}));
/* @internal */
exports.catchSome = catchSome;
const checkInterruptible = f => withFiberRuntime((_, status) => f(_runtimeFlags.interruption(status.runtimeFlags)));
/* @internal */
exports.checkInterruptible = checkInterruptible;
const die = defect => failCause(internalCause.die(defect));
/* @internal */
exports.die = die;
const dieMessage = message => failCauseSync(() => internalCause.die(internalCause.RuntimeException(message)));
/* @internal */
exports.dieMessage = dieMessage;
const dieSync = evaluate => failCauseSync(() => internalCause.die(evaluate()));
/* @internal */
exports.dieSync = dieSync;
const either = self => matchEffect(self, {
  onFailure: e => succeed(Either.left(e)),
  onSuccess: a => succeed(Either.right(a))
});
/* @internal */
exports.either = either;
const context = () => suspend(() => fiberRefGet(currentContext));
/* @internal */
exports.context = context;
const contextWithEffect = f => flatMap(context(), f);
/* @internal */
exports.contextWithEffect = contextWithEffect;
const exit = self => matchCause(self, {
  onFailure: exitFailCause,
  onSuccess: exitSucceed
});
/* @internal */
exports.exit = exit;
const fail = error => failCause(internalCause.fail(error));
/* @internal */
exports.fail = fail;
const failSync = evaluate => failCauseSync(() => internalCause.fail(evaluate()));
/* @internal */
exports.failSync = failSync;
const failCause = cause => {
  const effect = new EffectPrimitiveFailure(OpCodes.OP_FAILURE);
  effect.i0 = cause;
  return effect;
};
/* @internal */
exports.failCause = failCause;
const failCauseSync = evaluate => flatMap(sync(evaluate), failCause);
/* @internal */
exports.failCauseSync = failCauseSync;
const fiberId = /*#__PURE__*/withFiberRuntime(state => succeed(state.id()));
/* @internal */
exports.fiberId = fiberId;
const fiberIdWith = f => withFiberRuntime(state => f(state.id()));
/* @internal */
exports.fiberIdWith = fiberIdWith;
const flatMap = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  const effect = new EffectPrimitive(OpCodes.OP_ON_SUCCESS);
  effect.i0 = self;
  effect.i1 = f;
  return effect;
});
/* @internal */
exports.flatMap = flatMap;
const step = self => {
  const effect = new EffectPrimitive("OnStep");
  effect.i0 = self;
  effect.i1 = exitSucceed;
  return effect;
};
/* @internal */
exports.step = step;
const flatMapStep = (self, f) => {
  const effect = new EffectPrimitive("OnStep");
  effect.i0 = self;
  effect.i1 = f;
  return effect;
};
/* @internal */
exports.flatMapStep = flatMapStep;
const flatten = self => flatMap(self, _Function.identity);
/* @internal */
exports.flatten = flatten;
const flip = self => matchEffect(self, {
  onFailure: succeed,
  onSuccess: fail
});
/* @internal */
exports.flip = flip;
const matchCause = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => matchCauseEffect(self, {
  onFailure: cause => succeed(onFailure(cause)),
  onSuccess: a => succeed(onSuccess(a))
}));
/* @internal */
exports.matchCause = matchCause;
const matchCauseEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => {
  const effect = new EffectPrimitive(OpCodes.OP_ON_SUCCESS_AND_FAILURE);
  effect.i0 = self;
  effect.i1 = onFailure;
  effect.i2 = onSuccess;
  return effect;
});
/* @internal */
exports.matchCauseEffect = matchCauseEffect;
const matchEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => matchCauseEffect(self, {
  onFailure: cause => {
    const failures = internalCause.failures(cause);
    const defects = internalCause.defects(cause);
    if (defects.length > 0) {
      return failCause(internalCause.electFailures(cause));
    }
    if (failures.length > 0) {
      return onFailure(Chunk.unsafeHead(failures));
    }
    return failCause(cause);
  },
  onSuccess
}));
/* @internal */
exports.matchEffect = matchEffect;
const forEachSequential = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => suspend(() => {
  const arr = ReadonlyArray.fromIterable(self);
  const ret = new Array(arr.length);
  let i = 0;
  return as(whileLoop({
    while: () => i < arr.length,
    body: () => f(arr[i], i),
    step: b => {
      ret[i++] = b;
    }
  }), ret);
}));
/* @internal */
exports.forEachSequential = forEachSequential;
const forEachSequentialDiscard = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => suspend(() => {
  const arr = ReadonlyArray.fromIterable(self);
  let i = 0;
  return whileLoop({
    while: () => i < arr.length,
    body: () => f(arr[i], i),
    step: () => {
      i++;
    }
  });
}));
/* @internal */
exports.forEachSequentialDiscard = forEachSequentialDiscard;
const if_ = /*#__PURE__*/(0, _Function.dual)(args => typeof args[0] === "boolean" || isEffect(args[0]), (self, {
  onFalse,
  onTrue
}) => typeof self === "boolean" ? self ? onTrue : onFalse : flatMap(self, unified(b => b ? onTrue : onFalse)));
/* @internal */
exports.if_ = if_;
const interrupt = /*#__PURE__*/flatMap(fiberId, fiberId => interruptWith(fiberId));
/* @internal */
exports.interrupt = interrupt;
const interruptWith = fiberId => failCause(internalCause.interrupt(fiberId));
/* @internal */
exports.interruptWith = interruptWith;
const interruptible = self => {
  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS);
  effect.i0 = RuntimeFlagsPatch.enable(_runtimeFlags.Interruption);
  const _continue = orBlock => {
    if (orBlock._tag === "Blocked") {
      return blocked(orBlock.i0, interruptible(orBlock.i1));
    } else {
      return orBlock;
    }
  };
  effect.i1 = () => flatMapStep(self, _continue);
  return effect;
};
/* @internal */
exports.interruptible = interruptible;
const interruptibleMask = f => {
  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS);
  effect.i0 = RuntimeFlagsPatch.enable(_runtimeFlags.Interruption);
  const _continue = step => {
    if (step._tag === "Blocked") {
      return blocked(step.i0, interruptible(step.i1));
    }
    return step;
  };
  effect.i1 = oldFlags => _runtimeFlags.interruption(oldFlags) ? step(f(interruptible)) : step(f(uninterruptible));
  return flatMap(effect, _continue);
};
/* @internal */
exports.interruptibleMask = interruptibleMask;
const intoDeferred = /*#__PURE__*/(0, _Function.dual)(2, (self, deferred) => uninterruptibleMask(restore => flatMap(exit(restore(self)), exit => deferredDone(deferred, exit))));
/* @internal */
exports.intoDeferred = intoDeferred;
const map = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => flatMap(self, a => sync(() => f(a))));
/* @internal */
exports.map = map;
const mapBoth = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => matchEffect(self, {
  onFailure: e => failSync(() => onFailure(e)),
  onSuccess: a => sync(() => onSuccess(a))
}));
/* @internal */
exports.mapBoth = mapBoth;
const mapError = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => matchCauseEffect(self, {
  onFailure: cause => {
    const either = internalCause.failureOrCause(cause);
    switch (either._tag) {
      case "Left":
        {
          return failSync(() => f(either.left));
        }
      case "Right":
        {
          return failCause(either.right);
        }
    }
  },
  onSuccess: succeed
}));
/* @internal */
exports.mapError = mapError;
const onError = /*#__PURE__*/(0, _Function.dual)(2, (self, cleanup) => onExit(self, unified(exit => exitIsSuccess(exit) ? unit : cleanup(exit.i0))));
/* @internal */
exports.onError = onError;
const onExit = /*#__PURE__*/(0, _Function.dual)(2, (self, cleanup) => uninterruptibleMask(restore => matchCauseEffect(restore(self), {
  onFailure: cause1 => {
    const result = exitFailCause(cause1);
    return matchCauseEffect(cleanup(result), {
      onFailure: cause2 => exitFailCause(internalCause.sequential(cause1, cause2)),
      onSuccess: () => result
    });
  },
  onSuccess: success => {
    const result = exitSucceed(success);
    return zipRight(cleanup(result), result);
  }
})));
/* @internal */
exports.onExit = onExit;
const onInterrupt = /*#__PURE__*/(0, _Function.dual)(2, (self, cleanup) => onExit(self, exitMatch({
  onFailure: cause => internalCause.isInterruptedOnly(cause) ? asUnit(cleanup(internalCause.interruptors(cause))) : unit,
  onSuccess: () => unit
})));
/* @internal */
exports.onInterrupt = onInterrupt;
const orElse = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => attemptOrElse(self, that, succeed));
/* @internal */
exports.orElse = orElse;
const orDie = self => orDieWith(self, _Function.identity);
/* @internal */
exports.orDie = orDie;
const orDieWith = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => matchEffect(self, {
  onFailure: e => die(f(e)),
  onSuccess: succeed
}));
/* @internal */
exports.orDieWith = orDieWith;
const partitionMap = (elements, f) => ReadonlyArray.fromIterable(elements).reduceRight(([lefts, rights], current) => {
  const either = f(current);
  switch (either._tag) {
    case "Left":
      {
        return [[either.left, ...lefts], rights];
      }
    case "Right":
      {
        return [lefts, [either.right, ...rights]];
      }
  }
}, [new Array(), new Array()]);
/* @internal */
exports.partitionMap = partitionMap;
const provideContext = /*#__PURE__*/(0, _Function.dual)(2, (self, context) => fiberRefLocally(currentContext, context)(self));
/* @internal */
exports.provideContext = provideContext;
const provideSomeContext = /*#__PURE__*/(0, _Function.dual)(2, (self, context) => fiberRefLocallyWith(currentContext, parent => Context.merge(parent, context))(self));
/* @internal */
exports.provideSomeContext = provideSomeContext;
const mapInputContext = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => contextWithEffect(context => provideContext(self, f(context))));
/* @internal */
exports.mapInputContext = mapInputContext;
const runtimeFlags = /*#__PURE__*/withFiberRuntime((_, status) => succeed(status.runtimeFlags));
/* @internal */
exports.runtimeFlags = runtimeFlags;
const succeed = value => {
  const effect = new EffectPrimitiveSuccess(OpCodes.OP_SUCCESS);
  effect.i0 = value;
  return effect;
};
/* @internal */
exports.succeed = succeed;
const suspend = effect => flatMap(sync(effect), _Function.identity);
/* @internal */
exports.suspend = suspend;
const sync = evaluate => {
  const effect = new EffectPrimitive(OpCodes.OP_SYNC);
  effect.i0 = evaluate;
  return effect;
};
/* @internal */
exports.sync = sync;
const tap = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => flatMap(self, a => as(f(a), a)));
/* @internal */
exports.tap = tap;
const transplant = f => withFiberRuntime(state => {
  const scopeOverride = state.getFiberRef(currentForkScopeOverride);
  const scope = Option.getOrElse(() => state.scope())(scopeOverride);
  return f(fiberRefLocally(currentForkScopeOverride, Option.some(scope)));
});
/* @internal */
exports.transplant = transplant;
const attemptOrElse = /*#__PURE__*/(0, _Function.dual)(3, (self, that, onSuccess) => matchCauseEffect(self, {
  onFailure: cause => {
    const defects = internalCause.defects(cause);
    if (defects.length > 0) {
      return failCause(Option.getOrThrow(internalCause.keepDefectsAndElectFailures(cause)));
    }
    return that();
  },
  onSuccess
}));
/* @internal */
exports.attemptOrElse = attemptOrElse;
const uninterruptible = self => {
  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS);
  effect.i0 = RuntimeFlagsPatch.disable(_runtimeFlags.Interruption);
  effect.i1 = () => flatMapStep(self, _continue);
  const _continue = orBlock => {
    if (orBlock._tag === "Blocked") {
      return blocked(orBlock.i0, uninterruptible(orBlock.i1));
    } else {
      return orBlock;
    }
  };
  return effect;
};
/* @internal */
exports.uninterruptible = uninterruptible;
const uninterruptibleMask = f => {
  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS);
  effect.i0 = RuntimeFlagsPatch.disable(_runtimeFlags.Interruption);
  const _continue = step => {
    if (step._tag === "Blocked") {
      return blocked(step.i0, uninterruptible(step.i1));
    }
    return step;
  };
  effect.i1 = oldFlags => _runtimeFlags.interruption(oldFlags) ? step(f(interruptible)) : step(f(uninterruptible));
  return flatMap(effect, _continue);
};
/* @internal */
exports.uninterruptibleMask = uninterruptibleMask;
const unit = /*#__PURE__*/succeed(void 0);
/* @internal */
exports.unit = unit;
const updateRuntimeFlags = patch => {
  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS);
  effect.i0 = patch;
  effect.i1 = void 0;
  return effect;
};
/* @internal */
exports.updateRuntimeFlags = updateRuntimeFlags;
const whenEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => flatMap(predicate, b => {
  if (b) {
    return map(Option.some)(self);
  }
  return succeed(Option.none());
}));
/* @internal */
exports.whenEffect = whenEffect;
const whileLoop = options => {
  const effect = new EffectPrimitive(OpCodes.OP_WHILE);
  effect.i0 = options.while;
  effect.i1 = options.body;
  effect.i2 = options.step;
  return effect;
};
/* @internal */
exports.whileLoop = whileLoop;
const withConcurrency = /*#__PURE__*/(0, _Function.dual)(2, (self, concurrency) => fiberRefLocally(self, currentConcurrency, concurrency));
/* @internal */
exports.withConcurrency = withConcurrency;
const withRequestBatching = /*#__PURE__*/(0, _Function.dual)(2, (self, requestBatching) => fiberRefLocally(self, currentRequestBatching, requestBatching));
/* @internal */
exports.withRequestBatching = withRequestBatching;
const withRuntimeFlags = /*#__PURE__*/(0, _Function.dual)(2, (self, update) => {
  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS);
  effect.i0 = update;
  effect.i1 = () => self;
  return effect;
});
/** @internal */
exports.withRuntimeFlags = withRuntimeFlags;
const withTracerTiming = /*#__PURE__*/(0, _Function.dual)(2, (effect, enabled) => fiberRefLocally(effect, currentTracerTimingEnabled, enabled));
/* @internal */
exports.withTracerTiming = withTracerTiming;
const yieldNow = options => {
  const effect = new EffectPrimitive(OpCodes.OP_YIELD);
  return typeof options?.priority !== "undefined" ? withSchedulingPriority(options.priority)(effect) : effect;
};
/* @internal */
exports.yieldNow = yieldNow;
const zip = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => flatMap(self, a => map(that, b => [a, b])));
/* @internal */
exports.zip = zip;
const zipFlatten = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => flatMap(self, a => map(that, b => [...a, b])));
/* @internal */
exports.zipFlatten = zipFlatten;
const zipLeft = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => flatMap(self, a => as(that, a)));
/* @internal */
exports.zipLeft = zipLeft;
const zipRight = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => flatMap(self, () => that));
/* @internal */
exports.zipRight = zipRight;
const zipWith = /*#__PURE__*/(0, _Function.dual)(3, (self, that, f) => flatMap(self, a => map(that, b => f(a, b))));
/* @internal */
exports.zipWith = zipWith;
const never = /*#__PURE__*/asyncEither(() => {
  const interval = setInterval(() => {
    //
  }, 2 ** 31 - 1);
  return Either.left(sync(() => clearInterval(interval)));
});
// -----------------------------------------------------------------------------
// Fiber
// -----------------------------------------------------------------------------
/* @internal */
exports.never = never;
const interruptFiber = self => flatMap(fiberId, fiberId => interruptAsFiber(fiberId)(self));
/* @internal */
exports.interruptFiber = interruptFiber;
const interruptAsFiber = /*#__PURE__*/(0, _Function.dual)(2, (self, fiberId) => flatMap(self.interruptAsFork(fiberId), () => self.await()));
// -----------------------------------------------------------------------------
// LogLevel
// -----------------------------------------------------------------------------
/** @internal */
exports.interruptAsFiber = interruptAsFiber;
const logLevelAll = {
  _tag: "All",
  syslog: 0,
  label: "ALL",
  ordinal: Number.MIN_SAFE_INTEGER,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelAll = logLevelAll;
const logLevelFatal = {
  _tag: "Fatal",
  syslog: 2,
  label: "FATAL",
  ordinal: 50000,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelFatal = logLevelFatal;
const logLevelError = {
  _tag: "Error",
  syslog: 3,
  label: "ERROR",
  ordinal: 40000,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelError = logLevelError;
const logLevelWarning = {
  _tag: "Warning",
  syslog: 4,
  label: "WARN",
  ordinal: 30000,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelWarning = logLevelWarning;
const logLevelInfo = {
  _tag: "Info",
  syslog: 6,
  label: "INFO",
  ordinal: 20000,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelInfo = logLevelInfo;
const logLevelDebug = {
  _tag: "Debug",
  syslog: 7,
  label: "DEBUG",
  ordinal: 10000,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelDebug = logLevelDebug;
const logLevelTrace = {
  _tag: "Trace",
  syslog: 7,
  label: "TRACE",
  ordinal: 0,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelTrace = logLevelTrace;
const logLevelNone = {
  _tag: "None",
  syslog: 7,
  label: "OFF",
  ordinal: Number.MAX_SAFE_INTEGER,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
};
/** @internal */
exports.logLevelNone = logLevelNone;
const allLogLevels = [logLevelAll, logLevelTrace, logLevelDebug, logLevelInfo, logLevelWarning, logLevelError, logLevelFatal, logLevelNone];
// -----------------------------------------------------------------------------
// FiberRef
// -----------------------------------------------------------------------------
/** @internal */
exports.allLogLevels = allLogLevels;
const FiberRefSymbolKey = "@effect/io/FiberRef";
/** @internal */
const FiberRefTypeId = /*#__PURE__*/Symbol.for(FiberRefSymbolKey);
/** @internal */
exports.FiberRefTypeId = FiberRefTypeId;
const fiberRefVariance = {
  _A: _ => _
};
/* @internal */
const fiberRefGet = self => fiberRefModify(self, a => [a, a]);
/* @internal */
exports.fiberRefGet = fiberRefGet;
const fiberRefGetAndSet = /*#__PURE__*/(0, _Function.dual)(2, (self, value) => fiberRefModify(self, v => [v, value]));
/* @internal */
exports.fiberRefGetAndSet = fiberRefGetAndSet;
const fiberRefGetAndUpdate = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => fiberRefModify(self, v => [v, f(v)]));
/* @internal */
exports.fiberRefGetAndUpdate = fiberRefGetAndUpdate;
const fiberRefGetAndUpdateSome = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => fiberRefModify(self, v => [v, Option.getOrElse(pf(v), () => v)]));
/* @internal */
exports.fiberRefGetAndUpdateSome = fiberRefGetAndUpdateSome;
const fiberRefGetWith = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => flatMap(fiberRefGet(self), f));
/* @internal */
exports.fiberRefGetWith = fiberRefGetWith;
const fiberRefSet = /*#__PURE__*/(0, _Function.dual)(2, (self, value) => fiberRefModify(self, () => [void 0, value]));
/* @internal */
exports.fiberRefSet = fiberRefSet;
const fiberRefDelete = self => withFiberRuntime(state => {
  state.unsafeDeleteFiberRef(self);
  return unit;
});
/* @internal */
exports.fiberRefDelete = fiberRefDelete;
const fiberRefReset = self => fiberRefSet(self, self.initial);
/* @internal */
exports.fiberRefReset = fiberRefReset;
const fiberRefModify = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => withFiberRuntime(state => {
  const [b, a] = f(state.getFiberRef(self));
  state.setFiberRef(self, a);
  return succeed(b);
}));
/* @internal */
exports.fiberRefModify = fiberRefModify;
const fiberRefModifySome = (self, def, f) => fiberRefModify(self, v => Option.getOrElse(f(v), () => [def, v]));
/* @internal */
exports.fiberRefModifySome = fiberRefModifySome;
const fiberRefUpdate = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => fiberRefModify(self, v => [void 0, f(v)]));
/* @internal */
exports.fiberRefUpdate = fiberRefUpdate;
const fiberRefUpdateSome = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => fiberRefModify(self, v => [void 0, Option.getOrElse(pf(v), () => v)]));
/* @internal */
exports.fiberRefUpdateSome = fiberRefUpdateSome;
const fiberRefUpdateAndGet = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => fiberRefModify(self, v => {
  const result = f(v);
  return [result, result];
}));
/* @internal */
exports.fiberRefUpdateAndGet = fiberRefUpdateAndGet;
const fiberRefUpdateSomeAndGet = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => fiberRefModify(self, v => {
  const result = Option.getOrElse(pf(v), () => v);
  return [result, result];
}));
// circular
/** @internal */
exports.fiberRefUpdateSomeAndGet = fiberRefUpdateSomeAndGet;
const RequestResolverSymbolKey = "@effect/io/RequestResolver";
/** @internal */
const RequestResolverTypeId = /*#__PURE__*/Symbol.for(RequestResolverSymbolKey);
exports.RequestResolverTypeId = RequestResolverTypeId;
const dataSourceVariance = {
  _R: _ => _,
  _A: _ => _
};
/** @internal */
class RequestResolverImpl {
  constructor(runAll, target) {
    this.runAll = runAll;
    this.target = target;
    this[_d] = dataSourceVariance;
    this.runAll = runAll;
  }
  [(_d = RequestResolverTypeId, Hash.symbol)]() {
    return this.target ? Hash.hash(this.target) : Hash.random(this);
  }
  [Equal.symbol](that) {
    return this.target ? isRequestResolver(that) && Equal.equals(this.target, that.target) : this === that;
  }
  identified(...ids) {
    return new RequestResolverImpl(this.runAll, Chunk.fromIterable(ids));
  }
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
}
/** @internal */
exports.RequestResolverImpl = RequestResolverImpl;
const isRequestResolver = u => typeof u === "object" && u != null && RequestResolverTypeId in u;
// end
/** @internal */
exports.isRequestResolver = isRequestResolver;
const resolverLocally = /*#__PURE__*/(0, _Function.dual)(3, (use, self, value) => new RequestResolverImpl(requests => fiberRefLocally(use.runAll(requests), self, value), Chunk.make("Locally", use, self, value)));
/** @internal */
exports.resolverLocally = resolverLocally;
const requestBlockLocally = (self, ref, value) => _blockedRequests.reduce(self, LocallyReducer(ref, value));
exports.requestBlockLocally = requestBlockLocally;
const LocallyReducer = (ref, value) => ({
  emptyCase: () => _blockedRequests.empty,
  parCase: (left, right) => _blockedRequests.par(left, right),
  seqCase: (left, right) => _blockedRequests.seq(left, right),
  singleCase: (dataSource, blockedRequest) => _blockedRequests.single(resolverLocally(dataSource, ref, value), blockedRequest)
});
/* @internal */
const fiberRefLocally = /*#__PURE__*/(0, _Function.dual)(3, (use, self, value) => flatMap(acquireUseRelease(zipLeft(fiberRefGet(self), fiberRefSet(self, value)), () => step(use), oldValue => fiberRefSet(self, oldValue)), res => {
  if (res._tag === "Blocked") {
    return blocked(res.i0, fiberRefLocally(res.i1, self, value));
  }
  return res;
}));
/* @internal */
exports.fiberRefLocally = fiberRefLocally;
const fiberRefLocallyWith = /*#__PURE__*/(0, _Function.dual)(3, (use, self, f) => fiberRefGetWith(self, a => fiberRefLocally(use, self, f(a))));
/** @internal */
exports.fiberRefLocallyWith = fiberRefLocallyWith;
const fiberRefUnsafeMake = (initial, options) => fiberRefUnsafeMakePatch(initial, {
  differ: Differ.update(),
  fork: options?.fork ?? _Function.identity,
  join: options?.join
});
/** @internal */
exports.fiberRefUnsafeMake = fiberRefUnsafeMake;
const fiberRefUnsafeMakeHashSet = initial => fiberRefUnsafeMakePatch(initial, {
  differ: Differ.hashSet(),
  fork: HashSetPatch.empty()
});
/** @internal */
exports.fiberRefUnsafeMakeHashSet = fiberRefUnsafeMakeHashSet;
const fiberRefUnsafeMakeContext = initial => fiberRefUnsafeMakePatch(initial, {
  differ: Differ.environment(),
  fork: ContextPatch.empty()
});
/** @internal */
exports.fiberRefUnsafeMakeContext = fiberRefUnsafeMakeContext;
const fiberRefUnsafeMakePatch = (initial, options) => ({
  [FiberRefTypeId]: fiberRefVariance,
  initial,
  diff: (oldValue, newValue) => Differ.diff(oldValue, newValue)(options.differ),
  combine: (first, second) => Differ.combine(first, second)(options.differ),
  patch: patch => oldValue => Differ.patch(patch, oldValue)(options.differ),
  fork: options.fork,
  join: options.join ?? ((_, n) => n),
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
});
/** @internal */
exports.fiberRefUnsafeMakePatch = fiberRefUnsafeMakePatch;
const fiberRefUnsafeMakeRuntimeFlags = initial => fiberRefUnsafeMakePatch(initial, {
  differ: _runtimeFlags.differ,
  fork: RuntimeFlagsPatch.empty
});
/** @internal */
exports.fiberRefUnsafeMakeRuntimeFlags = fiberRefUnsafeMakeRuntimeFlags;
const currentContext = /*#__PURE__*/fiberRefUnsafeMakeContext( /*#__PURE__*/Context.empty());
/** @internal */
exports.currentContext = currentContext;
const currentSchedulingPriority = /*#__PURE__*/fiberRefUnsafeMake(0);
/** @internal */
exports.currentSchedulingPriority = currentSchedulingPriority;
const currentMaxFiberOps = /*#__PURE__*/fiberRefUnsafeMake(2048);
/** @internal */
exports.currentMaxFiberOps = currentMaxFiberOps;
const currentLogAnnotations = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentLogAnnotation"), () => fiberRefUnsafeMake(HashMap.empty()));
/** @internal */
exports.currentLogAnnotations = currentLogAnnotations;
const currentLogLevel = /*#__PURE__*/fiberRefUnsafeMake(logLevelInfo);
/** @internal */
exports.currentLogLevel = currentLogLevel;
const currentLogSpan = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentLogSpan"), () => fiberRefUnsafeMake(List.empty()));
/** @internal */
exports.currentLogSpan = currentLogSpan;
const currentScheduler = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentScheduler"), () => fiberRefUnsafeMake(scheduler.defaultScheduler));
/** @internal */
exports.currentScheduler = currentScheduler;
const withScheduler = /*#__PURE__*/(0, _Function.dual)(2, (self, scheduler) => fiberRefLocally(self, currentScheduler, scheduler));
/** @internal */
exports.withScheduler = withScheduler;
const withSchedulingPriority = /*#__PURE__*/(0, _Function.dual)(2, (self, scheduler) => fiberRefLocally(self, currentSchedulingPriority, scheduler));
/** @internal */
exports.withSchedulingPriority = withSchedulingPriority;
const withMaxFiberOps = /*#__PURE__*/(0, _Function.dual)(2, (self, ops) => fiberRefLocally(self, currentMaxFiberOps, ops));
/** @internal */
exports.withMaxFiberOps = withMaxFiberOps;
const currentConcurrency = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentConcurrency"), () => fiberRefUnsafeMake("unbounded"));
/**
 * @internal
 */
exports.currentConcurrency = currentConcurrency;
const currentRequestBatching = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentRequestBatching"), () => fiberRefUnsafeMake(true));
/** @internal */
exports.currentRequestBatching = currentRequestBatching;
const currentUnhandledErrorLogLevel = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentUnhandledErrorLogLevel"), () => fiberRefUnsafeMake(Option.some(logLevelDebug)));
/** @internal */
exports.currentUnhandledErrorLogLevel = currentUnhandledErrorLogLevel;
const withUnhandledErrorLogLevel = /*#__PURE__*/(0, _Function.dual)(2, (self, level) => fiberRefLocally(self, currentUnhandledErrorLogLevel, level));
/** @internal */
exports.withUnhandledErrorLogLevel = withUnhandledErrorLogLevel;
const currentMetricLabels = /*#__PURE__*/fiberRefUnsafeMakeHashSet( /*#__PURE__*/HashSet.empty());
/* @internal */
exports.currentMetricLabels = currentMetricLabels;
const metricLabels = /*#__PURE__*/fiberRefGet(currentMetricLabels);
/** @internal */
exports.metricLabels = metricLabels;
const currentForkScopeOverride = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentForkScopeOverride"), () => fiberRefUnsafeMake(Option.none(), {
  fork: () => Option.none(),
  join: (parent, _) => parent
}));
/** @internal */
exports.currentForkScopeOverride = currentForkScopeOverride;
const currentInterruptedCause = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentInterruptedCause"), () => fiberRefUnsafeMake(internalCause.empty, {
  fork: () => internalCause.empty,
  join: (parent, _) => parent
}));
/** @internal */
exports.currentInterruptedCause = currentInterruptedCause;
const currentTracerSpan = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentTracerSpan"), () => fiberRefUnsafeMake(List.empty()));
/** @internal */
exports.currentTracerSpan = currentTracerSpan;
const currentTracerTimingEnabled = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentTracerTiming"), () => fiberRefUnsafeMake(true));
/** @internal */
exports.currentTracerTimingEnabled = currentTracerTimingEnabled;
const currentTracerSpanAnnotations = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentTracerSpanAnnotations"), () => fiberRefUnsafeMake(HashMap.empty()));
/** @internal */
exports.currentTracerSpanAnnotations = currentTracerSpanAnnotations;
const currentTracerSpanLinks = /*#__PURE__*/(0, _Global.globalValue)( /*#__PURE__*/Symbol.for("@effect/io/FiberRef/currentTracerSpanLinks"), () => fiberRefUnsafeMake(Chunk.empty()));
// -----------------------------------------------------------------------------
// Scope
// -----------------------------------------------------------------------------
/** @internal */
exports.currentTracerSpanLinks = currentTracerSpanLinks;
const ScopeTypeId = /*#__PURE__*/Symbol.for("@effect/io/Scope");
/** @internal */
exports.ScopeTypeId = ScopeTypeId;
const CloseableScopeTypeId = /*#__PURE__*/Symbol.for("@effect/io/CloseableScope");
/* @internal */
exports.CloseableScopeTypeId = CloseableScopeTypeId;
const scopeAddFinalizer = (self, finalizer) => self.addFinalizer(() => asUnit(finalizer));
/* @internal */
exports.scopeAddFinalizer = scopeAddFinalizer;
const scopeAddFinalizerExit = (self, finalizer) => self.addFinalizer(finalizer);
/* @internal */
exports.scopeAddFinalizerExit = scopeAddFinalizerExit;
const scopeClose = (self, exit) => self.close(exit);
/* @internal */
exports.scopeClose = scopeClose;
const scopeFork = (self, strategy) => self.fork(strategy);
/* @internal */
exports.scopeFork = scopeFork;
const releaseMapAdd = /*#__PURE__*/(0, _Function.dual)(2, (self, finalizer) => map(releaseMapAddIfOpen(self, finalizer), Option.match({
  onNone: () => () => unit,
  onSome: key => exit => releaseMapRelease(key, exit)(self)
})));
/* @internal */
exports.releaseMapAdd = releaseMapAdd;
const releaseMapRelease = /*#__PURE__*/(0, _Function.dual)(3, (self, key, exit) => suspend(() => {
  switch (self.state._tag) {
    case "Exited":
      {
        return unit;
      }
    case "Running":
      {
        const finalizer = self.state.finalizers.get(key);
        self.state.finalizers.delete(key);
        if (finalizer != null) {
          return self.state.update(finalizer)(exit);
        }
        return unit;
      }
  }
}));
/* @internal */
exports.releaseMapRelease = releaseMapRelease;
const releaseMapAddIfOpen = /*#__PURE__*/(0, _Function.dual)(2, (self, finalizer) => suspend(() => {
  switch (self.state._tag) {
    case "Exited":
      {
        self.state.nextKey += 1;
        return as(finalizer(self.state.exit), Option.none());
      }
    case "Running":
      {
        const key = self.state.nextKey;
        self.state.finalizers.set(key, finalizer);
        self.state.nextKey += 1;
        return succeed(Option.some(key));
      }
  }
}));
/* @internal */
exports.releaseMapAddIfOpen = releaseMapAddIfOpen;
const releaseMapGet = /*#__PURE__*/(0, _Function.dual)(2, (self, key) => sync(() => self.state._tag === "Running" ? Option.fromNullable(self.state.finalizers.get(key)) : Option.none()));
/* @internal */
exports.releaseMapGet = releaseMapGet;
const releaseMapReplace = /*#__PURE__*/(0, _Function.dual)(3, (self, key, finalizer) => suspend(() => {
  switch (self.state._tag) {
    case "Exited":
      {
        return as(finalizer(self.state.exit), Option.none());
      }
    case "Running":
      {
        const fin = Option.fromNullable(self.state.finalizers.get(key));
        self.state.finalizers.set(key, finalizer);
        return succeed(fin);
      }
  }
}));
/* @internal */
exports.releaseMapReplace = releaseMapReplace;
const releaseMapRemove = /*#__PURE__*/(0, _Function.dual)(2, (self, key) => sync(() => {
  if (self.state._tag === "Exited") {
    return Option.none();
  }
  const fin = Option.fromNullable(self.state.finalizers.get(key));
  self.state.finalizers.delete(key);
  return fin;
}));
/* @internal */
exports.releaseMapRemove = releaseMapRemove;
const releaseMapMake = /*#__PURE__*/sync(() => ({
  state: {
    _tag: "Running",
    nextKey: 0,
    finalizers: new Map(),
    update: _Function.identity
  }
}));
// -----------------------------------------------------------------------------
// Exit
// -----------------------------------------------------------------------------
/** @internal */
exports.releaseMapMake = releaseMapMake;
const exitIsExit = u => isEffect(u) && "_tag" in u && (u._tag === "Success" || u._tag === "Failure");
/** @internal */
exports.exitIsExit = exitIsExit;
const exitIsFailure = self => self._tag === "Failure";
/** @internal */
exports.exitIsFailure = exitIsFailure;
const exitIsSuccess = self => self._tag === "Success";
/** @internal */
exports.exitIsSuccess = exitIsSuccess;
const exitIsInterrupted = self => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return internalCause.isInterrupted(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return false;
      }
  }
};
/** @internal */
exports.exitIsInterrupted = exitIsInterrupted;
const exitAs = /*#__PURE__*/(0, _Function.dual)(2, (self, value) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return exitFailCause(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return exitSucceed(value);
      }
  }
});
/** @internal */
exports.exitAs = exitAs;
const exitAsUnit = self => exitAs(self, void 0);
/** @internal */
exports.exitAsUnit = exitAsUnit;
const exitCauseOption = self => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return Option.some(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return Option.none();
      }
  }
};
/** @internal */
exports.exitCauseOption = exitCauseOption;
const exitCollectAll = (exits, options) => exitCollectAllInternal(exits, options?.parallel ? internalCause.parallel : internalCause.sequential);
/** @internal */
exports.exitCollectAll = exitCollectAll;
const exitDie = defect => exitFailCause(internalCause.die(defect));
/** @internal */
exports.exitDie = exitDie;
const exitExists = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return false;
      }
    case OpCodes.OP_SUCCESS:
      {
        return predicate(self.i0);
      }
  }
});
/** @internal */
exports.exitExists = exitExists;
const exitFail = error => exitFailCause(internalCause.fail(error));
/** @internal */
exports.exitFail = exitFail;
const exitFailCause = cause => {
  const effect = new EffectPrimitiveFailure(OpCodes.OP_FAILURE);
  effect.i0 = cause;
  return effect;
};
/** @internal */
exports.exitFailCause = exitFailCause;
const exitFlatMap = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return exitFailCause(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return f(self.i0);
      }
  }
});
/** @internal */
exports.exitFlatMap = exitFlatMap;
const exitFlatMapEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return succeed(exitFailCause(self.i0));
      }
    case OpCodes.OP_SUCCESS:
      {
        return f(self.i0);
      }
  }
});
/** @internal */
exports.exitFlatMapEffect = exitFlatMapEffect;
const exitFlatten = self => exitFlatMap(_Function.identity)(self);
/** @internal */
exports.exitFlatten = exitFlatten;
const exitForEachEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return succeed(exitFailCause(self.i0));
      }
    case OpCodes.OP_SUCCESS:
      {
        return exit(f(self.i0));
      }
  }
});
/** @internal */
exports.exitForEachEffect = exitForEachEffect;
const exitFromEither = either => {
  switch (either._tag) {
    case "Left":
      {
        return exitFail(either.left);
      }
    case "Right":
      {
        return exitSucceed(either.right);
      }
  }
};
/** @internal */
exports.exitFromEither = exitFromEither;
const exitFromOption = option => {
  switch (option._tag) {
    case "None":
      {
        return exitFail(void 0);
      }
    case "Some":
      {
        return exitSucceed(option.value);
      }
  }
};
/** @internal */
exports.exitFromOption = exitFromOption;
const exitGetOrElse = /*#__PURE__*/(0, _Function.dual)(2, (self, orElse) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return orElse(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return self.i0;
      }
  }
});
/** @internal */
exports.exitGetOrElse = exitGetOrElse;
const exitInterrupt = fiberId => exitFailCause(internalCause.interrupt(fiberId));
/** @internal */
exports.exitInterrupt = exitInterrupt;
const exitMap = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return exitFailCause(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return exitSucceed(f(self.i0));
      }
  }
});
/** @internal */
exports.exitMap = exitMap;
const exitMapBoth = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return exitFailCause(internalCause.map(onFailure)(self.i0));
      }
    case OpCodes.OP_SUCCESS:
      {
        return exitSucceed(onSuccess(self.i0));
      }
  }
});
/** @internal */
exports.exitMapBoth = exitMapBoth;
const exitMapError = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return exitFailCause(internalCause.map(f)(self.i0));
      }
    case OpCodes.OP_SUCCESS:
      {
        return exitSucceed(self.i0);
      }
  }
});
/** @internal */
exports.exitMapError = exitMapError;
const exitMapErrorCause = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return exitFailCause(f(self.i0));
      }
    case OpCodes.OP_SUCCESS:
      {
        return exitSucceed(self.i0);
      }
  }
});
/** @internal */
exports.exitMapErrorCause = exitMapErrorCause;
const exitMatch = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return onFailure(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return onSuccess(self.i0);
      }
  }
});
/** @internal */
exports.exitMatch = exitMatch;
const exitMatchEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        return onFailure(self.i0);
      }
    case OpCodes.OP_SUCCESS:
      {
        return onSuccess(self.i0);
      }
  }
});
/** @internal */
exports.exitMatchEffect = exitMatchEffect;
const exitSucceed = value => {
  const effect = new EffectPrimitiveSuccess(OpCodes.OP_SUCCESS);
  effect.i0 = value;
  return effect;
};
/** @internal */
exports.exitSucceed = exitSucceed;
const exitUnannotate = exit => exitIsSuccess(exit) ? exit : exitFailCause(internalCause.unannotate(exit.i0));
/** @internal */
exports.exitUnannotate = exitUnannotate;
const exitUnit = /*#__PURE__*/exitSucceed(void 0);
/** @internal */
exports.exitUnit = exitUnit;
const exitZip = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => exitZipWith(self, that, {
  onSuccess: (a, a2) => [a, a2],
  onFailure: internalCause.sequential
}));
/** @internal */
exports.exitZip = exitZip;
const exitZipLeft = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => exitZipWith(self, that, {
  onSuccess: (a, _) => a,
  onFailure: internalCause.sequential
}));
/** @internal */
exports.exitZipLeft = exitZipLeft;
const exitZipRight = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => exitZipWith(self, that, {
  onSuccess: (_, a2) => a2,
  onFailure: internalCause.sequential
}));
/** @internal */
exports.exitZipRight = exitZipRight;
const exitZipPar = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => exitZipWith(self, that, {
  onSuccess: (a, a2) => [a, a2],
  onFailure: internalCause.parallel
}));
/** @internal */
exports.exitZipPar = exitZipPar;
const exitZipParLeft = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => exitZipWith(self, that, {
  onSuccess: (a, _) => a,
  onFailure: internalCause.parallel
}));
/** @internal */
exports.exitZipParLeft = exitZipParLeft;
const exitZipParRight = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => exitZipWith(self, that, {
  onSuccess: (_, a2) => a2,
  onFailure: internalCause.parallel
}));
/** @internal */
exports.exitZipParRight = exitZipParRight;
const exitZipWith = /*#__PURE__*/(0, _Function.dual)(3, (self, that, {
  onFailure,
  onSuccess
}) => {
  switch (self._tag) {
    case OpCodes.OP_FAILURE:
      {
        switch (that._tag) {
          case OpCodes.OP_SUCCESS:
            {
              return exitFailCause(self.i0);
            }
          case OpCodes.OP_FAILURE:
            {
              return exitFailCause(onFailure(self.i0, that.i0));
            }
        }
      }
    case OpCodes.OP_SUCCESS:
      {
        switch (that._tag) {
          case OpCodes.OP_SUCCESS:
            {
              return exitSucceed(onSuccess(self.i0, that.i0));
            }
          case OpCodes.OP_FAILURE:
            {
              return exitFailCause(that.i0);
            }
        }
      }
  }
});
exports.exitZipWith = exitZipWith;
const exitCollectAllInternal = (exits, combineCauses) => {
  const list = Chunk.fromIterable(exits);
  if (!Chunk.isNonEmpty(list)) {
    return Option.none();
  }
  return Option.some(exitMap(chunk => Array.from(chunk))(exitMap(Chunk.reverse)(ReadonlyArray.reduce(exitMap(Chunk.of)(Chunk.headNonEmpty(list)), (accumulator, current) => exitZipWith(current, {
    onSuccess: (list, value) => Chunk.prepend(value)(list),
    onFailure: combineCauses
  })(accumulator))(Chunk.tailNonEmpty(list)))));
};
// -----------------------------------------------------------------------------
// Deferred
// -----------------------------------------------------------------------------
/** @internal */
const deferredUnsafeMake = fiberId => ({
  [deferred.DeferredTypeId]: deferred.deferredVariance,
  state: MutableRef.make(deferred.pending([])),
  blockingOn: fiberId,
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
});
/* @internal */
exports.deferredUnsafeMake = deferredUnsafeMake;
const deferredMake = () => flatMap(fiberId, id => deferredMakeAs(id));
/* @internal */
exports.deferredMake = deferredMake;
const deferredMakeAs = fiberId => sync(() => deferredUnsafeMake(fiberId));
/* @internal */
exports.deferredMakeAs = deferredMakeAs;
const deferredAwait = self => asyncEither(k => {
  const state = MutableRef.get(self.state);
  switch (state._tag) {
    case DeferredOpCodes.OP_STATE_DONE:
      {
        return Either.right(state.effect);
      }
    case DeferredOpCodes.OP_STATE_PENDING:
      {
        MutableRef.set(deferred.pending([k, ...state.joiners]))(self.state);
        return Either.left(deferredInterruptJoiner(self, k));
      }
  }
}, self.blockingOn);
/* @internal */
exports.deferredAwait = deferredAwait;
const deferredComplete = /*#__PURE__*/(0, _Function.dual)(2, (self, effect) => intoDeferred(effect, self));
/* @internal */
exports.deferredComplete = deferredComplete;
const deferredCompleteWith = /*#__PURE__*/(0, _Function.dual)(2, (self, effect) => sync(() => {
  const state = MutableRef.get(self.state);
  switch (state._tag) {
    case DeferredOpCodes.OP_STATE_DONE:
      {
        return false;
      }
    case DeferredOpCodes.OP_STATE_PENDING:
      {
        MutableRef.set(deferred.done(effect))(self.state);
        for (let i = 0; i < state.joiners.length; i++) {
          state.joiners[i](effect);
        }
        return true;
      }
  }
}));
/* @internal */
exports.deferredCompleteWith = deferredCompleteWith;
const deferredDone = /*#__PURE__*/(0, _Function.dual)(2, (self, exit) => deferredCompleteWith(self, exit));
/* @internal */
exports.deferredDone = deferredDone;
const deferredFail = /*#__PURE__*/(0, _Function.dual)(2, (self, error) => deferredCompleteWith(self, fail(error)));
/* @internal */
exports.deferredFail = deferredFail;
const deferredFailSync = /*#__PURE__*/(0, _Function.dual)(2, (self, evaluate) => deferredCompleteWith(self, failSync(evaluate)));
/* @internal */
exports.deferredFailSync = deferredFailSync;
const deferredFailCause = /*#__PURE__*/(0, _Function.dual)(2, (self, cause) => deferredCompleteWith(self, failCause(cause)));
/* @internal */
exports.deferredFailCause = deferredFailCause;
const deferredFailCauseSync = /*#__PURE__*/(0, _Function.dual)(2, (self, evaluate) => deferredCompleteWith(self, failCauseSync(evaluate)));
/* @internal */
exports.deferredFailCauseSync = deferredFailCauseSync;
const deferredDie = /*#__PURE__*/(0, _Function.dual)(2, (self, defect) => deferredCompleteWith(self, die(defect)));
/* @internal */
exports.deferredDie = deferredDie;
const deferredDieSync = /*#__PURE__*/(0, _Function.dual)(2, (self, evaluate) => deferredCompleteWith(self, dieSync(evaluate)));
/* @internal */
exports.deferredDieSync = deferredDieSync;
const deferredInterrupt = self => flatMap(fiberId, fiberId => deferredCompleteWith(self, interruptWith(fiberId)));
/* @internal */
exports.deferredInterrupt = deferredInterrupt;
const deferredInterruptWith = /*#__PURE__*/(0, _Function.dual)(2, (self, fiberId) => deferredCompleteWith(self, interruptWith(fiberId)));
/* @internal */
exports.deferredInterruptWith = deferredInterruptWith;
const deferredIsDone = self => sync(() => MutableRef.get(self.state)._tag === DeferredOpCodes.OP_STATE_DONE);
/* @internal */
exports.deferredIsDone = deferredIsDone;
const deferredPoll = self => sync(() => {
  const state = MutableRef.get(self.state);
  switch (state._tag) {
    case DeferredOpCodes.OP_STATE_DONE:
      {
        return Option.some(state.effect);
      }
    case DeferredOpCodes.OP_STATE_PENDING:
      {
        return Option.none();
      }
  }
});
/* @internal */
exports.deferredPoll = deferredPoll;
const deferredSucceed = /*#__PURE__*/(0, _Function.dual)(2, (self, value) => deferredCompleteWith(self, succeed(value)));
/* @internal */
exports.deferredSucceed = deferredSucceed;
const deferredSync = /*#__PURE__*/(0, _Function.dual)(2, (self, evaluate) => deferredCompleteWith(self, sync(evaluate)));
/** @internal */
exports.deferredSync = deferredSync;
const deferredUnsafeDone = (self, effect) => {
  const state = MutableRef.get(self.state);
  if (state._tag === DeferredOpCodes.OP_STATE_PENDING) {
    MutableRef.set(deferred.done(effect))(self.state);
    for (let i = state.joiners.length - 1; i >= 0; i--) {
      state.joiners[i](effect);
    }
  }
};
exports.deferredUnsafeDone = deferredUnsafeDone;
const deferredInterruptJoiner = (self, joiner) => sync(() => {
  const state = MutableRef.get(self.state);
  if (state._tag === DeferredOpCodes.OP_STATE_PENDING) {
    MutableRef.set(deferred.pending(state.joiners.filter(j => j !== joiner)))(self.state);
  }
});
//# sourceMappingURL=core.js.map