cachefor 1.0.0-test → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. This project follows [Semantic Versioning](https://semver.org/).
4
+
5
+ ## 1.0.0 - Unreleased
6
+
7
+ First release.
8
+
9
+ - `cachefor(ttl, options?)` creates an in-memory cache with a human-readable default TTL: `'30s'`, `'5m'`, `'1h 30m'`, `'2 days'`, `'forever'` or milliseconds.
10
+ - `get`, `set` (with a per-entry TTL), `has`, `peek` (no LRU or sliding update), `delete`, `clear`, `size`, `ttl(key)` (remaining milliseconds), `prune()`, and `keys` / `values` / `entries` / `for...of` iteration over unexpired entries.
11
+ - `getOrSet(key, loader, ttl?)`: concurrent misses share one in-flight promise, rejections are not cached, and `delete` / `clear` / `set` during a load stop its stale result from being cached. Loaders can set the TTL from the result with `ctx.setTtl()`. `getOrSetSync()` for synchronous loaders.
12
+ - `staleWhileRevalidate`: serve the expired value at once and refresh it in the background, once.
13
+ - `max` for LRU eviction, `sliding` expiration, and `onEvict(value, key, reason)` with reasons `'expired'`, `'evicted'`, `'deleted'`, `'replaced'` and `'cleared'`.
14
+ - Lazy expiry with no timers by default; optional `pruneInterval` uses an `unref()`'d timer that stops when the cache is garbage-collected.
15
+ - `now` option to inject a clock in tests; the default `Date.now` also follows fake timers.
16
+ - `memoize(fn, ttl | options)` and `cache.wrap(fn)` for sync and async functions, with custom `key`, in-flight dedup and `fn.cache` for invalidation.
17
+ - `parseTtl()` and `TtlError` for invalid TTLs (thrown when the cache is created).
18
+ - Strong TypeScript generics (`cachefor<User, number>('5m')`); TTL string literals are type-checked, so `'5 minuts'` is a compile error.
19
+ - ESM + CommonJS (`require('cachefor')('5m')` works), zero dependencies.
package/README.md CHANGED
@@ -1,18 +1,499 @@
1
1
  # cachefor
2
2
 
3
- Simple in-memory cache with readable TTLs: cachefor('5m'). Work in progress.
3
+ A small in-memory cache where you write the time to live in plain words: `cachefor('5m')`.
4
4
 
5
- > This is an early placeholder release. The full API is coming soon.
5
+ [![npm version](https://img.shields.io/npm/v/cachefor.svg)](https://www.npmjs.com/package/cachefor) [![bundle size](https://img.shields.io/bundlephobia/minzip/cachefor)](https://bundlephobia.com/package/cachefor) [![license](https://img.shields.io/npm/l/cachefor.svg)](LICENSE)
6
+
7
+ `cachefor` keeps values in memory for a set time, such as 5 minutes, and then forgets them. Use it to cache database calls, API responses or slow functions. The API is small, so you can learn it in a few minutes.
8
+
9
+ ## Features
10
+
11
+ - **Readable TTLs** (TTL = time to live, how long an entry stays in the cache): `'30s'`, `'5m'`, `'1h 30m'`, `'2 days'`, `'forever'` or milliseconds.
12
+ - **Typos are TypeScript errors**: `'5 minuts'` fails at compile time.
13
+ - **Shared loads**: `getOrSet()` runs the loader once, even when many calls ask for the same missing key at the same time. Failed loads are never cached.
14
+ - **Stale-while-revalidate**: return the old value right away and load a new one in the background.
15
+ - **Size limit and sliding expiration**: `max` removes the least recently used entry; `sliding` restarts the TTL on each read.
16
+ - **`onEvict` callback** tells you why each entry left the cache.
17
+ - **`memoize()`** caches the results of sync and async functions.
18
+ - **No timers by default**, so nothing keeps your process or test runner open.
19
+ - **Zero dependencies**, about 2.5 KB gzipped, ESM and CommonJS, TypeScript types included.
20
+
21
+ ## Installation
6
22
 
7
23
  ```sh
8
24
  npm install cachefor
9
25
  ```
10
26
 
27
+ ```sh
28
+ pnpm add cachefor
29
+ yarn add cachefor
30
+ bun add cachefor
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ ```js
36
+ import cachefor, { memoize } from 'cachefor'
37
+
38
+ // Entries live for 5 minutes. The cache holds at most 1000 entries.
39
+ const users = cachefor('5m', { max: 1000 })
40
+
41
+ users.set('ann', { name: 'Ann' })
42
+ users.get('ann') // => { name: 'Ann' }
43
+ users.set('bob', { name: 'Bob' }, '30s') // this entry lives 30 seconds only
44
+ users.get('nobody') // => undefined
45
+
46
+ // Load a value when it is missing. Calls at the same time share one load.
47
+ const cy = await users.getOrSet('cy', async (id) => ({ name: 'Cy' }))
48
+ cy // => { name: 'Cy' }
49
+
50
+ // Cache the results of a function for 1 hour
51
+ const double = memoize((n) => n * 2, '1h')
52
+ double(21) // => 42
53
+ ```
54
+
55
+ With CommonJS, use `const cachefor = require('cachefor')` and `const { memoize } = require('cachefor')`.
56
+
57
+ ## Table of contents
58
+
59
+ - [Usage](#usage)
60
+ - [API](#api)
61
+ - [Comparison](#comparison)
62
+ - [Migrating from other packages](#migrating-from-other-packages)
63
+ - [Notes and limitations](#notes-and-limitations)
64
+ - [Requirements](#requirements)
65
+ - [License](#license)
66
+
67
+ ## Usage
68
+
69
+ ### Write TTLs in plain words
70
+
71
+ You can pass a TTL as a number of milliseconds or as a string. This works everywhere a TTL is accepted.
72
+
73
+ ```js
74
+ cachefor(5000) // 5 seconds
75
+ cachefor('30s')
76
+ cachefor('5m') // 5 minutes
77
+ cachefor('1h 30m') // also '1h30m', '1 hour, 30 minutes', '1 hour and 30 minutes'
78
+ cachefor('1.5h')
79
+ cachefor('2 days')
80
+ cachefor('1w')
81
+ cachefor('forever') // same as Infinity
82
+ cachefor(process.env.CACHE_TTL ?? '10m')
83
+ ```
84
+
85
+ Units are not case-sensitive:
86
+
87
+ | Unit | Spellings |
88
+ |---|---|
89
+ | Milliseconds | `ms`, `msec`, `msecs`, `millisecond`, `milliseconds` |
90
+ | Seconds | `s`, `sec`, `secs`, `second`, `seconds` |
91
+ | Minutes | `m`, `min`, `mins`, `minute`, `minutes` |
92
+ | Hours | `h`, `hr`, `hrs`, `hour`, `hours` |
93
+ | Days | `d`, `day`, `days` |
94
+ | Weeks | `w`, `wk`, `wks`, `week`, `weeks` |
95
+
96
+ A string with only a number, like `'1500'`, means milliseconds. Months and years are not accepted, because their length changes.
97
+
98
+ An invalid TTL throws a `TtlError` when you create the cache. So a bad config value fails at startup, not later when the first entry expires.
99
+
100
+ `0` means "do not store". `set(key, value, 0)` removes any old value and stores nothing. `cachefor(0)` gives you shared loads with no caching at all.
101
+
102
+ ### Load a value when it is missing
103
+
104
+ `getOrSet(key, loader)` returns the cached value. If there is none, it calls `loader`, caches the result and returns it.
105
+
106
+ ```js
107
+ const cache = cachefor('10m')
108
+
109
+ app.get('/users/:id', async (req, res) => {
110
+ const user = await cache.getOrSet(req.params.id, (id) => db.users.find(id))
111
+ res.json(user)
112
+ })
113
+ ```
114
+
115
+ - **Calls at the same time share one load.** If 100 requests ask for the same missing key, the loader runs once. This stops a "cache stampede" (many requests loading the same thing at once).
116
+ - **Errors are not cached.** If the loader throws or rejects, every waiting caller gets the error and nothing is stored. The next call tries again.
117
+ - `getOrSet()` always returns a promise. The loader can be sync or async.
118
+ - If you call `delete()`, `clear()` or `set()` on the key while a load is running, the result of that load is not cached. Callers still receive it. This makes cache invalidation safe: an older read that finishes late cannot overwrite your change.
119
+
120
+ For sync work, `getOrSetSync(key, loader, ttl?)` returns the value directly.
121
+
122
+ ### Set the TTL from the loaded value
123
+
124
+ Pass a TTL as the third argument, or set it inside the loader once you know it:
125
+
126
+ ```js
127
+ await cache.getOrSet(key, load, '30s')
128
+
129
+ await tokens.getOrSet('github', async (key, ctx) => {
130
+ const { token, expires_in } = await refreshToken()
131
+ ctx.setTtl((expires_in - 60) * 1000) // expire one minute early
132
+ return token
133
+ })
134
+ ```
135
+
136
+ ### Return old values while a new one loads
137
+
138
+ Stale-while-revalidate means: when an entry has expired, return the old ("stale") value right away and load a fresh one in the background.
139
+
140
+ ```js
141
+ const prices = cachefor('1m', { staleWhileRevalidate: '5m' })
142
+
143
+ await prices.getOrSet('BTC', fetchPrice)
144
+ ```
145
+
146
+ - For up to 5 minutes after an entry expires, `getOrSet()`, `wrap()` and `memoize()` return the stale value at once. They refresh it in the background, once.
147
+ - If the refresh fails, the stale value is still returned and the next call tries again.
148
+ - After the 5 minutes, it is a normal miss.
149
+ - `staleWhileRevalidate: true` keeps stale values until they are replaced.
150
+ - `get()`, `has()`, `peek()`, `size` and iteration never return stale values.
151
+ - The loader can read the old value in `ctx.stale`.
152
+
153
+ ### Cache the results of a function
154
+
155
+ `memoize()` wraps a function and caches its results:
156
+
157
+ ```js
158
+ import { memoize } from 'cachefor'
159
+
160
+ const getUser = memoize(async (id) => db.users.find(id), { ttl: '5m' })
161
+ await getUser(1) // runs the query
162
+ await getUser(1) // returns the cached result
163
+
164
+ const slugify = memoize(expensiveSlugify, { max: 10_000 }) // sync functions work too
165
+ const getRates = memoize(fetchRates, '1h') // TTL shorthand
166
+
167
+ getUser.cache.delete(1) // remove one result
168
+ getUser.cache.clear() // remove all results
169
+ ```
170
+
171
+ - Async functions get the same features as `getOrSet()`: shared loads, no caching of errors, and stale-while-revalidate.
172
+ - Sync functions return values directly. Async functions always return a promise.
173
+ - The memoized function keeps `this`, `name` and `length`.
174
+
175
+ The cache key is the argument itself when the function takes one primitive argument (`1` and `'1'` are different keys). Otherwise it is `JSON.stringify(args)`. Pass `key` to build it yourself:
176
+
177
+ ```js
178
+ const getOrders = memoize(fetchOrders, {
179
+ ttl: '1m',
180
+ key: (user, opts) => `${user.id}:${opts.status}`,
181
+ })
182
+ ```
183
+
184
+ To cache a function in a cache you already have, use `cache.wrap(fn, { key, ttl })`.
185
+
186
+ ### Limit the size and restart the TTL on each read
187
+
188
+ ```js
189
+ const sessions = cachefor('30m', {
190
+ max: 10_000, // above this, remove the least recently used entry
191
+ sliding: true, // each get() restarts the 30 minutes
192
+ onEvict(session, id, reason) {
193
+ if (reason !== 'replaced') log(`session ${id} ended: ${reason}`)
194
+ },
195
+ })
196
+ ```
197
+
198
+ - `max` turns the cache into an LRU cache (least recently used). When it is full, the entry that was used longest ago is removed.
199
+ - `sliding: true` works like a session timeout. Each read gives the entry its full TTL again.
200
+
201
+ ### Know when entries leave the cache
202
+
203
+ `onEvict(value, key, reason)` runs after the cache is updated, once for each value that leaves. Use it to close or release values.
204
+
205
+ | Reason | When |
206
+ |---|---|
207
+ | `'expired'` | The TTL ran out. Reported when the entry is read or pruned, or when an expired entry is deleted, replaced, evicted or cleared. |
208
+ | `'evicted'` | Removed as least recently used, because of `max`. |
209
+ | `'deleted'` | Removed with `delete(key)`. |
210
+ | `'replaced'` | `set()` or a reload stored a different value for the key. Not called if the value is the same. |
211
+ | `'cleared'` | Removed by `clear()`. |
212
+
213
+ If `onEvict` throws, the cache stays correct and the other callbacks in the same batch still run. The first error is then thrown to the caller.
214
+
215
+ ### Remove expired entries on a timer
216
+
217
+ By default there are no timers. An expired entry is never returned. It is removed (and reported to `onEvict`) when you `get()` or `has()` it, or when you call `prune()`. So there is nothing to close and no open handles in Jest or Vitest.
218
+
219
+ If you store many keys that are never read again and want the memory back soon, call `cache.prune()` yourself, or ask for a timer:
220
+
221
+ ```js
222
+ const cache = cachefor('5m', { pruneInterval: '1m' })
223
+ ```
224
+
225
+ The timer is `unref()`'d, so it never keeps Node.js running. It stops by itself when the cache is garbage-collected.
226
+
227
+ ### Test with a fake clock
228
+
229
+ Pass your own clock with `now`:
230
+
231
+ ```js
232
+ let now = 0
233
+ const cache = cachefor('5m', { now: () => now })
234
+ cache.set('a', 1)
235
+ now += 5 * 60_000
236
+ cache.get('a') // => undefined
237
+ ```
238
+
239
+ The default clock is `Date.now`, so fake timers in Vitest or Jest (`vi.useFakeTimers()`, `vi.advanceTimersByTime()`) also work.
240
+
241
+ ### Use TypeScript types
242
+
243
+ `cachefor<V, K>()` sets the value and key types. TTL string literals are checked at compile time:
244
+
245
+ ```ts
246
+ cachefor('1h 30m') // OK
247
+ cachefor('5 minuts') // compile error
248
+ cache.set('a', 1, '10 sec') // OK
249
+ cache.set('a', 1, '10 sex') // compile error
250
+ ```
251
+
252
+ Values typed as plain `string`, such as env vars or config, are accepted and checked at runtime. When you pass type arguments, as in `cachefor<User>('5m')`, TypeScript cannot check that TTL literal. It is checked at runtime only.
253
+
254
+ ```ts
255
+ import cachefor, { type Cache, type TTL } from 'cachefor'
256
+
257
+ interface Config { userCacheTtl: TTL } // number | '5m' | ...
258
+ const users: Cache<User, number> = cachefor('5m')
259
+ ```
260
+
261
+ ## API
262
+
263
+ ### cachefor(ttl, options?)
264
+
265
+ ```ts
266
+ function cachefor<V = unknown, K = string>(ttl: TTL, options?: CacheOptions<V, K>): Cache<V, K>
267
+ ```
268
+
269
+ Creates a cache. `ttl` is the default time to live for entries. This is also the default export, and is available as `cachefor.cachefor`. Throws `TtlError` for an invalid TTL.
270
+
271
+ | Option | Type | Default | Description |
272
+ |---|---|---|---|
273
+ | `max` | `number` | `Infinity` | Maximum number of entries. Above it, the least recently used entry is removed. Must be a positive integer or `Infinity`, otherwise a `RangeError` is thrown. |
274
+ | `sliding` | `boolean` | `false` | Restart an entry's TTL each time `get()` or a loader hit reads it. |
275
+ | `staleWhileRevalidate` | `TTL \| boolean` | off | How long after expiry `getOrSet()`, `wrap()` and `memoize()` may return the old value while loading a new one. `true` means no limit. |
276
+ | `onEvict` | `(value, key, reason) => void` | none | Called after an entry leaves the cache. See [the reasons](#know-when-entries-leave-the-cache). |
277
+ | `now` | `() => number` | `Date.now` | Clock in milliseconds, for tests. |
278
+ | `pruneInterval` | `TTL` | off | Remove expired entries on an `unref()`'d timer, for example `'1m'`. Must be between 1 ms and about 24.8 days, otherwise a `RangeError` is thrown. |
279
+
280
+ ### Cache methods
281
+
282
+ | Method | Returns | Description |
283
+ |---|---|---|
284
+ | `get(key)` | `V \| undefined` | The value, if present and not expired. Marks it as recently used and restarts a sliding TTL. |
285
+ | `set(key, value, ttl?)` | `this` | Stores a value. `ttl` overrides the default for this entry. `0` means do not store. Chainable. |
286
+ | `has(key)` | `boolean` | `true` if a value exists and has not expired. Does not change the LRU order. |
287
+ | `peek(key)` | `V \| undefined` | Like `get()`, but with no side effects. |
288
+ | `delete(key)` | `boolean` | Removes the key. Returns `true` if it held a value that had not expired. Also stops a running load from being cached. |
289
+ | `clear()` | `void` | Removes everything, including running loads. |
290
+ | `ttl(key)` | `number \| undefined` | Milliseconds left. `Infinity` if it never expires, `undefined` if missing or expired. Does not change the TTL. |
291
+ | `size` | `number` | Number of entries that have not expired. A property, not a method. |
292
+ | `prune()` | `number` | Removes expired entries now. Returns how many were removed. |
293
+ | `getOrSet(key, loader, ttl?)` | `Promise<V>` | The cached value, or the result of `loader(key, ctx)`, with shared loads. See [Load a value when it is missing](#load-a-value-when-it-is-missing). |
294
+ | `getOrSetSync(key, loader, ttl?)` | `V` | Sync version of `getOrSet()`. |
295
+ | `wrap(fn, options?)` | function | Caches the results of `fn` in this cache. See [cache.wrap](#cachewrapfn-options). |
296
+ | `keys()`, `values()`, `entries()`, `[Symbol.iterator]` | iterator | Entries that have not expired. `new Map(cache)` works. |
297
+
298
+ Iteration order: with `max` set, least recently used first. Without `max`, the order in which keys were last set.
299
+
300
+ The loader gets `ctx` as its second argument (type `LoadContext<V>`):
301
+
302
+ | Property | Type | Description |
303
+ |---|---|---|
304
+ | `ctx.stale` | `V \| undefined` | The expired value being refreshed, if any. |
305
+ | `ctx.setTtl(ttl)` | `(ttl: TTL) => void` | Sets the TTL for the value being loaded. |
306
+
307
+ ### cache.wrap(fn, options?)
308
+
309
+ ```ts
310
+ cache.wrap(fn: (...args: A) => R, options?: WrapOptions<A, K>): (...args: A) => R
311
+ ```
312
+
313
+ Returns a cached version of `fn` that stores its results in this cache. Async functions get shared loads and stale-while-revalidate, like `getOrSet()`.
314
+
315
+ | Option | Type | Default | Description |
316
+ |---|---|---|---|
317
+ | `key` | `(...args) => K` | see below | Cache key for a call. Default: the argument itself for one primitive argument, otherwise `JSON.stringify(args)`. |
318
+ | `ttl` | `TTL` | the cache's TTL | TTL for the results of this function. |
319
+
320
+ ### memoize(fn, ttlOrOptions?)
321
+
322
+ ```ts
323
+ function memoize<F extends (...args: any[]) => any, K = unknown>(
324
+ fn: F,
325
+ options?: TTL | MemoizeOptions,
326
+ ): Memoized<F, K> // F plus a `cache` property
327
+ ```
328
+
329
+ Caches the results of `fn` in a new cache. The second argument is a TTL, or an object with every [`cachefor` option](#cacheforttl-options) plus:
330
+
331
+ | Option | Type | Default | Description |
332
+ |---|---|---|---|
333
+ | `ttl` | `TTL` | `Infinity` | How long results are cached. |
334
+ | `key` | `(...args) => K` | see [Cache the results of a function](#cache-the-results-of-a-function) | Cache key for a call. |
335
+
336
+ The returned function has a `cache` property (a `Cache`), for example `fn.cache.clear()`.
337
+
338
+ ### parseTtl(ttl)
339
+
340
+ ```ts
341
+ function parseTtl(ttl: TTL): number
342
+ ```
343
+
344
+ The TTL parser on its own. Returns milliseconds. Throws `TtlError` for negative numbers, `NaN` and unknown units.
345
+
346
+ ```js
347
+ import { parseTtl } from 'cachefor'
348
+
349
+ parseTtl('1h 30m') // => 5400000
350
+ parseTtl('2 days') // => 172800000
351
+ parseTtl(1500) // => 1500
352
+ parseTtl('forever') // => Infinity
353
+ ```
354
+
355
+ ### TtlError
356
+
357
+ ```ts
358
+ class TtlError extends TypeError {
359
+ readonly input: unknown
360
+ }
361
+ ```
362
+
363
+ Thrown for an invalid TTL. The bad value is in `error.input`.
364
+
11
365
  ```js
12
- const { hello } = require('cachefor') // or: import { hello } from 'cachefor'
13
- console.log(hello()) // 'Hello, world! (from cachefor)'
366
+ import { parseTtl, TtlError } from 'cachefor'
367
+
368
+ try {
369
+ parseTtl('5 minuts')
370
+ } catch (error) {
371
+ error instanceof TtlError // => true
372
+ error.input // => '5 minuts'
373
+ }
14
374
  ```
15
375
 
376
+ ### Types
377
+
378
+ All types are exported:
379
+
380
+ `Cache<V, K>`, `CacheOptions<V, K>`, `CacheFor`, `MemoizeOptions`, `Memoized<F, K>`, `LoadContext<V>`, `WrapOptions`, `EvictReason`, `TTL`, `TtlString`, `TtlUnit`, `ShortUnit`, `CheckTtl<T>`, `IsValidTtl<T>`.
381
+
382
+ ## Comparison
383
+
384
+ | | `node-cache` | `lru-cache` | `memory-cache` | `p-memoize` | `memoizee` | **cachefor** |
385
+ |---|---|---|---|---|---|---|
386
+ | TTL as `'5m'` / `'1h 30m'` | No (seconds) | No (ms) | No (ms) | No | No (ms) | Yes |
387
+ | Async loader per call (`getOrSet`) | No | Partial (one `fetchMethod` per cache) | No | n/a | n/a | Yes |
388
+ | Calls at the same time share one load | No | Yes | No | Yes | Yes (`promise: true`) | Yes |
389
+ | Failed loads not cached | n/a | Yes | n/a | Yes | Yes | Yes |
390
+ | Stale-while-revalidate | No | Yes | No | No | Partial (`preFetch` refreshes before expiry) | Yes |
391
+ | LRU limit | No (`maxKeys` throws when full) | Yes | No | Through a custom cache | Yes | Yes |
392
+ | Memoize any function | No | Partial (one `memoMethod` per cache) | No | Async only | Yes | Yes |
393
+ | Background timers | Interval by default | `unref()`'d; per entry with `ttlAutopurge` | One `setTimeout` per entry | n/a | Per entry with `maxAge` | None by default |
394
+ | Stores values as they are (no cloning) | No (clones by default) | Yes | Yes | Yes | Yes | Yes |
395
+ | Runtime dependencies | 1 | 0 | 0 | 1 | 8 | 0 |
396
+ | CommonJS `require()` | Yes | Yes | Yes | No (ESM only) | Yes | Yes |
397
+ | TypeScript types | Yes | Yes | `@types/memory-cache` | Yes | `@types/memoizee` | Yes, built in, TTL literals checked |
398
+
399
+ `n/a`: the package has no such feature to compare.
400
+
401
+ `lru-cache` has many more options (size-based limits, `AbortSignal`s, and more). Use it if you need them. Use `cachefor` when you want TTL caching with a small API.
402
+
403
+ ## Migrating from other packages
404
+
405
+ ### From node-cache
406
+
407
+ Before:
408
+
409
+ ```js
410
+ const cache = new NodeCache({ stdTTL: 300 }) // seconds
411
+ cache.set(key, value, 60)
412
+ cache.get(key)
413
+ cache.del(key)
414
+ cache.flushAll()
415
+ ```
416
+
417
+ After:
418
+
419
+ ```js
420
+ const cache = cachefor('5m') // or 300_000 (ms)
421
+ cache.set(key, value, '1m')
422
+ cache.get(key)
423
+ cache.delete(key)
424
+ cache.clear()
425
+ ```
426
+
427
+ - `stdTTL: 0` (never expire) is `cachefor(Infinity)`.
428
+ - Values are not cloned. Do not change objects after you cache them, or clone them yourself.
429
+ - `cache.ttl(key)` returns the milliseconds left. It does not change the TTL. Use `set(key, value, ttl)` for that.
430
+ - `on('expired')` and `on('del')` become `onEvict: (value, key, reason) => ...`.
431
+
432
+ ### From lru-cache
433
+
434
+ Before:
435
+
436
+ ```js
437
+ const cache = new LRUCache({ max: 500, ttl: 1000 * 60 * 5, fetchMethod: (key) => load(key) })
438
+ await cache.fetch(key)
439
+ ```
440
+
441
+ After:
442
+
443
+ ```js
444
+ const cache = cachefor('5m', { max: 500 })
445
+ await cache.getOrSet(key, load)
446
+ ```
447
+
448
+ | lru-cache | cachefor |
449
+ |---|---|
450
+ | `updateAgeOnGet` | `sliding` |
451
+ | `allowStale` + background fetch | `staleWhileRevalidate` |
452
+ | `dispose` | `onEvict` |
453
+ | reason `'evict'` | `'evicted'` |
454
+ | reason `'set'` | `'replaced'` |
455
+ | reason `'delete'` | `'deleted'` |
456
+
457
+ A cache with no expiry is `cachefor(Infinity, { max })`.
458
+
459
+ ### From memory-cache
460
+
461
+ `cache.put(key, value, ms)` becomes `cache.set(key, value, ms)`. There is no global shared cache. Create one with `cachefor()` and export it from a module.
462
+
463
+ ### From p-memoize or memoizee
464
+
465
+ Before:
466
+
467
+ ```js
468
+ pMemoize(fn, { cacheKey })
469
+ memoize(fn, { maxAge: 60000, promise: true, max: 100 }) // memoizee
470
+ ```
471
+
472
+ After:
473
+
474
+ ```js
475
+ memoize(fn, { key })
476
+ memoize(fn, { ttl: '1m', max: 100 }) // promises are detected automatically
477
+ ```
478
+
479
+ Clear the cache with `fn.cache.clear()` or `fn.cache.delete(key)`.
480
+
481
+ ## Notes and limitations
482
+
483
+ - **Values are not cloned.** If you change a cached object, the cached copy changes too.
484
+ - **Expired entries are removed lazily** (only when touched). Use `prune()` or `pruneInterval` if memory matters.
485
+ - **`size` and iteration scan all entries** (O(n)) once any entry can expire. Everything else is O(1).
486
+ - **Months and years are not valid TTL units**, because their length changes.
487
+ - **TTL typos are caught at compile time only for literals.** With type arguments like `cachefor<User>('5m')`, or with `string` values, the check runs at runtime.
488
+ - **The cache lives in the memory of one process.** Each `cachefor()` call creates a separate cache.
489
+
490
+ ## Requirements
491
+
492
+ - Node.js 20 or newer. Also works in Bun, Deno and browsers.
493
+ - ESM and CommonJS.
494
+ - TypeScript types included.
495
+ - Zero dependencies.
496
+
16
497
  ## License
17
498
 
18
499
  MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var U=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var G=(n,s)=>{for(var c in s)U(n,c,{get:s[c],enumerable:!0})},X=(n,s,c,d)=>{if(s&&typeof s=="object"||typeof s=="function")for(let u of H(s))!Y.call(n,u)&&u!==c&&U(n,u,{get:()=>s[u],enumerable:!(d=j(s,u))||d.enumerable});return n};var _=n=>X(U({},"__esModule",{value:!0}),n);var re={};G(re,{TtlError:()=>g,cachefor:()=>A,default:()=>ne,memoize:()=>M,parseTtl:()=>w});module.exports=_(re);var J={ms:1,msec:1,msecs:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,secs:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,mins:6e4,minute:6e4,minutes:6e4,h:36e5,hr:36e5,hrs:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,wk:6048e5,wks:6048e5,week:6048e5,weeks:6048e5},g=class extends TypeError{constructor(s,c){super(s),this.name="TtlError",this.input=c}},N=n=>typeof n=="string"?`'${n}'`:String(n),I=/(\d*\.?\d+)\s*([a-z]+)/g,q=/^\s*,?\s*(?:and\s+)?$/;function w(n){if(typeof n=="number"){if(n>=0)return n;throw new g(`TTL must be a number of milliseconds >= 0 (or Infinity), got ${n}.`,n)}if(typeof n!="string")throw new g(`TTL must be a string like '5m' or a number of milliseconds, got ${n===null?"null":typeof n}.`,n);let s=n.trim().toLowerCase();if(s==="forever"||s==="infinity")return 1/0;if(/^\d*\.?\d+$/.test(s))return Number(s);let c=0,d=0;I.lastIndex=0;for(let u=I.exec(s);u;u=I.exec(s)){let y=s.slice(d,u.index);if(d===0?y!=="":!q.test(y))break;let p=J[u[2]];if(p===void 0)throw new g(`Unknown TTL unit '${u[2]}' in ${N(n)}. Use ms, s, m, h, d or w, e.g. '30s', '5m', '1h 30m'.`,n);c+=Number(u[1])*p,d=I.lastIndex}if(d===0||d!==s.length)throw new g(`Invalid TTL ${N(n)}. Use e.g. '30s', '5m', '1h 30m', '2 days', 'forever' or a number of milliseconds.`,n);return c}var F=n=>n!==null&&(typeof n=="object"||typeof n=="function")&&typeof n.then=="function",B=()=>{},Q=2**31-1;function Z(n){if(n.length===1){let s=n[0];if(s===null||typeof s!="object"&&typeof s!="function")return s}return JSON.stringify(n)}var ee=n=>typeof WeakRef=="function"?new WeakRef(n):{deref:()=>n};function te(n,s){let c=setInterval(()=>{let d=n.deref();d?d.prune():clearInterval(c)},s);c.unref?.()}function A(n,s={}){let c=w(n),{onEvict:d,sliding:u=!1,pruneInterval:y}=s,p=s.max??1/0;if(!(p>=1)||p!==1/0&&!Number.isInteger(p))throw new RangeError(`cachefor: max must be a positive integer or Infinity, got ${String(s.max)}.`);let h=s.staleWhileRevalidate,D=h===!0?1/0:h===!1||h===void 0?0:w(h),T=s.now??(()=>Date.now());if(typeof T!="function")throw new TypeError("cachefor: now must be a function returning milliseconds.");if(d!==void 0&&typeof d!="function")throw new TypeError("cachefor: onEvict must be a function.");let a=new Map,x=new Map,$=c!==1/0,E=e=>e===void 0?c:w(e),v=e=>{if(!d||!e.length)return;let t,r=!1;for(let[o,m,l]of e)try{d(o,m,l)}catch(i){r||(r=!0,t=i)}if(r)throw t},O=(e,t)=>t>=e.e+D,C=(e,t)=>{let r=a.get(e);if(r){if(t<r.e)return r;O(r,t)&&(a.delete(e),v([[r.v,e,"expired"]]))}},P=(e,t,r)=>{u&&(t.e=r+t.t),p!==1/0&&(a.delete(e),a.set(e,t))},S=(e,t,r,o)=>{let m=T(),l=a.get(e),i=[];if(l&&(a.delete(e),Object.is(l.v,t)||i.push([l.v,e,m<l.e?"replaced":"expired"])),r>0)for(r!==1/0&&($=!0),a.set(e,{v:t,e:m+r,t:r,p:o});a.size>p;){let[b,K]=a.entries().next().value;a.delete(b),i.push([K.v,b,m<K.e?"evicted":"expired"])}v(i)},L=(e,t,r,o,m)=>{let l=T(),i=a.get(e);if(i){if(l<i.e)return P(e,i,l),o===1||o===2&&(m||i.p)?Promise.resolve(i.v):i.v;if(O(i,l)){a.delete(e);let f=i;i=void 0,v([[f.v,e,"expired"]])}}if(o!==0){let f=x.get(e);if(f)return i?Promise.resolve(i.v):f}let b=r,K={stale:i?.v,setTtl:f=>{b=w(f)}};if(o===0){let f=t(K);return x.delete(e),S(e,f,b,!1),f}let V=t(K);if(!F(V))return S(e,V,b,o===1),o===1?Promise.resolve(V):V;let k=Promise.resolve(V).then(f=>(x.get(e)===k&&(x.delete(e),S(e,f,b,!0)),f),f=>{throw x.get(e)===k&&x.delete(e),f});return x.set(e,k),i?(k.catch(B),Promise.resolve(i.v)):k};function*R(e){let t=T();for(let[r,o]of a)t<o.e&&(yield e(r,o.v))}let W={get(e){let t=T(),r=C(e,t);if(r)return P(e,r,t),r.v},peek(e){let t=a.get(e);return t&&T()<t.e?t.v:void 0},has(e){return C(e,T())!==void 0},set(e,t,r){let o=E(r);return x.delete(e),S(e,t,o,!1),this},delete(e){x.delete(e);let t=a.get(e);if(!t)return!1;a.delete(e);let r=T()<t.e;return v([[t.v,e,r?"deleted":"expired"]]),r},clear(){x.clear();let e=T(),t=[];for(let[r,o]of a)t.push([o.v,r,e<o.e?"cleared":"expired"]);a.clear(),v(t)},ttl(e){let t=T(),r=C(e,t);return r?r.e-t:void 0},get size(){if(!$)return a.size;let e=T(),t=0;for(let r of a.values())e<r.e&&t++;return t},prune(){let e=T(),t=[];for(let[r,o]of a)O(o,e)&&(a.delete(r),t.push([o.v,r,"expired"]));return v(t),t.length},getOrSet(e,t,r){try{let o=E(r);return L(e,m=>t(e,m),o,1,!1)}catch(o){return Promise.reject(o)}},getOrSetSync(e,t,r){return L(e,o=>t(e,o),E(r),0,!1)},wrap(e,t={}){if(typeof e!="function")throw new TypeError("cachefor: wrap() needs a function.");let r=E(t.ttl),o=t.key??((...l)=>Z(l)),m=Object.prototype.toString.call(e)==="[object AsyncFunction]";return function(...l){let i=L(o(...l),()=>e.apply(this,l),r,2,m);return!m&&F(i)&&(m=!0),i}},keys:()=>R(e=>e),values:()=>R((e,t)=>t),entries:()=>R((e,t)=>[e,t]),[Symbol.iterator]:()=>R((e,t)=>[e,t])};if(y!==void 0){let e=w(y);if(!(e>=1&&e<=Q))throw new RangeError(`cachefor: pruneInterval must be between 1ms and ~24.8 days, got ${String(y)}.`);te(ee(W),e)}return W}function M(n,s){if(typeof n!="function")throw new TypeError("memoize: expected a function.");let c=typeof s=="object"&&s!==null?s:{ttl:s},{ttl:d=1/0,key:u,...y}=c,p=A(d,y),h=p.wrap(n,u?{key:u}:{});return Object.defineProperty(h,"cache",{value:p,enumerable:!0}),Object.defineProperty(h,"name",{value:n.name,configurable:!0}),Object.defineProperty(h,"length",{value:n.length,configurable:!0}),h}var z=((n,s)=>A(n,s));Object.assign(z,{cachefor:A,memoize:M,parseTtl:w,TtlError:g});var ne=z;0&&(module.exports={TtlError,cachefor,memoize,parseTtl});
2
+ var __d=module.exports.default;for(var __k in module.exports)if(!(__k in __d))__d[__k]=module.exports[__k];__d.default=__d;module.exports=__d;
@@ -0,0 +1,193 @@
1
+ /** Short unit spellings. */
2
+ type ShortUnit = 'ms' | 's' | 'm' | 'h' | 'd' | 'w';
3
+ /** Every unit spelling accepted in TTL strings (case-insensitive at runtime). */
4
+ type TtlUnit = ShortUnit | 'msec' | 'msecs' | 'millisecond' | 'milliseconds' | 'sec' | 'secs' | 'second' | 'seconds' | 'min' | 'mins' | 'minute' | 'minutes' | 'hr' | 'hrs' | 'hour' | 'hours' | 'day' | 'days' | 'wk' | 'wks' | 'week' | 'weeks';
5
+ /** Loose shape of a TTL string, for typing config objects. */
6
+ type TtlString = `${number}${string}` | 'forever' | 'infinity' | 'Infinity';
7
+ /**
8
+ * A time-to-live: milliseconds (`5000`, `Infinity`) or a readable string
9
+ * (`'30s'`, `'5m'`, `'1h 30m'`, `'2 days'`, `'forever'`).
10
+ */
11
+ type TTL = number | TtlString;
12
+ type Words<S extends string, Acc extends string[] = []> = S extends `${infer W} ${infer R}` ? Words<R, W extends '' ? Acc : [...Acc, W]> : S extends '' ? Acc : [...Acc, S];
13
+ type NoComma<W extends string> = W extends `${infer X},` ? X : W;
14
+ type Glued<S extends string, U extends ShortUnit = ShortUnit> = U extends ShortUnit ? S extends `${number}${U}${infer R}` ? (R extends '' ? true : Glued<R>) : false : never;
15
+ type IsPart<S extends string> = S extends `-${string}` | `+${string}` ? false : S extends `${number}${TtlUnit}` ? true : true extends Glued<S> ? true : false;
16
+ type CheckWords<W extends string[], Started extends boolean = false> = W extends [] ? Started : W extends ['and', ...infer R extends string[]] ? Started extends true ? CheckWords<R, true> : false : W extends [infer A extends string, ...infer R extends string[]] ? IsPart<NoComma<A>> extends true ? CheckWords<R, true> : A extends `-${string}` | `+${string}` ? false : A extends `${number}` ? R extends [infer U extends string, ...infer R2 extends string[]] ? NoComma<U> extends TtlUnit ? CheckWords<R2, true> : false : false : false : false;
17
+ type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S;
18
+ type IsValidTrimmed<S extends string> = S extends 'forever' | 'infinity' ? true : S extends `-${string}` | `+${string}` ? false : S extends `${number}` ? true : CheckWords<Words<S>>;
19
+ /** `true` if the string literal `S` is a valid TTL. */
20
+ type IsValidTtl<S extends string> = IsValidTrimmed<Trim<Lowercase<S>>>;
21
+ /**
22
+ * Literal TTL strings are type-checked; values typed as plain `string` or `TTL`
23
+ * (env vars, config files) are accepted and checked at runtime.
24
+ */
25
+ type CheckTtl<T> = [T] extends [number] ? T : string extends T ? T : `${number}${string}` extends T ? T : T extends string ? IsValidTtl<T> extends true ? T : `Invalid TTL - use e.g. '30s', '5m', '1h 30m' or '2 days'` : T;
26
+ /** Thrown for an invalid TTL. The bad value is in `error.input`. */
27
+ declare class TtlError extends TypeError {
28
+ readonly input: unknown;
29
+ constructor(message: string, input: unknown);
30
+ }
31
+ /**
32
+ * Parses a TTL into milliseconds.
33
+ *
34
+ * parseTtl('5m') // 300000
35
+ * parseTtl('1h 30m') // 5400000
36
+ * parseTtl('2 days') // 172800000
37
+ * parseTtl(1500) // 1500
38
+ * parseTtl('forever') // Infinity
39
+ *
40
+ * Throws a `TtlError` for negative numbers, `NaN` and unknown units.
41
+ */
42
+ declare function parseTtl<T extends string | number>(input: T extends string ? CheckTtl<T> : T): number;
43
+
44
+ /**
45
+ * cachefor — a small in-memory cache with human-readable TTLs.
46
+ *
47
+ * const users = cachefor<User>('5m', { max: 1000 })
48
+ * const user = await users.getOrSet(id, () => db.users.find(id))
49
+ *
50
+ * const getRates = memoize(fetchRates, { ttl: '1h' })
51
+ */
52
+
53
+ /**
54
+ * Why an entry left the cache:
55
+ *
56
+ * - `'expired'`: its TTL ran out (also used when an already-expired entry is deleted, replaced or cleared)
57
+ * - `'evicted'`: dropped as least recently used because the cache hit `max`
58
+ * - `'deleted'`: removed with `delete()`
59
+ * - `'replaced'`: overwritten with a different value by `set()` or a reload
60
+ * - `'cleared'`: removed by `clear()`
61
+ */
62
+ type EvictReason = 'expired' | 'evicted' | 'deleted' | 'replaced' | 'cleared';
63
+ /** A TTL argument: literal strings are type-checked, everything else is checked at runtime. */
64
+ type TtlArg<T> = T extends string ? CheckTtl<T> : T;
65
+ interface CacheOptions<V = unknown, K = string> {
66
+ /**
67
+ * Maximum number of entries. When a new key would exceed it, the least recently used
68
+ * entry is evicted. Default: `Infinity` (no limit).
69
+ */
70
+ max?: number;
71
+ /**
72
+ * Reset an entry's TTL every time it is read with `get()` or a loader hit
73
+ * (sliding expiration, like a session timeout). Default: `false`.
74
+ */
75
+ sliding?: boolean;
76
+ /**
77
+ * After an entry expires, keep it this much longer (`'1m'`, or `true` for no limit) so that
78
+ * `getOrSet()`, `wrap()` and `memoize()` can return the stale value at once while reloading it
79
+ * in the background. `get()` and `has()` never return stale values. Default: off.
80
+ */
81
+ staleWhileRevalidate?: TTL | boolean;
82
+ /**
83
+ * Called after an entry leaves the cache, with the reason. Use it to close or release values.
84
+ * Not called when a key is set to the exact same value again.
85
+ */
86
+ onEvict?: (value: V, key: K, reason: EvictReason) => void;
87
+ /** Clock in milliseconds, for tests. Default: `Date.now`. */
88
+ now?: () => number;
89
+ /**
90
+ * Also remove expired entries every so often (`'1m'`). Off by default: expired entries are
91
+ * removed lazily when touched, or by calling `prune()`. The timer is `unref()`'d and stops
92
+ * when the cache is garbage-collected, so it never keeps a process alive or leaks.
93
+ */
94
+ pruneInterval?: TTL;
95
+ }
96
+ /** Passed to `getOrSet()` / `getOrSetSync()` loaders. */
97
+ interface LoadContext<V> {
98
+ /** The expired value being refreshed, when there is one (stale-while-revalidate). */
99
+ readonly stale: V | undefined;
100
+ /** Override the TTL for the value being loaded, e.g. from an HTTP `max-age` or token `expires_in`. */
101
+ setTtl(ttl: TTL): void;
102
+ }
103
+ /** Options for `cache.wrap()`. */
104
+ interface WrapOptions<A extends unknown[], K> {
105
+ /**
106
+ * Cache key for a call. Default: the argument itself for one primitive argument,
107
+ * otherwise `JSON.stringify(args)`.
108
+ */
109
+ key?: (...args: A) => K;
110
+ /** TTL for results of this function. Default: the cache's TTL. */
111
+ ttl?: TTL;
112
+ }
113
+ interface Cache<V = unknown, K = string> extends Iterable<[K, V]> {
114
+ /** The value for `key`, or `undefined` if missing or expired. Marks it as recently used. */
115
+ get(key: K): V | undefined;
116
+ /** Like `get()`, but does not mark it as recently used, reset a sliding TTL or remove anything. */
117
+ peek(key: K): V | undefined;
118
+ /** `true` if `key` holds a value that has not expired. Does not mark it as recently used. */
119
+ has(key: K): boolean;
120
+ /** Stores a value. `ttl` overrides the cache's TTL for this entry; `0` means do not store. */
121
+ set<T extends string | number = string | number>(key: K, value: V, ttl?: TtlArg<T>): this;
122
+ /** Removes `key`. Returns `true` if it held an unexpired value. Also cancels caching of an in-flight load. */
123
+ delete(key: K): boolean;
124
+ /** Removes everything, including in-flight loads. */
125
+ clear(): void;
126
+ /** Milliseconds until `key` expires: `Infinity` if it never does, `undefined` if missing or expired. */
127
+ ttl(key: K): number | undefined;
128
+ /** Number of unexpired entries. */
129
+ readonly size: number;
130
+ /** Removes all expired entries now. Returns how many were removed. */
131
+ prune(): number;
132
+ /**
133
+ * Returns the cached value, or calls `loader` once and caches what it resolves to.
134
+ * Concurrent calls for the same key share one promise. Rejections are not cached.
135
+ * With `staleWhileRevalidate`, an expired value is returned at once and reloaded in the background.
136
+ */
137
+ getOrSet<T extends string | number = string | number>(key: K, loader: (key: K, context: LoadContext<V>) => V | PromiseLike<V>, ttl?: TtlArg<T>): Promise<V>;
138
+ /** Synchronous `getOrSet()`: returns the cached value, or calls `loader` and caches its result. */
139
+ getOrSetSync<T extends string | number = string | number>(key: K, loader: (key: K, context: LoadContext<V>) => V, ttl?: TtlArg<T>): V;
140
+ /**
141
+ * Returns a cached version of `fn` that stores its results in this cache.
142
+ * Async functions get in-flight dedup and stale-while-revalidate, like `getOrSet()`.
143
+ */
144
+ wrap<A extends unknown[], R extends V | PromiseLike<V>, This = unknown>(fn: (this: This, ...args: A) => R, options?: WrapOptions<A, K>): (this: This, ...args: A) => R;
145
+ /** Unexpired keys, least recently used first. */
146
+ keys(): IterableIterator<K>;
147
+ /** Unexpired values, least recently used first. */
148
+ values(): IterableIterator<V>;
149
+ /** Unexpired `[key, value]` pairs, least recently used first. */
150
+ entries(): IterableIterator<[K, V]>;
151
+ [Symbol.iterator](): IterableIterator<[K, V]>;
152
+ }
153
+ /**
154
+ * Creates a cache whose entries live for `ttl`.
155
+ *
156
+ * const cache = cachefor('5m')
157
+ * const users = cachefor<User>('1h', { max: 500 })
158
+ * const forever = cachefor(Infinity, { max: 100 }) // plain LRU
159
+ */
160
+ declare function cachefor<V = unknown, K = string, T extends string | number = string | number>(ttl: TtlArg<T>, options?: CacheOptions<V, K>): Cache<V, K>;
161
+ interface MemoizeOptions<A extends unknown[] = unknown[], V = unknown, K = unknown> extends CacheOptions<V, K> {
162
+ /** How long results are cached. Default: `Infinity` (until evicted by `max`). */
163
+ ttl?: TTL;
164
+ /**
165
+ * Cache key for a call. Default: the argument itself for one primitive argument,
166
+ * otherwise `JSON.stringify(args)`.
167
+ */
168
+ key?: (...args: A) => K;
169
+ }
170
+ /** A memoized function: same signature, plus the `cache` holding its results. */
171
+ type Memoized<F extends (...args: any[]) => any, K = unknown> = F & {
172
+ /** The cache behind this function: `fn.cache.clear()`, `fn.cache.delete(key)`, ... */
173
+ readonly cache: Cache<Awaited<ReturnType<F>>, K>;
174
+ };
175
+ /**
176
+ * Caches a function's results. Works with sync and async functions; async ones get
177
+ * in-flight dedup (concurrent calls share one promise) and rejections are not cached.
178
+ *
179
+ * const getUser = memoize(fetchUser, { ttl: '5m' })
180
+ * const slugify = memoize(slowSlugify, { max: 1000 })
181
+ * const getRates = memoize(fetchRates, '1h')
182
+ */
183
+ declare function memoize<F extends (...args: any[]) => any, K = unknown>(fn: F, options?: TTL | MemoizeOptions<Parameters<F>, Awaited<ReturnType<F>>, K>): Memoized<F, K>;
184
+ interface CacheFor {
185
+ <V = unknown, K = string, T extends string | number = string | number>(ttl: TtlArg<T>, options?: CacheOptions<V, K>): Cache<V, K>;
186
+ cachefor: typeof cachefor;
187
+ memoize: typeof memoize;
188
+ parseTtl: typeof parseTtl;
189
+ TtlError: typeof TtlError;
190
+ }
191
+ declare const main: CacheFor;
192
+
193
+ export { type Cache, type CacheFor, type CacheOptions, type CheckTtl, type EvictReason, type IsValidTtl, type LoadContext, type MemoizeOptions, type Memoized, type ShortUnit, type TTL, TtlError, type TtlString, type TtlUnit, type WrapOptions, cachefor, main as default, memoize, parseTtl };
@@ -0,0 +1,193 @@
1
+ /** Short unit spellings. */
2
+ type ShortUnit = 'ms' | 's' | 'm' | 'h' | 'd' | 'w';
3
+ /** Every unit spelling accepted in TTL strings (case-insensitive at runtime). */
4
+ type TtlUnit = ShortUnit | 'msec' | 'msecs' | 'millisecond' | 'milliseconds' | 'sec' | 'secs' | 'second' | 'seconds' | 'min' | 'mins' | 'minute' | 'minutes' | 'hr' | 'hrs' | 'hour' | 'hours' | 'day' | 'days' | 'wk' | 'wks' | 'week' | 'weeks';
5
+ /** Loose shape of a TTL string, for typing config objects. */
6
+ type TtlString = `${number}${string}` | 'forever' | 'infinity' | 'Infinity';
7
+ /**
8
+ * A time-to-live: milliseconds (`5000`, `Infinity`) or a readable string
9
+ * (`'30s'`, `'5m'`, `'1h 30m'`, `'2 days'`, `'forever'`).
10
+ */
11
+ type TTL = number | TtlString;
12
+ type Words<S extends string, Acc extends string[] = []> = S extends `${infer W} ${infer R}` ? Words<R, W extends '' ? Acc : [...Acc, W]> : S extends '' ? Acc : [...Acc, S];
13
+ type NoComma<W extends string> = W extends `${infer X},` ? X : W;
14
+ type Glued<S extends string, U extends ShortUnit = ShortUnit> = U extends ShortUnit ? S extends `${number}${U}${infer R}` ? (R extends '' ? true : Glued<R>) : false : never;
15
+ type IsPart<S extends string> = S extends `-${string}` | `+${string}` ? false : S extends `${number}${TtlUnit}` ? true : true extends Glued<S> ? true : false;
16
+ type CheckWords<W extends string[], Started extends boolean = false> = W extends [] ? Started : W extends ['and', ...infer R extends string[]] ? Started extends true ? CheckWords<R, true> : false : W extends [infer A extends string, ...infer R extends string[]] ? IsPart<NoComma<A>> extends true ? CheckWords<R, true> : A extends `-${string}` | `+${string}` ? false : A extends `${number}` ? R extends [infer U extends string, ...infer R2 extends string[]] ? NoComma<U> extends TtlUnit ? CheckWords<R2, true> : false : false : false : false;
17
+ type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S;
18
+ type IsValidTrimmed<S extends string> = S extends 'forever' | 'infinity' ? true : S extends `-${string}` | `+${string}` ? false : S extends `${number}` ? true : CheckWords<Words<S>>;
19
+ /** `true` if the string literal `S` is a valid TTL. */
20
+ type IsValidTtl<S extends string> = IsValidTrimmed<Trim<Lowercase<S>>>;
21
+ /**
22
+ * Literal TTL strings are type-checked; values typed as plain `string` or `TTL`
23
+ * (env vars, config files) are accepted and checked at runtime.
24
+ */
25
+ type CheckTtl<T> = [T] extends [number] ? T : string extends T ? T : `${number}${string}` extends T ? T : T extends string ? IsValidTtl<T> extends true ? T : `Invalid TTL - use e.g. '30s', '5m', '1h 30m' or '2 days'` : T;
26
+ /** Thrown for an invalid TTL. The bad value is in `error.input`. */
27
+ declare class TtlError extends TypeError {
28
+ readonly input: unknown;
29
+ constructor(message: string, input: unknown);
30
+ }
31
+ /**
32
+ * Parses a TTL into milliseconds.
33
+ *
34
+ * parseTtl('5m') // 300000
35
+ * parseTtl('1h 30m') // 5400000
36
+ * parseTtl('2 days') // 172800000
37
+ * parseTtl(1500) // 1500
38
+ * parseTtl('forever') // Infinity
39
+ *
40
+ * Throws a `TtlError` for negative numbers, `NaN` and unknown units.
41
+ */
42
+ declare function parseTtl<T extends string | number>(input: T extends string ? CheckTtl<T> : T): number;
43
+
44
+ /**
45
+ * cachefor — a small in-memory cache with human-readable TTLs.
46
+ *
47
+ * const users = cachefor<User>('5m', { max: 1000 })
48
+ * const user = await users.getOrSet(id, () => db.users.find(id))
49
+ *
50
+ * const getRates = memoize(fetchRates, { ttl: '1h' })
51
+ */
52
+
53
+ /**
54
+ * Why an entry left the cache:
55
+ *
56
+ * - `'expired'`: its TTL ran out (also used when an already-expired entry is deleted, replaced or cleared)
57
+ * - `'evicted'`: dropped as least recently used because the cache hit `max`
58
+ * - `'deleted'`: removed with `delete()`
59
+ * - `'replaced'`: overwritten with a different value by `set()` or a reload
60
+ * - `'cleared'`: removed by `clear()`
61
+ */
62
+ type EvictReason = 'expired' | 'evicted' | 'deleted' | 'replaced' | 'cleared';
63
+ /** A TTL argument: literal strings are type-checked, everything else is checked at runtime. */
64
+ type TtlArg<T> = T extends string ? CheckTtl<T> : T;
65
+ interface CacheOptions<V = unknown, K = string> {
66
+ /**
67
+ * Maximum number of entries. When a new key would exceed it, the least recently used
68
+ * entry is evicted. Default: `Infinity` (no limit).
69
+ */
70
+ max?: number;
71
+ /**
72
+ * Reset an entry's TTL every time it is read with `get()` or a loader hit
73
+ * (sliding expiration, like a session timeout). Default: `false`.
74
+ */
75
+ sliding?: boolean;
76
+ /**
77
+ * After an entry expires, keep it this much longer (`'1m'`, or `true` for no limit) so that
78
+ * `getOrSet()`, `wrap()` and `memoize()` can return the stale value at once while reloading it
79
+ * in the background. `get()` and `has()` never return stale values. Default: off.
80
+ */
81
+ staleWhileRevalidate?: TTL | boolean;
82
+ /**
83
+ * Called after an entry leaves the cache, with the reason. Use it to close or release values.
84
+ * Not called when a key is set to the exact same value again.
85
+ */
86
+ onEvict?: (value: V, key: K, reason: EvictReason) => void;
87
+ /** Clock in milliseconds, for tests. Default: `Date.now`. */
88
+ now?: () => number;
89
+ /**
90
+ * Also remove expired entries every so often (`'1m'`). Off by default: expired entries are
91
+ * removed lazily when touched, or by calling `prune()`. The timer is `unref()`'d and stops
92
+ * when the cache is garbage-collected, so it never keeps a process alive or leaks.
93
+ */
94
+ pruneInterval?: TTL;
95
+ }
96
+ /** Passed to `getOrSet()` / `getOrSetSync()` loaders. */
97
+ interface LoadContext<V> {
98
+ /** The expired value being refreshed, when there is one (stale-while-revalidate). */
99
+ readonly stale: V | undefined;
100
+ /** Override the TTL for the value being loaded, e.g. from an HTTP `max-age` or token `expires_in`. */
101
+ setTtl(ttl: TTL): void;
102
+ }
103
+ /** Options for `cache.wrap()`. */
104
+ interface WrapOptions<A extends unknown[], K> {
105
+ /**
106
+ * Cache key for a call. Default: the argument itself for one primitive argument,
107
+ * otherwise `JSON.stringify(args)`.
108
+ */
109
+ key?: (...args: A) => K;
110
+ /** TTL for results of this function. Default: the cache's TTL. */
111
+ ttl?: TTL;
112
+ }
113
+ interface Cache<V = unknown, K = string> extends Iterable<[K, V]> {
114
+ /** The value for `key`, or `undefined` if missing or expired. Marks it as recently used. */
115
+ get(key: K): V | undefined;
116
+ /** Like `get()`, but does not mark it as recently used, reset a sliding TTL or remove anything. */
117
+ peek(key: K): V | undefined;
118
+ /** `true` if `key` holds a value that has not expired. Does not mark it as recently used. */
119
+ has(key: K): boolean;
120
+ /** Stores a value. `ttl` overrides the cache's TTL for this entry; `0` means do not store. */
121
+ set<T extends string | number = string | number>(key: K, value: V, ttl?: TtlArg<T>): this;
122
+ /** Removes `key`. Returns `true` if it held an unexpired value. Also cancels caching of an in-flight load. */
123
+ delete(key: K): boolean;
124
+ /** Removes everything, including in-flight loads. */
125
+ clear(): void;
126
+ /** Milliseconds until `key` expires: `Infinity` if it never does, `undefined` if missing or expired. */
127
+ ttl(key: K): number | undefined;
128
+ /** Number of unexpired entries. */
129
+ readonly size: number;
130
+ /** Removes all expired entries now. Returns how many were removed. */
131
+ prune(): number;
132
+ /**
133
+ * Returns the cached value, or calls `loader` once and caches what it resolves to.
134
+ * Concurrent calls for the same key share one promise. Rejections are not cached.
135
+ * With `staleWhileRevalidate`, an expired value is returned at once and reloaded in the background.
136
+ */
137
+ getOrSet<T extends string | number = string | number>(key: K, loader: (key: K, context: LoadContext<V>) => V | PromiseLike<V>, ttl?: TtlArg<T>): Promise<V>;
138
+ /** Synchronous `getOrSet()`: returns the cached value, or calls `loader` and caches its result. */
139
+ getOrSetSync<T extends string | number = string | number>(key: K, loader: (key: K, context: LoadContext<V>) => V, ttl?: TtlArg<T>): V;
140
+ /**
141
+ * Returns a cached version of `fn` that stores its results in this cache.
142
+ * Async functions get in-flight dedup and stale-while-revalidate, like `getOrSet()`.
143
+ */
144
+ wrap<A extends unknown[], R extends V | PromiseLike<V>, This = unknown>(fn: (this: This, ...args: A) => R, options?: WrapOptions<A, K>): (this: This, ...args: A) => R;
145
+ /** Unexpired keys, least recently used first. */
146
+ keys(): IterableIterator<K>;
147
+ /** Unexpired values, least recently used first. */
148
+ values(): IterableIterator<V>;
149
+ /** Unexpired `[key, value]` pairs, least recently used first. */
150
+ entries(): IterableIterator<[K, V]>;
151
+ [Symbol.iterator](): IterableIterator<[K, V]>;
152
+ }
153
+ /**
154
+ * Creates a cache whose entries live for `ttl`.
155
+ *
156
+ * const cache = cachefor('5m')
157
+ * const users = cachefor<User>('1h', { max: 500 })
158
+ * const forever = cachefor(Infinity, { max: 100 }) // plain LRU
159
+ */
160
+ declare function cachefor<V = unknown, K = string, T extends string | number = string | number>(ttl: TtlArg<T>, options?: CacheOptions<V, K>): Cache<V, K>;
161
+ interface MemoizeOptions<A extends unknown[] = unknown[], V = unknown, K = unknown> extends CacheOptions<V, K> {
162
+ /** How long results are cached. Default: `Infinity` (until evicted by `max`). */
163
+ ttl?: TTL;
164
+ /**
165
+ * Cache key for a call. Default: the argument itself for one primitive argument,
166
+ * otherwise `JSON.stringify(args)`.
167
+ */
168
+ key?: (...args: A) => K;
169
+ }
170
+ /** A memoized function: same signature, plus the `cache` holding its results. */
171
+ type Memoized<F extends (...args: any[]) => any, K = unknown> = F & {
172
+ /** The cache behind this function: `fn.cache.clear()`, `fn.cache.delete(key)`, ... */
173
+ readonly cache: Cache<Awaited<ReturnType<F>>, K>;
174
+ };
175
+ /**
176
+ * Caches a function's results. Works with sync and async functions; async ones get
177
+ * in-flight dedup (concurrent calls share one promise) and rejections are not cached.
178
+ *
179
+ * const getUser = memoize(fetchUser, { ttl: '5m' })
180
+ * const slugify = memoize(slowSlugify, { max: 1000 })
181
+ * const getRates = memoize(fetchRates, '1h')
182
+ */
183
+ declare function memoize<F extends (...args: any[]) => any, K = unknown>(fn: F, options?: TTL | MemoizeOptions<Parameters<F>, Awaited<ReturnType<F>>, K>): Memoized<F, K>;
184
+ interface CacheFor {
185
+ <V = unknown, K = string, T extends string | number = string | number>(ttl: TtlArg<T>, options?: CacheOptions<V, K>): Cache<V, K>;
186
+ cachefor: typeof cachefor;
187
+ memoize: typeof memoize;
188
+ parseTtl: typeof parseTtl;
189
+ TtlError: typeof TtlError;
190
+ }
191
+ declare const main: CacheFor;
192
+
193
+ export { type Cache, type CacheFor, type CacheOptions, type CheckTtl, type EvictReason, type IsValidTtl, type LoadContext, type MemoizeOptions, type Memoized, type ShortUnit, type TTL, TtlError, type TtlString, type TtlUnit, type WrapOptions, cachefor, main as default, memoize, parseTtl };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ var z={ms:1,msec:1,msecs:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,secs:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,mins:6e4,minute:6e4,minutes:6e4,h:36e5,hr:36e5,hrs:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,wk:6048e5,wks:6048e5,week:6048e5,weeks:6048e5},y=class extends TypeError{constructor(s,f){super(s),this.name="TtlError",this.input=f}},W=r=>typeof r=="string"?`'${r}'`:String(r),I=/(\d*\.?\d+)\s*([a-z]+)/g,D=/^\s*,?\s*(?:and\s+)?$/;function b(r){if(typeof r=="number"){if(r>=0)return r;throw new y(`TTL must be a number of milliseconds >= 0 (or Infinity), got ${r}.`,r)}if(typeof r!="string")throw new y(`TTL must be a string like '5m' or a number of milliseconds, got ${r===null?"null":typeof r}.`,r);let s=r.trim().toLowerCase();if(s==="forever"||s==="infinity")return 1/0;if(/^\d*\.?\d+$/.test(s))return Number(s);let f=0,d=0;I.lastIndex=0;for(let T=I.exec(s);T;T=I.exec(s)){let g=s.slice(d,T.index);if(d===0?g!=="":!D.test(g))break;let p=z[T[2]];if(p===void 0)throw new y(`Unknown TTL unit '${T[2]}' in ${W(r)}. Use ms, s, m, h, d or w, e.g. '30s', '5m', '1h 30m'.`,r);f+=Number(T[1])*p,d=I.lastIndex}if(d===0||d!==s.length)throw new y(`Invalid TTL ${W(r)}. Use e.g. '30s', '5m', '1h 30m', '2 days', 'forever' or a number of milliseconds.`,r);return f}var N=r=>r!==null&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function",j=()=>{},H=2**31-1;function Y(r){if(r.length===1){let s=r[0];if(s===null||typeof s!="object"&&typeof s!="function")return s}return JSON.stringify(r)}var G=r=>typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r};function X(r,s){let f=setInterval(()=>{let d=r.deref();d?d.prune():clearInterval(f)},s);f.unref?.()}function L(r,s={}){let f=b(r),{onEvict:d,sliding:T=!1,pruneInterval:g}=s,p=s.max??1/0;if(!(p>=1)||p!==1/0&&!Number.isInteger(p))throw new RangeError(`cachefor: max must be a positive integer or Infinity, got ${String(s.max)}.`);let h=s.staleWhileRevalidate,M=h===!0?1/0:h===!1||h===void 0?0:b(h),m=s.now??(()=>Date.now());if(typeof m!="function")throw new TypeError("cachefor: now must be a function returning milliseconds.");if(d!==void 0&&typeof d!="function")throw new TypeError("cachefor: onEvict must be a function.");let a=new Map,x=new Map,U=f!==1/0,E=e=>e===void 0?f:b(e),v=e=>{if(!d||!e.length)return;let t,n=!1;for(let[o,l,c]of e)try{d(o,l,c)}catch(i){n||(n=!0,t=i)}if(n)throw t},A=(e,t)=>t>=e.e+M,O=(e,t)=>{let n=a.get(e);if(n){if(t<n.e)return n;A(n,t)&&(a.delete(e),v([[n.v,e,"expired"]]))}},$=(e,t,n)=>{T&&(t.e=n+t.t),p!==1/0&&(a.delete(e),a.set(e,t))},S=(e,t,n,o)=>{let l=m(),c=a.get(e),i=[];if(c&&(a.delete(e),Object.is(c.v,t)||i.push([c.v,e,l<c.e?"replaced":"expired"])),n>0)for(n!==1/0&&(U=!0),a.set(e,{v:t,e:l+n,t:n,p:o});a.size>p;){let[w,K]=a.entries().next().value;a.delete(w),i.push([K.v,w,l<K.e?"evicted":"expired"])}v(i)},C=(e,t,n,o,l)=>{let c=m(),i=a.get(e);if(i){if(c<i.e)return $(e,i,c),o===1||o===2&&(l||i.p)?Promise.resolve(i.v):i.v;if(A(i,c)){a.delete(e);let u=i;i=void 0,v([[u.v,e,"expired"]])}}if(o!==0){let u=x.get(e);if(u)return i?Promise.resolve(i.v):u}let w=n,K={stale:i?.v,setTtl:u=>{w=b(u)}};if(o===0){let u=t(K);return x.delete(e),S(e,u,w,!1),u}let V=t(K);if(!N(V))return S(e,V,w,o===1),o===1?Promise.resolve(V):V;let k=Promise.resolve(V).then(u=>(x.get(e)===k&&(x.delete(e),S(e,u,w,!0)),u),u=>{throw x.get(e)===k&&x.delete(e),u});return x.set(e,k),i?(k.catch(j),Promise.resolve(i.v)):k};function*R(e){let t=m();for(let[n,o]of a)t<o.e&&(yield e(n,o.v))}let P={get(e){let t=m(),n=O(e,t);if(n)return $(e,n,t),n.v},peek(e){let t=a.get(e);return t&&m()<t.e?t.v:void 0},has(e){return O(e,m())!==void 0},set(e,t,n){let o=E(n);return x.delete(e),S(e,t,o,!1),this},delete(e){x.delete(e);let t=a.get(e);if(!t)return!1;a.delete(e);let n=m()<t.e;return v([[t.v,e,n?"deleted":"expired"]]),n},clear(){x.clear();let e=m(),t=[];for(let[n,o]of a)t.push([o.v,n,e<o.e?"cleared":"expired"]);a.clear(),v(t)},ttl(e){let t=m(),n=O(e,t);return n?n.e-t:void 0},get size(){if(!U)return a.size;let e=m(),t=0;for(let n of a.values())e<n.e&&t++;return t},prune(){let e=m(),t=[];for(let[n,o]of a)A(o,e)&&(a.delete(n),t.push([o.v,n,"expired"]));return v(t),t.length},getOrSet(e,t,n){try{let o=E(n);return C(e,l=>t(e,l),o,1,!1)}catch(o){return Promise.reject(o)}},getOrSetSync(e,t,n){return C(e,o=>t(e,o),E(n),0,!1)},wrap(e,t={}){if(typeof e!="function")throw new TypeError("cachefor: wrap() needs a function.");let n=E(t.ttl),o=t.key??((...c)=>Y(c)),l=Object.prototype.toString.call(e)==="[object AsyncFunction]";return function(...c){let i=C(o(...c),()=>e.apply(this,c),n,2,l);return!l&&N(i)&&(l=!0),i}},keys:()=>R(e=>e),values:()=>R((e,t)=>t),entries:()=>R((e,t)=>[e,t]),[Symbol.iterator]:()=>R((e,t)=>[e,t])};if(g!==void 0){let e=b(g);if(!(e>=1&&e<=H))throw new RangeError(`cachefor: pruneInterval must be between 1ms and ~24.8 days, got ${String(g)}.`);X(G(P),e)}return P}function _(r,s){if(typeof r!="function")throw new TypeError("memoize: expected a function.");let f=typeof s=="object"&&s!==null?s:{ttl:s},{ttl:d=1/0,key:T,...g}=f,p=L(d,g),h=p.wrap(r,T?{key:T}:{});return Object.defineProperty(h,"cache",{value:p,enumerable:!0}),Object.defineProperty(h,"name",{value:r.name,configurable:!0}),Object.defineProperty(h,"length",{value:r.length,configurable:!0}),h}var F=((r,s)=>L(r,s));Object.assign(F,{cachefor:L,memoize:_,parseTtl:b,TtlError:y});var B=F;export{y as TtlError,L as cachefor,B as default,_ as memoize,b as parseTtl};
package/package.json CHANGED
@@ -1,10 +1,60 @@
1
1
  {
2
2
  "name": "cachefor",
3
- "version": "1.0.0-test",
4
- "description": "Simple in-memory cache with readable TTLs: cachefor('5m'). Work in progress.",
5
- "main": "index.js",
6
- "types": "index.d.ts",
7
- "files": ["index.js", "index.d.ts"],
8
- "keywords": ["cachefor"],
9
- "license": "MIT"
3
+ "version": "1.0.0",
4
+ "description": "Tiny in-memory cache with human-readable TTLs: cachefor('5m'). LRU max, async getOrSet with in-flight dedup, stale-while-revalidate, memoize, eviction callbacks, no timers. Zero dependencies.",
5
+ "keywords": [
6
+ "cache",
7
+ "memory-cache",
8
+ "in-memory",
9
+ "ttl",
10
+ "expire",
11
+ "expiry",
12
+ "lru",
13
+ "lru-cache",
14
+ "node-cache",
15
+ "memoize",
16
+ "memoization",
17
+ "memo",
18
+ "async",
19
+ "promise",
20
+ "dedupe",
21
+ "deduplication",
22
+ "stale-while-revalidate",
23
+ "swr",
24
+ "get-or-set",
25
+ "duration",
26
+ "typescript"
27
+ ],
28
+ "license": "MIT",
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "main": "./dist/index.cjs",
32
+ "module": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "import": {
37
+ "types": "./dist/index.d.ts",
38
+ "default": "./dist/index.js"
39
+ },
40
+ "require": {
41
+ "types": "./dist/index.d.cts",
42
+ "default": "./dist/index.cjs"
43
+ }
44
+ },
45
+ "./package.json": "./package.json"
46
+ },
47
+ "files": [
48
+ "dist",
49
+ "CHANGELOG.md"
50
+ ],
51
+ "engines": {
52
+ "node": ">=20"
53
+ },
54
+ "scripts": {
55
+ "build": "tsup",
56
+ "test": "vitest run",
57
+ "typecheck": "tsc -p .",
58
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
59
+ }
10
60
  }
package/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- /** Placeholder: returns a greeting. The real cachefor API is coming soon. */
2
- export declare function hello(name?: string): string;
package/index.js DELETED
@@ -1,8 +0,0 @@
1
- 'use strict';
2
-
3
- /** Placeholder: returns a greeting. The real cachefor API is coming soon. */
4
- function hello(name) {
5
- return 'Hello, ' + (name || 'world') + '! (from cachefor)';
6
- }
7
-
8
- module.exports = { hello };