const locks = new Map>(); export function withKeyedLock( key: string, fn: () => Promise, ): Promise { const prev = locks.get(key) ?? Promise.resolve(); const next = prev.then(fn, fn); const cleanup = next.then( () => {}, () => {}, ); locks.set(key, cleanup); cleanup.then(() => { if (locks.get(key) === cleanup) locks.delete(key); }); return next; }