@ix-xs/node-comfort 1.1.31 → 2.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/LICENSE +21 -0
  3. package/README.md +210 -748
  4. package/index.js +84 -13
  5. package/package.json +201 -21
  6. package/src/Arr.js +901 -0
  7. package/src/Async.js +585 -0
  8. package/src/Cache.js +329 -0
  9. package/src/Checker.js +979 -188
  10. package/src/Cli.js +1034 -0
  11. package/src/Color.js +415 -0
  12. package/src/Crypto.js +707 -0
  13. package/src/Emitter.js +289 -0
  14. package/src/Env.js +555 -0
  15. package/src/FS.js +1483 -768
  16. package/src/Func.js +692 -0
  17. package/src/Http.js +538 -0
  18. package/src/Id.js +418 -0
  19. package/src/Logger.js +739 -307
  20. package/src/Num.js +849 -0
  21. package/src/Obj.js +904 -0
  22. package/src/SQLite.js +1308 -994
  23. package/src/Schema.js +1586 -0
  24. package/src/Str.js +999 -0
  25. package/src/Sys.js +511 -0
  26. package/src/Time.js +1323 -0
  27. package/src/Utils.js +321 -325
  28. package/src/errors.js +292 -0
  29. package/types/index.d.ts +693 -120
  30. package/types/src/Arr.d.ts +562 -0
  31. package/types/src/Arr.d.ts.map +1 -0
  32. package/types/src/Async.d.ts +321 -0
  33. package/types/src/Async.d.ts.map +1 -0
  34. package/types/src/Cache.d.ts +195 -0
  35. package/types/src/Cache.d.ts.map +1 -0
  36. package/types/src/Checker.d.ts +609 -81
  37. package/types/src/Checker.d.ts.map +1 -1
  38. package/types/src/Cli.d.ts +582 -0
  39. package/types/src/Cli.d.ts.map +1 -0
  40. package/types/src/Color.d.ts +294 -0
  41. package/types/src/Color.d.ts.map +1 -0
  42. package/types/src/Crypto.d.ts +534 -0
  43. package/types/src/Crypto.d.ts.map +1 -0
  44. package/types/src/Emitter.d.ts +170 -0
  45. package/types/src/Emitter.d.ts.map +1 -0
  46. package/types/src/Env.d.ts +382 -0
  47. package/types/src/Env.d.ts.map +1 -0
  48. package/types/src/FS.d.ts +709 -201
  49. package/types/src/FS.d.ts.map +1 -1
  50. package/types/src/Func.d.ts +455 -0
  51. package/types/src/Func.d.ts.map +1 -0
  52. package/types/src/Http.d.ts +374 -0
  53. package/types/src/Http.d.ts.map +1 -0
  54. package/types/src/Id.d.ts +200 -0
  55. package/types/src/Id.d.ts.map +1 -0
  56. package/types/src/Logger.d.ts +374 -24
  57. package/types/src/Logger.d.ts.map +1 -1
  58. package/types/src/Num.d.ts +578 -0
  59. package/types/src/Num.d.ts.map +1 -0
  60. package/types/src/Obj.d.ts +475 -0
  61. package/types/src/Obj.d.ts.map +1 -0
  62. package/types/src/SQLite.d.ts +647 -305
  63. package/types/src/SQLite.d.ts.map +1 -1
  64. package/types/src/Schema.d.ts +940 -0
  65. package/types/src/Schema.d.ts.map +1 -0
  66. package/types/src/Str.d.ts +696 -0
  67. package/types/src/Str.d.ts.map +1 -0
  68. package/types/src/Sys.d.ts +269 -0
  69. package/types/src/Sys.d.ts.map +1 -0
  70. package/types/src/Time.d.ts +664 -0
  71. package/types/src/Time.d.ts.map +1 -0
  72. package/types/src/Utils.d.ts +154 -102
  73. package/types/src/Utils.d.ts.map +1 -1
  74. package/types/src/errors.d.ts +292 -0
  75. package/types/src/errors.d.ts.map +1 -0
  76. package/tsconfig.json +0 -18
  77. package/types/index.d.ts.map +0 -1
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Options for `map()`, `forEach()` and `filter()`.
3
+ */
4
+ export type MapOptions = {
5
+ /**
6
+ * How many run at the same time. No limit by default.
7
+ */
8
+ concurrency?: number | undefined;
9
+ /**
10
+ * Stop at the first error. With `false`, everything runs and you get an `AggregateError` of all failures. Defaults to `true`.
11
+ */
12
+ stopOnError?: boolean | undefined;
13
+ /**
14
+ * Stops starting new work and rejects with an `AbortError`.
15
+ */
16
+ signal?: AbortSignal | undefined;
17
+ };
18
+ /**
19
+ * A limiter from `limit()`. Call it with a function to run it when there's room.
20
+ */
21
+ export type Limiter = (<T>(fn: () => T | PromiseLike<T>) => Promise<Awaited<T>>) & {
22
+ readonly activeCount: number;
23
+ readonly pendingCount: number;
24
+ concurrency: number;
25
+ clearQueue(): void;
26
+ onIdle(): Promise<void>;
27
+ };
28
+ /**
29
+ * Options for `queue()`.
30
+ */
31
+ export type QueueOptions = {
32
+ /**
33
+ * How many tasks run at the same time. Defaults to `1`.
34
+ */
35
+ concurrency?: number | undefined;
36
+ /**
37
+ * Start right away. Defaults to `true`.
38
+ */
39
+ autoStart?: boolean | undefined;
40
+ /**
41
+ * Time limit per task, like `"30s"`. A slower task rejects with a `TimeoutError`.
42
+ */
43
+ timeout?: string | number | undefined;
44
+ };
45
+ /**
46
+ * Options for `queue.add()`.
47
+ */
48
+ export type QueueAddOptions = {
49
+ /**
50
+ * Higher goes first; equal priorities keep their order. Defaults to `0`.
51
+ */
52
+ priority?: number | undefined;
53
+ };
54
+ /**
55
+ * A queue from `queue()`.
56
+ */
57
+ export type Queue = {
58
+ /**
59
+ * Adds a task; resolves with its result.
60
+ */
61
+ add: <T>(task: () => T | PromiseLike<T>, options?: QueueAddOptions) => Promise<Awaited<T>>;
62
+ /**
63
+ * Adds several tasks; resolves with all results.
64
+ */
65
+ addAll: <T>(tasks: Array<() => T | PromiseLike<T>>, options?: QueueAddOptions) => Promise<Array<Awaited<T>>>;
66
+ /**
67
+ * Stops starting tasks. Running ones finish.
68
+ */
69
+ pause: () => Queue;
70
+ /**
71
+ * Starts again.
72
+ */
73
+ start: () => Queue;
74
+ /**
75
+ * Drops the tasks that haven't started. Their promises never settle.
76
+ */
77
+ clear: () => void;
78
+ /**
79
+ * Resolves when nothing is waiting or running.
80
+ */
81
+ onIdle: () => Promise<void>;
82
+ /**
83
+ * Resolves when nothing is waiting.
84
+ */
85
+ onEmpty: () => Promise<void>;
86
+ /**
87
+ * Tasks waiting.
88
+ */
89
+ size: number;
90
+ /**
91
+ * Tasks running.
92
+ */
93
+ pending: number;
94
+ isPaused: boolean;
95
+ /**
96
+ * Can be changed on the fly.
97
+ */
98
+ concurrency: number;
99
+ };
100
+ /**
101
+ * A promise with its `resolve` and `reject`.
102
+ */
103
+ export type Deferred<T> = {
104
+ promise: Promise<T>;
105
+ resolve: (value: T | PromiseLike<T>) => void;
106
+ reject: (reason?: unknown) => void;
107
+ /**
108
+ * Whether it's already resolved or rejected.
109
+ */
110
+ settled: boolean;
111
+ };
112
+ /**
113
+ * What `settle()` returns.
114
+ */
115
+ export type Settled<T> = {
116
+ /**
117
+ * Successful values, in order.
118
+ */
119
+ fulfilled: T[];
120
+ /**
121
+ * Errors, in order.
122
+ */
123
+ rejected: unknown[];
124
+ /**
125
+ * Everything, like `Promise.allSettled`.
126
+ */
127
+ results: Array<PromiseSettledResult<T>>;
128
+ };
129
+ /**
130
+ * Options for `poll()`.
131
+ */
132
+ export type PollOptions = {
133
+ /**
134
+ * Time between tries. Defaults to 100 ms.
135
+ */
136
+ interval?: string | number | undefined;
137
+ /**
138
+ * Give up with a `TimeoutError` after this long.
139
+ */
140
+ timeout?: string | number | undefined;
141
+ /**
142
+ * Stops with an `AbortError`.
143
+ */
144
+ signal?: AbortSignal | undefined;
145
+ };
146
+ /**
147
+ * A mutex from `mutex()`.
148
+ */
149
+ export type Mutex = {
150
+ /**
151
+ * Runs `fn` once no other `run` is in progress.
152
+ */
153
+ run: <T>(fn: () => T | PromiseLike<T>) => Promise<Awaited<T>>;
154
+ /**
155
+ * Waits for the lock and gives you the function that releases it.
156
+ */
157
+ lock: () => Promise<() => void>;
158
+ isLocked: boolean;
159
+ };
160
+ /**
161
+ * Waits for a while. Same as `nc.wait()`.
162
+ *
163
+ * @example
164
+ * await async.sleep("250ms");
165
+ *
166
+ * @param {number | string} duration
167
+ * @param {{ signal?: AbortSignal }} [options]
168
+ * @returns {Promise<void>}
169
+ */
170
+ export function sleep(duration: number | string, options?: {
171
+ signal?: AbortSignal;
172
+ }): Promise<void>;
173
+ /**
174
+ * Maps items through an async function, with at most `concurrency` calls
175
+ * at once. Results stay in order.
176
+ *
177
+ * @example
178
+ * const users = await async.map(ids, (id) => api.getUser(id), { concurrency: 10 });
179
+ *
180
+ * @template T
181
+ * @template R
182
+ * @param {Iterable<T> | AsyncIterable<T>} items
183
+ * @param {(item: T, index: number) => R | PromiseLike<R>} fn
184
+ * @param {MapOptions} [options]
185
+ * @returns {Promise<Array<Awaited<R>>>}
186
+ * @throws The first error, an `AggregateError` with `stopOnError: false`, or an `AbortError`.
187
+ */
188
+ export function map<T, R>(items: Iterable<T> | AsyncIterable<T>, fn: (item: T, index: number) => R | PromiseLike<R>, options?: MapOptions): Promise<Array<Awaited<R>>>;
189
+ /**
190
+ * Runs an async function for every item, with a concurrency limit.
191
+ *
192
+ * @example
193
+ * await async.forEach(images, (image) => optimize(image), { concurrency: 4 });
194
+ *
195
+ * @template T
196
+ * @param {Iterable<T> | AsyncIterable<T>} items
197
+ * @param {(item: T, index: number) => unknown} fn
198
+ * @param {MapOptions} [options]
199
+ * @returns {Promise<void>}
200
+ */
201
+ export function forEach<T>(items: Iterable<T> | AsyncIterable<T>, fn: (item: T, index: number) => unknown, options?: MapOptions): Promise<void>;
202
+ /**
203
+ * Keeps the items that pass an async test, with a concurrency limit.
204
+ * Order is preserved.
205
+ *
206
+ * @example
207
+ * const alive = await async.filter(hosts, (host) => ping(host), { concurrency: 20 });
208
+ *
209
+ * @template T
210
+ * @param {Iterable<T> | AsyncIterable<T>} items
211
+ * @param {(item: T, index: number) => unknown} predicate
212
+ * @param {MapOptions} [options]
213
+ * @returns {Promise<T[]>}
214
+ */
215
+ export function filter<T>(items: Iterable<T> | AsyncIterable<T>, predicate: (item: T, index: number) => unknown, options?: MapOptions): Promise<T[]>;
216
+ /**
217
+ * Runs async functions one after the other and returns their results.
218
+ *
219
+ * @example
220
+ * await async.series([() => migrateUsers(), () => migrateOrders()]);
221
+ *
222
+ * @template T
223
+ * @param {Iterable<() => T | PromiseLike<T>>} tasks
224
+ * @returns {Promise<Array<Awaited<T>>>}
225
+ */
226
+ export function series<T>(tasks: Iterable<() => T | PromiseLike<T>>): Promise<Array<Awaited<T>>>;
227
+ /**
228
+ * A limiter: wrap calls with it, and at most `concurrency` run at once
229
+ * while the rest wait their turn. Like `p-limit`.
230
+ *
231
+ * @example
232
+ * const limit = async.limit(3);
233
+ * const results = await Promise.all(urls.map((url) => limit(() => fetch(url))));
234
+ *
235
+ * @param {number} concurrency
236
+ * @returns {Limiter}
237
+ */
238
+ export function limit(concurrency: number): Limiter;
239
+ /**
240
+ * A task queue with a concurrency limit, priorities, pause and per-task
241
+ * timeouts.
242
+ *
243
+ * @example
244
+ * const jobs = async.queue({ concurrency: 2, timeout: "30s" });
245
+ * jobs.add(() => sendEmail(a));
246
+ * jobs.add(() => sendEmail(vip), { priority: 10 }); // jumps the line
247
+ * await jobs.onIdle();
248
+ *
249
+ * @param {QueueOptions} [options]
250
+ * @returns {Queue}
251
+ */
252
+ export function queue(options?: QueueOptions): Queue;
253
+ /**
254
+ * A mutex: tasks given to `run()` never overlap. Put it around
255
+ * read-modify-write steps, like updating a file or refreshing a token.
256
+ *
257
+ * @example
258
+ * const lock = async.mutex();
259
+ * await lock.run(async () => {
260
+ * const data = nc.readJSON("./counter.json", { n: 0 });
261
+ * nc.writeJSON("./counter.json", { n: data.n + 1 });
262
+ * });
263
+ *
264
+ * @returns {Mutex}
265
+ */
266
+ export function mutex(): Mutex;
267
+ /**
268
+ * A promise along with its `resolve` and `reject`. Handy to connect
269
+ * callbacks or events to `await`.
270
+ *
271
+ * @example
272
+ * const ready = async.deferred();
273
+ * socket.once("open", () => ready.resolve());
274
+ * await ready.promise;
275
+ *
276
+ * @template [T=void]
277
+ * @returns {Deferred<T>}
278
+ */
279
+ export function deferred<T = void>(): Deferred<T>;
280
+ /**
281
+ * Waits for every promise and sorts successes from failures.
282
+ *
283
+ * @example
284
+ * const { fulfilled, rejected } = await async.settle(emails.map(send));
285
+ * nc.info(`${fulfilled.length} sent, ${rejected.length} failed`);
286
+ *
287
+ * @template T
288
+ * @param {Iterable<T | PromiseLike<T>>} promises
289
+ * @returns {Promise<Settled<Awaited<T>>>}
290
+ */
291
+ export function settle<T>(promises: Iterable<T | PromiseLike<T>>): Promise<Settled<Awaited<T>>>;
292
+ /**
293
+ * Like `Promise.all`, for an object of promises.
294
+ *
295
+ * @example
296
+ * const { user, orders } = await async.props({ user: getUser(id), orders: getOrders(id) });
297
+ *
298
+ * @template {Record<string, unknown>} T
299
+ * @param {T} object
300
+ * @returns {Promise<{ [K in keyof T]: Awaited<T[K]> }>}
301
+ */
302
+ export function props<T extends Record<string, unknown>>(object: T): Promise<{ [K in keyof T]: Awaited<T[K]>; }>;
303
+ /**
304
+ * Calls `fn` until it returns something truthy, and resolves with it.
305
+ * Errors count as "not yet".
306
+ *
307
+ * @example
308
+ * await async.poll(() => fetch(healthUrl).then((res) => res.ok), { interval: "500ms", timeout: "30s" });
309
+ *
310
+ * @template T
311
+ * @param {() => T | PromiseLike<T>} fn
312
+ * @param {PollOptions} [options]
313
+ * @returns {Promise<NonNullable<Awaited<T>>>}
314
+ * @throws {TimeoutError}
315
+ * @throws {AbortError}
316
+ */
317
+ export function poll<T>(fn: () => T | PromiseLike<T>, options?: PollOptions): Promise<NonNullable<Awaited<T>>>;
318
+ import { retry } from "./Func.js";
319
+ import { timeout } from "./Func.js";
320
+ export { retry, timeout };
321
+ //# sourceMappingURL=Async.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Async.d.ts","sourceRoot":"","sources":["../../src/Async.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;sBA4Ba,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,M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F,QAAQ,CAAC,CAAC,CAAC,CAwBvB;AAED;;;;;;;;;;GAUG;AACH,uBAJa,CAAC,YACH,QAAQ,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CASxC;AAED;;;;;;;;;GASG;AACH,sBAJuC,CAAC,SAA1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAE,UAC3B,CAAC,GACC,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAE,CAAC,CAWtD;AAED;;;;;;;;;;;;;GAaG;AACH,qBAPa,CAAC,MACH,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,YACxB,WAAW,GACT,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAoB5C"}
@@ -0,0 +1,195 @@
1
+ export = Cache;
2
+ /**
3
+ * An in-memory cache with a size limit and expiry.
4
+ *
5
+ * @template K
6
+ * @template V
7
+ */
8
+ declare class Cache<K, V> {
9
+ /**
10
+ * @example
11
+ * const cache = new nc.Cache({ max: 500, ttl: "1h", updateAgeOnGet: true });
12
+ *
13
+ * @param {CacheOptions<K, V>} [options]
14
+ */
15
+ constructor(options?: CacheOptions<K, V>);
16
+ /**
17
+ * Reads a value and marks it as recently used.
18
+ *
19
+ * @param {K} key
20
+ * @returns {V | undefined} `undefined` if missing or expired.
21
+ */
22
+ get(key: K): V | undefined;
23
+ /**
24
+ * Reads a value without counting it as a use or touching the stats.
25
+ *
26
+ * @param {K} key
27
+ * @returns {V | undefined}
28
+ */
29
+ peek(key: K): V | undefined;
30
+ /**
31
+ * Stores a value. When the cache is full, the least recently used entry
32
+ * goes.
33
+ *
34
+ * @example
35
+ * cache.set("token", token, { ttl: "15m" });
36
+ *
37
+ * @param {K} key
38
+ * @param {V} value
39
+ * @param {CacheSetOptions} [options]
40
+ * @returns {this}
41
+ */
42
+ set(key: K, value: V, options?: CacheSetOptions): this;
43
+ /**
44
+ * Returns the cached value, or calls `loader`, stores the result and
45
+ * returns it. Simultaneous calls for the same key share one `loader` call,
46
+ * and a failed load caches nothing.
47
+ *
48
+ * @example
49
+ * const profile = await cache.getOrSet(`profile:${id}`, () => api.fetchProfile(id), { ttl: "10m" });
50
+ *
51
+ * @param {K} key
52
+ * @param {() => V | PromiseLike<V>} loader
53
+ * @param {CacheSetOptions} [options]
54
+ * @returns {Promise<V>}
55
+ */
56
+ getOrSet(key: K, loader: () => V | PromiseLike<V>, options?: CacheSetOptions): Promise<V>;
57
+ /**
58
+ * Is there a fresh entry for this key? Doesn't count as a use.
59
+ *
60
+ * @param {K} key
61
+ * @returns {boolean}
62
+ */
63
+ has(key: K): boolean;
64
+ /**
65
+ * Removes an entry.
66
+ *
67
+ * @param {K} key
68
+ * @returns {boolean} `true` if there was one.
69
+ */
70
+ delete(key: K): boolean;
71
+ /**
72
+ * Removes every entry. Stats are kept.
73
+ *
74
+ * @returns {void}
75
+ */
76
+ clear(): void;
77
+ /**
78
+ * Removes expired entries now instead of waiting for them to be read.
79
+ *
80
+ * @returns {number} How many were removed.
81
+ */
82
+ prune(): number;
83
+ /**
84
+ * Time left before an entry expires.
85
+ *
86
+ * @param {K} key
87
+ * @returns {number | undefined} Milliseconds, `Infinity` if it never expires, `undefined` if missing.
88
+ */
89
+ ttl(key: K): number | undefined;
90
+ /**
91
+ * Wraps a function so its results are cached here.
92
+ *
93
+ * @example
94
+ * const getWeather = cache.wrap((city) => api.weather(city), { key: (city) => city.toLowerCase(), ttl: "30m" });
95
+ * await getWeather("Paris");
96
+ *
97
+ * @template {any[]} A
98
+ * @param {(...args: A) => V | PromiseLike<V>} fn
99
+ * @param {{ key?: (...args: A) => K, ttl?: number | string }} [options] `key` builds the cache key from the arguments; by default they're turned into JSON.
100
+ * @returns {(...args: A) => Promise<V>}
101
+ */
102
+ wrap<A extends any[]>(fn: (...args: A) => V | PromiseLike<V>, options?: {
103
+ key?: (...args: A) => K;
104
+ ttl?: number | string;
105
+ }): (...args: A) => Promise<V>;
106
+ /** Number of entries, including expired ones not yet removed. */
107
+ get size(): number;
108
+ /** Hit and miss counts. */
109
+ get stats(): CacheStats;
110
+ /**
111
+ * Fresh keys, least recently used first.
112
+ * @returns {K[]}
113
+ */
114
+ keys(): K[];
115
+ /**
116
+ * Fresh values, least recently used first.
117
+ * @returns {V[]}
118
+ */
119
+ values(): V[];
120
+ /**
121
+ * Fresh `[key, value]` pairs, least recently used first.
122
+ * @returns {Array<[K, V]>}
123
+ */
124
+ entries(): Array<[K, V]>;
125
+ /**
126
+ * Lets you write `for (const [key, value] of cache)`.
127
+ * @returns {IterableIterator<[K, V]>}
128
+ */
129
+ [Symbol.iterator](): IterableIterator<[K, V]>;
130
+ #private;
131
+ }
132
+ declare namespace Cache {
133
+ export { CacheRemovalReason, CacheOptions, CacheSetOptions, CacheStats };
134
+ }
135
+ /**
136
+ * Why an entry left the cache.
137
+ */
138
+ type CacheRemovalReason = "evict" | "expire" | "delete" | "set" | "clear";
139
+ /**
140
+ * Options for `new Cache()`.
141
+ */
142
+ type CacheOptions<K, V> = {
143
+ /**
144
+ * Maximum number of entries. When full, the least recently used goes. No limit by default.
145
+ */
146
+ max?: number | undefined;
147
+ /**
148
+ * How long entries live, in ms or like `"10m"`. `0` means forever, the default.
149
+ */
150
+ ttl?: string | number | undefined;
151
+ /**
152
+ * Reading an entry restarts its time to live.
153
+ */
154
+ updateAgeOnGet?: boolean | undefined;
155
+ /**
156
+ * Called whenever an entry leaves the cache.
157
+ */
158
+ onRemove?: ((key: K, value: V, reason: CacheRemovalReason) => void) | undefined;
159
+ };
160
+ /**
161
+ * Options for `set()` and `getOrSet()`.
162
+ */
163
+ type CacheSetOptions = {
164
+ /**
165
+ * Time to live of this entry. `0` means forever.
166
+ */
167
+ ttl?: string | number | undefined;
168
+ };
169
+ /**
170
+ * Cache stats.
171
+ */
172
+ type CacheStats = {
173
+ /**
174
+ * Reads that found a fresh entry.
175
+ */
176
+ hits: number;
177
+ /**
178
+ * Reads that found nothing or an expired entry.
179
+ */
180
+ misses: number;
181
+ sets: number;
182
+ /**
183
+ * Entries dropped because the cache was full.
184
+ */
185
+ evictions: number;
186
+ /**
187
+ * Entries dropped because they expired.
188
+ */
189
+ expirations: number;
190
+ /**
191
+ * From 0 to 1.
192
+ */
193
+ hitRate: number;
194
+ };
195
+ //# sourceMappingURL=Cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Cache.d.ts","sourceRoot":"","sources":["../../src/Cache.js"],"names":[],"mappings":";AA4DA;;;;;GAKG;AACH,oBAHa,CAAC,EACD,CAAC;IAcZ;;;;;OAKG;IACH,sBAFW,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,EAO5B;IA4BD;;;;;OAKG;IACH,SAHW,CAAC,GACC,CAAC,GAAG,SAAS,CAazB;IAED;;;;;OAKG;IACH,UAHW,CAAC,GACC,CAAC,GAAG,SAAS,CAIzB;IAED;;;;;;;;;;;OAWG;IACH,SALW,CAAC,SACD,CAAC,YACD,eAAe,GACb,IAAI,CAahB;IAED;;;;;;;;;;;;OAYG;IACH,cALW,CAAC,UACD,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,YACxB,eAAe,GACb,OAAO,CAAC,CAAC,CAAC,CAiBtB;IAED;;;;;OAKG;IACH,SAHW,CAAC,GACC,OAAO,CAInB;IAED;;;;;OAKG;IACH,YAHW,CAAC,GACC,OAAO,CAOnB;IAED;;;;OAIG;IACH,SAFa,IAAI,CAIhB;IAED;;;;OAIG;IACH,SAFa,MAAM,CAYlB;IAED;;;;;OAKG;IACH,SAHW,CAAC,GACC,MAAM,GAAG,SAAS,CAM9B;IAED;;;;;;;;;;;OAWG;IACH,KALqB,CAAC,SAAR,GAAG,EAAG,MACT,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,WAAW,CAAC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