Write a TypeScript function named createIdempotencyGuard for a high-throughput job worker.
Requirements:
- It accepts an object with
key, ttlMs, optional maxEntries (default 10_000), and an async handler function.
- If the same key is currently being processed, return the same in-flight Promise instead of running handler again (single-flight / stampede protection).
- After successful completion, cache and return the result until ttlMs expires.
- If handler throws, do not cache the failure; a future call with the same key must retry.
- When the cache would exceed maxEntries, evict the oldest completed entry (FIFO among completed keys only; never evict in-flight keys).
- Use only in-memory JavaScript/TypeScript primitives; no libraries.
- Explain time and space complexity.
- Include at least 5 test cases covering concurrency, caching, expiry, eviction, and errors.
Output format:
{
"code": "...",
"explanation": "...",
"complexity": {
"time": "...",
"space": "..."
},
"tests": ["...", "...", "...", "...", "..."]
}