@isaacs/ttlcache 1.4.1 → 2.0.1

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/index.d.ts DELETED
@@ -1,231 +0,0 @@
1
- // Type definitions for ttlcache 1.0.0
2
- // Project: https://github.com/isaacs/ttlcache
3
- // Loosely based on @isaacs/lru-cache
4
- // https://github.com/isaacs/node-lru-cache/blob/v7.10.1/index.d.ts
5
-
6
- declare class TTLCache<K, V> implements Iterable<[K, V]> {
7
- constructor(options?: TTLCache.Options<K, V>)
8
-
9
- ttl: number
10
- max: number
11
- updateAgeOnGet: boolean
12
- checkAgeOnGet: boolean
13
- noUpdateTTL: boolean
14
- noDisposeOnSet: boolean
15
-
16
- /**
17
- * The total number of items held in the cache at the current moment.
18
- */
19
- public readonly size: number
20
-
21
- /**
22
- * Add a value to the cache.
23
- */
24
- public set(key: K, value: V, options?: TTLCache.SetOptions): this
25
-
26
- /**
27
- * Return a value from the cache.
28
- * If the key is not found, `get()` will return `undefined`.
29
- * This can be confusing when setting values specifically to `undefined`,
30
- * as in `cache.set(key, undefined)`. Use `cache.has()` to determine
31
- * whether a key is present in the cache at all.
32
- */
33
- public get<T = V>(
34
- key: K,
35
- options?: TTLCache.GetOptions
36
- ): T | undefined
37
-
38
- /**
39
- * Check if a key is in the cache.
40
- * Will return false if the item is stale, even though it is technically
41
- * in the cache.
42
- */
43
- public has(key: K): boolean
44
-
45
- /**
46
- * Deletes a key out of the cache.
47
- * Returns true if the key was deleted, false otherwise.
48
- */
49
- public delete(key: K): boolean
50
-
51
- /**
52
- * Clear the cache entirely, throwing away all values.
53
- */
54
- public clear(): void
55
-
56
- /**
57
- * Delete any stale entries. Returns true if anything was removed, false
58
- * otherwise.
59
- */
60
- public purgeStale(): boolean
61
-
62
- /**
63
- * Return the remaining time before an item expires.
64
- * Returns 0 if the item is not found in the cache or is already expired.
65
- */
66
- public getRemainingTTL(key: K): number
67
-
68
- /**
69
- * Set the ttl explicitly to a value, defaulting to the TTL set on the ctor
70
- */
71
- public setTTL(key: K, ttl?: number): void
72
-
73
- /**
74
- * Return a generator yielding `[key, value]` pairs, from soonest expiring
75
- * to latest expiring. (Items expiring at the same time are walked in insertion order.)
76
- */
77
- public entries(): Generator<[K, V]>
78
-
79
- /**
80
- * Return a generator yielding the keys in the cache,
81
- * from soonest expiring to latest expiring.
82
- */
83
- public keys(): Generator<K>
84
-
85
- /**
86
- * Return a generator yielding the values in the cache,
87
- * from soonest expiring to latest expiring.
88
- */
89
- public values(): Generator<V>
90
-
91
- /**
92
- * Iterating over the cache itself yields the same results as
93
- * `cache.entries()`
94
- */
95
- public [Symbol.iterator](): Iterator<[K, V]>
96
-
97
- /**
98
- * Cancel the timer and stop automatically expiring entries.
99
- * This allows the process to gracefully exit where Timer.unref()
100
- * is not available.
101
- */
102
- public cancelTimer(): void
103
- }
104
-
105
- declare namespace TTLCache {
106
- type DisposeReason = 'evict' | 'set' | 'delete' | 'stale'
107
-
108
- type Disposer<K, V> = (
109
- value: V,
110
- key: K,
111
- reason: DisposeReason
112
- ) => void
113
-
114
- type TTLOptions = {
115
- /**
116
- * Max time in milliseconds for items to live in cache before they are
117
- * considered stale. Note that stale items are NOT preemptively removed
118
- * by default, and MAY live in the cache, contributing to max,
119
- * long after they have expired.
120
- *
121
- * Must be an integer number of ms, or Infinity. Defaults to `undefined`,
122
- * meaning that a TTL must be set explicitly for each set()
123
- */
124
- ttl?: number
125
-
126
- /**
127
- * Boolean flag to tell the cache to not update the TTL when
128
- * setting a new value for an existing key (ie, when updating a value
129
- * rather than inserting a new value). Note that the TTL value is
130
- * _always_ set when adding a new entry into the cache.
131
- *
132
- * @default false
133
- */
134
- noUpdateTTL?: boolean
135
- }
136
-
137
- type Options<K, V> = {
138
- /**
139
- * The number of items to keep.
140
- *
141
- * @default Infinity
142
- */
143
- max?: number
144
-
145
- /**
146
- * Update the age of items on cache.get(), renewing their TTL
147
- *
148
- * @default false
149
- */
150
- updateAgeOnGet?: boolean
151
-
152
- /**
153
- * In the event that an item's expiration timer hasn't yet fired,
154
- * and an attempt is made to get() it, then return undefined and
155
- * delete it, rather than returning the cached value.
156
- *
157
- * By default, items are only expired when their timer fires, so there's
158
- * a bit of a "best effort" expiration, and the cache will return a value
159
- * if it has one, even if it's technically stale.
160
- *
161
- * @default false
162
- */
163
- checkAgeOnGet?: boolean
164
-
165
- /**
166
- * Do not call dispose() function when overwriting a key with a new value
167
- *
168
- * @default false
169
- */
170
- noDisposeOnSet?: boolean
171
-
172
- /**
173
- * Function that is called on items when they are dropped from the cache.
174
- * This can be handy if you want to close file descriptors or do other
175
- * cleanup tasks when items are no longer accessible. Called with `key,
176
- * value`. It's called before actually removing the item from the
177
- * internal cache, so it is *NOT* safe to re-add them.
178
- * Use `disposeAfter` if you wish to dispose items after they have been
179
- * full removed, when it is safe to add them back to the cache.
180
- */
181
- dispose?: Disposer<K, V>
182
- } & TTLOptions
183
-
184
- type SetOptions = {
185
- /**
186
- * Do not call dispose() function when overwriting a key with a new value
187
- * Overrides the value set in the constructor.
188
- */
189
- noDisposeOnSet?: boolean
190
-
191
- /**
192
- * Do not update the TTL when overwriting an existing item.
193
- */
194
- noUpdateTTL?: boolean
195
-
196
- /**
197
- * Override the default TTL for this one set() operation.
198
- * Required if a TTL was not set in the constructor options.
199
- */
200
- ttl?: number
201
- }
202
-
203
- type GetOptions = {
204
- /**
205
- * Update the age of items on cache.get(), renewing their TTL
206
- *
207
- * @default false
208
- */
209
- updateAgeOnGet?: boolean
210
-
211
- /**
212
- * In the event that an item's expiration timer hasn't yet fired,
213
- * and an attempt is made to get() it, then return undefined and
214
- * delete it, rather than returning the cached value.
215
- *
216
- * By default, items are only expired when their timer fires, so there's
217
- * a bit of a "best effort" expiration, and the cache will return a value
218
- * if it has one, even if it's technically stale.
219
- *
220
- * @default false
221
- */
222
- checkAgeOnGet?: boolean
223
-
224
- /**
225
- * Set new TTL, applied only when `updateAgeOnGet` is true
226
- */
227
- ttl?: number
228
- }
229
- }
230
-
231
- export = TTLCache
package/index.js DELETED
@@ -1,324 +0,0 @@
1
- // A simple TTL cache with max capacity option, ms resolution,
2
- // autopurge, and reasonably optimized performance
3
- // Relies on the fact that integer Object keys are kept sorted,
4
- // and managed very efficiently by V8.
5
-
6
- /* istanbul ignore next */
7
- const perf =
8
- typeof performance === 'object' &&
9
- performance &&
10
- typeof performance.now === 'function'
11
- ? performance
12
- : Date
13
-
14
- const now = () => perf.now()
15
- const isPosInt = n => n && n === Math.floor(n) && n > 0 && isFinite(n)
16
- const isPosIntOrInf = n => n === Infinity || isPosInt(n)
17
-
18
- class TTLCache {
19
- constructor({
20
- max = Infinity,
21
- ttl,
22
- updateAgeOnGet = false,
23
- checkAgeOnGet = false,
24
- noUpdateTTL = false,
25
- dispose,
26
- noDisposeOnSet = false,
27
- } = {}) {
28
- // {[expirationTime]: [keys]}
29
- this.expirations = Object.create(null)
30
- // {key=>val}
31
- this.data = new Map()
32
- // {key=>expiration}
33
- this.expirationMap = new Map()
34
- if (ttl !== undefined && !isPosIntOrInf(ttl)) {
35
- throw new TypeError(
36
- 'ttl must be positive integer or Infinity if set'
37
- )
38
- }
39
- if (!isPosIntOrInf(max)) {
40
- throw new TypeError('max must be positive integer or Infinity')
41
- }
42
- this.ttl = ttl
43
- this.max = max
44
- this.updateAgeOnGet = !!updateAgeOnGet
45
- this.checkAgeOnGet = !!checkAgeOnGet
46
- this.noUpdateTTL = !!noUpdateTTL
47
- this.noDisposeOnSet = !!noDisposeOnSet
48
- if (dispose !== undefined) {
49
- if (typeof dispose !== 'function') {
50
- throw new TypeError('dispose must be function if set')
51
- }
52
- this.dispose = dispose
53
- }
54
-
55
- this.timer = undefined
56
- this.timerExpiration = undefined
57
- }
58
-
59
- setTimer(expiration, ttl) {
60
- if (this.timerExpiration < expiration) {
61
- return
62
- }
63
-
64
- if (this.timer) {
65
- clearTimeout(this.timer)
66
- }
67
-
68
- const t = setTimeout(() => {
69
- this.timer = undefined
70
- this.timerExpiration = undefined
71
- this.purgeStale()
72
- for (const exp in this.expirations) {
73
- this.setTimer(exp, exp - now())
74
- break
75
- }
76
- }, ttl)
77
-
78
- /* istanbul ignore else - affordance for non-node envs */
79
- if (t.unref) t.unref()
80
-
81
- this.timerExpiration = expiration
82
- this.timer = t
83
- }
84
-
85
- // hang onto the timer so we can clearTimeout if all items
86
- // are deleted. Deno doesn't have Timer.unref(), so it
87
- // hangs otherwise.
88
- cancelTimer() {
89
- if (this.timer) {
90
- clearTimeout(this.timer)
91
- this.timerExpiration = undefined
92
- this.timer = undefined
93
- }
94
- }
95
-
96
- /* istanbul ignore next */
97
- cancelTimers() {
98
- process.emitWarning(
99
- 'TTLCache.cancelTimers has been renamed to ' +
100
- 'TTLCache.cancelTimer (no "s"), and will be removed in the next ' +
101
- 'major version update'
102
- )
103
- return this.cancelTimer()
104
- }
105
-
106
- clear() {
107
- const entries =
108
- this.dispose !== TTLCache.prototype.dispose ? [...this] : []
109
- this.data.clear()
110
- this.expirationMap.clear()
111
- // no need for any purging now
112
- this.cancelTimer()
113
- this.expirations = Object.create(null)
114
- for (const [key, val] of entries) {
115
- this.dispose(val, key, 'delete')
116
- }
117
- }
118
-
119
- setTTL(key, ttl = this.ttl) {
120
- const current = this.expirationMap.get(key)
121
- if (current !== undefined) {
122
- // remove from the expirations list, so it isn't purged
123
- const exp = this.expirations[current]
124
- if (!exp || exp.length <= 1) {
125
- delete this.expirations[current]
126
- } else {
127
- this.expirations[current] = exp.filter(k => k !== key)
128
- }
129
- }
130
-
131
- if (ttl !== Infinity) {
132
- const expiration = Math.floor(now() + ttl)
133
- this.expirationMap.set(key, expiration)
134
- if (!this.expirations[expiration]) {
135
- this.expirations[expiration] = []
136
- this.setTimer(expiration, ttl)
137
- }
138
- this.expirations[expiration].push(key)
139
- } else {
140
- this.expirationMap.set(key, Infinity)
141
- }
142
- }
143
-
144
- set(
145
- key,
146
- val,
147
- {
148
- ttl = this.ttl,
149
- noUpdateTTL = this.noUpdateTTL,
150
- noDisposeOnSet = this.noDisposeOnSet,
151
- } = {}
152
- ) {
153
- if (!isPosIntOrInf(ttl)) {
154
- throw new TypeError('ttl must be positive integer or Infinity')
155
- }
156
- if (this.expirationMap.has(key)) {
157
- if (!noUpdateTTL) {
158
- this.setTTL(key, ttl)
159
- }
160
- // has old value
161
- const oldValue = this.data.get(key)
162
- if (oldValue !== val) {
163
- this.data.set(key, val)
164
- if (!noDisposeOnSet) {
165
- this.dispose(oldValue, key, 'set')
166
- }
167
- }
168
- } else {
169
- this.setTTL(key, ttl)
170
- this.data.set(key, val)
171
- }
172
-
173
- while (this.size > this.max) {
174
- this.purgeToCapacity()
175
- }
176
-
177
- return this
178
- }
179
-
180
- has(key) {
181
- return this.data.has(key)
182
- }
183
-
184
- getRemainingTTL(key) {
185
- const expiration = this.expirationMap.get(key)
186
- return expiration === Infinity
187
- ? expiration
188
- : expiration !== undefined
189
- ? Math.max(0, Math.ceil(expiration - now()))
190
- : 0
191
- }
192
-
193
- get(
194
- key,
195
- {
196
- updateAgeOnGet = this.updateAgeOnGet,
197
- ttl = this.ttl,
198
- checkAgeOnGet = this.checkAgeOnGet,
199
- } = {}
200
- ) {
201
- const val = this.data.get(key)
202
- if (checkAgeOnGet && this.getRemainingTTL(key) === 0) {
203
- this.delete(key)
204
- return undefined
205
- }
206
- if (updateAgeOnGet) {
207
- this.setTTL(key, ttl)
208
- }
209
- return val
210
- }
211
-
212
- dispose(_, __) {}
213
-
214
- delete(key) {
215
- const current = this.expirationMap.get(key)
216
- if (current !== undefined) {
217
- const value = this.data.get(key)
218
- this.data.delete(key)
219
- this.expirationMap.delete(key)
220
- const exp = this.expirations[current]
221
- if (exp) {
222
- if (exp.length <= 1) {
223
- delete this.expirations[current]
224
- } else {
225
- this.expirations[current] = exp.filter(k => k !== key)
226
- }
227
- }
228
- this.dispose(value, key, 'delete')
229
- if (this.size === 0) {
230
- this.cancelTimer()
231
- }
232
- return true
233
- }
234
- return false
235
- }
236
-
237
- purgeToCapacity() {
238
- for (const exp in this.expirations) {
239
- const keys = this.expirations[exp]
240
- if (this.size - keys.length >= this.max) {
241
- delete this.expirations[exp]
242
- const entries = []
243
- for (const key of keys) {
244
- entries.push([key, this.data.get(key)])
245
- this.data.delete(key)
246
- this.expirationMap.delete(key)
247
- }
248
- for (const [key, val] of entries) {
249
- this.dispose(val, key, 'evict')
250
- }
251
- } else {
252
- const s = this.size - this.max
253
- const entries = []
254
- for (const key of keys.splice(0, s)) {
255
- entries.push([key, this.data.get(key)])
256
- this.data.delete(key)
257
- this.expirationMap.delete(key)
258
- }
259
- for (const [key, val] of entries) {
260
- this.dispose(val, key, 'evict')
261
- }
262
- return
263
- }
264
- }
265
- }
266
-
267
- get size() {
268
- return this.data.size
269
- }
270
-
271
- purgeStale() {
272
- const n = Math.ceil(now())
273
- for (const exp in this.expirations) {
274
- if (exp === 'Infinity' || exp > n) {
275
- return
276
- }
277
-
278
- /* istanbul ignore next
279
- * mysterious need for a guard here?
280
- * https://github.com/isaacs/ttlcache/issues/26 */
281
- const keys = [...(this.expirations[exp] || [])]
282
- const entries = []
283
- delete this.expirations[exp]
284
- for (const key of keys) {
285
- entries.push([key, this.data.get(key)])
286
- this.data.delete(key)
287
- this.expirationMap.delete(key)
288
- }
289
- for (const [key, val] of entries) {
290
- this.dispose(val, key, 'stale')
291
- }
292
- }
293
- if (this.size === 0) {
294
- this.cancelTimer()
295
- }
296
- }
297
-
298
- *entries() {
299
- for (const exp in this.expirations) {
300
- for (const key of this.expirations[exp]) {
301
- yield [key, this.data.get(key)]
302
- }
303
- }
304
- }
305
- *keys() {
306
- for (const exp in this.expirations) {
307
- for (const key of this.expirations[exp]) {
308
- yield key
309
- }
310
- }
311
- }
312
- *values() {
313
- for (const exp in this.expirations) {
314
- for (const key of this.expirations[exp]) {
315
- yield this.data.get(key)
316
- }
317
- }
318
- }
319
- [Symbol.iterator]() {
320
- return this.entries()
321
- }
322
- }
323
-
324
- module.exports = TTLCache