import { resolver } from "@rocicorp/resolver";
import { AbortError } from "./abort-error.js";
const promiseVoid = Promise.resolve();
const promiseNever = new Promise(() => void 0);
function sleep(ms, signal) {
  const newAbortError = () => new AbortError("Aborted");
  if (signal?.aborted) {
    return Promise.reject(newAbortError());
  }
  if (ms === 0) {
    return promiseVoid;
  }
  return new Promise((resolve, reject) => {
    let handleAbort;
    if (signal) {
      handleAbort = () => {
        clearTimeout(id);
        reject(newAbortError());
      };
      signal.addEventListener("abort", handleAbort, { once: true });
    }
    const id = setTimeout(() => {
      resolve();
      signal?.removeEventListener("abort", handleAbort);
    }, ms);
  });
}
function sleepWithAbort(ms, signal) {
  if (ms === 0) {
    return [promiseVoid, promiseNever];
  }
  const { promise: abortedPromise, resolve: abortedResolve } = resolver();
  const sleepPromise = new Promise((resolve) => {
    const handleAbort = () => {
      clearTimeout(id);
      abortedResolve();
    };
    const id = setTimeout(() => {
      resolve();
      signal.removeEventListener("abort", handleAbort);
    }, ms);
    signal.addEventListener("abort", handleAbort, { once: true });
  });
  return [sleepPromise, abortedPromise];
}
export {
  sleep,
  sleepWithAbort
};
//# sourceMappingURL=sleep.js.map
