{{ message }}
Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
565 lines (514 loc) · 14.5 KB
/
Copy pathindex.ts
File metadata and controls
565 lines (514 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import fs from "node:fs";
import path from "node:path";
import { CacheableMemory } from "cacheable";
import { parse, stringify } from "flatted";
import { Hookified } from "hookified";
export type FlatCacheOptions = {
ttl?: number | string;
useClone?: boolean;
lruSize?: number;
expirationInterval?: number;
persistInterval?: number;
cacheDir?: string;
cacheId?: string;
// biome-ignore lint/suspicious/noExplicitAny: type format
deserialize?: (data: string) => any;
// biome-ignore lint/suspicious/noExplicitAny: type format
serialize?: (data: any) => string;
};
export enum FlatCacheEvents {
SAVE = "save",
LOAD = "load",
DELETE = "delete",
CLEAR = "clear",
DESTROY = "destroy",
ERROR = "error",
EXPIRED = "expired",
}
export class FlatCache extends Hookified {
private readonly _cache = new CacheableMemory();
private _cacheDir = ".cache";
private _cacheId = "cache1";
private _persistInterval = 0;
private _persistTimer: NodeJS.Timeout | undefined;
private _changesSinceLastSave = false;
private readonly _parse = parse;
private readonly _stringify = stringify;
constructor(options?: FlatCacheOptions) {
super({ throwOnEmptyListeners: false });
if (options) {
this._cache = new CacheableMemory({
ttl: options.ttl,
useClone: options.useClone,
lruSize: options.lruSize,
checkInterval: options.expirationInterval,
});
}
if (options?.cacheDir) {
this._cacheDir = options.cacheDir;
}
if (options?.cacheId) {
this._cacheId = options.cacheId;
}
if (options?.persistInterval) {
this._persistInterval = options.persistInterval;
this.startAutoPersist();
}
if (options?.deserialize) {
this._parse = options.deserialize;
}
if (options?.serialize) {
this._stringify = options.serialize;
}
}
/**
* The cache object
* @property cache
* @type {CacheableMemory}
*/
public get cache() {
return this._cache;
}
/**
* The cache directory
* @property cacheDir
* @type {String}
* @default '.cache'
*/
public get cacheDir() {
return this._cacheDir;
}
/**
* Set the cache directory
* @property cacheDir
* @type {String}
* @default '.cache'
*/
public set cacheDir(value: string) {
this._cacheDir = value;
}
/**
* The cache id
* @property cacheId
* @type {String}
* @default 'cache1'
*/
public get cacheId() {
return this._cacheId;
}
/**
* Set the cache id
* @property cacheId
* @type {String}
* @default 'cache1'
*/
public set cacheId(value: string) {
this._cacheId = value;
}
/**
* The flag to indicate if there are changes since the last save
* @property changesSinceLastSave
* @type {Boolean}
* @default false
*/
public get changesSinceLastSave() {
return this._changesSinceLastSave;
}
/**
* The interval to persist the cache to disk. 0 means no timed persistence
* @property persistInterval
* @type {Number}
* @default 0
*/
public get persistInterval() {
return this._persistInterval;
}
/**
* Set the interval to persist the cache to disk. 0 means no timed persistence
* @property persistInterval
* @type {Number}
* @default 0
*/
public set persistInterval(value: number) {
this._persistInterval = value;
}
/**
* Load a cache identified by the given Id. If the element does not exists, then initialize an empty
* cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
* then the cache module directory `.cacheDir` will be used instead
*
* @method load
* @param cacheId {String} the id of the cache, would also be used as the name of the file cache
* @param cacheDir {String} directory for the cache entry
*/
public load(cacheId?: string, cacheDir?: string) {
try {
const filePath = path.resolve(
`${cacheDir ?? this._cacheDir}/${cacheId ?? this._cacheId}`,
);
this.loadFile(filePath);
this.emit(FlatCacheEvents.LOAD);
/* v8 ignore next -- @preserve */
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit(FlatCacheEvents.ERROR, error);
}
}
/**
* Load the cache from the provided file
* @method loadFile
* @param {String} pathToFile the path to the file containing the info for the cache
*/
public loadFile(pathToFile: string) {
if (fs.existsSync(pathToFile)) {
const data = fs.readFileSync(pathToFile, "utf8");
// biome-ignore lint/suspicious/noExplicitAny: legacy format
const items = this._parse(data) as any;
// legacy array
if (Array.isArray(items)) {
for (const item of items) {
if (item && typeof item === "object" && "key" in item) {
if (item.expires) {
this._cache.set(item.key, item.value, { expire: item.expires });
} else if (item.timestamp) {
/* v8 ignore next -- @preserve */
this._cache.set(item.key, item.value, { expire: item.timestamp });
} else {
this._cache.set(item.key, item.value);
}
}
}
} else {
// legacy object format - check if items have "key" property or are direct key-value pairs
for (const key of Object.keys(items)) {
const item = items[key];
// Check if this is the new format with key/value/expires properties
/* v8 ignore next -- @preserve */
if (item && typeof item === "object" && "key" in item) {
this._cache.set(item.key as string, item.value, {
expire: item.expires as number,
});
} else {
// Old legacy format - key is the cache key, value is the cache value
if (item && typeof item === "object" && item.timestamp) {
/* v8 ignore next -- @preserve */
this._cache.set(key, item, { expire: item.timestamp });
} else {
this._cache.set(key, item);
}
}
}
}
this._changesSinceLastSave = true;
}
}
public loadFileStream(
pathToFile: string,
onProgress: (progress: number, total: number) => void,
onEnd: () => void,
onError?: (error: Error) => void,
) {
if (fs.existsSync(pathToFile)) {
const stats = fs.statSync(pathToFile);
const total = stats.size;
let loaded = 0;
let streamData = "";
const readStream = fs.createReadStream(pathToFile, { encoding: "utf8" });
readStream.on("data", (chunk) => {
loaded += chunk.length;
streamData += chunk as string;
onProgress(loaded, total);
});
readStream.on("end", () => {
const items = this._parse(streamData);
for (const key of Object.keys(items)) {
this._cache.set(items[key].key as string, items[key].value, {
expire: items[key].expires as number,
});
}
this._changesSinceLastSave = true;
onEnd();
});
/* v8 ignore next -- @preserve */
readStream.on("error", (error) => {
this.emit(FlatCacheEvents.ERROR, error);
if (onError) {
onError(error);
}
});
} else {
const error = new Error(`Cache file ${pathToFile} does not exist`);
this.emit(FlatCacheEvents.ERROR, error);
/* v8 ignore next -- @preserve */
if (onError) {
onError(error);
}
}
}
/**
* Returns the entire persisted object
* @method all
* @returns {*}
*/
public all() {
// biome-ignore lint/suspicious/noExplicitAny: type format
const result: Record<string, any> = {};
const items = [...this._cache.items];
for (const item of items) {
result[item.key] = item.value;
}
return result;
}
/**
* Returns an array with all the items in the cache { key, value, expires }
* @method items
* @returns {Array}
*/
// biome-ignore lint/suspicious/noExplicitAny: cache items can store any value
public get items(): Array<{ key: string; value: any; expires?: number }> {
return [...this._cache.items];
}
/**
* Returns the path to the file where the cache is persisted
* @method cacheFilePath
* @returns {String}
*/
public get cacheFilePath() {
return path.resolve(`${this._cacheDir}/${this._cacheId}`);
}
/**
* Returns the path to the cache directory
* @method cacheDirPath
* @returns {String}
*/
public get cacheDirPath() {
return path.resolve(this._cacheDir);
}
/**
* Returns an array with all the keys in the cache
* @method keys
* @returns {Array}
*/
public keys() {
return [...this._cache.keys];
}
/**
* (Legacy) set key method. This method will be deprecated in the future
* @method setKey
* @param key {string} the key to set
* @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
*/
// biome-ignore lint/suspicious/noExplicitAny: type format
public setKey(key: string, value: any, ttl?: number | string) {
this.set(key, value, ttl);
}
/**
* Sets a key to a given value
* @method set
* @param key {string} the key to set
* @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
* @param [ttl] {number} the time to live in milliseconds
*/
// biome-ignore lint/suspicious/noExplicitAny: type format
public set(key: string, value: any, ttl?: number | string) {
this._cache.set(key, value, ttl);
this._changesSinceLastSave = true;
}
/**
* (Legacy) Remove a given key from the cache. This method will be deprecated in the future
* @method removeKey
* @param key {String} the key to remove from the object
*/
public removeKey(key: string) {
this.delete(key);
}
/**
* Remove a given key from the cache
* @method delete
* @param key {String} the key to remove from the object
*/
public delete(key: string) {
this._cache.delete(key);
this._changesSinceLastSave = true;
this.emit(FlatCacheEvents.DELETE, key);
}
/**
* (Legacy) Return the value of the provided key. This method will be deprecated in the future
* @method getKey<T>
* @param key {String} the name of the key to retrieve
* @returns {*} at T the value from the key
*/
public getKey<T>(key: string) {
return this.get<T>(key);
}
/**
* Return the value of the provided key
* @method get<T>
* @param key {String} the name of the key to retrieve
* @returns {*} at T the value from the key
*/
public get<T>(key: string) {
return this._cache.get(key) as T;
}
/**
* Clear the cache and save the state to disk
* @method clear
*/
public clear() {
try {
this._cache.clear();
this._changesSinceLastSave = true;
this.save();
this.emit(FlatCacheEvents.CLEAR);
/* v8 ignore next -- @preserve */
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit(FlatCacheEvents.ERROR, error);
}
}
/**
* Save the state of the cache identified by the docId to disk
* as a JSON structure
* @method save
*/
public save(force = false) {
try {
/* v8 ignore next -- @preserve */
if (this._changesSinceLastSave || force) {
const filePath = this.cacheFilePath;
const items = [...this._cache.items];
const data = this._stringify(items);
// Ensure the directory exists
if (!fs.existsSync(this._cacheDir)) {
fs.mkdirSync(this._cacheDir, { recursive: true });
}
fs.writeFileSync(filePath, data);
this._changesSinceLastSave = false;
this.emit(FlatCacheEvents.SAVE);
}
/* v8 ignore next -- @preserve */
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit(FlatCacheEvents.ERROR, error);
}
}
/**
* Remove the file where the cache is persisted
* @method removeCacheFile
* @return {Boolean} true or false if the file was successfully deleted
*/
public removeCacheFile() {
try {
if (fs.existsSync(this.cacheFilePath)) {
fs.rmSync(this.cacheFilePath);
return true;
}
/* v8 ignore next -- @preserve */
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit(FlatCacheEvents.ERROR, error);
}
return false;
}
/**
* Destroy the cache. This will remove the directory, file, and memory cache
* @method destroy
* @param [includeCacheDir=false] {Boolean} if true, the cache directory will be removed
* @return {undefined}
*/
public destroy(includeCacheDirectory = false) {
try {
this._cache.clear();
this.stopAutoPersist();
if (includeCacheDirectory) {
fs.rmSync(this.cacheDirPath, { recursive: true, force: true });
} else {
fs.rmSync(this.cacheFilePath, { recursive: true, force: true });
}
this._changesSinceLastSave = false;
this.emit(FlatCacheEvents.DESTROY);
/* v8 ignore next -- @preserve */
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit(FlatCacheEvents.ERROR, error);
}
}
/**
* Start the auto persist interval
* @method startAutoPersist
*/
public startAutoPersist() {
/* v8 ignore next -- @preserve */
if (this._persistInterval > 0) {
if (this._persistTimer) {
clearInterval(this._persistTimer);
this._persistTimer = undefined;
}
this._persistTimer = setInterval(() => {
this.save();
}, this._persistInterval);
}
}
/**
* Stop the auto persist interval
* @method stopAutoPersist
*/
public stopAutoPersist() {
if (this._persistTimer) {
clearInterval(this._persistTimer);
this._persistTimer = undefined;
}
}
}
// biome-ignore lint/complexity/noStaticOnlyClass: legacy
export default class FlatCacheDefault {
static create = create;
static createFromFile = createFromFile;
static clearCacheById = clearCacheById;
static clearAll = clearAll;
}
/**
* Load a cache identified by the given Id. If the element does not exists, then initialize an empty
* cache storage.
*
* @method create
* @param docId {String} the id of the cache, would also be used as the name of the file cache
* @param cacheDirectory {String} directory for the cache entry
* @param options {FlatCacheOptions} options for the cache
* @returns {cache} cache instance
*/
export function create(options?: FlatCacheOptions) {
const cache = new FlatCache(options);
cache.load();
return cache;
}
/**
* Load a cache from the provided file
* @method createFromFile
* @param {String} filePath the path to the file containing the info for the cache
* @param options {FlatCacheOptions} options for the cache
* @returns {cache} cache instance
*/
export function createFromFile(filePath: string, options?: FlatCacheOptions) {
const cache = new FlatCache(options);
cache.loadFile(filePath);
return cache;
}
/**
* Clear the cache identified by the given Id. This will only remove the cache from disk.
* @method clearCacheById
* @param cacheId {String} the id of the cache
* @param cacheDirectory {String} directory for the cache entry
*/
export function clearCacheById(cacheId: string, cacheDirectory?: string) {
const cache = new FlatCache({ cacheId, cacheDir: cacheDirectory });
cache.destroy();
}
/**
* Clear the cache directory
* @method clearAll
* @param cacheDir {String} directory for the cache entry
*/
export function clearAll(cacheDirectory?: string) {
fs.rmSync(cacheDirectory ?? ".cache", { recursive: true, force: true });
}
You can’t perform that action at this time.
