import { __commonJSMin } from "../../../../_virtual/rolldown_runtime.js";
import { require_ral } from "./ral.js";
var require_semaphore = /* @__PURE__ */ __commonJSMin(((e) => {
	Object.defineProperty(e, "__esModule", { value: !0 }), e.Semaphore = void 0;
	var n = require_ral();
	e.Semaphore = class {
		constructor(e = 1) {
			if (e <= 0) throw Error("Capacity must be greater than 0");
			this._capacity = e, this._active = 0, this._waiting = [];
		}
		lock(e) {
			return new Promise((t, n) => {
				this._waiting.push({
					thunk: e,
					resolve: t,
					reject: n
				}), this.runNext();
			});
		}
		get active() {
			return this._active;
		}
		runNext() {
			this._waiting.length === 0 || this._active === this._capacity || (0, n.default)().timer.setImmediate(() => this.doRunNext());
		}
		doRunNext() {
			if (this._waiting.length === 0 || this._active === this._capacity) return;
			let e = this._waiting.shift();
			if (this._active++, this._active > this._capacity) throw Error("To many thunks active");
			try {
				let t = e.thunk();
				t instanceof Promise ? t.then((t) => {
					this._active--, e.resolve(t), this.runNext();
				}, (t) => {
					this._active--, e.reject(t), this.runNext();
				}) : (this._active--, e.resolve(t), this.runNext());
			} catch (t) {
				this._active--, e.reject(t), this.runNext();
			}
		}
	};
}));
export default require_semaphore();
export { require_semaphore };
