var _a;
import * as Context from "@effect/data/Context";
import * as Debug from "@effect/data/Debug";
import * as Either from "@effect/data/Either";
import { constFalse } from "@effect/data/Function";
import * as core from "@effect/io/internal_effect_untraced/core";
/** @internal */
const ClockSymbolKey = "@effect/io/Clock";
/** @internal */
export const ClockTypeId = /*#__PURE__*/Symbol.for(ClockSymbolKey);
/** @internal */
export const clockTag = /*#__PURE__*/Context.Tag(ClockTypeId);
/** @internal */
export const MAX_TIMER_MILLIS = 2 ** 31 - 1;
/** @internal */
export const globalClockScheduler = {
  unsafeSchedule(task, duration) {
    // If the duration is greater than the value allowable by the JS timer
    // functions, treat the value as an infinite duration
    if (duration.millis > MAX_TIMER_MILLIS) {
      return constFalse;
    }
    let completed = false;
    const handle = setTimeout(() => {
      completed = true;
      task();
    }, duration.millis);
    return () => {
      clearTimeout(handle);
      return !completed;
    };
  }
};
const performanceNowNanos = /*#__PURE__*/function () {
  const origin = /*#__PURE__*/BigInt( /*#__PURE__*/Math.round(performance.timeOrigin * 1000000));
  return () => {
    const now = performance.now();
    const millis = Math.floor(now);
    return origin + BigInt(millis * 1000000) + BigInt(Math.round((now - millis) * 1000000));
  };
}();
/** @internal */
class ClockImpl {
  constructor() {
    this[_a] = ClockTypeId;
    this.processHrtime = typeof process === "object" && "hrtime" in process ? process.hrtime : undefined;
    this.timeOrigin = this.processHrtime ? performanceNowNanos() - this.processHrtime.bigint() : 0n;
  }
  unsafeCurrentTimeMillis() {
    return Date.now();
  }
  unsafeCurrentTimeNanos() {
    return this.processHrtime ? this.timeOrigin + this.processHrtime.bigint() : performanceNowNanos();
  }
  currentTimeMillis() {
    return Debug.bodyWithTrace(trace => core.sync(() => this.unsafeCurrentTimeMillis()).traced(trace));
  }
  currentTimeNanos() {
    return Debug.bodyWithTrace(trace => core.sync(() => this.unsafeCurrentTimeNanos()).traced(trace));
  }
  scheduler() {
    return Debug.bodyWithTrace(trace => core.succeed(globalClockScheduler).traced(trace));
  }
  sleep(duration) {
    return Debug.bodyWithTrace(trace => core.asyncInterruptEither(cb => {
      const canceler = globalClockScheduler.unsafeSchedule(() => cb(core.unit()), duration);
      return Either.left(core.asUnit(core.sync(canceler)));
    }).traced(trace));
  }
}
_a = ClockTypeId;
/** @internal */
export const make = () => new ClockImpl();
//# sourceMappingURL=clock.mjs.map