class LRU {
    max;
    map = new Map();
    head = null; // MRU end
    tail = null; // LRU end
    constructor(max) {
        this.max = max;
    }
    get(key) {
        const node = this.map.get(key);
        if (!node)
            return undefined;
        if (node.exp && Date.now() > node.exp) {
            this.evict(node);
            return undefined;
        }
        this.promote(node);
        return node.val;
    }
    set(key, val, ttlMs) {
        const existing = this.map.get(key);
        if (existing) {
            existing.val = val;
            existing.exp = ttlMs ? Date.now() + ttlMs : 0;
            this.promote(existing);
            return;
        }
        const node = { key, val, exp: ttlMs ? Date.now() + ttlMs : 0, prev: null, next: this.head };
        if (this.head)
            this.head.prev = node;
        this.head = node;
        if (!this.tail)
            this.tail = node;
        this.map.set(key, node);
        if (this.map.size > this.max)
            this.evictTail();
    }
    delete(key) { const n = this.map.get(key); if (n)
        this.evict(n); }
    keys() { return this.map.keys(); }
    promote(node) {
        if (node === this.head)
            return;
        if (node.prev)
            node.prev.next = node.next;
        if (node.next)
            node.next.prev = node.prev;
        if (node === this.tail)
            this.tail = node.prev;
        node.prev = null;
        node.next = this.head;
        if (this.head)
            this.head.prev = node;
        this.head = node;
    }
    evict(node) {
        if (node.prev)
            node.prev.next = node.next;
        else
            this.head = node.next;
        if (node.next)
            node.next.prev = node.prev;
        else
            this.tail = node.prev;
        this.map.delete(node.key);
    }
    evictTail() { if (this.tail)
        this.evict(this.tail); }
}
const store = new LRU(2_000);
export class MemoryCacheAdapter {
    async get(key) {
        const raw = store.get(key);
        return raw !== undefined ? JSON.parse(raw) : null;
    }
    async set(key, value, ttlSeconds) {
        store.set(key, JSON.stringify(value), ttlSeconds * 1_000);
    }
    async delByPrefix(prefix) {
        for (const key of store.keys()) {
            if (key.startsWith(prefix))
                store.delete(key);
        }
    }
}
