// Plausible bug: `<= 0` checks let NaN through, last-seen time follows a backwards clock, available() rounds, and refill 0 yields Infinity.export type LimiterConfig = { capacity: number; refillPerSecond: number };export type Limiter = { tryTake(n: number): boolean; available(): number; retryAfterMs(n: number): number | undefined;};export class LimiterError extends Error { constructor(public readonly kind: "invalid_config") { super(kind); }}export function createLimiter(config: LimiterConfig, now: () => number): Limiter { const { capacity, refillPerSecond: rate } = config; if (capacity <= 0 || rate < 0) throw new LimiterError("invalid_config"); let tokens = capacity; let last = now(); const refill = () => { const t = now(); tokens = Math.min(capacity, tokens + (Math.max(0, t - last) * rate) / 1000); last = t; }; return { tryTake(n) { refill(); if (n <= 0 || tokens < n) return false; tokens -= n; return true; }, available() { refill(); return Math.round(tokens); }, retryAfterMs(n) { refill(); if (n > capacity) return undefined; if (tokens >= n) return 0; return Math.ceil(((n - tokens) / rate) * 1000); }, };}