"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.takeWhile = exports.takeUntil = exports.tagMetrics = exports.summarized = exports.succeedSome = exports.succeedNone = exports.spanLinks = exports.spanAnnotations = exports.some = exports.sleep = exports.setFiberRefs = exports.serviceFunctionEffect = exports.serviceFunction = exports.sandbox = exports.repeatN = exports.reduceWhile = exports.reduceRight = exports.reduce = exports.random = exports.provideServiceEffect = exports.provideService = exports.promise = exports.patchFiberRefs = exports.parallelErrors = exports.orElseSucceed = exports.orElseFail = exports.optionFromOptional = exports.option = exports.once = exports.none = exports.negate = exports.merge = exports.memoize = exports.match = exports.mapErrorCause = exports.mapAccum = exports.makeSpan = exports.loop = exports.logWarning = exports.logTrace = exports.logInfo = exports.logFatal = exports.logError = exports.logDebug = exports.logAnnotations = exports.log = exports.linkSpans = exports.labelMetricsSet = exports.labelMetrics = exports.iterate = exports.isSuccess = exports.isFailure = exports.inheritFiberRefs = exports.ignoreLogged = exports.ignore = exports.head = exports.getFiberRefs = exports.gen = exports.fromNullable = exports.forever = exports.flipWith = exports.firstSuccessOf = exports.findFirst = exports.filterOrFail = exports.filterOrElse = exports.filterOrDieMessage = exports.filterOrDie = exports.filterMap = exports.every = exports.eventually = exports.dropWhile = exports.dropUntil = exports.diffFiberRefs = exports.descriptorWith = exports.descriptor = exports.delay = exports.currentTimeNanosTracing = exports.currentSpan = exports.currentParentSpan = exports.contextWith = exports.clockWith = exports.clock = exports.cause = exports.catchTags = exports.catchTag = exports.catchSomeDefect = exports.catchSomeCause = exports.catchAllDefect = exports.bindValue = exports.bindTo = exports.bind = exports.asyncOption = exports.asSomeError = exports.asSome = exports.annotateSpans = exports.annotateLogs = exports.annotateCurrentSpan = exports.allowInterrupt = exports._catch = exports.Do = void 0;
exports.withSpan = exports.withParentSpan = exports.withMetric = exports.withLogSpan = exports.whenRef = exports.whenFiberRef = exports.when = exports.useSpan = exports.updateService = exports.updateFiberRefs = exports.unsandbox = exports.unlessEffect = exports.unless = exports.try_ = exports.tryPromise = exports.tryMapPromise = exports.tryMap = exports.tracerWith = exports.tracer = exports.timedWith = exports.timed = exports.tapErrorTag = exports.tapErrorCause = exports.tapError = exports.tapDefect = exports.tapBoth = void 0;
var Chunk = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Chunk"));
var Context = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Context"));
var Duration = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Duration"));
var Either = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Either"));
var _Function = /*#__PURE__*/require("@effect/data/Function");
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 Option = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Option"));
var Predicate = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Predicate"));
var ReadonlyArray = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/ReadonlyArray"));
var Clock = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Clock"));
var FiberId = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Fiber/Id"));
var FiberRefs = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/FiberRefs"));
var internalCause = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/cause"));
var core = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/core"));
var defaultServices = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/defaultServices"));
var fiberRefsPatch = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/fiberRefs/patch"));
var metricLabel = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/metric/label"));
var SingleShotGen = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/singleShotGen"));
var LogLevel = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Logger/Level"));
var LogSpan = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Logger/Span"));
var Ref = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Ref"));
var Tracer = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Tracer"));
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; }
/* @internal */
const annotateLogs = /*#__PURE__*/(0, _Function.dual)(args => core.isEffect(args[0]), function () {
  const args = arguments;
  return core.fiberRefLocallyWith(args[0], core.currentLogAnnotations, typeof args[1] === "string" ? HashMap.set(args[1], args[2]) : annotations => Object.entries(args[1]).reduce((acc, [key, value]) => HashMap.set(acc, key, value), annotations));
});
/* @internal */
exports.annotateLogs = annotateLogs;
const asSome = self => core.map(self, Option.some);
/* @internal */
exports.asSome = asSome;
const asSomeError = self => core.mapError(self, Option.some);
/* @internal */
exports.asSomeError = asSomeError;
const asyncOption = (register, blockingOn = FiberId.none) => core.asyncEither(cb => {
  const option = register(cb);
  switch (option._tag) {
    case "None":
      {
        return Either.left(core.unit);
      }
    case "Some":
      {
        return Either.right(option.value);
      }
  }
}, blockingOn);
/* @internal */
exports.asyncOption = asyncOption;
const try_ = arg => {
  let evaluate;
  let onFailure = undefined;
  if (typeof arg === "function") {
    evaluate = arg;
  } else {
    evaluate = arg.try;
    onFailure = arg.catch;
  }
  return core.sync(() => {
    try {
      return evaluate();
    } catch (error) {
      throw core.makeEffectError(internalCause.fail(onFailure ? onFailure(error) : error));
    }
  });
};
/* @internal */
exports.try_ = try_;
const _catch = /*#__PURE__*/(0, _Function.dual)(
// @ts-expect-error
3, (self, tag, options) => core.catchAll(self, e => {
  if (typeof e === "object" && e != null && tag in e && e[tag] === options.failure) {
    return options.onFailure(e);
  }
  return core.fail(e);
}));
/* @internal */
exports._catch = _catch;
const catchAllDefect = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.catchAllCause(self, core.unified(cause => {
  const option = internalCause.find(cause, _ => internalCause.isDieType(_) ? Option.some(_) : Option.none());
  switch (option._tag) {
    case "None":
      {
        return core.failCause(cause);
      }
    case "Some":
      {
        return f(option.value.defect);
      }
  }
})));
/* @internal */
exports.catchAllDefect = catchAllDefect;
const catchSomeCause = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: cause => {
    const option = f(cause);
    switch (option._tag) {
      case "None":
        {
          return core.failCause(cause);
        }
      case "Some":
        {
          return option.value;
        }
    }
  },
  onSuccess: core.succeed
}));
/* @internal */
exports.catchSomeCause = catchSomeCause;
const catchSomeDefect = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => core.catchAllCause(self, core.unified(cause => {
  const option = internalCause.find(cause, _ => internalCause.isDieType(_) ? Option.some(_) : Option.none());
  switch (option._tag) {
    case "None":
      {
        return core.failCause(cause);
      }
    case "Some":
      {
        const optionEffect = pf(option.value.defect);
        return optionEffect._tag === "Some" ? optionEffect.value : core.failCause(cause);
      }
  }
})));
/* @internal */
exports.catchSomeDefect = catchSomeDefect;
const catchTag = /*#__PURE__*/(0, _Function.dual)(3, (self, k, f) => core.catchAll(self, e => {
  if (Predicate.isObject(e) && "_tag" in e && e["_tag"] === k) {
    return f(e);
  }
  return core.fail(e);
}));
/** @internal */
exports.catchTag = catchTag;
const catchTags = /*#__PURE__*/(0, _Function.dual)(2, (self, cases) => core.catchAll(self, e => {
  const keys = Object.keys(cases);
  if (Predicate.isObject(e) && "_tag" in e && keys.includes(e["_tag"])) {
    return cases[e["_tag"]](e);
  }
  return core.fail(e);
}));
/* @internal */
exports.catchTags = catchTags;
const cause = self => core.matchCause(self, {
  onFailure: _Function.identity,
  onSuccess: () => internalCause.empty
});
/* @internal */
exports.cause = cause;
const clockWith = Clock.clockWith;
/* @internal */
exports.clockWith = clockWith;
const clock = /*#__PURE__*/clockWith(core.succeed);
/* @internal */
exports.clock = clock;
const delay = /*#__PURE__*/(0, _Function.dual)(2, (self, duration) => core.zipRight(Clock.sleep(duration), self));
/* @internal */
exports.delay = delay;
const descriptorWith = f => core.withFiberRuntime((state, status) => f({
  id: state.id(),
  status,
  interruptors: internalCause.interruptors(state.getFiberRef(core.currentInterruptedCause))
}));
/* @internal */
exports.descriptorWith = descriptorWith;
const allowInterrupt = /*#__PURE__*/descriptorWith(descriptor => HashSet.size(descriptor.interruptors) > 0 ? core.interrupt : core.unit);
/* @internal */
exports.allowInterrupt = allowInterrupt;
const descriptor = /*#__PURE__*/descriptorWith(core.succeed);
/* @internal */
exports.descriptor = descriptor;
const diffFiberRefs = self => summarized(self, getFiberRefs, fiberRefsPatch.diff);
/* @internal */
exports.diffFiberRefs = diffFiberRefs;
const Do = /*#__PURE__*/core.succeed({});
/* @internal */
exports.Do = Do;
const bind = /*#__PURE__*/(0, _Function.dual)(3, (self, tag, f) => core.flatMap(self, k => core.map(f(k), a => ({
  ...k,
  [tag]: a
}))));
/* @internal */
exports.bind = bind;
const bindTo = /*#__PURE__*/(0, _Function.dual)(2, (self, tag) => core.map(self, a => ({
  [tag]: a
})));
/* @internal */
exports.bindTo = bindTo;
const bindValue = /*#__PURE__*/(0, _Function.dual)(3, (self, tag, f) => core.map(self, k => ({
  ...k,
  [tag]: f(k)
})));
/* @internal */
exports.bindValue = bindValue;
const dropUntil = /*#__PURE__*/(0, _Function.dual)(2, (elements, predicate) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let dropping = core.succeed(false);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    dropping = core.flatMap(dropping, bool => {
      if (bool) {
        builder.push(a);
        return core.succeed(true);
      }
      return predicate(a, index);
    });
  }
  return core.map(dropping, () => builder);
}));
/* @internal */
exports.dropUntil = dropUntil;
const dropWhile = /*#__PURE__*/(0, _Function.dual)(2, (elements, f) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let dropping = core.succeed(true);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    dropping = core.flatMap(dropping, d => core.map(d ? f(a, index) : core.succeed(false), b => {
      if (!b) {
        builder.push(a);
      }
      return b;
    }));
  }
  return core.map(dropping, () => builder);
}));
/* @internal */
exports.dropWhile = dropWhile;
const contextWith = f => core.map(core.context(), f);
/* @internal */
exports.contextWith = contextWith;
const eventually = self => core.orElse(self, () => core.flatMap(core.yieldNow(), () => eventually(self)));
/* @internal */
exports.eventually = eventually;
const filterMap = /*#__PURE__*/(0, _Function.dual)(2, (elements, pf) => core.map(core.forEachSequential(elements, _Function.identity), ReadonlyArray.filterMap(pf)));
/* @internal */
exports.filterMap = filterMap;
const filterOrDie = /*#__PURE__*/(0, _Function.dual)(3, (self, filter, orDieWith) => filterOrElse(self, filter, () => core.dieSync(orDieWith)));
/* @internal */
exports.filterOrDie = filterOrDie;
const filterOrDieMessage = /*#__PURE__*/(0, _Function.dual)(3, (self, filter, message) => filterOrElse(self, filter, () => core.dieMessage(message)));
/* @internal */
exports.filterOrDieMessage = filterOrDieMessage;
const filterOrElse = /*#__PURE__*/(0, _Function.dual)(3, (self, filter, orElse) => core.flatMap(self, a => filter(a) ? core.succeed(a) : orElse(a)));
/* @internal */
exports.filterOrElse = filterOrElse;
const filterOrFail = /*#__PURE__*/(0, _Function.dual)(3, (self, filter, orFailWith) => filterOrElse(self, filter, a => core.failSync(() => orFailWith(a))));
/* @internal */
exports.filterOrFail = filterOrFail;
const findFirst = /*#__PURE__*/(0, _Function.dual)(2, (elements, f) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const next = iterator.next();
  if (!next.done) {
    return findLoop(iterator, 0, f, next.value);
  }
  return core.succeed(Option.none());
}));
exports.findFirst = findFirst;
const findLoop = (iterator, index, f, value) => core.flatMap(f(value, index), result => {
  if (result) {
    return core.succeed(Option.some(value));
  }
  const next = iterator.next();
  if (!next.done) {
    return findLoop(iterator, index + 1, f, next.value);
  }
  return core.succeed(Option.none());
});
/* @internal */
const firstSuccessOf = effects => core.suspend(() => {
  const list = Chunk.fromIterable(effects);
  if (!Chunk.isNonEmpty(list)) {
    return core.dieSync(() => internalCause.IllegalArgumentException(`Received an empty collection of effects`));
  }
  return ReadonlyArray.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right))(Chunk.tailNonEmpty(list));
});
/* @internal */
exports.firstSuccessOf = firstSuccessOf;
const flipWith = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.flip(f(core.flip(self))));
/* @internal */
exports.flipWith = flipWith;
const match = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => core.matchEffect(self, {
  onFailure: e => core.succeed(onFailure(e)),
  onSuccess: a => core.succeed(onSuccess(a))
}));
/* @internal */
exports.match = match;
const every = /*#__PURE__*/(0, _Function.dual)(2, (elements, f) => core.suspend(() => forAllLoop(elements[Symbol.iterator](), 0, f)));
exports.every = every;
const forAllLoop = (iterator, index, f) => {
  const next = iterator.next();
  return next.done ? core.succeed(true) : core.flatMap(f(next.value, index), b => b ? forAllLoop(iterator, index + 1, f) : core.succeed(b));
};
/* @internal */
const forever = self => {
  const loop = core.flatMap(core.flatMap(self, () => core.yieldNow()), () => loop);
  return loop;
};
/** @internal */
exports.forever = forever;
class EffectGen {
  constructor(value) {
    this.value = value;
  }
  [Symbol.iterator]() {
    return new SingleShotGen.SingleShotGen(this);
  }
}
const adapter = function () {
  let x = arguments[0];
  for (let i = 1; i < arguments.length; i++) {
    x = arguments[i](x);
  }
  return new EffectGen(x);
};
/**
 * Inspired by https://github.com/tusharmath/qio/pull/22 (revised)
  @internal */
const gen = f => core.suspend(() => {
  const iterator = f(adapter);
  const state = iterator.next();
  const run = state => state.done ? core.succeed(state.value) : core.flatMap(val => run(iterator.next(val)))(state.value.value);
  return run(state);
});
/* @internal */
exports.gen = gen;
const getFiberRefs = /*#__PURE__*/core.withFiberRuntime(state => core.succeed(state.unsafeGetFiberRefs()));
/* @internal */
exports.getFiberRefs = getFiberRefs;
const head = self => core.matchEffect(self, {
  onFailure: e => core.fail(Option.some(e)),
  onSuccess: as => {
    const iterator = as[Symbol.iterator]();
    const next = iterator.next();
    if (next.done) {
      return core.fail(Option.none());
    }
    return core.succeed(next.value);
  }
});
/* @internal */
exports.head = head;
const ignore = self => match(self, {
  onFailure: _Function.constVoid,
  onSuccess: _Function.constVoid
});
/* @internal */
exports.ignore = ignore;
const ignoreLogged = self => core.matchCauseEffect(self, {
  onFailure: cause => logDebug(cause, "An error was silently ignored because it is not anticipated to be useful"),
  onSuccess: () => core.unit
});
/* @internal */
exports.ignoreLogged = ignoreLogged;
const inheritFiberRefs = childFiberRefs => updateFiberRefs((parentFiberId, parentFiberRefs) => FiberRefs.joinAs(parentFiberRefs, parentFiberId, childFiberRefs));
/* @internal */
exports.inheritFiberRefs = inheritFiberRefs;
const isFailure = self => match(self, {
  onFailure: _Function.constTrue,
  onSuccess: _Function.constFalse
});
/* @internal */
exports.isFailure = isFailure;
const isSuccess = self => match(self, {
  onFailure: _Function.constFalse,
  onSuccess: _Function.constTrue
});
/* @internal */
exports.isSuccess = isSuccess;
const iterate = (initial, options) => core.suspend(() => {
  if (options.while(initial)) {
    return core.flatMap(options.body(initial), z2 => iterate(z2, options));
  }
  return core.succeed(initial);
});
exports.iterate = iterate;
const logWithLevel = level => (messageOrCause, supplementary) => {
  const levelOption = Option.fromNullable(level);
  let message;
  let cause;
  if (internalCause.isCause(messageOrCause)) {
    cause = messageOrCause;
    message = supplementary ?? "";
  } else {
    message = messageOrCause;
    cause = supplementary ?? internalCause.empty;
  }
  return core.withFiberRuntime(fiberState => {
    fiberState.log(message, cause, levelOption);
    return core.unit;
  });
};
/** @internal */
const log = /*#__PURE__*/logWithLevel();
/** @internal */
exports.log = log;
const logTrace = /*#__PURE__*/logWithLevel(LogLevel.Trace);
/** @internal */
exports.logTrace = logTrace;
const logDebug = /*#__PURE__*/logWithLevel(LogLevel.Debug);
/** @internal */
exports.logDebug = logDebug;
const logInfo = /*#__PURE__*/logWithLevel(LogLevel.Info);
/** @internal */
exports.logInfo = logInfo;
const logWarning = /*#__PURE__*/logWithLevel(LogLevel.Warning);
/** @internal */
exports.logWarning = logWarning;
const logError = /*#__PURE__*/logWithLevel(LogLevel.Error);
/** @internal */
exports.logError = logError;
const logFatal = /*#__PURE__*/logWithLevel(LogLevel.Fatal);
/* @internal */
exports.logFatal = logFatal;
const withLogSpan = /*#__PURE__*/(0, _Function.dual)(2, (effect, label) => core.flatMap(Clock.currentTimeMillis, now => core.fiberRefLocallyWith(effect, core.currentLogSpan, List.prepend(LogSpan.make(label, now)))));
/* @internal */
exports.withLogSpan = withLogSpan;
const logAnnotations = /*#__PURE__*/core.fiberRefGet(core.currentLogAnnotations);
/* @internal */
// @ts-expect-error
exports.logAnnotations = logAnnotations;
const loop = (initial, options) => options.discard ? loopDiscard(initial, options.while, options.step, options.body) : core.map(loopInternal(initial, options.while, options.step, options.body), x => Array.from(x));
exports.loop = loop;
const loopInternal = (initial, cont, inc, body) => core.suspend(() => cont(initial) ? core.flatMap(body(initial), a => core.map(loopInternal(inc(initial), cont, inc, body), List.prepend(a))) : core.sync(() => List.empty()));
const loopDiscard = (initial, cont, inc, body) => core.suspend(() => cont(initial) ? core.flatMap(body(initial), () => loopDiscard(inc(initial), cont, inc, body)) : core.unit);
/* @internal */
const mapAccum = /*#__PURE__*/(0, _Function.dual)(3, (elements, zero, f) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let result = core.succeed(zero);
  let next;
  let i = 0;
  while (!(next = iterator.next()).done) {
    const index = i++;
    result = core.flatMap(result, state => core.map(f(state, next.value, index), ([z, b]) => {
      builder.push(b);
      return z;
    }));
  }
  return core.map(result, z => [z, builder]);
}));
/* @internal */
exports.mapAccum = mapAccum;
const mapErrorCause = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: c => core.failCauseSync(() => f(c)),
  onSuccess: core.succeed
}));
/* @internal */
exports.mapErrorCause = mapErrorCause;
const memoize = self => core.flatMap(deferred => core.map(complete => core.zipRight(complete, core.flatMap(([patch, a]) => core.as(patchFiberRefs(patch), a))(core.deferredAwait(deferred))))(once(core.intoDeferred(deferred)(diffFiberRefs(self)))))(core.deferredMake());
/* @internal */
exports.memoize = memoize;
const merge = self => core.matchEffect(self, {
  onFailure: e => core.succeed(e),
  onSuccess: core.succeed
});
/* @internal */
exports.merge = merge;
const negate = self => core.map(self, b => !b);
/* @internal */
exports.negate = negate;
const none = self => core.matchEffect(self, {
  onFailure: e => core.fail(Option.some(e)),
  onSuccess: option => {
    switch (option._tag) {
      case "None":
        {
          return core.unit;
        }
      case "Some":
        {
          return core.fail(Option.none());
        }
    }
  }
});
/* @internal */
exports.none = none;
const once = self => core.map(Ref.make(true), ref => core.asUnit(core.whenEffect(self, Ref.getAndSet(ref, false))));
/* @internal */
exports.once = once;
const option = self => core.matchEffect(self, {
  onFailure: () => core.succeed(Option.none()),
  onSuccess: a => core.succeed(Option.some(a))
});
/* @internal */
exports.option = option;
const orElseFail = /*#__PURE__*/(0, _Function.dual)(2, (self, evaluate) => core.orElse(self, () => core.failSync(evaluate)));
/* @internal */
exports.orElseFail = orElseFail;
const orElseSucceed = /*#__PURE__*/(0, _Function.dual)(2, (self, evaluate) => core.orElse(self, () => core.sync(evaluate)));
/* @internal */
exports.orElseSucceed = orElseSucceed;
const parallelErrors = self => core.matchCauseEffect(self, {
  onFailure: cause => {
    const errors = Array.from(internalCause.failures(cause));
    return errors.length === 0 ? core.failCause(cause) : core.fail(errors);
  },
  onSuccess: core.succeed
});
/* @internal */
exports.parallelErrors = parallelErrors;
const patchFiberRefs = patch => updateFiberRefs((fiberId, fiberRefs) => fiberRefsPatch.patch(fiberId, fiberRefs)(patch));
/* @internal */
exports.patchFiberRefs = patchFiberRefs;
const promise = evaluate => evaluate.length >= 1 ? core.async((resolve, signal) => {
  evaluate(signal).then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitDie(e)));
}) : core.async(resolve => {
  ;
  evaluate().then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitDie(e)));
});
/* @internal */
exports.promise = promise;
const provideService = /*#__PURE__*/(0, _Function.dual)(3, (self, tag, service) => provideServiceEffect(self, tag, core.succeed(service)));
/* @internal */
exports.provideService = provideService;
const provideServiceEffect = /*#__PURE__*/(0, _Function.dual)(3, (self, tag, effect) => core.contextWithEffect(env => core.flatMap(effect, service => core.provideContext(self, Context.add(tag, service)(env)))));
/* @internal */
exports.provideServiceEffect = provideServiceEffect;
const random = /*#__PURE__*/defaultServices.randomWith(core.succeed);
/* @internal */
exports.random = random;
const reduce = /*#__PURE__*/(0, _Function.dual)(3, (elements, zero, f) => ReadonlyArray.fromIterable(elements).reduce((acc, el, i) => core.flatMap(acc, a => f(a, el, i)), core.succeed(zero)));
/* @internal */
exports.reduce = reduce;
const reduceRight = /*#__PURE__*/(0, _Function.dual)(3, (elements, zero, f) => ReadonlyArray.fromIterable(elements).reduceRight((acc, el, i) => core.flatMap(acc, a => f(el, a, i)), core.succeed(zero)));
/* @internal */
exports.reduceRight = reduceRight;
const reduceWhile = /*#__PURE__*/(0, _Function.dual)(3, (elements, zero, options) => core.flatMap(core.sync(() => elements[Symbol.iterator]()), iterator => reduceWhileLoop(iterator, 0, zero, options.while, options.body)));
exports.reduceWhile = reduceWhile;
const reduceWhileLoop = (iterator, index, state, predicate, f) => {
  const next = iterator.next();
  if (!next.done && predicate(state)) {
    return core.flatMap(f(state, next.value, index), nextState => reduceWhileLoop(iterator, index + 1, nextState, predicate, f));
  }
  return core.succeed(state);
};
/* @internal */
const repeatN = /*#__PURE__*/(0, _Function.dual)(2, (self, n) => core.suspend(() => repeatNLoop(self, n)));
/* @internal */
exports.repeatN = repeatN;
const repeatNLoop = (self, n) => core.flatMap(self, a => n <= 0 ? core.succeed(a) : core.zipRight(core.yieldNow(), repeatNLoop(self, n - 1)));
/* @internal */
const sandbox = self => core.matchCauseEffect(self, {
  onFailure: core.fail,
  onSuccess: core.succeed
});
/* @internal */
exports.sandbox = sandbox;
const setFiberRefs = fiberRefs => core.suspend(() => FiberRefs.setAll(fiberRefs));
/* @internal */
exports.setFiberRefs = setFiberRefs;
const sleep = Clock.sleep;
/* @internal */
exports.sleep = sleep;
const some = self => core.matchEffect(self, {
  onFailure: e => core.fail(Option.some(e)),
  onSuccess: option => {
    switch (option._tag) {
      case "None":
        {
          return core.fail(Option.none());
        }
      case "Some":
        {
          return core.succeed(option.value);
        }
    }
  }
});
/* @internal */
exports.some = some;
const succeedNone = /*#__PURE__*/core.succeed( /*#__PURE__*/Option.none());
/* @internal */
exports.succeedNone = succeedNone;
const succeedSome = value => core.succeed(Option.some(value));
/* @internal */
exports.succeedSome = succeedSome;
const summarized = /*#__PURE__*/(0, _Function.dual)(3, (self, summary, f) => core.flatMap(summary, start => core.flatMap(self, value => core.map(summary, end => [f(start, end), value]))));
/* @internal */
exports.summarized = summarized;
const tagMetrics = /*#__PURE__*/(0, _Function.dual)(3, (self, key, value) => labelMetrics(self, [metricLabel.make(key, value)]));
/* @internal */
exports.tagMetrics = tagMetrics;
const labelMetrics = /*#__PURE__*/(0, _Function.dual)(2, (self, labels) => labelMetricsSet(self, HashSet.fromIterable(labels)));
/* @internal */
exports.labelMetrics = labelMetrics;
const labelMetricsSet = /*#__PURE__*/(0, _Function.dual)(2, (self, labels) => core.fiberRefLocallyWith(core.currentMetricLabels, set => HashSet.union(labels)(set))(self));
/* @internal */
exports.labelMetricsSet = labelMetricsSet;
const takeUntil = /*#__PURE__*/(0, _Function.dual)(2, (elements, predicate) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let effect = core.succeed(false);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    effect = core.flatMap(effect, bool => {
      if (bool) {
        return core.succeed(true);
      }
      builder.push(a);
      return predicate(a, index);
    });
  }
  return core.map(effect, () => builder);
}));
/* @internal */
exports.takeUntil = takeUntil;
const takeWhile = /*#__PURE__*/(0, _Function.dual)(2, (elements, predicate) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let taking = core.succeed(true);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    taking = core.flatMap(taking, taking => core.map(bool => {
      if (bool) {
        builder.push(a);
      }
      return bool;
    })(taking ? predicate(a, index) : core.succeed(false)));
  }
  return core.map(taking, () => builder);
}));
/* @internal */
exports.takeWhile = takeWhile;
const tapBoth = /*#__PURE__*/(0, _Function.dual)(2, (self, {
  onFailure,
  onSuccess
}) => core.matchCauseEffect(self, {
  onFailure: cause => {
    const either = internalCause.failureOrCause(cause);
    switch (either._tag) {
      case "Left":
        {
          return core.zipRight(onFailure(either.left), core.failCause(cause));
        }
      case "Right":
        {
          return core.failCause(cause);
        }
    }
  },
  onSuccess: a => core.as(onSuccess(a), a)
}));
/* @internal */
exports.tapBoth = tapBoth;
const tapDefect = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.catchAllCause(self, cause => Option.match(internalCause.keepDefects(cause), {
  onNone: () => core.failCause(cause),
  onSome: a => core.zipRight(f(a), core.failCause(cause))
})));
/* @internal */
exports.tapDefect = tapDefect;
const tapError = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: cause => {
    const either = internalCause.failureOrCause(cause);
    switch (either._tag) {
      case "Left":
        {
          return core.zipRight(f(either.left), core.failCause(cause));
        }
      case "Right":
        {
          return core.failCause(cause);
        }
    }
  },
  onSuccess: core.succeed
}));
/* @internal */
exports.tapError = tapError;
const tapErrorTag = /*#__PURE__*/(0, _Function.dual)(3, (self, k, f) => tapError(self, e => {
  if (Predicate.isObject(e) && "_tag" in e && e["_tag"] === k) {
    return f(e);
  }
  return core.unit;
}));
/* @internal */
exports.tapErrorTag = tapErrorTag;
const tapErrorCause = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: cause => core.zipRight(f(cause), core.failCause(cause)),
  onSuccess: core.succeed
}));
/* @internal */
exports.tapErrorCause = tapErrorCause;
const timed = self => timedWith(self, Clock.currentTimeNanos);
/* @internal */
exports.timed = timed;
const timedWith = /*#__PURE__*/(0, _Function.dual)(2, (self, nanos) => summarized(self, nanos, (start, end) => Duration.nanos(end - start)));
/* @internal */
exports.timedWith = timedWith;
const tracerWith = Tracer.tracerWith;
/** @internal */
exports.tracerWith = tracerWith;
const tracer = /*#__PURE__*/tracerWith(core.succeed);
/* @internal */
exports.tracer = tracer;
const tryPromise = arg => {
  let evaluate;
  let catcher = undefined;
  if (typeof arg === "function") {
    evaluate = arg;
  } else {
    evaluate = arg.try;
    catcher = arg.catch;
  }
  if (evaluate.length >= 1) {
    return core.suspend(() => {
      const controller = new AbortController();
      return core.flatMap(try_(() => evaluate(controller.signal)), promise => core.async(resolve => {
        promise.then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitFail(catcher ? catcher(e) : e)));
        return core.sync(() => controller.abort());
      }));
    });
  }
  return core.flatMap(try_(arg), promise => core.async(resolve => {
    promise.then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitFail(catcher ? catcher(e) : e)));
  }));
};
/* @internal */
exports.tryPromise = tryPromise;
const tryMap = /*#__PURE__*/(0, _Function.dual)(2, (self, options) => core.flatMap(self, a => try_({
  try: () => options.try(a),
  catch: options.catch
})));
/* @internal */
exports.tryMap = tryMap;
const tryMapPromise = /*#__PURE__*/(0, _Function.dual)(2, (self, options) => core.flatMap(self, a => tryPromise({
  try: options.try.length >= 1 ? signal => options.try(a, signal) : () => options.try(a),
  catch: options.catch
})));
/* @internal */
exports.tryMapPromise = tryMapPromise;
const unless = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => core.suspend(() => predicate() ? succeedNone : asSome(self)));
/* @internal */
exports.unless = unless;
const unlessEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => core.flatMap(predicate, b => b ? succeedNone : asSome(self)));
/* @internal */
exports.unlessEffect = unlessEffect;
const unsandbox = self => mapErrorCause(self, internalCause.flatten);
/* @internal */
exports.unsandbox = unsandbox;
const updateFiberRefs = f => core.withFiberRuntime(state => {
  state.setFiberRefs(f(state.id(), state.unsafeGetFiberRefs()));
  return core.unit;
});
/* @internal */
exports.updateFiberRefs = updateFiberRefs;
const updateService = /*#__PURE__*/(0, _Function.dual)(3, (self, tag, f) => core.mapInputContext(self, context => Context.add(context, tag, f(Context.unsafeGet(context, tag)))));
/* @internal */
exports.updateService = updateService;
const when = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => core.suspend(() => predicate() ? core.map(self, Option.some) : core.succeed(Option.none())));
/* @internal */
exports.when = when;
const whenFiberRef = /*#__PURE__*/(0, _Function.dual)(3, (self, fiberRef, predicate) => core.flatMap(core.fiberRefGet(fiberRef), s => predicate(s) ? core.map(self, a => [s, Option.some(a)]) : core.succeed([s, Option.none()])));
/* @internal */
exports.whenFiberRef = whenFiberRef;
const whenRef = /*#__PURE__*/(0, _Function.dual)(3, (self, ref, predicate) => core.flatMap(Ref.get(ref), s => predicate(s) ? core.map(self, a => [s, Option.some(a)]) : core.succeed([s, Option.none()])));
/* @internal */
exports.whenRef = whenRef;
const withMetric = /*#__PURE__*/(0, _Function.dual)(2, (self, metric) => metric(self));
/** @internal */
exports.withMetric = withMetric;
const serviceFunctionEffect = (service, f) => (...args) => core.flatMap(service, a => f(a)(...args));
/** @internal */
exports.serviceFunctionEffect = serviceFunctionEffect;
const serviceFunction = (service, f) => (...args) => core.map(service, a => f(a)(...args));
// -----------------------------------------------------------------------------
// tracing
// -----------------------------------------------------------------------------
/* @internal */
exports.serviceFunction = serviceFunction;
const annotateCurrentSpan = function () {
  const args = arguments;
  return core.flatMap(currentSpan, span => span._tag === "Some" ? core.sync(() => {
    if (typeof args[0] === "string") {
      span.value.attribute(args[0], args[1]);
    } else {
      for (const key in args[0]) {
        span.value.attribute(key, args[0][key]);
      }
    }
  }) : core.unit);
};
/* @internal */
exports.annotateCurrentSpan = annotateCurrentSpan;
const annotateSpans = /*#__PURE__*/(0, _Function.dual)(args => core.isEffect(args[0]), function () {
  const args = arguments;
  return core.fiberRefLocallyWith(args[0], core.currentTracerSpanAnnotations, typeof args[1] === "string" ? HashMap.set(args[1], args[2]) : annotations => Object.entries(args[1]).reduce((acc, [key, value]) => HashMap.set(acc, key, value), annotations));
});
/* @internal */
exports.annotateSpans = annotateSpans;
const currentParentSpan = /*#__PURE__*/core.map( /*#__PURE__*/core.fiberRefGet(core.currentTracerSpan), List.head);
/* @internal */
exports.currentParentSpan = currentParentSpan;
const currentSpan = /*#__PURE__*/core.map( /*#__PURE__*/core.fiberRefGet(core.currentTracerSpan), /*#__PURE__*/List.findFirst(span => span._tag === "Span"));
exports.currentSpan = currentSpan;
const bigint0 = /*#__PURE__*/BigInt(0);
/** @internal */
const currentTimeNanosTracing = /*#__PURE__*/core.fiberRefGetWith(core.currentTracerTimingEnabled, enabled => enabled ? Clock.currentTimeNanos : core.succeed(bigint0));
/* @internal */
exports.currentTimeNanosTracing = currentTimeNanosTracing;
const linkSpans = /*#__PURE__*/(0, _Function.dual)(args => core.isEffect(args[0]), (self, span, attributes) => core.fiberRefLocallyWith(self, core.currentTracerSpanLinks, Chunk.append({
  _tag: "SpanLink",
  span,
  attributes: attributes ?? {}
})));
/** @internal */
exports.linkSpans = linkSpans;
const makeSpan = (name, options) => tracerWith(tracer => core.flatMap(options?.parent ? succeedSome(options.parent) : options?.root ? succeedNone : currentParentSpan, parent => core.flatMap(core.fiberRefGet(core.currentTracerSpanAnnotations), annotations => core.flatMap(core.fiberRefGet(core.currentTracerSpanLinks), links => core.flatMap(currentTimeNanosTracing, startTime => core.sync(() => {
  const linksArray = options?.links ? [...Chunk.toReadonlyArray(links), ...options.links] : Chunk.toReadonlyArray(links);
  const span = tracer.span(name, parent, options?.context ?? Context.empty(), linksArray, startTime);
  HashMap.forEach(annotations, (value, key) => span.attribute(key, value));
  Object.entries(options?.attributes ?? {}).forEach(([k, v]) => span.attribute(k, v));
  return span;
}))))));
/* @internal */
exports.makeSpan = makeSpan;
const spanAnnotations = /*#__PURE__*/core.fiberRefGet(core.currentTracerSpanAnnotations);
/* @internal */
exports.spanAnnotations = spanAnnotations;
const spanLinks = /*#__PURE__*/core.fiberRefGet(core.currentTracerSpanLinks);
/** @internal */
exports.spanLinks = spanLinks;
const useSpan = (name, ...args) => {
  const options = args.length === 1 ? undefined : args[0];
  const evaluate = args[args.length - 1];
  return core.acquireUseRelease(makeSpan(name, options), evaluate, (span, exit) => core.flatMap(currentTimeNanosTracing, endTime => core.sync(() => span.end(endTime, exit))));
};
/** @internal */
exports.useSpan = useSpan;
const withParentSpan = /*#__PURE__*/(0, _Function.dual)(2, (self, span) => core.fiberRefLocallyWith(self, core.currentTracerSpan, List.prepend(span)));
/** @internal */
exports.withParentSpan = withParentSpan;
const withSpan = /*#__PURE__*/(0, _Function.dual)(args => typeof args[0] !== "string", (self, name, options) => useSpan(name, options ?? {}, span => withParentSpan(self, span)));
// -------------------------------------------------------------------------------------
// optionality
// -------------------------------------------------------------------------------------
/* @internal */
exports.withSpan = withSpan;
const fromNullable = evaluate => core.suspend(() => {
  const a = evaluate();
  if (a === null || a === undefined) {
    return core.fail(internalCause.NoSuchElementException());
  }
  return core.succeed(a);
});
/* @internal */
exports.fromNullable = fromNullable;
const optionFromOptional = self => core.catchAll(core.map(self, Option.some), error => internalCause.isNoSuchElementException(error) ? succeedNone : core.fail(error));
exports.optionFromOptional = optionFromOptional;
//# sourceMappingURL=effect.js.map