export class IdleAwareCadence {
    opts;
    timer = null;
    stopped = false;
    running = false;
    constructor(opts) {
        this.opts = opts;
    }
    start() {
        if (this.timer || this.stopped)
            return;
        this.schedule();
    }
    stop() {
        this.stopped = true;
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    }
    /** The delay (ms) the NEXT tick will wait, given the current idle state. */
    currentIntervalMs() {
        return this.idleSafe() ? this.opts.idleMs : this.opts.activeMs;
    }
    idleSafe() {
        try {
            return this.opts.isIdle();
        }
        catch {
            return false;
        } // @silent-fallback-ok — ambiguous ⇒ ACTIVE (never back off on error)
    }
    schedule() {
        if (this.stopped)
            return;
        const delay = this.idleSafe() ? this.opts.idleMs : this.opts.activeMs;
        this.timer = setTimeout(() => { void this.run(); }, delay);
        if (typeof this.timer.unref === 'function')
            this.timer.unref();
    }
    async run() {
        if (this.stopped || this.running) {
            this.schedule();
            return;
        }
        this.running = true;
        try {
            await this.opts.tick();
        }
        catch { /* never throw out of the timer loop */ }
        finally {
            this.running = false;
        }
        this.schedule(); // re-evaluate idle state on every reschedule
    }
}
//# sourceMappingURL=IdleAwareCadence.js.map