class MutableTaskHandle {
    id;
    cancelled = false;
    constructor(id) {
        this.id = id;
    }
    cancel() {
        this.cancelled = true;
    }
}
export class TaskQueue {
    queue = [];
    nextId = 1;
    enqueue(task) {
        const handle = new MutableTaskHandle(this.nextId++);
        this.queue.push({ handle, task });
        return handle;
    }
    get size() {
        return this.queue.length;
    }
    async flush() {
        const errors = [];
        while (this.queue.length > 0) {
            const batch = this.queue;
            this.queue = [];
            for (const item of batch) {
                if (item.handle.cancelled)
                    continue;
                try {
                    await item.task();
                }
                catch (error) {
                    errors.push(error);
                }
            }
        }
        if (errors.length > 0)
            throw new AggregateError(errors, "One or more queued tasks failed.");
    }
}
//# sourceMappingURL=TaskQueue.js.map