@catbee/utils 0.0.1 → 0.0.2

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 (197) hide show
  1. package/README.md +303 -107
  2. package/build/esm/config.d.ts +12 -0
  3. package/build/esm/config.js +12 -0
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +1 -0
  6. package/build/esm/index.js +1 -0
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/types/api-response.d.ts +82 -0
  9. package/build/esm/types/api-response.js.map +1 -1
  10. package/build/esm/utils/array.utils.d.ts +64 -1
  11. package/build/esm/utils/array.utils.js +139 -2
  12. package/build/esm/utils/array.utils.js.map +1 -1
  13. package/build/esm/utils/async.utils.d.ts +60 -1
  14. package/build/esm/utils/async.utils.js +160 -2
  15. package/build/esm/utils/async.utils.js.map +1 -1
  16. package/build/esm/utils/cache.utils.d.ts +67 -4
  17. package/build/esm/utils/cache.utils.js +210 -28
  18. package/build/esm/utils/cache.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +101 -0
  20. package/build/esm/utils/context-store.utils.js +182 -0
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/crypto.utils.d.ts +110 -8
  23. package/build/esm/utils/crypto.utils.js +298 -15
  24. package/build/esm/utils/crypto.utils.js.map +1 -1
  25. package/build/esm/utils/decorators.utils.d.ts +40 -0
  26. package/build/esm/utils/decorators.utils.js +312 -0
  27. package/build/esm/utils/decorators.utils.js.map +1 -0
  28. package/build/esm/utils/dir.utils.d.ts +121 -0
  29. package/build/esm/utils/dir.utils.js +577 -0
  30. package/build/esm/utils/dir.utils.js.map +1 -1
  31. package/build/esm/utils/env.utils.d.ts +83 -0
  32. package/build/esm/utils/env.utils.js +233 -0
  33. package/build/esm/utils/env.utils.js.map +1 -1
  34. package/build/esm/utils/exception.utils.d.ts +116 -0
  35. package/build/esm/utils/exception.utils.js +322 -0
  36. package/build/esm/utils/exception.utils.js.map +1 -1
  37. package/build/esm/utils/fs.utils.d.ts +132 -0
  38. package/build/esm/utils/fs.utils.js +421 -0
  39. package/build/esm/utils/fs.utils.js.map +1 -1
  40. package/build/esm/utils/http-status-codes.d.ts +87 -178
  41. package/build/esm/utils/http-status-codes.js +92 -178
  42. package/build/esm/utils/http-status-codes.js.map +1 -1
  43. package/build/esm/utils/id.utils.d.ts +11 -10
  44. package/build/esm/utils/id.utils.js +29 -20
  45. package/build/esm/utils/id.utils.js.map +1 -1
  46. package/build/esm/utils/logger.utils.d.ts +24 -0
  47. package/build/esm/utils/logger.utils.js +54 -0
  48. package/build/esm/utils/logger.utils.js.map +1 -1
  49. package/build/esm/utils/middleware.utils.d.ts +72 -0
  50. package/build/esm/utils/middleware.utils.js +158 -0
  51. package/build/esm/utils/middleware.utils.js.map +1 -0
  52. package/build/esm/utils/obj.utils.d.ts +65 -3
  53. package/build/esm/utils/obj.utils.js +205 -6
  54. package/build/esm/utils/obj.utils.js.map +1 -1
  55. package/build/esm/utils/response.utils.d.ts +101 -0
  56. package/build/esm/utils/response.utils.js +153 -0
  57. package/build/esm/utils/response.utils.js.map +1 -1
  58. package/build/esm/utils/string.utils.d.ts +61 -5
  59. package/build/esm/utils/string.utils.js +101 -11
  60. package/build/esm/utils/string.utils.js.map +1 -1
  61. package/build/esm/utils/url.utils.d.ts +117 -0
  62. package/build/esm/utils/url.utils.js +287 -0
  63. package/build/esm/utils/url.utils.js.map +1 -1
  64. package/build/esm/utils/validate.utils.d.ts +110 -0
  65. package/build/esm/utils/validate.utils.js +186 -0
  66. package/build/esm/utils/validate.utils.js.map +1 -1
  67. package/build/esnext/config.d.ts +12 -0
  68. package/build/esnext/config.js +12 -0
  69. package/build/esnext/config.js.map +1 -1
  70. package/build/esnext/index.d.ts +1 -0
  71. package/build/esnext/index.js +1 -0
  72. package/build/esnext/index.js.map +1 -1
  73. package/build/esnext/types/api-response.d.ts +82 -0
  74. package/build/esnext/types/api-response.js.map +1 -1
  75. package/build/esnext/utils/array.utils.d.ts +64 -1
  76. package/build/esnext/utils/array.utils.js +129 -2
  77. package/build/esnext/utils/array.utils.js.map +1 -1
  78. package/build/esnext/utils/async.utils.d.ts +60 -1
  79. package/build/esnext/utils/async.utils.js +117 -1
  80. package/build/esnext/utils/async.utils.js.map +1 -1
  81. package/build/esnext/utils/cache.utils.d.ts +67 -4
  82. package/build/esnext/utils/cache.utils.js +137 -9
  83. package/build/esnext/utils/cache.utils.js.map +1 -1
  84. package/build/esnext/utils/context-store.utils.d.ts +101 -0
  85. package/build/esnext/utils/context-store.utils.js +168 -0
  86. package/build/esnext/utils/context-store.utils.js.map +1 -1
  87. package/build/esnext/utils/crypto.utils.d.ts +110 -8
  88. package/build/esnext/utils/crypto.utils.js +205 -15
  89. package/build/esnext/utils/crypto.utils.js.map +1 -1
  90. package/build/esnext/utils/decorators.utils.d.ts +40 -0
  91. package/build/esnext/utils/decorators.utils.js +155 -0
  92. package/build/esnext/utils/decorators.utils.js.map +1 -0
  93. package/build/esnext/utils/dir.utils.d.ts +121 -0
  94. package/build/esnext/utils/dir.utils.js +306 -0
  95. package/build/esnext/utils/dir.utils.js.map +1 -1
  96. package/build/esnext/utils/env.utils.d.ts +83 -0
  97. package/build/esnext/utils/env.utils.js +185 -0
  98. package/build/esnext/utils/env.utils.js.map +1 -1
  99. package/build/esnext/utils/exception.utils.d.ts +116 -0
  100. package/build/esnext/utils/exception.utils.js +213 -0
  101. package/build/esnext/utils/exception.utils.js.map +1 -1
  102. package/build/esnext/utils/fs.utils.d.ts +132 -0
  103. package/build/esnext/utils/fs.utils.js +268 -0
  104. package/build/esnext/utils/fs.utils.js.map +1 -1
  105. package/build/esnext/utils/http-status-codes.d.ts +87 -178
  106. package/build/esnext/utils/http-status-codes.js +92 -178
  107. package/build/esnext/utils/http-status-codes.js.map +1 -1
  108. package/build/esnext/utils/id.utils.d.ts +11 -10
  109. package/build/esnext/utils/id.utils.js +27 -19
  110. package/build/esnext/utils/id.utils.js.map +1 -1
  111. package/build/esnext/utils/logger.utils.d.ts +24 -0
  112. package/build/esnext/utils/logger.utils.js +42 -0
  113. package/build/esnext/utils/logger.utils.js.map +1 -1
  114. package/build/esnext/utils/middleware.utils.d.ts +72 -0
  115. package/build/esnext/utils/middleware.utils.js +157 -0
  116. package/build/esnext/utils/middleware.utils.js.map +1 -0
  117. package/build/esnext/utils/obj.utils.d.ts +65 -3
  118. package/build/esnext/utils/obj.utils.js +167 -3
  119. package/build/esnext/utils/obj.utils.js.map +1 -1
  120. package/build/esnext/utils/response.utils.d.ts +101 -0
  121. package/build/esnext/utils/response.utils.js +138 -0
  122. package/build/esnext/utils/response.utils.js.map +1 -1
  123. package/build/esnext/utils/string.utils.d.ts +61 -5
  124. package/build/esnext/utils/string.utils.js +110 -14
  125. package/build/esnext/utils/string.utils.js.map +1 -1
  126. package/build/esnext/utils/url.utils.d.ts +117 -0
  127. package/build/esnext/utils/url.utils.js +248 -0
  128. package/build/esnext/utils/url.utils.js.map +1 -1
  129. package/build/esnext/utils/validate.utils.d.ts +110 -0
  130. package/build/esnext/utils/validate.utils.js +184 -0
  131. package/build/esnext/utils/validate.utils.js.map +1 -1
  132. package/build/src/config.d.ts +12 -0
  133. package/build/src/config.js +12 -0
  134. package/build/src/config.js.map +1 -1
  135. package/build/src/index.d.ts +1 -0
  136. package/build/src/index.js +1 -0
  137. package/build/src/index.js.map +1 -1
  138. package/build/src/types/api-response.d.ts +82 -0
  139. package/build/src/types/api-response.js.map +1 -1
  140. package/build/src/utils/array.utils.d.ts +64 -1
  141. package/build/src/utils/array.utils.js +137 -4
  142. package/build/src/utils/array.utils.js.map +1 -1
  143. package/build/src/utils/async.utils.d.ts +60 -1
  144. package/build/src/utils/async.utils.js +124 -4
  145. package/build/src/utils/async.utils.js.map +1 -1
  146. package/build/src/utils/cache.utils.d.ts +67 -4
  147. package/build/src/utils/cache.utils.js +137 -9
  148. package/build/src/utils/cache.utils.js.map +1 -1
  149. package/build/src/utils/context-store.utils.d.ts +101 -0
  150. package/build/src/utils/context-store.utils.js +171 -1
  151. package/build/src/utils/context-store.utils.js.map +1 -1
  152. package/build/src/utils/crypto.utils.d.ts +110 -8
  153. package/build/src/utils/crypto.utils.js +224 -27
  154. package/build/src/utils/crypto.utils.js.map +1 -1
  155. package/build/src/utils/decorators.utils.d.ts +40 -0
  156. package/build/src/utils/decorators.utils.js +165 -0
  157. package/build/src/utils/decorators.utils.js.map +1 -0
  158. package/build/src/utils/dir.utils.d.ts +121 -0
  159. package/build/src/utils/dir.utils.js +316 -0
  160. package/build/src/utils/dir.utils.js.map +1 -1
  161. package/build/src/utils/env.utils.d.ts +83 -0
  162. package/build/src/utils/env.utils.js +186 -1
  163. package/build/src/utils/env.utils.js.map +1 -1
  164. package/build/src/utils/exception.utils.d.ts +116 -0
  165. package/build/src/utils/exception.utils.js +226 -1
  166. package/build/src/utils/exception.utils.js.map +1 -1
  167. package/build/src/utils/fs.utils.d.ts +132 -0
  168. package/build/src/utils/fs.utils.js +282 -0
  169. package/build/src/utils/fs.utils.js.map +1 -1
  170. package/build/src/utils/http-status-codes.d.ts +87 -178
  171. package/build/src/utils/http-status-codes.js +92 -178
  172. package/build/src/utils/http-status-codes.js.map +1 -1
  173. package/build/src/utils/id.utils.d.ts +11 -10
  174. package/build/src/utils/id.utils.js +27 -19
  175. package/build/src/utils/id.utils.js.map +1 -1
  176. package/build/src/utils/logger.utils.d.ts +24 -0
  177. package/build/src/utils/logger.utils.js +45 -0
  178. package/build/src/utils/logger.utils.js.map +1 -1
  179. package/build/src/utils/middleware.utils.d.ts +72 -0
  180. package/build/src/utils/middleware.utils.js +163 -0
  181. package/build/src/utils/middleware.utils.js.map +1 -0
  182. package/build/src/utils/obj.utils.d.ts +65 -3
  183. package/build/src/utils/obj.utils.js +177 -7
  184. package/build/src/utils/obj.utils.js.map +1 -1
  185. package/build/src/utils/response.utils.d.ts +101 -0
  186. package/build/src/utils/response.utils.js +146 -1
  187. package/build/src/utils/response.utils.js.map +1 -1
  188. package/build/src/utils/string.utils.d.ts +61 -5
  189. package/build/src/utils/string.utils.js +122 -20
  190. package/build/src/utils/string.utils.js.map +1 -1
  191. package/build/src/utils/url.utils.d.ts +117 -0
  192. package/build/src/utils/url.utils.js +257 -0
  193. package/build/src/utils/url.utils.js.map +1 -1
  194. package/build/src/utils/validate.utils.d.ts +110 -0
  195. package/build/src/utils/validate.utils.js +198 -0
  196. package/build/src/utils/validate.utils.js.map +1 -1
  197. package/package.json +20 -12
@@ -1,3 +1,14 @@
1
+ /**
2
+ * Options for configuring a TTLCache instance.
3
+ */
4
+ export interface TTLCacheOptions {
5
+ /** Default time-to-live in milliseconds for cache entries */
6
+ ttlMs?: number;
7
+ /** Maximum number of entries to keep in cache (uses LRU eviction policy) */
8
+ maxSize?: number;
9
+ /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */
10
+ autoCleanupMs?: number;
11
+ }
1
12
  /**
2
13
  * An in-memory cache with time-to-live (TTL) support for each entry.
3
14
  *
@@ -5,17 +16,19 @@
5
16
  * @typeParam V - Type of the value.
6
17
  *
7
18
  * @example
8
- * const cache = new TTLCache<string, number>(1000);
19
+ * const cache = new TTLCache<string, number>({ ttlMs: 1000 });
9
20
  * cache.set("x", 123);
10
21
  * const value = cache.get("x"); // 123
11
22
  */
12
23
  export declare class TTLCache<K, V> {
13
- private ttlMs;
14
24
  private cache;
25
+ private ttlMs;
26
+ private maxSize?;
27
+ private cleanupInterval?;
15
28
  /**
16
- * @param ttlMs - Default time-to-live in milliseconds for cache entries.
29
+ * @param options - Configuration options for the cache
17
30
  */
18
- constructor(ttlMs?: number);
31
+ constructor(options?: TTLCacheOptions);
19
32
  /**
20
33
  * Sets a key-value pair in the cache with the default TTL.
21
34
  *
@@ -38,6 +51,15 @@ export declare class TTLCache<K, V> {
38
51
  * @returns The cached value, or undefined if not found or expired.
39
52
  */
40
53
  get(key: K): V | undefined;
54
+ /**
55
+ * Retrieves or computes a value if it's not in the cache or has expired.
56
+ *
57
+ * @param key - The key to retrieve
58
+ * @param producer - Function to generate the value if not cached
59
+ * @param ttlMs - Optional custom TTL for the computed value
60
+ * @returns The cached or computed value
61
+ */
62
+ getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V>;
41
63
  /**
42
64
  * Checks if the key exists and hasn't expired.
43
65
  *
@@ -62,6 +84,19 @@ export declare class TTLCache<K, V> {
62
84
  * @returns Number of items in the cache (may include expired keys).
63
85
  */
64
86
  size(): number;
87
+ /**
88
+ * Set multiple key-value pairs at once with the default TTL.
89
+ *
90
+ * @param entries - Array of [key, value] tuples to set
91
+ */
92
+ setMany(entries: [K, V][]): void;
93
+ /**
94
+ * Get multiple values at once.
95
+ *
96
+ * @param keys - Array of keys to retrieve
97
+ * @returns Array of values (undefined for keys that don't exist or expired)
98
+ */
99
+ getMany(keys: K[]): (V | undefined)[];
65
100
  /**
66
101
  * Removes all expired entries from the cache.
67
102
  *
@@ -86,5 +121,33 @@ export declare class TTLCache<K, V> {
86
121
  * @returns IterableIterator<V>
87
122
  */
88
123
  values(): IterableIterator<V>;
124
+ /**
125
+ * Extends the expiration of a key by the specified time or default TTL.
126
+ *
127
+ * @param key - The key to refresh
128
+ * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)
129
+ * @returns true if the key was found and refreshed, false otherwise
130
+ */
131
+ refresh(key: K, ttlMs?: number): boolean;
132
+ /**
133
+ * Returns a snapshot of cache stats.
134
+ *
135
+ * @returns Object containing cache statistics
136
+ */
137
+ stats(): {
138
+ size: number;
139
+ validEntries: number;
140
+ expiredEntries: number;
141
+ maxSize: number | undefined;
142
+ };
143
+ /**
144
+ * Stop the auto-cleanup interval if it's running.
145
+ */
146
+ destroy(): void;
147
+ /**
148
+ * Evict the least recently used entry from the cache.
149
+ * @private
150
+ */
151
+ private evictLRU;
89
152
  }
90
153
  //# sourceMappingURL=cache.utils.d.ts.map
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TTLCache = void 0;
4
+ const config_1 = require("../config");
4
5
  /**
5
6
  * An in-memory cache with time-to-live (TTL) support for each entry.
6
7
  *
@@ -8,17 +9,26 @@ exports.TTLCache = void 0;
8
9
  * @typeParam V - Type of the value.
9
10
  *
10
11
  * @example
11
- * const cache = new TTLCache<string, number>(1000);
12
+ * const cache = new TTLCache<string, number>({ ttlMs: 1000 });
12
13
  * cache.set("x", 123);
13
14
  * const value = cache.get("x"); // 123
14
15
  */
15
16
  class TTLCache {
16
17
  /**
17
- * @param ttlMs - Default time-to-live in milliseconds for cache entries.
18
+ * @param options - Configuration options for the cache
18
19
  */
19
- constructor(ttlMs = 5 * 60 * 1000) {
20
- this.ttlMs = ttlMs;
20
+ constructor(options = {}) {
21
+ var _a;
21
22
  this.cache = new Map();
23
+ this.ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : config_1.Config.Cache.defaultTtl;
24
+ this.maxSize = options.maxSize;
25
+ // Setup auto-cleanup if enabled
26
+ const autoCleanupMs = options.autoCleanupMs;
27
+ if (autoCleanupMs && autoCleanupMs > 0) {
28
+ this.cleanupInterval = setInterval(() => {
29
+ this.cleanup();
30
+ }, autoCleanupMs);
31
+ }
22
32
  }
23
33
  /**
24
34
  * Sets a key-value pair in the cache with the default TTL.
@@ -27,8 +37,7 @@ class TTLCache {
27
37
  * @param value - The value to associate with the key.
28
38
  */
29
39
  set(key, value) {
30
- const expiresAt = Date.now() + this.ttlMs;
31
- this.cache.set(key, { value, expiresAt });
40
+ this.setWithTTL(key, value, this.ttlMs);
32
41
  }
33
42
  /**
34
43
  * Sets a key-value pair in the cache with a custom TTL.
@@ -38,8 +47,13 @@ class TTLCache {
38
47
  * @param ttlMs - Time-to-live in milliseconds.
39
48
  */
40
49
  setWithTTL(key, value, ttlMs) {
41
- const expiresAt = Date.now() + ttlMs;
42
- this.cache.set(key, { value, expiresAt });
50
+ const now = Date.now();
51
+ const expiresAt = now + ttlMs;
52
+ this.cache.set(key, { value, expiresAt, lastAccessed: now });
53
+ // Enforce max size limit if configured
54
+ if (this.maxSize && this.cache.size > this.maxSize) {
55
+ this.evictLRU();
56
+ }
43
57
  }
44
58
  /**
45
59
  * Retrieves the value for a given key if it hasn't expired.
@@ -51,12 +65,31 @@ class TTLCache {
51
65
  const entry = this.cache.get(key);
52
66
  if (!entry)
53
67
  return undefined;
54
- if (Date.now() > entry.expiresAt) {
68
+ const now = Date.now();
69
+ if (now > entry.expiresAt) {
55
70
  this.cache.delete(key);
56
71
  return undefined;
57
72
  }
73
+ // Update last access time for LRU tracking
74
+ entry.lastAccessed = now;
58
75
  return entry.value;
59
76
  }
77
+ /**
78
+ * Retrieves or computes a value if it's not in the cache or has expired.
79
+ *
80
+ * @param key - The key to retrieve
81
+ * @param producer - Function to generate the value if not cached
82
+ * @param ttlMs - Optional custom TTL for the computed value
83
+ * @returns The cached or computed value
84
+ */
85
+ async getOrCompute(key, producer, ttlMs) {
86
+ const value = this.get(key);
87
+ if (value !== undefined)
88
+ return value;
89
+ const newValue = await producer();
90
+ this.setWithTTL(key, newValue, ttlMs !== null && ttlMs !== void 0 ? ttlMs : this.ttlMs);
91
+ return newValue;
92
+ }
60
93
  /**
61
94
  * Checks if the key exists and hasn't expired.
62
95
  *
@@ -89,6 +122,25 @@ class TTLCache {
89
122
  size() {
90
123
  return this.cache.size;
91
124
  }
125
+ /**
126
+ * Set multiple key-value pairs at once with the default TTL.
127
+ *
128
+ * @param entries - Array of [key, value] tuples to set
129
+ */
130
+ setMany(entries) {
131
+ for (const [key, value] of entries) {
132
+ this.set(key, value);
133
+ }
134
+ }
135
+ /**
136
+ * Get multiple values at once.
137
+ *
138
+ * @param keys - Array of keys to retrieve
139
+ * @returns Array of values (undefined for keys that don't exist or expired)
140
+ */
141
+ getMany(keys) {
142
+ return keys.map((key) => this.get(key));
143
+ }
92
144
  /**
93
145
  * Removes all expired entries from the cache.
94
146
  *
@@ -141,6 +193,82 @@ class TTLCache {
141
193
  }
142
194
  }
143
195
  }
196
+ /**
197
+ * Extends the expiration of a key by the specified time or default TTL.
198
+ *
199
+ * @param key - The key to refresh
200
+ * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)
201
+ * @returns true if the key was found and refreshed, false otherwise
202
+ */
203
+ refresh(key, ttlMs) {
204
+ const entry = this.cache.get(key);
205
+ if (!entry)
206
+ return false;
207
+ const now = Date.now();
208
+ if (now > entry.expiresAt) {
209
+ this.cache.delete(key);
210
+ return false;
211
+ }
212
+ entry.expiresAt = now + (ttlMs !== null && ttlMs !== void 0 ? ttlMs : this.ttlMs);
213
+ entry.lastAccessed = now;
214
+ return true;
215
+ }
216
+ /**
217
+ * Returns a snapshot of cache stats.
218
+ *
219
+ * @returns Object containing cache statistics
220
+ */
221
+ stats() {
222
+ const now = Date.now();
223
+ let expired = 0;
224
+ let valid = 0;
225
+ for (const entry of this.cache.values()) {
226
+ if (now > entry.expiresAt) {
227
+ expired++;
228
+ }
229
+ else {
230
+ valid++;
231
+ }
232
+ }
233
+ return {
234
+ size: this.cache.size,
235
+ validEntries: valid,
236
+ expiredEntries: expired,
237
+ maxSize: this.maxSize,
238
+ };
239
+ }
240
+ /**
241
+ * Stop the auto-cleanup interval if it's running.
242
+ */
243
+ destroy() {
244
+ if (this.cleanupInterval) {
245
+ clearInterval(this.cleanupInterval);
246
+ this.cleanupInterval = undefined;
247
+ }
248
+ }
249
+ /**
250
+ * Evict the least recently used entry from the cache.
251
+ * @private
252
+ */
253
+ evictLRU() {
254
+ let oldestKey;
255
+ let oldestAccess = Infinity;
256
+ for (const [key, entry] of this.cache.entries()) {
257
+ // Skip entries that are already expired
258
+ if (Date.now() > entry.expiresAt) {
259
+ this.cache.delete(key);
260
+ return;
261
+ }
262
+ // Find the oldest accessed entry
263
+ if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {
264
+ oldestAccess = entry.lastAccessed;
265
+ oldestKey = key;
266
+ }
267
+ }
268
+ if (oldestKey) {
269
+ this.cache.delete(oldestKey);
270
+ }
271
+ }
144
272
  }
145
273
  exports.TTLCache = TTLCache;
146
274
  //# sourceMappingURL=cache.utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAQA;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAGnB;;OAEG;IACH,YAAoB,QAAgB,CAAC,GAAG,EAAE,GAAG,IAAI;QAA7B,UAAK,GAAL,KAAK,CAAwB;QALzC,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;IAKQ,CAAC;IAErD;;;;;OAKG;IACH,GAAG,CAAC,GAAM,EAAE,KAAQ;QAClB,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,GAAM,EAAE,KAAQ,EAAE,KAAa;QACxC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;QACrC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAC,GAAM;QACR,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC7B,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACvB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,KAAK,CAAC,KAAK,CAAC;IACrB,CAAC;IAED;;;;;OAKG;IACH,G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AAI,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBAClC,MAAM,GAAG,CAAC;YACZ,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,CAAC,MAAM;QACL,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACxC,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBAClC,MAAM,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA1ID,4BA0IC","sourcesContent":["/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n};\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>(1000);\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n\n /**\n * @param ttlMs - Default time-to-live in milliseconds for cache entries.\n */\n constructor(private ttlMs: number = 5 * 60 * 1000) {}\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n const expiresAt = Date.now() + this.ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const expiresAt = Date.now() + ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAAA,sCAAmC;AAuBnC;;;;;;;;;;GAUG;AACH,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K,EAAE,CAAC;YACV,CAAC;QACH,CAAC;QAED,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI;YACrB,YAAY,EAAE,KAAK;YACnB,cAAc,EAAE,OAAO;YACvB,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,OAAO;QACL,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACzB,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACpC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;IAED;;;OAGG;IACK,QAAQ;QACd,IAAI,SAAwB,CAAC;QAC7B,IAAI,YAAY,GAAG,QAAQ,CAAC;QAE5B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;YAChD,wCAAwC;YACxC,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;gBACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACvB,OAAO;YACT,CAAC;YAED,iCAAiC;YACjC,IAAI,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,GAAG,YAAY,EAAE,CAAC;gBAC5D,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;gBAClC,SAAS,GAAG,GAAG,CAAC;YAClB,CAAC;QACH,CAAC;QAED,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;CACF;AAjSD,4BAiSC","sourcesContent":["import { Config } from \"../config\";\n\n/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n lastAccessed?: number; // Track last access time for LRU functionality\n};\n\n/**\n * Options for configuring a TTLCache instance.\n */\nexport interface TTLCacheOptions {\n /** Default time-to-live in milliseconds for cache entries */\n ttlMs?: number;\n /** Maximum number of entries to keep in cache (uses LRU eviction policy) */\n maxSize?: number;\n /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */\n autoCleanupMs?: number;\n}\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>({ ttlMs: 1000 });\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n private ttlMs: number;\n private maxSize?: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n /**\n * @param options - Configuration options for the cache\n */\n constructor(options: TTLCacheOptions = {}) {\n this.ttlMs = options.ttlMs ?? Config.Cache.defaultTtl;\n this.maxSize = options.maxSize;\n\n // Setup auto-cleanup if enabled\n const autoCleanupMs = options.autoCleanupMs;\n if (autoCleanupMs && autoCleanupMs > 0) {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, autoCleanupMs);\n }\n }\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n this.setWithTTL(key, value, this.ttlMs);\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const now = Date.now();\n const expiresAt = now + ttlMs;\n this.cache.set(key, { value, expiresAt, lastAccessed: now });\n\n // Enforce max size limit if configured\n if (this.maxSize && this.cache.size > this.maxSize) {\n this.evictLRU();\n }\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n // Update last access time for LRU tracking\n entry.lastAccessed = now;\n return entry.value;\n }\n\n /**\n * Retrieves or computes a value if it's not in the cache or has expired.\n *\n * @param key - The key to retrieve\n * @param producer - Function to generate the value if not cached\n * @param ttlMs - Optional custom TTL for the computed value\n * @returns The cached or computed value\n */\n async getOrCompute(\n key: K,\n producer: () => Promise<V>,\n ttlMs?: number,\n ): Promise<V> {\n const value = this.get(key);\n if (value !== undefined) return value;\n\n const newValue = await producer();\n this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);\n return newValue;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Set multiple key-value pairs at once with the default TTL.\n *\n * @param entries - Array of [key, value] tuples to set\n */\n setMany(entries: [K, V][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get multiple values at once.\n *\n * @param keys - Array of keys to retrieve\n * @returns Array of values (undefined for keys that don't exist or expired)\n */\n getMany(keys: K[]): (V | undefined)[] {\n return keys.map((key) => this.get(key));\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n\n /**\n * Extends the expiration of a key by the specified time or default TTL.\n *\n * @param key - The key to refresh\n * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)\n * @returns true if the key was found and refreshed, false otherwise\n */\n refresh(key: K, ttlMs?: number): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return false;\n }\n\n entry.expiresAt = now + (ttlMs ?? this.ttlMs);\n entry.lastAccessed = now;\n return true;\n }\n\n /**\n * Returns a snapshot of cache stats.\n *\n * @returns Object containing cache statistics\n */\n stats() {\n const now = Date.now();\n let expired = 0;\n let valid = 0;\n\n for (const entry of this.cache.values()) {\n if (now > entry.expiresAt) {\n expired++;\n } else {\n valid++;\n }\n }\n\n return {\n size: this.cache.size,\n validEntries: valid,\n expiredEntries: expired,\n maxSize: this.maxSize,\n };\n }\n\n /**\n * Stop the auto-cleanup interval if it's running.\n */\n destroy() {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * Evict the least recently used entry from the cache.\n * @private\n */\n private evictLRU(): void {\n let oldestKey: K | undefined;\n let oldestAccess = Infinity;\n\n for (const [key, entry] of this.cache.entries()) {\n // Skip entries that are already expired\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return;\n }\n\n // Find the oldest accessed entry\n if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {\n oldestAccess = entry.lastAccessed;\n oldestKey = key;\n }\n }\n\n if (oldestKey) {\n this.cache.delete(oldestKey);\n }\n }\n}\n"]}
@@ -13,6 +13,10 @@ export interface Store {
13
13
  export declare const StoreKeys: {
14
14
  LOGGER: symbol;
15
15
  REQUEST_ID: symbol;
16
+ USER_ID: symbol;
17
+ TENANT_ID: symbol;
18
+ TRACE_ID: symbol;
19
+ CORRELATION_ID: symbol;
16
20
  };
17
21
  /**
18
22
  * Retrieves the current request ID from the async context, if available.
@@ -20,6 +24,13 @@ export declare const StoreKeys: {
20
24
  * @returns {string | undefined} The request ID string or undefined if not present in the current context.
21
25
  */
22
26
  export declare function getRequestId(): string | undefined;
27
+ /**
28
+ * Type-safe getter for common context values.
29
+ *
30
+ * @param key The store key symbol
31
+ * @returns The typed value from the store
32
+ */
33
+ export declare function getFromContext<T>(key: symbol): T | undefined;
23
34
  /**
24
35
  * ContextStore manages per-request scoped context using AsyncLocalStorage.
25
36
  * It allows storing and retrieving data across async calls (e.g., request ID, logger).
@@ -81,5 +92,95 @@ export declare class ContextStore {
81
92
  * @returns {T} The result of the callback function.
82
93
  */
83
94
  static run<T>(store: Store, callback: () => T): T;
95
+ /**
96
+ * Checks if a key exists in the current context store.
97
+ *
98
+ * @param {symbol} key - The symbol key to check.
99
+ * @returns {boolean} True if the key exists, false otherwise.
100
+ */
101
+ static has(key: symbol): boolean;
102
+ /**
103
+ * Removes a value from the current context store by symbol key.
104
+ *
105
+ * @param {symbol} key - The symbol key to delete.
106
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
107
+ * @throws {Error} If called outside an active context.
108
+ */
109
+ static delete(key: symbol): boolean;
110
+ /**
111
+ * Updates multiple values in the current context store at once.
112
+ *
113
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
114
+ * @throws {Error} If called outside an active context.
115
+ */
116
+ static patch(values: Partial<Record<symbol, unknown>>): void;
117
+ /**
118
+ * Executes a callback with a temporary store value that only exists during execution.
119
+ * Original store is restored after callback completes.
120
+ *
121
+ * @typeParam T - The callback's return type.
122
+ * @param {symbol} key - The symbol key to temporarily set.
123
+ * @param {unknown} value - The temporary value.
124
+ * @param {() => T} callback - The function to execute with the temporary value.
125
+ * @returns {T} The result of the callback function.
126
+ * @throws {Error} If called outside an active context.
127
+ */
128
+ static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
129
+ /**
130
+ * Creates a new context that inherits values from the current context.
131
+ *
132
+ * @typeParam T - The callback's return type.
133
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
134
+ * @param {() => T} callback - The function to execute in the new context.
135
+ * @returns {T} The result of the callback function.
136
+ */
137
+ static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
138
+ /**
139
+ * Creates Express middleware that initializes a context for each request.
140
+ *
141
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
142
+ * @returns Express middleware function.
143
+ */
144
+ static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, res: any, next: any) => void;
145
+ }
146
+ /**
147
+ * Type-safe wrapper for accessing and modifying context values with specific types.
148
+ *
149
+ * @typeParam T - The value type.
150
+ */
151
+ export declare class TypedContextKey<T> {
152
+ private symbol;
153
+ private defaultValue?;
154
+ /**
155
+ * Creates a new typed context key.
156
+ *
157
+ * @param symbol - The unique symbol for this key
158
+ * @param defaultValue - Optional default value if key is not found
159
+ */
160
+ constructor(symbol: symbol, defaultValue?: T | undefined);
161
+ /**
162
+ * Gets the current value for this key.
163
+ *
164
+ * @returns The value or defaultValue if not found
165
+ */
166
+ get(): T | undefined;
167
+ /**
168
+ * Sets the value for this key.
169
+ *
170
+ * @param value The value to set
171
+ */
172
+ set(value: T): void;
173
+ /**
174
+ * Checks if this key exists in the context.
175
+ *
176
+ * @returns True if the key exists
177
+ */
178
+ exists(): boolean;
179
+ /**
180
+ * Deletes this key from the context.
181
+ *
182
+ * @returns True if the key was deleted
183
+ */
184
+ delete(): boolean;
84
185
  }
85
186
  //# sourceMappingURL=context-store.utils.d.ts.map
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ContextStore = exports.StoreKeys = void 0;
3
+ exports.TypedContextKey = exports.ContextStore = exports.StoreKeys = void 0;
4
4
  exports.getRequestId = getRequestId;
5
+ exports.getFromContext = getFromContext;
5
6
  const async_hooks_1 = require("async_hooks");
6
7
  /**
7
8
  * Predefined symbols used as keys in AsyncLocalStorage.
@@ -10,6 +11,10 @@ const async_hooks_1 = require("async_hooks");
10
11
  exports.StoreKeys = {
11
12
  LOGGER: Symbol("logger"),
12
13
  REQUEST_ID: Symbol("requestId"),
14
+ USER_ID: Symbol("userId"),
15
+ TENANT_ID: Symbol("tenantId"),
16
+ TRACE_ID: Symbol("traceId"),
17
+ CORRELATION_ID: Symbol("correlationId"),
13
18
  };
14
19
  /**
15
20
  * Retrieves the current request ID from the async context, if available.
@@ -19,6 +24,15 @@ exports.StoreKeys = {
19
24
  function getRequestId() {
20
25
  return ContextStore.get(exports.StoreKeys.REQUEST_ID);
21
26
  }
27
+ /**
28
+ * Type-safe getter for common context values.
29
+ *
30
+ * @param key The store key symbol
31
+ * @returns The typed value from the store
32
+ */
33
+ function getFromContext(key) {
34
+ return ContextStore.get(key);
35
+ }
22
36
  /**
23
37
  * ContextStore manages per-request scoped context using AsyncLocalStorage.
24
38
  * It allows storing and retrieving data across async calls (e.g., request ID, logger).
@@ -90,6 +104,111 @@ class ContextStore {
90
104
  static run(store, callback) {
91
105
  return this.storage.run(store, callback);
92
106
  }
107
+ /**
108
+ * Checks if a key exists in the current context store.
109
+ *
110
+ * @param {symbol} key - The symbol key to check.
111
+ * @returns {boolean} True if the key exists, false otherwise.
112
+ */
113
+ static has(key) {
114
+ const store = this.storage.getStore();
115
+ return store !== undefined && key in store;
116
+ }
117
+ /**
118
+ * Removes a value from the current context store by symbol key.
119
+ *
120
+ * @param {symbol} key - The symbol key to delete.
121
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
122
+ * @throws {Error} If called outside an active context.
123
+ */
124
+ static delete(key) {
125
+ const store = this.storage.getStore();
126
+ if (!store) {
127
+ throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
128
+ }
129
+ return delete store[key];
130
+ }
131
+ /**
132
+ * Updates multiple values in the current context store at once.
133
+ *
134
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
135
+ * @throws {Error} If called outside an active context.
136
+ */
137
+ static patch(values) {
138
+ const store = this.storage.getStore();
139
+ if (!store) {
140
+ throw new Error("Failed to patch: AsyncLocalStorage store is not initialized.");
141
+ }
142
+ Object.getOwnPropertySymbols(values).forEach((key) => {
143
+ store[key] = values[key];
144
+ });
145
+ }
146
+ /**
147
+ * Executes a callback with a temporary store value that only exists during execution.
148
+ * Original store is restored after callback completes.
149
+ *
150
+ * @typeParam T - The callback's return type.
151
+ * @param {symbol} key - The symbol key to temporarily set.
152
+ * @param {unknown} value - The temporary value.
153
+ * @param {() => T} callback - The function to execute with the temporary value.
154
+ * @returns {T} The result of the callback function.
155
+ * @throws {Error} If called outside an active context.
156
+ */
157
+ static withValue(key, value, callback) {
158
+ const store = this.storage.getStore();
159
+ if (!store) {
160
+ throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
161
+ }
162
+ // Save original value
163
+ const hasOriginal = key in store;
164
+ const originalValue = store[key];
165
+ // Set temporary value
166
+ store[key] = value;
167
+ try {
168
+ // Run callback
169
+ return callback();
170
+ }
171
+ finally {
172
+ // Restore original value
173
+ if (hasOriginal) {
174
+ store[key] = originalValue;
175
+ }
176
+ else {
177
+ delete store[key];
178
+ }
179
+ }
180
+ }
181
+ /**
182
+ * Creates a new context that inherits values from the current context.
183
+ *
184
+ * @typeParam T - The callback's return type.
185
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
186
+ * @param {() => T} callback - The function to execute in the new context.
187
+ * @returns {T} The result of the callback function.
188
+ */
189
+ static extend(newValues, callback) {
190
+ const currentStore = this.storage.getStore() || {};
191
+ // Create new store with current values plus new ones
192
+ const newStore = Object.assign({}, currentStore);
193
+ // Add new values
194
+ Object.getOwnPropertySymbols(newValues).forEach((key) => {
195
+ newStore[key] = newValues[key];
196
+ });
197
+ // Run with extended store
198
+ return this.storage.run(newStore, callback);
199
+ }
200
+ /**
201
+ * Creates Express middleware that initializes a context for each request.
202
+ *
203
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
204
+ * @returns Express middleware function.
205
+ */
206
+ static createExpressMiddleware(initialValuesFactory = () => ({})) {
207
+ return (req, res, next) => {
208
+ const initialValues = initialValuesFactory(req);
209
+ ContextStore.run(initialValues, next);
210
+ };
211
+ }
93
212
  }
94
213
  exports.ContextStore = ContextStore;
95
214
  /**
@@ -97,4 +216,55 @@ exports.ContextStore = ContextStore;
97
216
  * @private
98
217
  */
99
218
  ContextStore.storage = new async_hooks_1.AsyncLocalStorage();
219
+ /**
220
+ * Type-safe wrapper for accessing and modifying context values with specific types.
221
+ *
222
+ * @typeParam T - The value type.
223
+ */
224
+ class TypedContextKey {
225
+ /**
226
+ * Creates a new typed context key.
227
+ *
228
+ * @param symbol - The unique symbol for this key
229
+ * @param defaultValue - Optional default value if key is not found
230
+ */
231
+ constructor(symbol, defaultValue) {
232
+ this.symbol = symbol;
233
+ this.defaultValue = defaultValue;
234
+ }
235
+ /**
236
+ * Gets the current value for this key.
237
+ *
238
+ * @returns The value or defaultValue if not found
239
+ */
240
+ get() {
241
+ const value = ContextStore.get(this.symbol);
242
+ return value !== undefined ? value : this.defaultValue;
243
+ }
244
+ /**
245
+ * Sets the value for this key.
246
+ *
247
+ * @param value The value to set
248
+ */
249
+ set(value) {
250
+ ContextStore.set(this.symbol, value);
251
+ }
252
+ /**
253
+ * Checks if this key exists in the context.
254
+ *
255
+ * @returns True if the key exists
256
+ */
257
+ exists() {
258
+ return ContextStore.has(this.symbol);
259
+ }
260
+ /**
261
+ * Deletes this key from the context.
262
+ *
263
+ * @returns True if the key was deleted
264
+ */
265
+ delete() {
266
+ return ContextStore.delete(this.symbol);
267
+ }
268
+ }
269
+ exports.TypedContextKey = TypedContextKey;
100
270
  //# sourceMappingURL=context-store.utils.js.map