import * as Context from "@effect/data/Context";
import * as Debug from "@effect/data/Debug";
import * as Option from "@effect/data/Option";
import * as Exit from "@effect/io/Exit";
import * as Fiber from "@effect/io/Fiber";
import * as FiberId from "@effect/io/Fiber/Id";
import * as FiberRefs from "@effect/io/FiberRefs";
import * as CausePretty from "@effect/io/internal_effect_untraced/cause-pretty";
import * as core from "@effect/io/internal_effect_untraced/core";
import * as FiberRuntime from "@effect/io/internal_effect_untraced/fiberRuntime";
import * as fiberScope from "@effect/io/internal_effect_untraced/fiberScope";
import * as OpCodes from "@effect/io/internal_effect_untraced/opCodes/effect";
import * as runtimeFlags from "@effect/io/internal_effect_untraced/runtimeFlags";
import * as _supervisor from "@effect/io/internal_effect_untraced/supervisor";
import * as _scheduler from "@effect/io/Scheduler";
/** @internal */
export const unsafeFork = runtime => Debug.methodWithTrace(trace => (self, options) => {
  const fiberId = FiberId.unsafeMake();
  const effect = self.traced(trace);
  let fiberRefs = FiberRefs.updatedAs(runtime.fiberRefs, fiberId, core.currentContext, runtime.context);
  if (options?.scheduler) {
    fiberRefs = FiberRefs.updatedAs(fiberRefs, fiberId, core.currentScheduler, options.scheduler);
  }
  if (options?.updateRefs) {
    fiberRefs = options.updateRefs(fiberRefs, fiberId);
  }
  const fiberRuntime = new FiberRuntime.FiberRuntime(fiberId, FiberRefs.forkAs(fiberRefs, fiberId), runtime.runtimeFlags);
  const supervisor = fiberRuntime.getSupervisor();
  if (supervisor !== _supervisor.none) {
    supervisor.onStart(runtime.context, effect, Option.none(), fiberRuntime);
    fiberRuntime.unsafeAddObserver(exit => supervisor.onEnd(exit, fiberRuntime));
  }
  fiberScope.globalScope.add(runtime.runtimeFlags, fiberRuntime);
  fiberRuntime.start(effect);
  return fiberRuntime;
});
/** @internal */
export const unsafeRunCallback = runtime => Debug.methodWithTrace(trace => (effect, onExit) => {
  const fiberRuntime = unsafeFork(runtime)(effect.traced(trace));
  if (onExit) {
    fiberRuntime.unsafeAddObserver(exit => {
      onExit(exit);
    });
  }
  return (id, onExitInterrupt) => unsafeRunCallback(runtime)(Fiber.interruptAs(id ?? FiberId.none)(fiberRuntime), onExitInterrupt ? exit => onExitInterrupt(Exit.flatten(exit)) : void 0);
});
/** @internal */
export const unsafeRunSync = runtime => Debug.methodWithTrace(trace => effect => {
  const scheduler = new _scheduler.SyncScheduler();
  const fiberRuntime = unsafeFork(runtime)(effect.traced(trace), {
    scheduler
  });
  scheduler.flush();
  const result = fiberRuntime.unsafePoll();
  if (result) {
    if (result._tag === "Failure") {
      throw fiberFailure(result.i0);
    } else {
      return result.i0;
    }
  }
  throw asyncFiberException(fiberRuntime);
});
/** @internal */
const asyncFiberException = fiber => {
  const limit = Error.stackTraceLimit;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = limit;
  const message = `Fiber #${fiber.id().id} has suspended work asynchronously`;
  const _tag = "AsyncFiberException";
  Object.defineProperties(error, {
    _tag: {
      value: _tag
    },
    message: {
      value: message
    },
    name: {
      value: _tag
    },
    toString: {
      get() {
        return () => message;
      }
    },
    [NodePrint]: {
      get() {
        return () => message;
      }
    }
  });
  return error;
};
/** @internal */
export const isAsyncFiberException = u => typeof u === "object" && u !== null && "_tag" in u && u._tag === "AsyncFiberException" && "fiber" in u;
/** @internal */
export const FiberFailureId = /*#__PURE__*/Symbol.for("@effect/io/Runtime/FiberFailure");
/** @internal */
export const FiberFailureCauseId = /*#__PURE__*/Symbol.for("@effect/io/Runtime/FiberFailure/Cause");
/** @internal */
export const NodePrint = /*#__PURE__*/Symbol.for("nodejs.util.inspect.custom");
/** @internal */
export const fiberFailure = cause => {
  const limit = Error.stackTraceLimit;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = limit;
  const pretty = CausePretty.prettyErrors(cause);
  if (pretty.length > 0) {
    error.name = pretty[0].message.split(":")[0];
    error.message = pretty[0].message.substring(error.name.length + 2);
    error.stack = `${error.name}: ${error.message}\n${pretty[0].stack}`;
  }
  error[FiberFailureId] = FiberFailureId;
  error[FiberFailureCauseId] = cause;
  error.toString = () => {
    return CausePretty.pretty(cause);
  };
  error[NodePrint] = () => {
    return error.toString();
  };
  return error;
};
/** @internal */
export const isFiberFailure = u => typeof u === "object" && u !== null && FiberFailureId in u;
/** @internal */
export const unsafeRunSyncExit = runtime => Debug.methodWithTrace(trace => effect => {
  const scheduler = new _scheduler.SyncScheduler();
  const fiberRuntime = unsafeFork(runtime)(core.exit(effect).traced(trace), {
    scheduler
  });
  scheduler.flush();
  const result = fiberRuntime.unsafePoll();
  if (result) {
    if (result._tag === "Failure") {
      throw fiberFailure(result.i0);
    } else {
      return result.i0;
    }
  }
  throw asyncFiberException(fiberRuntime);
});
/** @internal */
export const unsafeRunSyncEither = runtime => effect => Debug.untraced(() => unsafeRunSync(runtime)(core.either(effect)));
/** @internal */
export const unsafeRunPromise = runtime => Debug.methodWithTrace(trace => effect => new Promise((resolve, reject) => {
  unsafeFork(runtime)(effect.traced(trace)).unsafeAddObserver(result => {
    switch (result._tag) {
      case OpCodes.OP_SUCCESS:
        {
          resolve(result.i0);
          break;
        }
      case OpCodes.OP_FAILURE:
        {
          reject(fiberFailure(result.i0));
          break;
        }
    }
  });
}));
/** @internal */
export const unsafeRunPromiseExit = runtime => Debug.methodWithTrace(trace => effect => new Promise((resolve, reject) => {
  unsafeFork(runtime)(core.exit(effect).traced(trace)).unsafeAddObserver(exit => {
    switch (exit._tag) {
      case OpCodes.OP_SUCCESS:
        {
          resolve(exit.i0);
          break;
        }
      case OpCodes.OP_FAILURE:
        {
          reject(fiberFailure(exit.i0));
          break;
        }
    }
  });
}));
/** @internal */
export const unsafeRunPromiseEither = runtime => effect => unsafeRunPromise(runtime)(core.either(effect));
/** @internal */
export class RuntimeImpl {
  constructor(context, runtimeFlags, fiberRefs) {
    this.context = context;
    this.runtimeFlags = runtimeFlags;
    this.fiberRefs = fiberRefs;
  }
}
/** @internal */
export const make = (context, runtimeFlags, fiberRefs) => new RuntimeImpl(context, runtimeFlags, fiberRefs);
/** @internal */
export const runtime = /*#__PURE__*/Debug.methodWithTrace(trace => () => core.withFiberRuntime((state, status) => core.succeed(new RuntimeImpl(state.getFiberRef(core.currentContext), status.runtimeFlags, state.unsafeGetFiberRefs()))).traced(trace));
/** @internal */
export const defaultRuntimeFlags = /*#__PURE__*/runtimeFlags.make(runtimeFlags.Interruption, runtimeFlags.CooperativeYielding);
/** @internal */
export const defaultRuntime = /*#__PURE__*/make( /*#__PURE__*/Context.empty(), defaultRuntimeFlags, /*#__PURE__*/FiberRefs.unsafeMake( /*#__PURE__*/new Map()));
/** @internal */
export const unsafeRunEffect = /*#__PURE__*/unsafeRunCallback(defaultRuntime);
/** @internal */
export const unsafeForkEffect = /*#__PURE__*/unsafeFork(defaultRuntime);
/** @internal */
export const unsafeRunPromiseEffect = /*#__PURE__*/unsafeRunPromise(defaultRuntime);
/** @internal */
export const unsafeRunPromiseEitherEffect = /*#__PURE__*/unsafeRunPromiseEither(defaultRuntime);
/** @internal */
export const unsafeRunPromiseExitEffect = /*#__PURE__*/unsafeRunPromiseExit(defaultRuntime);
/** @internal */
export const unsafeRunSyncEffect = /*#__PURE__*/unsafeRunSync(defaultRuntime);
/** @internal */
export const unsafeRunSyncExitEffect = /*#__PURE__*/unsafeRunSyncExit(defaultRuntime);
/** @internal */
export const unsafeRunSyncEitherEffect = /*#__PURE__*/unsafeRunSyncEither(defaultRuntime);
// circular with Effect
/** @internal */
export const asyncEffect = /*#__PURE__*/Debug.methodWithTrace((trace, restoreTrace) => register => core.flatMap(core.deferredMake(), deferred => core.flatMap(runtime(), runtime => core.uninterruptibleMask(restore => core.zipRight(FiberRuntime.fork(restore(core.catchAllCause(restoreTrace(register)(cb => unsafeRunCallback(runtime)(core.intoDeferred(deferred)(cb))), cause => core.deferredFailCause(deferred, cause)))), restore(core.deferredAwait(deferred)))))).traced(trace));
//# sourceMappingURL=runtime.mjs.map