class EventBus {
    handlers = new Map();
    interceptors = new Map();
    subscribe(event, handler) {
        if (!this.handlers.has(event)) this.handlers.set(event, []);
        this.handlers.get(event).push({
            handler
        });
        return ()=>{
            const handlers = this.handlers.get(event);
            const index = handlers.findIndex((h)=>h.handler === handler);
            if (index > -1) handlers.splice(index, 1);
        };
    }
    async publish(event, data) {
        const handlers = this.handlers.get(event);
        const interceptors = this.interceptors.get(event);
        let hijacked = false;
        if (interceptors) {
            const results = await Promise.all(interceptors.map((interceptor)=>interceptor.interceptor(data)));
            hijacked = results.some((result)=>true === result);
        }
        if (handlers) handlers.forEach((handler)=>{
            handler.handler(hijacked ? {
                ...data,
                hijacked: true
            } : data);
        });
    }
    intercept(event, interceptor) {
        if (!this.interceptors.has(event)) this.interceptors.set(event, []);
        this.interceptors.get(event).push({
            interceptor
        });
        return ()=>{
            const interceptors = this.interceptors.get(event);
            const index = interceptors.findIndex((i)=>i.interceptor === interceptor);
            if (index > -1) interceptors.splice(index, 1);
        };
    }
    clear(event) {
        if (event) {
            this.handlers.delete(event);
            this.interceptors.delete(event);
        } else {
            this.handlers.clear();
            this.interceptors.clear();
        }
    }
}
export { EventBus };
