/**
 * Per-ID ordered message relay queue.
 * Guarantees messages for the same ID are processed sequentially,
 * preventing out-of-order delivery caused by async encryption/compression.
 */
export class MessageRelay {
    queues = new Map();
    /**
     * Enqueue a message handler for the given ID.
     * Handlers for the same ID execute in order; different IDs run concurrently.
     */
    enqueue(id, handler) {
        const prev = this.queues.get(id) || Promise.resolve();
        const next = prev.then(handler).catch(() => { });
        this.queues.set(id, next);
        // Reset chain after completion to prevent unbounded promise chain growth.
        // Safe: if a new message was enqueued before this fires, the map entry
        // will have moved on and the comparison will fail — no clobbering.
        next.then(() => {
            if (this.queues.get(id) === next) {
                this.queues.set(id, Promise.resolve());
            }
        });
    }
    /**
     * Remove the queue for the given ID (call on disconnect).
     */
    cleanup(id) {
        this.queues.delete(id);
    }
}
//# sourceMappingURL=message-relay.js.map