@warlock.js/cache 4.0.42 → 4.0.46

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/cjs/index.js CHANGED
@@ -1,1702 +1,42 @@
1
1
  'use strict';
2
2
 
3
- var logger = require('@warlock.js/logger');
4
- var reinforcements = require('@mongez/reinforcements');
5
- var fs = require('@mongez/fs');
6
- var path = require('path');
7
-
8
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
-
10
- var path__default = /*#__PURE__*/_interopDefault(path);
11
-
12
- // ../../warlock.js/cache/src/types.ts
13
- var CacheError = class extends Error {
14
- constructor(message) {
15
- super(message);
16
- this.name = "CacheError";
17
- }
18
- };
19
- var CacheConnectionError = class extends CacheError {
20
- constructor(message) {
21
- super(message);
22
- this.name = "CacheConnectionError";
23
- }
24
- };
25
- var CacheConfigurationError = class extends CacheError {
26
- constructor(message) {
27
- super(message);
28
- this.name = "CacheConfigurationError";
29
- }
30
- };
31
- var CacheDriverNotInitializedError = class extends CacheError {
32
- constructor(message = "No cache driver initialized. Call cache.init() or cache.use() first.") {
33
- super(message);
34
- this.name = "CacheDriverNotInitializedError";
35
- }
36
- };
37
-
38
- // ../../warlock.js/cache/src/cache-manager.ts
39
- var CacheManager = class {
40
- /**
41
- * Cache Driver
42
- */
43
- currentDriver;
44
- /**
45
- * Loaded drivers
46
- */
47
- loadedDrivers = {};
48
- /**
49
- * Configurations list
50
- */
51
- configurations = {
52
- drivers: {},
53
- options: {}
54
- };
55
- /**
56
- * Global event listeners
57
- */
58
- globalEventListeners = /* @__PURE__ */ new Map();
59
- /**
60
- * {@inheritdoc}
61
- */
62
- name = "cacheManager";
63
- /**
64
- * {@inheritdoc}
65
- */
66
- get client() {
67
- return this.currentDriver?.client;
68
- }
69
- /**
70
- * Set the cache configurations
71
- */
72
- setCacheConfigurations(configurations) {
73
- this.configurations.default = configurations.default;
74
- this.configurations.drivers = configurations.drivers;
75
- this.configurations.options = configurations.options;
76
- }
77
- /**
78
- * Use the given driver
79
- */
80
- async use(driver) {
81
- if (typeof driver === "string") {
82
- const driverInstance = await this.load(driver);
83
- if (!driverInstance) {
84
- throw new CacheConfigurationError(
85
- `Cache driver ${driver} is not found, please declare it in the cache drivers in the configurations list.`
86
- );
87
- }
88
- driver = driverInstance;
89
- }
90
- this.attachGlobalListeners(driver);
91
- this.currentDriver = driver;
92
- return this;
93
- }
94
- /**
95
- * Ensure driver is initialized before operations
96
- */
97
- ensureDriverInitialized() {
98
- if (!this.currentDriver) {
99
- throw new CacheDriverNotInitializedError();
100
- }
101
- }
102
- /**
103
- * {@inheritdoc}
104
- */
105
- async get(key) {
106
- this.ensureDriverInitialized();
107
- return this.currentDriver.get(key);
108
- }
109
- /**
110
- * Set a value in the cache
111
- *
112
- * @param key The cache key, could be an object or string
113
- * @param value The value to be stored in the cache
114
- * @param ttl The time to live in seconds
115
- */
116
- async set(key, value, ttl) {
117
- this.ensureDriverInitialized();
118
- return this.currentDriver.set(key, value, ttl);
119
- }
120
- /**
121
- * {@inheritdoc}
122
- */
123
- async remove(key) {
124
- this.ensureDriverInitialized();
125
- return this.currentDriver.remove(key);
126
- }
127
- /**
128
- * {@inheritdoc}
129
- */
130
- async removeNamespace(namespace) {
131
- this.ensureDriverInitialized();
132
- return this.currentDriver.removeNamespace(namespace);
133
- }
134
- /**
135
- * {@inheritdoc}
136
- */
137
- async flush() {
138
- this.ensureDriverInitialized();
139
- return this.currentDriver.flush();
140
- }
141
- /**
142
- * {@inheritdoc}
143
- */
144
- async connect() {
145
- this.ensureDriverInitialized();
146
- return this.currentDriver.connect();
147
- }
148
- /**
149
- * {@inheritdoc}
150
- */
151
- parseKey(key) {
152
- this.ensureDriverInitialized();
153
- return this.currentDriver.parseKey(key);
154
- }
155
- /**
156
- * {@inheritdoc}
157
- */
158
- get options() {
159
- this.ensureDriverInitialized();
160
- return this.currentDriver.options;
161
- }
162
- /**
163
- * {@inheritdoc}
164
- */
165
- setOptions(options) {
166
- this.ensureDriverInitialized();
167
- return this.currentDriver.setOptions(options || {});
168
- }
169
- /**
170
- * Get an instance of the cache driver
171
- */
172
- async driver(driverName) {
173
- return this.loadedDrivers[driverName] || await this.load(driverName);
174
- }
175
- /**
176
- * Initialize the cache manager and pick the default driver
177
- */
178
- async init() {
179
- const defaultCacheDriverName = this.configurations.default;
180
- if (!defaultCacheDriverName) {
181
- return;
182
- }
183
- const driver = await this.driver(defaultCacheDriverName);
184
- await this.use(driver);
185
- }
186
- /**
187
- * Load the given cache driver name
188
- */
189
- async load(driver) {
190
- if (this.loadedDrivers[driver]) return this.loadedDrivers[driver];
191
- const Driver = this.configurations.drivers[driver];
192
- if (!Driver) {
193
- throw new CacheConfigurationError(
194
- `Cache driver ${driver} is not found, please declare it in the cache drivers in the configurations list.`
195
- );
196
- }
197
- const driverInstance = new Driver();
198
- driverInstance.setOptions(
199
- this.configurations.options[driver] || {}
200
- );
201
- await driverInstance.connect();
202
- this.attachGlobalListeners(driverInstance);
203
- this.loadedDrivers[driver] = driverInstance;
204
- return driverInstance;
205
- }
206
- /**
207
- * Register and bind a driver
208
- */
209
- registerDriver(driverName, driverClass) {
210
- this.configurations.drivers[driverName] = driverClass;
211
- }
212
- /**
213
- * Disconnect the cache manager
214
- */
215
- async disconnect() {
216
- if (this.currentDriver) {
217
- await this.currentDriver.disconnect();
218
- }
219
- }
220
- /**
221
- * {@inheritdoc}
222
- */
223
- async has(key) {
224
- this.ensureDriverInitialized();
225
- return this.currentDriver.has(key);
226
- }
227
- /**
228
- * {@inheritdoc}
229
- */
230
- async remember(key, ttl, callback) {
231
- this.ensureDriverInitialized();
232
- return this.currentDriver.remember(key, ttl, callback);
233
- }
234
- /**
235
- * {@inheritdoc}
236
- */
237
- async pull(key) {
238
- this.ensureDriverInitialized();
239
- return this.currentDriver.pull(key);
240
- }
241
- /**
242
- * {@inheritdoc}
243
- */
244
- async forever(key, value) {
245
- this.ensureDriverInitialized();
246
- return this.currentDriver.forever(key, value);
247
- }
248
- /**
249
- * {@inheritdoc}
250
- */
251
- async increment(key, value) {
252
- this.ensureDriverInitialized();
253
- return this.currentDriver.increment(key, value);
254
- }
255
- /**
256
- * {@inheritdoc}
257
- */
258
- async decrement(key, value) {
259
- this.ensureDriverInitialized();
260
- return this.currentDriver.decrement(key, value);
261
- }
262
- /**
263
- * {@inheritdoc}
264
- */
265
- async many(keys) {
266
- this.ensureDriverInitialized();
267
- return this.currentDriver.many(keys);
268
- }
269
- /**
270
- * {@inheritdoc}
271
- */
272
- async setMany(items, ttl) {
273
- this.ensureDriverInitialized();
274
- return this.currentDriver.setMany(items, ttl);
275
- }
276
- /**
277
- * Register a global event listener (applies to all drivers)
278
- */
279
- on(event, handler) {
280
- if (!this.globalEventListeners.has(event)) {
281
- this.globalEventListeners.set(event, /* @__PURE__ */ new Set());
282
- }
283
- this.globalEventListeners.get(event).add(handler);
284
- if (this.currentDriver) {
285
- this.currentDriver.on(event, handler);
286
- }
287
- for (const driver of Object.values(this.loadedDrivers)) {
288
- driver.on(event, handler);
289
- }
290
- return this;
291
- }
292
- /**
293
- * Remove a global event listener
294
- */
295
- off(event, handler) {
296
- const handlers = this.globalEventListeners.get(event);
297
- if (handlers) {
298
- handlers.delete(handler);
299
- }
300
- if (this.currentDriver) {
301
- this.currentDriver.off(event, handler);
302
- }
303
- for (const driver of Object.values(this.loadedDrivers)) {
304
- driver.off(event, handler);
305
- }
306
- return this;
307
- }
308
- /**
309
- * Register a one-time global event listener
310
- */
311
- once(event, handler) {
312
- const onceHandler = async (data) => {
313
- await handler(data);
314
- this.off(event, onceHandler);
315
- };
316
- return this.on(event, onceHandler);
317
- }
318
- /**
319
- * Attach global listeners to a driver
320
- */
321
- attachGlobalListeners(driver) {
322
- for (const [event, handlers] of this.globalEventListeners) {
323
- for (const handler of handlers) {
324
- driver.on(event, handler);
325
- }
326
- }
327
- }
328
- /**
329
- * Set if not exists (atomic operation)
330
- * Returns true if key was set, false if key already existed
331
- * Note: Only supported by drivers that implement setNX (e.g., Redis)
332
- */
333
- async setNX(key, value, ttl) {
334
- this.ensureDriverInitialized();
335
- if (!this.currentDriver.setNX) {
336
- throw new Error(
337
- `setNX is not supported by the current cache driver: ${this.currentDriver.name}`
338
- );
339
- }
340
- return this.currentDriver.setNX(key, value, ttl);
341
- }
342
- /**
343
- * Create a tagged cache instance for the given tags
344
- */
345
- tags(tags) {
346
- this.ensureDriverInitialized();
347
- return this.currentDriver.tags(tags);
348
- }
349
- };
350
- var cache = new CacheManager();
351
-
352
- // ../../warlock.js/cache/src/tagged-cache.ts
353
- var TaggedCache = class {
354
- /**
355
- * The tags associated with this tagged cache instance
356
- */
357
- cacheTags;
358
- /**
359
- * The underlying cache driver
360
- */
361
- driver;
362
- /**
363
- * Constructor
364
- */
365
- constructor(tags, driver) {
366
- this.cacheTags = tags;
367
- this.driver = driver;
368
- }
369
- /**
370
- * Get the tag key prefix for storing tag-key relationships
371
- */
372
- tagKey(tag) {
373
- return `cache:tags:${tag}`;
374
- }
375
- /**
376
- * Store tag-key relationship
377
- */
378
- async storeTaggedKey(key) {
379
- for (const tag of this.cacheTags) {
380
- const tagKey = this.tagKey(tag);
381
- const keys = await this.driver.get(tagKey) || [];
382
- if (!keys.includes(key)) {
383
- keys.push(key);
384
- await this.driver.set(tagKey, keys, Infinity);
385
- }
386
- }
387
- }
388
- /**
389
- * Get all keys associated with tags
390
- */
391
- async getTaggedKeys() {
392
- const allKeys = /* @__PURE__ */ new Set();
393
- for (const tag of this.cacheTags) {
394
- const tagKey = this.tagKey(tag);
395
- const keys = await this.driver.get(tagKey) || [];
396
- for (const key of keys) {
397
- allKeys.add(key);
398
- }
399
- }
400
- return allKeys;
401
- }
402
- /**
403
- * {@inheritdoc}
404
- */
405
- async set(key, value, ttl) {
406
- const parsedKey = this.driver.parseKey(key);
407
- await this.driver.set(key, value, ttl);
408
- await this.storeTaggedKey(parsedKey);
409
- return value;
410
- }
411
- /**
412
- * {@inheritdoc}
413
- */
414
- async get(key) {
415
- return this.driver.get(key);
416
- }
417
- /**
418
- * {@inheritdoc}
419
- */
420
- async remove(key) {
421
- const parsedKey = this.driver.parseKey(key);
422
- await this.driver.remove(key);
423
- for (const tag of this.cacheTags) {
424
- const tagKey = this.tagKey(tag);
425
- const keys = await this.driver.get(tagKey) || [];
426
- const updatedKeys = keys.filter((k) => k !== parsedKey);
427
- await this.driver.set(tagKey, updatedKeys, Infinity);
428
- }
429
- }
430
- /**
431
- * Invalidate (clear) all keys associated with the current tags
432
- */
433
- async invalidate() {
434
- const keysToRemove = await this.getTaggedKeys();
435
- for (const key of keysToRemove) {
436
- await this.driver.remove(key);
437
- }
438
- for (const tag of this.cacheTags) {
439
- await this.driver.remove(this.tagKey(tag));
440
- }
441
- }
442
- /**
443
- * Flush all keys associated with the current tags
444
- * @deprecated Use invalidate() instead for better semantics
445
- */
446
- async flush() {
447
- return this.invalidate();
448
- }
449
- /**
450
- * {@inheritdoc}
451
- */
452
- async has(key) {
453
- return this.driver.has(key);
454
- }
455
- /**
456
- * {@inheritdoc}
457
- */
458
- async remember(key, ttl, callback) {
459
- const value = await this.get(key);
460
- if (value !== null) {
461
- return value;
462
- }
463
- const result = await callback();
464
- await this.set(key, result, ttl);
465
- return result;
466
- }
467
- /**
468
- * {@inheritdoc}
469
- */
470
- async pull(key) {
471
- const value = await this.get(key);
472
- if (value !== null) {
473
- await this.remove(key);
474
- }
475
- return value;
476
- }
477
- /**
478
- * {@inheritdoc}
479
- */
480
- async forever(key, value) {
481
- return this.set(key, value, Infinity);
482
- }
483
- /**
484
- * {@inheritdoc}
485
- */
486
- async increment(key, value = 1) {
487
- const current = await this.get(key) || 0;
488
- if (typeof current !== "number") {
489
- throw new Error(
490
- `Cannot increment non-numeric value for key: ${this.driver.parseKey(key)}`
491
- );
492
- }
493
- const newValue = current + value;
494
- await this.set(key, newValue);
495
- return newValue;
496
- }
497
- /**
498
- * {@inheritdoc}
499
- */
500
- async decrement(key, value = 1) {
501
- return this.increment(key, -value);
502
- }
503
- };
504
- function parseCacheKey(key, options = {}) {
505
- if (typeof key === "object") {
506
- key = JSON.stringify(key);
507
- }
508
- key = key.replace(/[{}"[\]]/g, "").replaceAll(/[:,]/g, ".");
509
- const cachePrefix = typeof options.globalPrefix === "function" ? options.globalPrefix() : options.globalPrefix;
510
- return reinforcements.rtrim(String(cachePrefix ? reinforcements.rtrim(cachePrefix, ".") + "." + key : key), ".");
511
- }
512
- var CACHE_FOR = /* @__PURE__ */ ((CACHE_FOR2) => {
513
- CACHE_FOR2[CACHE_FOR2["HALF_HOUR"] = 1800] = "HALF_HOUR";
514
- CACHE_FOR2[CACHE_FOR2["ONE_HOUR"] = 3600] = "ONE_HOUR";
515
- CACHE_FOR2[CACHE_FOR2["HALF_DAY"] = 43200] = "HALF_DAY";
516
- CACHE_FOR2[CACHE_FOR2["ONE_DAY"] = 86400] = "ONE_DAY";
517
- CACHE_FOR2[CACHE_FOR2["ONE_WEEK"] = 604800] = "ONE_WEEK";
518
- CACHE_FOR2[CACHE_FOR2["HALF_MONTH"] = 1296e3] = "HALF_MONTH";
519
- CACHE_FOR2[CACHE_FOR2["ONE_MONTH"] = 2592e3] = "ONE_MONTH";
520
- CACHE_FOR2[CACHE_FOR2["TWO_MONTHS"] = 5184e3] = "TWO_MONTHS";
521
- CACHE_FOR2[CACHE_FOR2["SIX_MONTHS"] = 15768e3] = "SIX_MONTHS";
522
- CACHE_FOR2[CACHE_FOR2["ONE_YEAR"] = 31536e3] = "ONE_YEAR";
523
- return CACHE_FOR2;
524
- })(CACHE_FOR || {});
525
-
526
- // ../../warlock.js/cache/src/drivers/base-cache-driver.ts
527
- var messages = {
528
- clearing: "Clearing namespace",
529
- cleared: "Namespace cleared",
530
- fetching: "Fetching key",
531
- fetched: "Key fetched",
532
- caching: "Caching key",
533
- cached: "Key cached",
534
- flushing: "Flushing cache",
535
- flushed: "Cache flushed",
536
- removing: "Removing key",
537
- removed: "Key removed",
538
- expired: "Key expired",
539
- notFound: "Key not found",
540
- connecting: "Connecting to the cache engine.",
541
- connected: "Connected to the cache engine.",
542
- disconnecting: "Disconnecting from the cache engine.",
543
- disconnected: "Disconnected from the cache engine.",
544
- error: "Error occurred"
545
- };
546
- var BaseCacheDriver = class {
547
- /**
548
- * CLient driver
549
- */
550
- clientDriver;
551
- /**
552
- * {@inheritdoc}
553
- */
554
- get client() {
555
- return this.clientDriver || this;
556
- }
557
- /**
558
- * Set client driver
559
- */
560
- set client(client) {
561
- this.clientDriver = client;
562
- }
563
- /**
564
- * Options list
565
- */
566
- options;
567
- /**
568
- * Event listeners storage
569
- */
570
- eventListeners = /* @__PURE__ */ new Map();
571
- /**
572
- * {@inheritdoc}
573
- */
574
- parseKey(key) {
575
- return parseCacheKey(key, this.options);
576
- }
577
- /**
578
- * {@inheritdoc}
579
- */
580
- setOptions(options) {
581
- this.options = options || {};
582
- return this;
583
- }
584
- /**
585
- * Register an event listener
586
- */
587
- on(event, handler) {
588
- if (!this.eventListeners.has(event)) {
589
- this.eventListeners.set(event, /* @__PURE__ */ new Set());
590
- }
591
- this.eventListeners.get(event).add(handler);
592
- return this;
593
- }
594
- /**
595
- * Remove an event listener
596
- */
597
- off(event, handler) {
598
- const handlers = this.eventListeners.get(event);
599
- if (handlers) {
600
- handlers.delete(handler);
601
- }
602
- return this;
603
- }
604
- /**
605
- * Register a one-time event listener
606
- */
607
- once(event, handler) {
608
- const onceHandler = async (data) => {
609
- await handler(data);
610
- this.off(event, onceHandler);
611
- };
612
- return this.on(event, onceHandler);
613
- }
614
- /**
615
- * Emit an event to all registered listeners
616
- */
617
- async emit(event, data = {}) {
618
- const handlers = this.eventListeners.get(event);
619
- if (!handlers || handlers.size === 0) return;
620
- const eventData = {
621
- driver: this.name,
622
- ...data
623
- };
624
- const promises = [];
625
- for (const handler of handlers) {
626
- try {
627
- const result = handler(eventData);
628
- if (result instanceof Promise) {
629
- promises.push(result);
630
- }
631
- } catch (error) {
632
- this.logError(`Error in event handler for '${event}'`, error);
633
- }
634
- }
635
- if (promises.length > 0) {
636
- await Promise.allSettled(promises);
637
- }
638
- }
639
- /**
640
- * {@inheritdoc}
641
- */
642
- async has(key) {
643
- const value = await this.get(key);
644
- return value !== null;
645
- }
646
- /**
647
- * Lock storage for preventing cache stampede
648
- */
649
- locks = /* @__PURE__ */ new Map();
650
- /**
651
- * {@inheritdoc}
652
- */
653
- async remember(key, ttl, callback) {
654
- const parsedKey = this.parseKey(key);
655
- const cachedValue = await this.get(key);
656
- if (cachedValue !== null) {
657
- return cachedValue;
658
- }
659
- const existingLock = this.locks.get(parsedKey);
660
- if (existingLock) {
661
- return existingLock;
662
- }
663
- const promise = callback().then(async (result) => {
664
- await this.set(key, result, ttl);
665
- this.locks.delete(parsedKey);
666
- return result;
667
- }).catch((err) => {
668
- this.locks.delete(parsedKey);
669
- throw err;
670
- });
671
- this.locks.set(parsedKey, promise);
672
- return promise;
673
- }
674
- /**
675
- * {@inheritdoc}
676
- */
677
- async pull(key) {
678
- const value = await this.get(key);
679
- if (value !== null) {
680
- await this.remove(key);
681
- }
682
- return value;
683
- }
684
- /**
685
- * {@inheritdoc}
686
- */
687
- async forever(key, value) {
688
- return this.set(key, value, Infinity);
689
- }
690
- /**
691
- * {@inheritdoc}
692
- */
693
- async increment(key, value = 1) {
694
- const current = await this.get(key) || 0;
695
- if (typeof current !== "number") {
696
- throw new Error(`Cannot increment non-numeric value for key: ${this.parseKey(key)}`);
697
- }
698
- const newValue = current + value;
699
- await this.set(key, newValue);
700
- return newValue;
701
- }
702
- /**
703
- * {@inheritdoc}
704
- */
705
- async decrement(key, value = 1) {
706
- return this.increment(key, -value);
707
- }
708
- /**
709
- * {@inheritdoc}
710
- */
711
- async many(keys) {
712
- return Promise.all(keys.map((key) => this.get(key)));
713
- }
714
- /**
715
- * {@inheritdoc}
716
- */
717
- async setMany(items, ttl) {
718
- await Promise.all(Object.entries(items).map(([key, value]) => this.set(key, value, ttl)));
719
- }
720
- /**
721
- * Log the operation
722
- */
723
- log(operation, key) {
724
- if (key) {
725
- key = key.replaceAll("/", ".");
726
- }
727
- if (operation == "notFound" || operation == "expired") {
728
- return logger.log.warn(
729
- "cache:" + this.name,
730
- operation,
731
- (key ? key + " " : "") + messages[operation]
732
- );
733
- }
734
- if (operation.endsWith("ed")) {
735
- return logger.log.success(
736
- "cache:" + this.name,
737
- operation,
738
- (key ? key + " " : "") + messages[operation]
739
- );
740
- }
741
- logger.log.info("cache:" + this.name, operation, (key ? key + " " : "") + messages[operation]);
742
- }
743
- /**
744
- * Log error message
745
- */
746
- logError(message, error) {
747
- logger.log.error("cache:" + this.name, "error", message);
748
- if (error) {
749
- console.log(error);
750
- }
751
- }
752
- /**
753
- * Get time to live value
754
- */
755
- get ttl() {
756
- return this.options.ttl !== void 0 ? this.options.ttl : Infinity;
757
- }
758
- /**
759
- * Get time to live value in milliseconds
760
- */
761
- getExpiresAt(ttl = this.ttl) {
762
- if (ttl) {
763
- return (/* @__PURE__ */ new Date()).getTime() + ttl * 1e3;
764
- }
765
- }
766
- /**
767
- * Prepare data for storage
768
- */
769
- prepareDataForStorage(data, ttl) {
770
- const preparedData = {
771
- data
772
- };
773
- if (ttl) {
774
- preparedData.ttl = ttl;
775
- preparedData.expiresAt = this.getExpiresAt(ttl);
776
- }
777
- return preparedData;
778
- }
779
- /**
780
- * Parse fetched data from cache
781
- */
782
- async parseCachedData(key, data) {
783
- this.log("fetched", key);
784
- if (data.expiresAt && data.expiresAt < Date.now()) {
785
- this.remove(key);
786
- return null;
787
- }
788
- const value = data.data;
789
- if (value === null || value === void 0) {
790
- return value;
791
- }
792
- const type = typeof value;
793
- if (type === "string" || type === "number" || type === "boolean") {
794
- return value;
795
- }
796
- try {
797
- return structuredClone(value);
798
- } catch (error) {
799
- console.log(value);
800
- this.logError(
801
- `Failed to clone cached value for ${key}, typeof value: ${typeof value}`,
802
- error
803
- );
804
- throw error;
805
- }
806
- }
807
- /**
808
- * {@inheritdoc}
809
- */
810
- async connect() {
811
- this.log("connecting");
812
- this.log("connected");
813
- await this.emit("connected");
814
- }
815
- /**
816
- * {@inheritdoc}
817
- */
818
- async disconnect() {
819
- this.log("disconnected");
820
- await this.emit("disconnected");
821
- }
822
- /**
823
- * Create a tagged cache instance for the given tags
824
- */
825
- tags(tags) {
826
- return new TaggedCache(tags, this);
827
- }
828
- };
829
- var FileCacheDriver = class extends BaseCacheDriver {
830
- /**
831
- * {@inheritdoc}
832
- */
833
- name = "file";
834
- /**
835
- * {@inheritdoc}
836
- */
837
- setOptions(options) {
838
- if (!options.directory) {
839
- throw new CacheConfigurationError(
840
- "File driver requires 'directory' option to be configured."
841
- );
842
- }
843
- return super.setOptions(options);
844
- }
845
- /**
846
- * Get the cache directory
847
- */
848
- get directory() {
849
- const directory = this.options.directory;
850
- if (typeof directory === "function") {
851
- return directory();
852
- }
853
- throw new CacheConfigurationError(
854
- "Cache directory is not defined, please define it in the file driver options"
855
- );
856
- }
857
- /**
858
- * Get file name
859
- */
860
- get fileName() {
861
- const fileName = this.options.fileName;
862
- if (typeof fileName === "function") {
863
- return fileName();
864
- }
865
- return "cache.json";
866
- }
867
- /**
868
- * {@inheritdoc}
869
- */
870
- async removeNamespace(namespace) {
871
- this.log("clearing", namespace);
872
- try {
873
- await fs.removeDirectoryAsync(path__default.default.resolve(this.directory, namespace));
874
- this.log("cleared", namespace);
875
- } catch (error) {
876
- }
877
- return this;
878
- }
879
- /**
880
- * {@inheritdoc}
881
- */
882
- async set(key, value, ttl) {
883
- key = this.parseKey(key);
884
- this.log("caching", key);
885
- const data = this.prepareDataForStorage(value, ttl);
886
- const fileDirectory = path__default.default.resolve(this.directory, key);
887
- await fs.ensureDirectoryAsync(fileDirectory);
888
- await fs.putJsonFileAsync(path__default.default.resolve(fileDirectory, this.fileName), data);
889
- this.log("cached", key);
890
- await this.emit("set", { key, value, ttl });
891
- return this;
892
- }
893
- /**
894
- * {@inheritdoc}
895
- */
896
- async get(key) {
897
- const parsedKey = this.parseKey(key);
898
- this.log("fetching", parsedKey);
899
- const fileDirectory = path__default.default.resolve(this.directory, parsedKey);
900
- try {
901
- const value = await fs.getJsonFileAsync(
902
- path__default.default.resolve(fileDirectory, this.fileName)
903
- );
904
- const result = await this.parseCachedData(parsedKey, value);
905
- if (result === null) {
906
- await this.emit("miss", { key: parsedKey });
907
- } else {
908
- await this.emit("hit", { key: parsedKey, value: result });
909
- }
910
- return result;
911
- } catch (error) {
912
- this.log("notFound", parsedKey);
913
- await this.emit("miss", { key: parsedKey });
914
- this.remove(key);
915
- return null;
916
- }
917
- }
918
- /**
919
- * {@inheritdoc}
920
- */
921
- async remove(key) {
922
- const parsedKey = this.parseKey(key);
923
- this.log("removing", parsedKey);
924
- const fileDirectory = path__default.default.resolve(this.directory, parsedKey);
925
- try {
926
- await fs.removeDirectoryAsync(fileDirectory);
927
- this.log("removed", parsedKey);
928
- await this.emit("removed", { key: parsedKey });
929
- } catch (error) {
930
- }
931
- }
932
- /**
933
- * {@inheritdoc}
934
- */
935
- async flush() {
936
- this.log("flushing");
937
- if (this.options.globalPrefix) {
938
- await this.removeNamespace("");
939
- } else {
940
- await fs.removeDirectoryAsync(this.directory);
941
- }
942
- this.log("flushed");
943
- await this.emit("flushed");
944
- }
945
- /**
946
- * {@inheritdoc}
947
- */
948
- async connect() {
949
- this.log("connecting");
950
- await fs.ensureDirectoryAsync(this.directory);
951
- this.log("connected");
952
- await this.emit("connected");
953
- }
954
- };
955
-
956
- // ../../warlock.js/cache/src/drivers/lru-memory-cache-driver.ts
957
- var CacheNode = class {
958
- constructor(key, value, ttl) {
959
- this.key = key;
960
- this.value = value;
961
- if (ttl && ttl !== Infinity) {
962
- this.expiresAt = Date.now() + ttl * 1e3;
963
- }
964
- }
965
- next = null;
966
- prev = null;
967
- expiresAt;
968
- get isExpired() {
969
- return this.expiresAt !== void 0 && this.expiresAt < Date.now();
970
- }
971
- };
972
- var LRUMemoryCacheDriver = class extends BaseCacheDriver {
973
- /**
974
- * {@inheritdoc}
975
- */
976
- name = "lru";
977
- /**
978
- * Cache map
979
- */
980
- cache = /* @__PURE__ */ new Map();
981
- /**
982
- * Head of the cache
983
- */
984
- head = new CacheNode("", null);
985
- /**
986
- * Tail of the cache
987
- */
988
- tail = new CacheNode("", null);
989
- /**
990
- * Cleanup interval reference
991
- */
992
- cleanupInterval;
993
- /**
994
- * {@inheritdoc}
995
- */
996
- constructor() {
997
- super();
998
- this.init();
999
- this.startCleanup();
1000
- }
1001
- /**
1002
- * Initialize the cache
1003
- */
1004
- init() {
1005
- this.head.next = this.tail;
1006
- this.tail.prev = this.head;
1007
- }
1008
- /**
1009
- * Start the cleanup process for expired items
1010
- */
1011
- startCleanup() {
1012
- if (this.cleanupInterval) {
1013
- clearInterval(this.cleanupInterval);
1014
- }
1015
- this.cleanupInterval = setInterval(async () => {
1016
- const now = Date.now();
1017
- const expiredKeys = [];
1018
- for (const [key, node] of this.cache) {
1019
- if (node.expiresAt && node.expiresAt <= now) {
1020
- expiredKeys.push(key);
1021
- }
1022
- }
1023
- for (const key of expiredKeys) {
1024
- const node = this.cache.get(key);
1025
- if (node) {
1026
- this.removeNode(node);
1027
- this.cache.delete(key);
1028
- this.log("expired", key);
1029
- await this.emit("expired", { key });
1030
- }
1031
- }
1032
- }, 1e3);
1033
- this.cleanupInterval.unref();
1034
- }
1035
- /**
1036
- * {@inheritdoc}
1037
- */
1038
- async removeNamespace(_namespace) {
1039
- throw new Error("Namespace is not supported in LRU cache driver.");
1040
- }
1041
- /**
1042
- * {@inheritdoc}
1043
- */
1044
- async set(key, value, ttl) {
1045
- key = this.parseKey(key);
1046
- this.log("caching", key);
1047
- if (ttl === void 0) {
1048
- ttl = this.ttl;
1049
- }
1050
- const existingNode = this.cache.get(key);
1051
- if (existingNode) {
1052
- existingNode.value = value;
1053
- if (ttl && ttl !== Infinity) {
1054
- existingNode.expiresAt = Date.now() + ttl * 1e3;
1055
- } else {
1056
- existingNode.expiresAt = void 0;
1057
- }
1058
- this.moveHead(existingNode);
1059
- } else {
1060
- const newNode = new CacheNode(key, value, ttl);
1061
- this.cache.set(key, newNode);
1062
- this.addNode(newNode);
1063
- if (this.cache.size > this.capacity) {
1064
- this.removeTail();
1065
- }
1066
- }
1067
- this.log("cached", key);
1068
- await this.emit("set", { key, value, ttl });
1069
- return this;
1070
- }
1071
- /**
1072
- * Move the node to the head
1073
- */
1074
- moveHead(node) {
1075
- this.removeNode(node);
1076
- this.addNode(node);
1077
- }
1078
- /**
1079
- * Remove the node from the cache
1080
- */
1081
- removeNode(node) {
1082
- node.prev.next = node.next;
1083
- node.next.prev = node.prev;
1084
- }
1085
- /**
1086
- * Add the node to the head
1087
- */
1088
- addNode(node) {
1089
- node.next = this.head.next;
1090
- node.prev = this.head;
1091
- this.head.next.prev = node;
1092
- this.head.next = node;
1093
- }
1094
- /**
1095
- * Remove the tail node
1096
- */
1097
- removeTail() {
1098
- const node = this.tail.prev;
1099
- this.removeNode(node);
1100
- this.cache.delete(node.key);
1101
- }
1102
- /**
1103
- * {@inheritdoc}
1104
- */
1105
- async get(key) {
1106
- const parsedKey = this.parseKey(key);
1107
- this.log("fetching", parsedKey);
1108
- const node = this.cache.get(parsedKey);
1109
- if (!node) {
1110
- this.log("notFound", parsedKey);
1111
- await this.emit("miss", { key: parsedKey });
1112
- return null;
1113
- }
1114
- if (node.isExpired) {
1115
- this.removeNode(node);
1116
- this.cache.delete(parsedKey);
1117
- this.log("expired", parsedKey);
1118
- await this.emit("expired", { key: parsedKey });
1119
- await this.emit("miss", { key: parsedKey });
1120
- return null;
1121
- }
1122
- this.moveHead(node);
1123
- this.log("fetched", parsedKey);
1124
- const value = node.value;
1125
- if (value === null || value === void 0) {
1126
- return value;
1127
- }
1128
- const type = typeof value;
1129
- if (type === "string" || type === "number" || type === "boolean") {
1130
- await this.emit("hit", { key: parsedKey, value });
1131
- return value;
1132
- }
1133
- try {
1134
- const clonedValue = structuredClone(value);
1135
- await this.emit("hit", { key: parsedKey, value: clonedValue });
1136
- return clonedValue;
1137
- } catch (error) {
1138
- this.logError(`Failed to clone cached value for ${parsedKey}`, error);
1139
- throw error;
1140
- }
1141
- }
1142
- /**
1143
- * {@inheritdoc}
1144
- */
1145
- async remove(key) {
1146
- const parsedKey = this.parseKey(key);
1147
- this.log("removing", parsedKey);
1148
- const node = this.cache.get(parsedKey);
1149
- if (node) {
1150
- this.removeNode(node);
1151
- this.cache.delete(parsedKey);
1152
- }
1153
- this.log("removed", parsedKey);
1154
- await this.emit("removed", { key: parsedKey });
1155
- }
1156
- /**
1157
- * {@inheritdoc}
1158
- */
1159
- async flush() {
1160
- this.log("flushing");
1161
- this.cache.clear();
1162
- this.init();
1163
- this.log("flushed");
1164
- await this.emit("flushed");
1165
- }
1166
- /**
1167
- * Get lru capacity
1168
- */
1169
- get capacity() {
1170
- return this.options.capacity || 1e3;
1171
- }
1172
- /**
1173
- * {@inheritdoc}
1174
- */
1175
- async disconnect() {
1176
- if (this.cleanupInterval) {
1177
- clearInterval(this.cleanupInterval);
1178
- this.cleanupInterval = void 0;
1179
- }
1180
- await super.disconnect();
1181
- }
1182
- };
1183
- var MemoryCacheDriver = class extends BaseCacheDriver {
1184
- /**
1185
- * {@inheritdoc}
1186
- */
1187
- name = "memory";
1188
- /**
1189
- * Cached data
1190
- */
1191
- data = {};
1192
- /**
1193
- * List of data that will be cleared from cache
1194
- */
1195
- temporaryData = {};
1196
- /**
1197
- * Cleanup interval reference
1198
- */
1199
- cleanupInterval;
1200
- /**
1201
- * Access order tracking for LRU eviction (when maxSize is set)
1202
- */
1203
- accessOrder = [];
1204
- /**
1205
- * {@inheritdoc}
1206
- */
1207
- constructor() {
1208
- super();
1209
- this.startCleanup();
1210
- }
1211
- /**
1212
- * Start the cleanup process whenever a data that has a cache key is set
1213
- */
1214
- startCleanup() {
1215
- if (this.cleanupInterval) {
1216
- clearInterval(this.cleanupInterval);
1217
- }
1218
- this.cleanupInterval = setInterval(async () => {
1219
- const now = Date.now();
1220
- for (const key in this.temporaryData) {
1221
- if (this.temporaryData[key].expiresAt <= now) {
1222
- await this.remove(this.temporaryData[key].key);
1223
- delete this.temporaryData[key];
1224
- this.log("expired", key);
1225
- await this.emit("expired", { key });
1226
- }
1227
- }
1228
- }, 1e3);
1229
- this.cleanupInterval.unref();
1230
- }
1231
- /**
1232
- * {@inheritdoc}
1233
- */
1234
- async removeNamespace(namespace) {
1235
- this.log("clearing", namespace);
1236
- namespace = this.parseKey(namespace);
1237
- reinforcements.unset(this.data, [namespace]);
1238
- this.log("cleared", namespace);
1239
- return this;
1240
- }
1241
- /**
1242
- * {@inheritdoc}
1243
- */
1244
- async set(key, value, ttl) {
1245
- const parsedKey = this.parseKey(key);
1246
- this.log("caching", parsedKey);
1247
- if (ttl === void 0) {
1248
- ttl = this.ttl;
1249
- }
1250
- const data = this.prepareDataForStorage(value, ttl);
1251
- if (ttl) {
1252
- this.setTemporaryData(key, parsedKey, ttl);
1253
- }
1254
- const existingData = reinforcements.get(this.data, parsedKey);
1255
- const isNewKey = !existingData;
1256
- reinforcements.set(this.data, parsedKey, data);
1257
- this.trackAccess(parsedKey);
1258
- if (isNewKey && this.options.maxSize) {
1259
- await this.enforceMaxSize();
1260
- }
1261
- this.log("cached", parsedKey);
1262
- await this.emit("set", { key: parsedKey, value, ttl });
1263
- return this;
1264
- }
1265
- /**
1266
- * {@inheritdoc}
1267
- */
1268
- async get(key) {
1269
- const parsedKey = this.parseKey(key);
1270
- this.log("fetching", parsedKey);
1271
- const value = reinforcements.get(this.data, parsedKey);
1272
- if (!value) {
1273
- this.log("notFound", parsedKey);
1274
- await this.emit("miss", { key: parsedKey });
1275
- return null;
1276
- }
1277
- const result = await this.parseCachedData(parsedKey, value);
1278
- if (result === null) {
1279
- await this.emit("miss", { key: parsedKey });
1280
- } else {
1281
- this.trackAccess(parsedKey);
1282
- await this.emit("hit", { key: parsedKey, value: result });
1283
- }
1284
- return result;
1285
- }
1286
- /**
1287
- * {@inheritdoc}
1288
- */
1289
- async remove(key) {
1290
- const parsedKey = this.parseKey(key);
1291
- this.log("removing", parsedKey);
1292
- reinforcements.unset(this.data, [parsedKey]);
1293
- delete this.temporaryData[parsedKey];
1294
- this.removeFromAccessOrder(parsedKey);
1295
- this.log("removed", parsedKey);
1296
- await this.emit("removed", { key: parsedKey });
1297
- }
1298
- /**
1299
- * {@inheritdoc}
1300
- */
1301
- async flush() {
1302
- this.log("flushing");
1303
- if (this.options.globalPrefix) {
1304
- this.removeNamespace("");
1305
- } else {
1306
- this.data = {};
1307
- this.accessOrder = [];
1308
- }
1309
- this.log("flushed");
1310
- await this.emit("flushed");
1311
- }
1312
- /**
1313
- * Set the temporary data
1314
- */
1315
- setTemporaryData(key, parsedKey, ttl) {
1316
- this.temporaryData[parsedKey] = {
1317
- key: JSON.stringify(key),
1318
- expiresAt: Date.now() + ttl * 1e3
1319
- };
1320
- }
1321
- /**
1322
- * Track access for LRU eviction
1323
- */
1324
- trackAccess(key) {
1325
- if (!this.options.maxSize) return;
1326
- const index = this.accessOrder.indexOf(key);
1327
- if (index > -1) {
1328
- this.accessOrder.splice(index, 1);
1329
- }
1330
- this.accessOrder.push(key);
1331
- }
1332
- /**
1333
- * Remove key from access order tracking
1334
- */
1335
- removeFromAccessOrder(key) {
1336
- const index = this.accessOrder.indexOf(key);
1337
- if (index > -1) {
1338
- this.accessOrder.splice(index, 1);
1339
- }
1340
- }
1341
- /**
1342
- * Enforce max size by evicting least recently used items
1343
- */
1344
- async enforceMaxSize() {
1345
- if (!this.options.maxSize) return;
1346
- const cacheSize = this.getCacheSize();
1347
- while (cacheSize > this.options.maxSize && this.accessOrder.length > 0) {
1348
- const lruKey = this.accessOrder.shift();
1349
- if (lruKey) {
1350
- this.log("removing", lruKey);
1351
- reinforcements.unset(this.data, [lruKey]);
1352
- delete this.temporaryData[lruKey];
1353
- this.log("removed", lruKey);
1354
- }
1355
- }
1356
- }
1357
- /**
1358
- * Get current cache size (number of cached items)
1359
- */
1360
- getCacheSize() {
1361
- return Object.keys(this.data).length;
1362
- }
1363
- /**
1364
- * {@inheritdoc}
1365
- */
1366
- async disconnect() {
1367
- if (this.cleanupInterval) {
1368
- clearInterval(this.cleanupInterval);
1369
- this.cleanupInterval = void 0;
1370
- }
1371
- await super.disconnect();
1372
- }
1373
- };
1374
- var MemoryExtendedCacheDriver = class extends MemoryCacheDriver {
1375
- /**
1376
- * {@inheritdoc}
1377
- */
1378
- name = "memoryExtended";
1379
- /**
1380
- * {@inheritdoc}
1381
- */
1382
- async get(key) {
1383
- const parsedKey = this.parseKey(key);
1384
- this.log("fetching", parsedKey);
1385
- const value = reinforcements.get(this.data, parsedKey);
1386
- if (!value) {
1387
- this.log("notFound", parsedKey);
1388
- return null;
1389
- }
1390
- const ttl = value.ttl || this.options.ttl;
1391
- if (ttl) {
1392
- this.setTemporaryData(key, parsedKey, ttl);
1393
- value.expiresAt = this.getExpiresAt(ttl);
1394
- }
1395
- return this.parseCachedData(parsedKey, value);
1396
- }
1397
- };
1398
- var NullCacheDriver = class extends BaseCacheDriver {
1399
- /**
1400
- * Options list
1401
- */
1402
- options = {};
1403
- /**
1404
- * {@inheritdoc}
1405
- */
1406
- name = "null";
1407
- /**
1408
- * Cached data
1409
- */
1410
- data = {};
1411
- /**
1412
- * {@inheritdoc}
1413
- */
1414
- get client() {
1415
- return this;
1416
- }
1417
- /**
1418
- * Constructor
1419
- */
1420
- constructor(options = {}) {
1421
- super();
1422
- this.setOptions(options);
1423
- }
1424
- /**
1425
- * {@inheritdoc}
1426
- */
1427
- setOptions(options) {
1428
- this.options = options;
1429
- return this;
1430
- }
1431
- /**
1432
- * {@inheritdoc}
1433
- */
1434
- parseKey(_key) {
1435
- return "";
1436
- }
1437
- /**
1438
- * {@inheritdoc}
1439
- */
1440
- async removeNamespace(namespace) {
1441
- logger.log.info("cache", "clearing namespace", namespace);
1442
- logger.log.success("cache", "namespace cleared", namespace);
1443
- return this;
1444
- }
1445
- /**
1446
- * {@inheritdoc}
1447
- */
1448
- async set(key, _value) {
1449
- logger.log.info("cache", "setting key", key);
1450
- logger.log.success("cache", "key set", key);
1451
- return this;
1452
- }
1453
- /**
1454
- * {@inheritdoc}
1455
- */
1456
- async get(key) {
1457
- logger.log.info("cache", "fetching", key);
1458
- logger.log.success("cache", "fetched", key);
1459
- return null;
1460
- }
1461
- /**
1462
- * {@inheritdoc}
1463
- */
1464
- async remove(key) {
1465
- logger.log.info("cache", "removing", key);
1466
- logger.log.success("cache", "removed", key);
1467
- }
1468
- /**
1469
- * {@inheritdoc}
1470
- */
1471
- async flush() {
1472
- logger.log.info("cache", "flushing", "all");
1473
- logger.log.success("cache", "flushed", "all");
1474
- }
1475
- /**
1476
- * {@inheritdoc}
1477
- */
1478
- async connect() {
1479
- logger.log.success("cache", "connected", "Connected to null cache driver");
1480
- }
1481
- };
1482
- var RedisCacheDriver = class extends BaseCacheDriver {
1483
- /**
1484
- * Cache driver name
1485
- */
1486
- name = "redis";
1487
- /**
1488
- * {@inheritdoc}
1489
- */
1490
- setOptions(options) {
1491
- if (!options.url && !options.host) {
1492
- throw new CacheConfigurationError(
1493
- "Redis driver requires either 'url' or 'host' option to be configured."
1494
- );
1495
- }
1496
- return super.setOptions(options);
1497
- }
1498
- /**
1499
- * {@inheritDoc}
1500
- */
1501
- async removeNamespace(namespace) {
1502
- namespace = this.parseKey(namespace);
1503
- this.log("clearing", namespace);
1504
- const keys = await this.client?.keys(`${namespace}*`);
1505
- if (!keys || keys.length === 0) {
1506
- this.log("notFound", namespace);
1507
- return;
1508
- }
1509
- await this.client?.del(keys);
1510
- this.log("cleared", namespace);
1511
- return keys;
1512
- }
1513
- /**
1514
- * {@inheritDoc}
1515
- */
1516
- async set(key, value, ttl) {
1517
- key = this.parseKey(key);
1518
- this.log("caching", key);
1519
- if (ttl === void 0) {
1520
- ttl = this.ttl;
1521
- }
1522
- if (ttl && ttl !== Infinity) {
1523
- await this.client?.set(key, JSON.stringify(value), { EX: ttl });
1524
- } else {
1525
- await this.client?.set(key, JSON.stringify(value));
1526
- }
1527
- this.log("cached", key);
1528
- await this.emit("set", { key, value, ttl });
1529
- return value;
1530
- }
1531
- /**
1532
- * {@inheritDoc}
1533
- */
1534
- async get(key) {
1535
- key = this.parseKey(key);
1536
- this.log("fetching", key);
1537
- const value = await this.client?.get(key);
1538
- if (!value) {
1539
- this.log("notFound", key);
1540
- await this.emit("miss", { key });
1541
- return null;
1542
- }
1543
- this.log("fetched", key);
1544
- const parsedValue = JSON.parse(value);
1545
- if (parsedValue === null || parsedValue === void 0) {
1546
- await this.emit("hit", { key, value: parsedValue });
1547
- return parsedValue;
1548
- }
1549
- const type = typeof parsedValue;
1550
- if (type === "string" || type === "number" || type === "boolean") {
1551
- await this.emit("hit", { key, value: parsedValue });
1552
- return parsedValue;
1553
- }
1554
- try {
1555
- const clonedValue = structuredClone(parsedValue);
1556
- await this.emit("hit", { key, value: clonedValue });
1557
- return clonedValue;
1558
- } catch (error) {
1559
- this.logError(`Failed to clone cached value for ${key}`, error);
1560
- throw error;
1561
- }
1562
- }
1563
- /**
1564
- * {@inheritDoc}
1565
- */
1566
- async remove(key) {
1567
- key = this.parseKey(key);
1568
- this.log("removing", key);
1569
- await this.client?.del(key);
1570
- this.log("removed", key);
1571
- await this.emit("removed", { key });
1572
- }
1573
- /**
1574
- * {@inheritDoc}
1575
- */
1576
- async flush() {
1577
- this.log("flushing");
1578
- if (this.options.globalPrefix) {
1579
- await this.removeNamespace("");
1580
- } else {
1581
- await this.client?.flushAll();
1582
- }
1583
- this.log("flushed");
1584
- await this.emit("flushed");
1585
- }
1586
- /**
1587
- * {@inheritDoc}
1588
- */
1589
- async connect() {
1590
- if (this.clientDriver) return;
1591
- const options = this.options;
1592
- if (options && !options.url && options.host) {
1593
- const auth = options.password || options.username ? `${options.username}:${options.password}@` : "";
1594
- if (!options.url) {
1595
- const host = options.host || "localhost";
1596
- const port = options.port || 6379;
1597
- options.url = `redis://${auth}${host}:${port}`;
1598
- }
1599
- }
1600
- const clientOptions = {
1601
- ...options,
1602
- ...this.options.clientOptions || {}
1603
- };
1604
- this.log("connecting");
1605
- const { createClient } = await import('redis');
1606
- this.client = createClient(clientOptions);
1607
- this.client.on("error", (error) => {
1608
- this.log("error", error.message);
1609
- });
1610
- try {
1611
- await this.client.connect();
1612
- this.log("connected");
1613
- await this.emit("connected");
1614
- } catch (error) {
1615
- logger.log.error("cache", "redis", error);
1616
- await this.emit("error", { error });
1617
- }
1618
- }
1619
- /**
1620
- * {@inheritDoc}
1621
- */
1622
- async disconnect() {
1623
- if (!this.client) return;
1624
- this.log("disconnecting");
1625
- await this.client.quit();
1626
- this.log("disconnected");
1627
- await this.emit("disconnected");
1628
- }
1629
- /**
1630
- * Atomic increment using Redis native INCRBY command
1631
- * {@inheritdoc}
1632
- */
1633
- async increment(key, value = 1) {
1634
- const parsedKey = this.parseKey(key);
1635
- this.log("caching", parsedKey);
1636
- const result = await this.client?.incrBy(parsedKey, value);
1637
- this.log("cached", parsedKey);
1638
- await this.emit("set", { key: parsedKey, value: result, ttl: void 0 });
1639
- return result || 0;
1640
- }
1641
- /**
1642
- * Atomic decrement using Redis native DECRBY command
1643
- * {@inheritdoc}
1644
- */
1645
- async decrement(key, value = 1) {
1646
- const parsedKey = this.parseKey(key);
1647
- this.log("caching", parsedKey);
1648
- const result = await this.client?.decrBy(parsedKey, value);
1649
- this.log("cached", parsedKey);
1650
- await this.emit("set", { key: parsedKey, value: result, ttl: void 0 });
1651
- return result || 0;
1652
- }
1653
- /**
1654
- * Set if not exists (atomic operation)
1655
- * Returns true if key was set, false if key already existed
1656
- */
1657
- async setNX(key, value, ttl) {
1658
- const parsedKey = this.parseKey(key);
1659
- this.log("caching", parsedKey);
1660
- if (ttl === void 0) {
1661
- ttl = this.ttl;
1662
- }
1663
- let result;
1664
- if (ttl && ttl !== Infinity) {
1665
- result = await this.client?.set(parsedKey, JSON.stringify(value), {
1666
- NX: true,
1667
- EX: ttl
1668
- });
1669
- } else {
1670
- result = await this.client?.set(parsedKey, JSON.stringify(value), {
1671
- NX: true
1672
- });
1673
- }
1674
- const wasSet = result === "OK";
1675
- if (wasSet) {
1676
- this.log("cached", parsedKey);
1677
- await this.emit("set", { key: parsedKey, value, ttl });
1678
- } else {
1679
- this.log("notFound", parsedKey);
1680
- }
1681
- return wasSet;
1682
- }
1683
- };
1684
-
1685
- exports.BaseCacheDriver = BaseCacheDriver;
1686
- exports.CACHE_FOR = CACHE_FOR;
1687
- exports.CacheConfigurationError = CacheConfigurationError;
1688
- exports.CacheConnectionError = CacheConnectionError;
1689
- exports.CacheDriverNotInitializedError = CacheDriverNotInitializedError;
1690
- exports.CacheError = CacheError;
1691
- exports.CacheManager = CacheManager;
1692
- exports.FileCacheDriver = FileCacheDriver;
1693
- exports.LRUMemoryCacheDriver = LRUMemoryCacheDriver;
1694
- exports.MemoryCacheDriver = MemoryCacheDriver;
1695
- exports.MemoryExtendedCacheDriver = MemoryExtendedCacheDriver;
1696
- exports.NullCacheDriver = NullCacheDriver;
1697
- exports.RedisCacheDriver = RedisCacheDriver;
1698
- exports.TaggedCache = TaggedCache;
1699
- exports.cache = cache;
1700
- exports.parseCacheKey = parseCacheKey;
3
+ var cacheManager = require('./cache-manager');
4
+ var drivers = require('./drivers');
5
+ var taggedCache = require('./tagged-cache');
6
+ var types = require('./types');
7
+ var utils = require('./utils');
8
+
9
+
10
+
11
+ Object.keys(cacheManager).forEach(function (k) {
12
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
13
+ enumerable: true,
14
+ get: function () { return cacheManager[k]; }
15
+ });
16
+ });
17
+ Object.keys(drivers).forEach(function (k) {
18
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
19
+ enumerable: true,
20
+ get: function () { return drivers[k]; }
21
+ });
22
+ });
23
+ Object.keys(taggedCache).forEach(function (k) {
24
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
25
+ enumerable: true,
26
+ get: function () { return taggedCache[k]; }
27
+ });
28
+ });
29
+ Object.keys(types).forEach(function (k) {
30
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
31
+ enumerable: true,
32
+ get: function () { return types[k]; }
33
+ });
34
+ });
35
+ Object.keys(utils).forEach(function (k) {
36
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
37
+ enumerable: true,
38
+ get: function () { return utils[k]; }
39
+ });
40
+ });
1701
41
  //# sourceMappingURL=index.js.map
1702
42
  //# sourceMappingURL=index.js.map