import { getRandomInt } from './chunk-MBFX3DT4.mjs';

// src/p.delay.ts
var createAbortError = () => {
  const error = new Error("Delay aborted");
  error.name = "AbortError";
  return error;
};
var clearMethods = /* @__PURE__ */ new WeakMap();
function delay(milliseconds, options) {
  return createDelay(milliseconds, options);
}
function createDelay(milliseconds, { value, signal } = {}) {
  if (signal?.aborted) {
    return Promise.reject(createAbortError());
  }
  let timeoutId;
  let settle;
  let rejectFunction;
  const signalListener = () => {
    clearTimeout(timeoutId);
    rejectFunction(createAbortError());
  };
  const cleanup = () => {
    if (signal) {
      signal.removeEventListener("abort", signalListener);
    }
  };
  const delayPromise = new Promise((resolve, reject) => {
    settle = () => {
      cleanup();
      if (value)
        resolve(value);
    };
    rejectFunction = reject;
    timeoutId = setTimeout(settle, milliseconds);
  });
  if (signal) {
    signal.addEventListener("abort", signalListener, { once: true });
  }
  clearMethods.set(delayPromise, () => {
    clearTimeout(timeoutId);
    timeoutId = void 0;
    settle();
  });
  return delayPromise;
}
async function rangeDelay(minimum, maximum, options = {}) {
  return delay(getRandomInt(minimum, maximum), options);
}
function clearDelay(promise) {
  clearMethods.get(promise)?.();
}

export { clearDelay, createDelay, delay, rangeDelay };
