The module will be called cachify-function. It should export functions:
cachify(func, options) -> CachifyFunctionContext
runCache(cfc, ...funcArgs) // returns the cached
runStale(cfc, ...funcArgs)
runFresh(cfc, ...funcArgs) // basically just a wrapper for the main function, with the difference being it stores the in-flight promise in case cache or stale use it
runFreshCached(cfc, ...funcArgs) // this only matters for promises, but basically if a promise is still pending it should return that, but if its already resolved or doesn't exist, then run a new one. Fyi, you should be storing its state by using .then, .catch because regardless you need to do .catch to check if theres an error, and if so to remove it from storage and to either throw it or not depending on the situation (check suppress_stale_revalidate_errors below)
invalidate(cfc, ...funcArgs)
invalidateAll(cfc)
there should be options such as:
max_age (ms)
max_age_auto_invalidate (this is in ms, and it should default to 1.5x the max_age, and allow 0 or false which means it is never auto invalidated. It must be greater than or equal to max_age or throw an error. Keep in mind whatever design you use should be efficient and should cancel if invalidate() is ran for example. FYI - .runCache should still follow max_age. This value only matters for .runStale since it basically deletes the cached value regardless after max_age_auto_invalidate, while cache follows max_age.
suppress_stale_revalidate_errors (default true. Note that this shouldn't be confused with non-stale errors. For example it should throw an error if you're running cache() and the function throws an error. Or for example if you're running stale() and it hasn't been cached before. But if you run stale() and it returns a cached value then revalidates in the background, it should not throw an error while this is enabled)
At all times, with the exception of fresh(), if there is an in-flight
Think of corner cases and ensure this is all robust. If you include any comments, keep them short and to the point. Don't put comments in self explanatory easy to understand code.
This library should be usable in both js and nodejs.
Assistant
Below is a TypeScript implementation of the cachify-function library based on your requirements. The code is modular, type-safe, and optimized for performance. It avoids third-party dependencies and follows best practices as of 2025.