ext/Ratelimiter.js

"use strict";
// Ratelimiter.ts - cuz b1nzy (noud02)
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Ratelimiter bucket
 *
 * @export
 * @class Ratelimiter
 */
class Ratelimiter {
    constructor(max = 10, time = 10000) {
        this.max = max;
        this.time = time;
        /**
         * If the bucket is soft ratelimited or not
         *
         * @type {boolean}
         */
        this.soft = false;
        /**
         * If the warning was sent
         *
         * @type {boolean}
         */
        this.sentWarn = false;
        /**
         * Last use (timestamp)
         *
         * @type {number}
         */
        this.lastUse = 0;
        /**
         * Uses
         *
         * @type {number}
         */
        this.uses = 0;
        /**
         * Bucket reset interval
         *
         * @type {NodeJS.Timer}
         */
        this.interval = setInterval(() => { this.uses = 0; this.sentWarn = false; this.soft = false; }, this.time);
    }
    /**
     * Use the bucket
     *
     * @returns {string}
     */
    use() {
        if (this.uses < this.max) {
            this.uses++;
            if (this.lastUse !== 0 ? (this.lastUse + this.time / 2) - Date.now() <= 0 : true) {
                this.soft = false;
                this.lastUse = Date.now();
                return "OK";
            }
            else {
                this.soft = true;
                return "RATELIMITED";
            }
        }
        this.lastUse = Date.now();
        return "RATELIMITED";
    }
}
exports.Ratelimiter = Ratelimiter;