@catbee/utils 0.0.8-rc.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +3 -2
  2. package/build/index.cjs +6912 -0
  3. package/build/index.d.ts +5284 -0
  4. package/build/index.mjs +6635 -0
  5. package/package.json +13 -292
  6. package/build/cjs/config.d.ts +0 -121
  7. package/build/cjs/config.js +0 -137
  8. package/build/cjs/index.d.ts +0 -26
  9. package/build/cjs/index.js +0 -68
  10. package/build/cjs/servers/server.builder.d.ts +0 -507
  11. package/build/cjs/servers/server.builder.js +0 -658
  12. package/build/cjs/servers/server.d.ts +0 -255
  13. package/build/cjs/servers/server.js +0 -970
  14. package/build/cjs/types/api-response.d.ts +0 -151
  15. package/build/cjs/types/api-response.js +0 -36
  16. package/build/cjs/types/index.d.ts +0 -124
  17. package/build/cjs/types/index.js +0 -25
  18. package/build/cjs/types/server.d.ts +0 -267
  19. package/build/cjs/types/server.js +0 -25
  20. package/build/cjs/utils/array.utils.d.ts +0 -167
  21. package/build/cjs/utils/array.utils.js +0 -363
  22. package/build/cjs/utils/async.utils.d.ts +0 -264
  23. package/build/cjs/utils/async.utils.js +0 -640
  24. package/build/cjs/utils/cache.utils.d.ts +0 -152
  25. package/build/cjs/utils/cache.utils.js +0 -298
  26. package/build/cjs/utils/context-store.utils.d.ts +0 -188
  27. package/build/cjs/utils/context-store.utils.js +0 -297
  28. package/build/cjs/utils/crypto.utils.d.ts +0 -159
  29. package/build/cjs/utils/crypto.utils.js +0 -295
  30. package/build/cjs/utils/date.utils.d.ts +0 -158
  31. package/build/cjs/utils/date.utils.js +0 -395
  32. package/build/cjs/utils/decorators.utils.d.ts +0 -511
  33. package/build/cjs/utils/decorators.utils.js +0 -1035
  34. package/build/cjs/utils/dir.utils.d.ts +0 -195
  35. package/build/cjs/utils/dir.utils.js +0 -500
  36. package/build/cjs/utils/env.utils.d.ts +0 -376
  37. package/build/cjs/utils/env.utils.js +0 -786
  38. package/build/cjs/utils/exception.utils.d.ts +0 -229
  39. package/build/cjs/utils/exception.utils.js +0 -408
  40. package/build/cjs/utils/fs.utils.d.ts +0 -163
  41. package/build/cjs/utils/fs.utils.js +0 -371
  42. package/build/cjs/utils/http-status-codes.d.ts +0 -265
  43. package/build/cjs/utils/http-status-codes.js +0 -297
  44. package/build/cjs/utils/id.utils.d.ts +0 -35
  45. package/build/cjs/utils/id.utils.js +0 -90
  46. package/build/cjs/utils/logger.utils.d.ts +0 -159
  47. package/build/cjs/utils/logger.utils.js +0 -350
  48. package/build/cjs/utils/middleware.utils.d.ts +0 -99
  49. package/build/cjs/utils/middleware.utils.js +0 -243
  50. package/build/cjs/utils/obj.utils.d.ts +0 -123
  51. package/build/cjs/utils/obj.utils.js +0 -428
  52. package/build/cjs/utils/performance.utils.d.ts +0 -135
  53. package/build/cjs/utils/performance.utils.js +0 -280
  54. package/build/cjs/utils/request.utils.d.ts +0 -85
  55. package/build/cjs/utils/request.utils.js +0 -199
  56. package/build/cjs/utils/response.utils.d.ts +0 -162
  57. package/build/cjs/utils/response.utils.js +0 -274
  58. package/build/cjs/utils/stream.utils.d.ts +0 -87
  59. package/build/cjs/utils/stream.utils.js +0 -217
  60. package/build/cjs/utils/string.utils.d.ts +0 -92
  61. package/build/cjs/utils/string.utils.js +0 -178
  62. package/build/cjs/utils/type.utils.d.ts +0 -89
  63. package/build/cjs/utils/type.utils.js +0 -195
  64. package/build/cjs/utils/url.utils.d.ts +0 -140
  65. package/build/cjs/utils/url.utils.js +0 -316
  66. package/build/cjs/utils/validate.utils.d.ts +0 -176
  67. package/build/cjs/utils/validate.utils.js +0 -344
  68. package/build/esm/config.d.ts +0 -121
  69. package/build/esm/config.js +0 -132
  70. package/build/esm/index.d.ts +0 -26
  71. package/build/esm/index.js +0 -49
  72. package/build/esm/servers/server.builder.d.ts +0 -507
  73. package/build/esm/servers/server.builder.js +0 -654
  74. package/build/esm/servers/server.d.ts +0 -255
  75. package/build/esm/servers/server.js +0 -963
  76. package/build/esm/types/api-response.d.ts +0 -151
  77. package/build/esm/types/api-response.js +0 -33
  78. package/build/esm/types/index.d.ts +0 -124
  79. package/build/esm/types/index.js +0 -24
  80. package/build/esm/types/server.d.ts +0 -267
  81. package/build/esm/types/server.js +0 -24
  82. package/build/esm/utils/array.utils.d.ts +0 -167
  83. package/build/esm/utils/array.utils.js +0 -344
  84. package/build/esm/utils/async.utils.d.ts +0 -264
  85. package/build/esm/utils/async.utils.js +0 -619
  86. package/build/esm/utils/cache.utils.d.ts +0 -152
  87. package/build/esm/utils/cache.utils.js +0 -294
  88. package/build/esm/utils/context-store.utils.d.ts +0 -188
  89. package/build/esm/utils/context-store.utils.js +0 -290
  90. package/build/esm/utils/crypto.utils.d.ts +0 -159
  91. package/build/esm/utils/crypto.utils.js +0 -278
  92. package/build/esm/utils/date.utils.d.ts +0 -158
  93. package/build/esm/utils/date.utils.js +0 -383
  94. package/build/esm/utils/decorators.utils.d.ts +0 -511
  95. package/build/esm/utils/decorators.utils.js +0 -1013
  96. package/build/esm/utils/dir.utils.d.ts +0 -195
  97. package/build/esm/utils/dir.utils.js +0 -476
  98. package/build/esm/utils/env.utils.d.ts +0 -376
  99. package/build/esm/utils/env.utils.js +0 -782
  100. package/build/esm/utils/exception.utils.d.ts +0 -229
  101. package/build/esm/utils/exception.utils.js +0 -382
  102. package/build/esm/utils/fs.utils.d.ts +0 -163
  103. package/build/esm/utils/fs.utils.js +0 -348
  104. package/build/esm/utils/http-status-codes.d.ts +0 -265
  105. package/build/esm/utils/http-status-codes.js +0 -294
  106. package/build/esm/utils/id.utils.d.ts +0 -35
  107. package/build/esm/utils/id.utils.js +0 -83
  108. package/build/esm/utils/logger.utils.d.ts +0 -159
  109. package/build/esm/utils/logger.utils.js +0 -304
  110. package/build/esm/utils/middleware.utils.d.ts +0 -99
  111. package/build/esm/utils/middleware.utils.js +0 -235
  112. package/build/esm/utils/obj.utils.d.ts +0 -123
  113. package/build/esm/utils/obj.utils.js +0 -412
  114. package/build/esm/utils/performance.utils.d.ts +0 -135
  115. package/build/esm/utils/performance.utils.js +0 -273
  116. package/build/esm/utils/request.utils.d.ts +0 -85
  117. package/build/esm/utils/request.utils.js +0 -190
  118. package/build/esm/utils/response.utils.d.ts +0 -162
  119. package/build/esm/utils/response.utils.js +0 -261
  120. package/build/esm/utils/stream.utils.d.ts +0 -87
  121. package/build/esm/utils/stream.utils.js +0 -209
  122. package/build/esm/utils/string.utils.d.ts +0 -92
  123. package/build/esm/utils/string.utils.js +0 -164
  124. package/build/esm/utils/type.utils.d.ts +0 -89
  125. package/build/esm/utils/type.utils.js +0 -186
  126. package/build/esm/utils/url.utils.d.ts +0 -140
  127. package/build/esm/utils/url.utils.js +0 -303
  128. package/build/esm/utils/validate.utils.d.ts +0 -176
  129. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,152 +0,0 @@
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
- }
12
- /**
13
- * An in-memory cache with time-to-live (TTL) support for each entry.
14
- *
15
- * @typeParam K - Type of the key.
16
- * @typeParam V - Type of the value.
17
- *
18
- * @example
19
- * const cache = new TTLCache<string, number>({ ttlMs: 1000 });
20
- * cache.set("x", 123);
21
- * const value = cache.get("x"); // 123
22
- */
23
- export declare class TTLCache<K, V> {
24
- private cache;
25
- private ttlMs;
26
- private maxSize?;
27
- private cleanupInterval?;
28
- /**
29
- * @param options - Configuration options for the cache
30
- */
31
- constructor(options?: TTLCacheOptions);
32
- /**
33
- * Sets a key-value pair in the cache with the default TTL.
34
- *
35
- * @param key - The key to set.
36
- * @param value - The value to associate with the key.
37
- */
38
- set(key: K, value: V): void;
39
- /**
40
- * Sets a key-value pair in the cache with a custom TTL.
41
- *
42
- * @param key - The key to set.
43
- * @param value - The value to associate with the key.
44
- * @param ttlMs - Time-to-live in milliseconds.
45
- */
46
- setWithTTL(key: K, value: V, ttlMs: number): void;
47
- /**
48
- * Retrieves the value for a given key if it hasn't expired.
49
- *
50
- * @param key - The key to retrieve.
51
- * @returns The cached value, or undefined if not found or expired.
52
- */
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>;
63
- /**
64
- * Checks if the key exists and hasn't expired.
65
- *
66
- * @param key - The key to check.
67
- * @returns `true` if key exists and is valid, otherwise `false`.
68
- */
69
- has(key: K): boolean;
70
- /**
71
- * Deletes a key from the cache.
72
- *
73
- * @param key - The key to delete.
74
- * @returns `true` if the key existed and was removed, `false` otherwise.
75
- */
76
- delete(key: K): boolean;
77
- /**
78
- * Clears all entries from the cache.
79
- */
80
- clear(): void;
81
- /**
82
- * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
83
- *
84
- * @returns Number of items in the cache (may include expired keys).
85
- */
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)[];
100
- /**
101
- * Removes all expired entries from the cache.
102
- *
103
- * @returns Number of entries removed.
104
- */
105
- cleanup(): number;
106
- /**
107
- * Returns an iterator of all current valid [key, value] pairs.
108
- *
109
- * @returns IterableIterator<[K, V]>
110
- */
111
- entries(): IterableIterator<[K, V]>;
112
- /**
113
- * Returns an iterator of all current valid keys.
114
- *
115
- * @returns IterableIterator<K>
116
- */
117
- keys(): IterableIterator<K>;
118
- /**
119
- * Returns an iterator of all current valid values.
120
- *
121
- * @returns IterableIterator<V>
122
- */
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;
152
- }
@@ -1,298 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in all
15
- * copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.
24
- */
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.TTLCache = void 0;
27
- const config_1 = require("../config");
28
- /**
29
- * An in-memory cache with time-to-live (TTL) support for each entry.
30
- *
31
- * @typeParam K - Type of the key.
32
- * @typeParam V - Type of the value.
33
- *
34
- * @example
35
- * const cache = new TTLCache<string, number>({ ttlMs: 1000 });
36
- * cache.set("x", 123);
37
- * const value = cache.get("x"); // 123
38
- */
39
- class TTLCache {
40
- cache = new Map();
41
- ttlMs;
42
- maxSize;
43
- cleanupInterval;
44
- /**
45
- * @param options - Configuration options for the cache
46
- */
47
- constructor(options = {}) {
48
- this.ttlMs = options.ttlMs ?? config_1.config.cache.defaultTtl;
49
- this.maxSize = options.maxSize;
50
- // Setup auto-cleanup if enabled
51
- const autoCleanupMs = options.autoCleanupMs;
52
- if (autoCleanupMs && autoCleanupMs > 0) {
53
- this.cleanupInterval = setInterval(() => {
54
- this.cleanup();
55
- }, autoCleanupMs);
56
- }
57
- }
58
- /**
59
- * Sets a key-value pair in the cache with the default TTL.
60
- *
61
- * @param key - The key to set.
62
- * @param value - The value to associate with the key.
63
- */
64
- set(key, value) {
65
- this.setWithTTL(key, value, this.ttlMs);
66
- }
67
- /**
68
- * Sets a key-value pair in the cache with a custom TTL.
69
- *
70
- * @param key - The key to set.
71
- * @param value - The value to associate with the key.
72
- * @param ttlMs - Time-to-live in milliseconds.
73
- */
74
- setWithTTL(key, value, ttlMs) {
75
- const now = Date.now();
76
- const expiresAt = now + ttlMs;
77
- if (this.cache.has(key)) {
78
- this.cache.delete(key); // remove old entry to maintain LRU order
79
- }
80
- this.cache.set(key, { value, expiresAt, lastAccessed: now });
81
- if (this.maxSize && this.cache.size > this.maxSize) {
82
- this.evictLRU();
83
- }
84
- }
85
- /**
86
- * Retrieves the value for a given key if it hasn't expired.
87
- *
88
- * @param key - The key to retrieve.
89
- * @returns The cached value, or undefined if not found or expired.
90
- */
91
- get(key) {
92
- const entry = this.cache.get(key);
93
- if (!entry)
94
- return undefined;
95
- const now = Date.now();
96
- if (now > entry.expiresAt) {
97
- this.cache.delete(key);
98
- return undefined;
99
- }
100
- // Update lastAccessed and move key to the end (most recently used)
101
- entry.lastAccessed = now;
102
- // Re-insert to end of Map to maintain LRU order
103
- this.cache.delete(key);
104
- this.cache.set(key, entry);
105
- return entry.value;
106
- }
107
- /**
108
- * Retrieves or computes a value if it's not in the cache or has expired.
109
- *
110
- * @param key - The key to retrieve
111
- * @param producer - Function to generate the value if not cached
112
- * @param ttlMs - Optional custom TTL for the computed value
113
- * @returns The cached or computed value
114
- */
115
- async getOrCompute(key, producer, ttlMs) {
116
- const value = this.get(key);
117
- if (value !== undefined)
118
- return value;
119
- const newValue = await producer();
120
- this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);
121
- return newValue;
122
- }
123
- /**
124
- * Checks if the key exists and hasn't expired.
125
- *
126
- * @param key - The key to check.
127
- * @returns `true` if key exists and is valid, otherwise `false`.
128
- */
129
- has(key) {
130
- return this.get(key) !== undefined;
131
- }
132
- /**
133
- * Deletes a key from the cache.
134
- *
135
- * @param key - The key to delete.
136
- * @returns `true` if the key existed and was removed, `false` otherwise.
137
- */
138
- delete(key) {
139
- return this.cache.delete(key);
140
- }
141
- /**
142
- * Clears all entries from the cache.
143
- */
144
- clear() {
145
- this.cache.clear();
146
- }
147
- /**
148
- * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
149
- *
150
- * @returns Number of items in the cache (may include expired keys).
151
- */
152
- size() {
153
- return this.cache.size;
154
- }
155
- /**
156
- * Set multiple key-value pairs at once with the default TTL.
157
- *
158
- * @param entries - Array of [key, value] tuples to set
159
- */
160
- setMany(entries) {
161
- for (const [key, value] of entries) {
162
- this.set(key, value);
163
- }
164
- }
165
- /**
166
- * Get multiple values at once.
167
- *
168
- * @param keys - Array of keys to retrieve
169
- * @returns Array of values (undefined for keys that don't exist or expired)
170
- */
171
- getMany(keys) {
172
- return keys.map(key => this.get(key));
173
- }
174
- /**
175
- * Removes all expired entries from the cache.
176
- *
177
- * @returns Number of entries removed.
178
- */
179
- cleanup() {
180
- let removed = 0;
181
- const now = Date.now();
182
- for (const [key, entry] of this.cache.entries()) {
183
- if (now > entry.expiresAt) {
184
- this.cache.delete(key);
185
- removed++;
186
- }
187
- }
188
- return removed;
189
- }
190
- /**
191
- * Returns an iterator of all current valid [key, value] pairs.
192
- *
193
- * @returns IterableIterator<[K, V]>
194
- */
195
- *entries() {
196
- for (const [key, entry] of this.cache.entries()) {
197
- if (Date.now() <= entry.expiresAt) {
198
- yield [key, entry.value];
199
- }
200
- }
201
- }
202
- /**
203
- * Returns an iterator of all current valid keys.
204
- *
205
- * @returns IterableIterator<K>
206
- */
207
- *keys() {
208
- for (const [key, entry] of this.cache.entries()) {
209
- if (Date.now() <= entry.expiresAt) {
210
- yield key;
211
- }
212
- }
213
- }
214
- /**
215
- * Returns an iterator of all current valid values.
216
- *
217
- * @returns IterableIterator<V>
218
- */
219
- *values() {
220
- for (const entry of this.cache.values()) {
221
- if (Date.now() <= entry.expiresAt) {
222
- yield entry.value;
223
- }
224
- }
225
- }
226
- /**
227
- * Extends the expiration of a key by the specified time or default TTL.
228
- *
229
- * @param key - The key to refresh
230
- * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)
231
- * @returns true if the key was found and refreshed, false otherwise
232
- */
233
- refresh(key, ttlMs) {
234
- const entry = this.cache.get(key);
235
- if (!entry)
236
- return false;
237
- const now = Date.now();
238
- if (now > entry.expiresAt) {
239
- this.cache.delete(key);
240
- return false;
241
- }
242
- entry.expiresAt = now + (ttlMs ?? this.ttlMs);
243
- entry.lastAccessed = now;
244
- return true;
245
- }
246
- /**
247
- * Returns a snapshot of cache stats.
248
- *
249
- * @returns Object containing cache statistics
250
- */
251
- stats() {
252
- const now = Date.now();
253
- let expired = 0;
254
- let valid = 0;
255
- for (const entry of this.cache.values()) {
256
- if (now > entry.expiresAt) {
257
- expired++;
258
- }
259
- else {
260
- valid++;
261
- }
262
- }
263
- return {
264
- size: this.cache.size,
265
- validEntries: valid,
266
- expiredEntries: expired,
267
- maxSize: this.maxSize
268
- };
269
- }
270
- /**
271
- * Stop the auto-cleanup interval if it's running.
272
- */
273
- destroy() {
274
- if (this.cleanupInterval) {
275
- clearInterval(this.cleanupInterval);
276
- this.cleanupInterval = undefined;
277
- }
278
- }
279
- /**
280
- * Evict the least recently used entry from the cache.
281
- * @private
282
- */
283
- evictLRU() {
284
- const now = Date.now();
285
- // Remove all expired items first
286
- for (const [key, entry] of Array.from(this.cache.entries())) {
287
- if (now > entry.expiresAt) {
288
- this.cache.delete(key);
289
- }
290
- }
291
- // Evict oldest entries until within max size
292
- while (this.maxSize && this.cache.size > this.maxSize) {
293
- const oldestKey = this.cache.keys().next().value;
294
- this.cache.delete(oldestKey);
295
- }
296
- }
297
- }
298
- exports.TTLCache = TTLCache;
@@ -1,188 +0,0 @@
1
- import { AsyncLocalStorage } from 'async_hooks';
2
- /**
3
- * Type representing the store object used in AsyncLocalStorage.
4
- * Keys must be unique symbols to ensure isolation and prevent collisions.
5
- */
6
- export interface Store {
7
- [key: symbol]: unknown;
8
- }
9
- /**
10
- * Predefined symbols used as keys in AsyncLocalStorage.
11
- * Add new symbols here to avoid duplication.
12
- */
13
- export declare const StoreKeys: {
14
- LOGGER: symbol;
15
- REQUEST_ID: symbol;
16
- USER: symbol;
17
- SESSION: symbol;
18
- TRANSACTION_ID: symbol;
19
- USER_ID: symbol;
20
- TENANT_ID: symbol;
21
- TRACE_ID: symbol;
22
- CORRELATION_ID: symbol;
23
- };
24
- /**
25
- * Retrieves the current request ID from the async context, if available.
26
- *
27
- * @returns {string | undefined} The request ID string or undefined if not present in the current context.
28
- */
29
- export declare function getRequestId(): string | undefined;
30
- /**
31
- * Type-safe getter for common context values.
32
- *
33
- * @param key The store key symbol
34
- * @returns The typed value from the store
35
- */
36
- export declare function getFromContext<T>(key: symbol): T | undefined;
37
- /**
38
- * ContextStore manages per-request scoped context using AsyncLocalStorage.
39
- * It allows storing and retrieving data across async calls (e.g., request ID, logger).
40
- *
41
- * Example (Express middleware):
42
- * ```
43
- * // Middleware to initialize context and logger
44
- * app.use((req, res, next) => {
45
- * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
46
- * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
47
- * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
48
- * next();
49
- * });
50
- * });
51
- * ```
52
- */
53
- export declare class ContextStore {
54
- /**
55
- * The underlying AsyncLocalStorage instance for context.
56
- * @private
57
- */
58
- private static readonly storage;
59
- /**
60
- * Returns the raw AsyncLocalStorage instance for advanced access.
61
- *
62
- * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
63
- */
64
- static getInstance(): AsyncLocalStorage<Store>;
65
- /**
66
- * Retrieves a value from the async context store by symbol key.
67
- *
68
- * @typeParam T - The expected return type of the value.
69
- * @param {symbol} key - Unique symbol used as the store key.
70
- * @returns {T | undefined} The value found (typed) or undefined if not present.
71
- */
72
- static get<T>(key: symbol): T | undefined;
73
- /**
74
- * Sets a value in the current context store by symbol key.
75
- *
76
- * @typeParam T - The value type to set.
77
- * @param {symbol} key - Unique symbol key.
78
- * @param {T} value - Value to set in context.
79
- * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
80
- */
81
- static set<T>(key: symbol, value: T): void;
82
- /**
83
- * Retrieves the entire context store object for the current async context.
84
- *
85
- * @returns {Store | undefined} The current store object or undefined if called outside a context.
86
- */
87
- static getAll(): Store | undefined;
88
- /**
89
- * Initializes a new async context and executes a callback within it.
90
- * This must be called at the beginning of a request or logical async flow.
91
- *
92
- * @typeParam T - The callback's return type.
93
- * @param {Store} store - The initial key-value store object.
94
- * @param {() => T} callback - The function to run within the new context.
95
- * @returns {T} The result of the callback function.
96
- */
97
- static run<T>(store: Store, callback: () => T): T;
98
- /**
99
- * Checks if a key exists in the current context store.
100
- *
101
- * @param {symbol} key - The symbol key to check.
102
- * @returns {boolean} True if the key exists, false otherwise.
103
- */
104
- static has(key: symbol): boolean;
105
- /**
106
- * Removes a value from the current context store by symbol key.
107
- *
108
- * @param {symbol} key - The symbol key to delete.
109
- * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
110
- * @throws {Error} If called outside an active context.
111
- */
112
- static delete(key: symbol): boolean;
113
- /**
114
- * Updates multiple values in the current context store at once.
115
- *
116
- * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
117
- * @throws {Error} If called outside an active context.
118
- */
119
- static patch(values: Partial<Record<symbol, unknown>>): void;
120
- /**
121
- * Executes a callback with a temporary store value that only exists during execution.
122
- * Original store is restored after callback completes.
123
- *
124
- * @typeParam T - The callback's return type.
125
- * @param {symbol} key - The symbol key to temporarily set.
126
- * @param {unknown} value - The temporary value.
127
- * @param {() => T} callback - The function to execute with the temporary value.
128
- * @returns {T} The result of the callback function.
129
- * @throws {Error} If called outside an active context.
130
- */
131
- static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
132
- /**
133
- * Creates a new context that inherits values from the current context.
134
- *
135
- * @typeParam T - The callback's return type.
136
- * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
137
- * @param {() => T} callback - The function to execute in the new context.
138
- * @returns {T} The result of the callback function.
139
- */
140
- static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
141
- /**
142
- * Creates Express middleware that initializes a context for each request.
143
- *
144
- * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
145
- * @returns Express middleware function.
146
- */
147
- static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, _res: any, next: any) => void;
148
- }
149
- /**
150
- * Type-safe wrapper for accessing and modifying context values with specific types.
151
- *
152
- * @typeParam T - The value type.
153
- */
154
- export declare class TypedContextKey<T> {
155
- private symbol;
156
- private defaultValue?;
157
- /**
158
- * Creates a new typed context key.
159
- *
160
- * @param symbol - The unique symbol for this key
161
- * @param defaultValue - Optional default value if key is not found
162
- */
163
- constructor(symbol: symbol, defaultValue?: T | undefined);
164
- /**
165
- * Gets the current value for this key.
166
- *
167
- * @returns The value or defaultValue if not found
168
- */
169
- get(): T | undefined;
170
- /**
171
- * Sets the value for this key.
172
- *
173
- * @param value The value to set
174
- */
175
- set(value: T): void;
176
- /**
177
- * Checks if this key exists in the context.
178
- *
179
- * @returns True if the key exists
180
- */
181
- exists(): boolean;
182
- /**
183
- * Deletes this key from the context.
184
- *
185
- * @returns True if the key was deleted
186
- */
187
- delete(): boolean;
188
- }