@catbee/utils 1.1.0 → 2.0.0-next.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 (90) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +79 -43
  3. package/array/index.cjs +355 -0
  4. package/array/index.d.ts +317 -0
  5. package/array/index.mjs +327 -0
  6. package/async/index.cjs +484 -0
  7. package/async/index.d.ts +299 -0
  8. package/async/index.mjs +463 -0
  9. package/cache/index.cjs +292 -0
  10. package/cache/index.d.ts +179 -0
  11. package/cache/index.mjs +290 -0
  12. package/config/index.cjs +150 -0
  13. package/config/index.d.ts +88 -0
  14. package/config/index.mjs +143 -0
  15. package/context-store/index.cjs +267 -0
  16. package/context-store/index.d.ts +216 -0
  17. package/context-store/index.mjs +261 -0
  18. package/crypto/index.cjs +182 -0
  19. package/crypto/index.d.ts +187 -0
  20. package/crypto/index.mjs +166 -0
  21. package/date/index.cjs +340 -0
  22. package/date/index.d.ts +214 -0
  23. package/date/index.mjs +326 -0
  24. package/decorators/index.cjs +2051 -0
  25. package/decorators/index.d.ts +708 -0
  26. package/decorators/index.mjs +2010 -0
  27. package/dir/index.cjs +417 -0
  28. package/dir/index.d.ts +219 -0
  29. package/dir/index.mjs +390 -0
  30. package/env/index.cjs +745 -0
  31. package/env/index.d.ts +403 -0
  32. package/env/index.mjs +742 -0
  33. package/exception/index.cjs +362 -0
  34. package/exception/index.d.ts +256 -0
  35. package/exception/index.mjs +338 -0
  36. package/fs/index.cjs +287 -0
  37. package/fs/index.d.ts +229 -0
  38. package/fs/index.mjs +258 -0
  39. package/http-status-codes/index.cjs +96 -0
  40. package/http-status-codes/index.d.ts +291 -0
  41. package/http-status-codes/index.mjs +94 -0
  42. package/id/index.cjs +62 -0
  43. package/id/index.d.ts +61 -0
  44. package/id/index.mjs +56 -0
  45. package/index.cjs +218 -0
  46. package/index.d.ts +51 -0
  47. package/index.mjs +51 -0
  48. package/logger/index.cjs +334 -0
  49. package/logger/index.d.ts +213 -0
  50. package/logger/index.mjs +313 -0
  51. package/middleware/index.cjs +177 -0
  52. package/middleware/index.d.ts +127 -0
  53. package/middleware/index.mjs +170 -0
  54. package/obj/index.cjs +305 -0
  55. package/obj/index.d.ts +160 -0
  56. package/obj/index.mjs +289 -0
  57. package/package.json +172 -20
  58. package/performance/index.cjs +231 -0
  59. package/performance/index.d.ts +162 -0
  60. package/performance/index.mjs +225 -0
  61. package/request/index.cjs +202 -0
  62. package/request/index.d.ts +265 -0
  63. package/request/index.mjs +194 -0
  64. package/response/index.cjs +234 -0
  65. package/response/index.d.ts +342 -0
  66. package/response/index.mjs +222 -0
  67. package/server/index.cjs +1631 -0
  68. package/server/index.d.ts +809 -0
  69. package/server/index.mjs +1622 -0
  70. package/stream/index.cjs +151 -0
  71. package/stream/index.d.ts +114 -0
  72. package/stream/index.mjs +144 -0
  73. package/string/index.cjs +109 -0
  74. package/string/index.d.ts +126 -0
  75. package/string/index.mjs +95 -0
  76. package/type/index.cjs +129 -0
  77. package/type/index.d.ts +131 -0
  78. package/type/index.mjs +119 -0
  79. package/types/index.cjs +34 -0
  80. package/types/index.d.ts +798 -0
  81. package/types/index.mjs +32 -0
  82. package/url/index.cjs +199 -0
  83. package/url/index.d.ts +166 -0
  84. package/url/index.mjs +187 -0
  85. package/validation/index.cjs +259 -0
  86. package/validation/index.d.ts +209 -0
  87. package/validation/index.mjs +231 -0
  88. package/build/index.cjs +0 -7694
  89. package/build/index.d.ts +0 -5792
  90. package/build/index.mjs +0 -7386
@@ -0,0 +1,267 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ var async_hooks = require('async_hooks');
28
+
29
+ var __defProp = Object.defineProperty;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ var StoreKeys = {
32
+ LOGGER: Symbol("LOGGER"),
33
+ REQUEST_ID: Symbol("REQUEST_ID"),
34
+ USER: Symbol("USER"),
35
+ SESSION: Symbol("SESSION"),
36
+ TRANSACTION_ID: Symbol("TRANSACTION_ID"),
37
+ USER_ID: Symbol("USER_ID"),
38
+ TENANT_ID: Symbol("TENANT_ID"),
39
+ TRACE_ID: Symbol("TRACE_ID"),
40
+ CORRELATION_ID: Symbol("CORRELATION_ID")
41
+ };
42
+ function getRequestId() {
43
+ return ContextStore.get(StoreKeys.REQUEST_ID);
44
+ }
45
+ __name(getRequestId, "getRequestId");
46
+ function getFromContext(key) {
47
+ return ContextStore.get(key);
48
+ }
49
+ __name(getFromContext, "getFromContext");
50
+ var ContextStore = class _ContextStore {
51
+ static {
52
+ __name(this, "ContextStore");
53
+ }
54
+ /**
55
+ * The underlying AsyncLocalStorage instance for context.
56
+ * @private
57
+ */
58
+ static storage = new async_hooks.AsyncLocalStorage();
59
+ /**
60
+ * Returns the raw AsyncLocalStorage instance for advanced access.
61
+ *
62
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
63
+ */
64
+ static getInstance() {
65
+ return this.storage;
66
+ }
67
+ /**
68
+ * Retrieves a value from the async context store by symbol key.
69
+ *
70
+ * @typeParam T - The expected return type of the value.
71
+ * @param {symbol} key - Unique symbol used as the store key.
72
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
73
+ */
74
+ static get(key) {
75
+ const store = this.storage.getStore();
76
+ return store?.[key];
77
+ }
78
+ /**
79
+ * Sets a value in the current context store by symbol key.
80
+ *
81
+ * @typeParam T - The value type to set.
82
+ * @param {symbol} key - Unique symbol key.
83
+ * @param {T} value - Value to set in context.
84
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
85
+ */
86
+ static set(key, value) {
87
+ const store = this.storage.getStore();
88
+ if (!store) {
89
+ throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);
90
+ }
91
+ store[key] = value;
92
+ }
93
+ /**
94
+ * Retrieves the entire context store object for the current async context.
95
+ *
96
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
97
+ */
98
+ static getAll() {
99
+ return this.storage.getStore();
100
+ }
101
+ /**
102
+ * Initializes a new async context and executes a callback within it.
103
+ * This must be called at the beginning of a request or logical async flow.
104
+ *
105
+ * @typeParam T - The callback's return type.
106
+ * @param {Store} store - The initial key-value store object.
107
+ * @param {() => T} callback - The function to run within the new context.
108
+ * @returns {T} The result of the callback function.
109
+ */
110
+ static run(store, callback) {
111
+ return this.storage.run(store, callback);
112
+ }
113
+ /**
114
+ * Checks if a key exists in the current context store.
115
+ *
116
+ * @param {symbol} key - The symbol key to check.
117
+ * @returns {boolean} True if the key exists, false otherwise.
118
+ */
119
+ static has(key) {
120
+ const store = this.storage.getStore();
121
+ return store !== void 0 && key in store;
122
+ }
123
+ /**
124
+ * Removes a value from the current context store by symbol key.
125
+ *
126
+ * @param {symbol} key - The symbol key to delete.
127
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
128
+ * @throws {Error} If called outside an active context.
129
+ */
130
+ static delete(key) {
131
+ const store = this.storage.getStore();
132
+ if (!store) {
133
+ throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
134
+ }
135
+ return delete store[key];
136
+ }
137
+ /**
138
+ * Updates multiple values in the current context store at once.
139
+ *
140
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
141
+ * @throws {Error} If called outside an active context.
142
+ */
143
+ static patch(values) {
144
+ const store = this.storage.getStore();
145
+ if (!store) {
146
+ throw new Error("Failed to patch: AsyncLocalStorage store is not initialized.");
147
+ }
148
+ Object.getOwnPropertySymbols(values).forEach((key) => {
149
+ store[key] = values[key];
150
+ });
151
+ }
152
+ /**
153
+ * Executes a callback with a temporary store value that only exists during execution.
154
+ * Original store is restored after callback completes.
155
+ *
156
+ * @typeParam T - The callback's return type.
157
+ * @param {symbol} key - The symbol key to temporarily set.
158
+ * @param {unknown} value - The temporary value.
159
+ * @param {() => T} callback - The function to execute with the temporary value.
160
+ * @returns {T} The result of the callback function.
161
+ * @throws {Error} If called outside an active context.
162
+ */
163
+ static withValue(key, value, callback) {
164
+ const store = this.storage.getStore();
165
+ if (!store) {
166
+ throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
167
+ }
168
+ const hasOriginal = key in store;
169
+ const originalValue = store[key];
170
+ store[key] = value;
171
+ try {
172
+ return callback();
173
+ } finally {
174
+ if (hasOriginal) {
175
+ store[key] = originalValue;
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
+ const newStore = {
192
+ ...currentStore
193
+ };
194
+ Object.getOwnPropertySymbols(newValues).forEach((key) => {
195
+ newStore[key] = newValues[key];
196
+ });
197
+ return this.storage.run(newStore, callback);
198
+ }
199
+ /**
200
+ * Creates Express middleware that initializes a context for each request.
201
+ *
202
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
203
+ * @returns Express middleware function.
204
+ */
205
+ static createExpressMiddleware(initialValuesFactory = () => ({})) {
206
+ return (req, _res, next) => {
207
+ const initialValues = initialValuesFactory(req);
208
+ _ContextStore.run(initialValues, next);
209
+ };
210
+ }
211
+ };
212
+ var TypedContextKey = class {
213
+ static {
214
+ __name(this, "TypedContextKey");
215
+ }
216
+ symbol;
217
+ defaultValue;
218
+ /**
219
+ * Creates a new typed context key.
220
+ *
221
+ * @param symbol - The unique symbol for this key
222
+ * @param defaultValue - Optional default value if key is not found
223
+ */
224
+ constructor(symbol, defaultValue) {
225
+ this.symbol = symbol;
226
+ this.defaultValue = defaultValue;
227
+ }
228
+ /**
229
+ * Gets the current value for this key.
230
+ *
231
+ * @returns The value or defaultValue if not found
232
+ */
233
+ get() {
234
+ const value = ContextStore.get(this.symbol);
235
+ return value !== void 0 ? value : this.defaultValue;
236
+ }
237
+ /**
238
+ * Sets the value for this key.
239
+ *
240
+ * @param value The value to set
241
+ */
242
+ set(value) {
243
+ ContextStore.set(this.symbol, value);
244
+ }
245
+ /**
246
+ * Checks if this key exists in the context.
247
+ *
248
+ * @returns True if the key exists
249
+ */
250
+ exists() {
251
+ return ContextStore.has(this.symbol);
252
+ }
253
+ /**
254
+ * Deletes this key from the context.
255
+ *
256
+ * @returns True if the key was deleted
257
+ */
258
+ delete() {
259
+ return ContextStore.delete(this.symbol);
260
+ }
261
+ };
262
+
263
+ exports.ContextStore = ContextStore;
264
+ exports.StoreKeys = StoreKeys;
265
+ exports.TypedContextKey = TypedContextKey;
266
+ exports.getFromContext = getFromContext;
267
+ exports.getRequestId = getRequestId;
@@ -0,0 +1,216 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { AsyncLocalStorage } from 'node:async_hooks';
26
+
27
+ /**
28
+ * Type representing the store object used in AsyncLocalStorage.
29
+ * Keys must be unique symbols to ensure isolation and prevent collisions.
30
+ */
31
+ interface Store {
32
+ [key: symbol]: unknown;
33
+ }
34
+ /**
35
+ * Predefined symbols used as keys in AsyncLocalStorage.
36
+ * Add new symbols here to avoid duplication.
37
+ */
38
+ declare const StoreKeys: {
39
+ LOGGER: symbol;
40
+ REQUEST_ID: symbol;
41
+ USER: symbol;
42
+ SESSION: symbol;
43
+ TRANSACTION_ID: symbol;
44
+ USER_ID: symbol;
45
+ TENANT_ID: symbol;
46
+ TRACE_ID: symbol;
47
+ CORRELATION_ID: symbol;
48
+ };
49
+ /**
50
+ * Retrieves the current request ID from the async context, if available.
51
+ *
52
+ * @returns {string | undefined} The request ID string or undefined if not present in the current context.
53
+ */
54
+ declare function getRequestId(): string | undefined;
55
+ /**
56
+ * Type-safe getter for common context values.
57
+ *
58
+ * @param key The store key symbol
59
+ * @returns The typed value from the store
60
+ */
61
+ declare function getFromContext<T>(key: symbol): T | undefined;
62
+ /**
63
+ * ContextStore manages per-request scoped context using AsyncLocalStorage.
64
+ * It allows storing and retrieving data across async calls (e.g., request ID, logger).
65
+ *
66
+ * Example (Express middleware):
67
+ * ```
68
+ * // Middleware to initialize context and logger
69
+ * app.use((req, res, next) => {
70
+ * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
71
+ * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
72
+ * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
73
+ * next();
74
+ * });
75
+ * });
76
+ * ```
77
+ */
78
+ declare class ContextStore {
79
+ /**
80
+ * The underlying AsyncLocalStorage instance for context.
81
+ * @private
82
+ */
83
+ private static readonly storage;
84
+ /**
85
+ * Returns the raw AsyncLocalStorage instance for advanced access.
86
+ *
87
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
88
+ */
89
+ static getInstance(): AsyncLocalStorage<Store>;
90
+ /**
91
+ * Retrieves a value from the async context store by symbol key.
92
+ *
93
+ * @typeParam T - The expected return type of the value.
94
+ * @param {symbol} key - Unique symbol used as the store key.
95
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
96
+ */
97
+ static get<T>(key: symbol): T | undefined;
98
+ /**
99
+ * Sets a value in the current context store by symbol key.
100
+ *
101
+ * @typeParam T - The value type to set.
102
+ * @param {symbol} key - Unique symbol key.
103
+ * @param {T} value - Value to set in context.
104
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
105
+ */
106
+ static set<T>(key: symbol, value: T): void;
107
+ /**
108
+ * Retrieves the entire context store object for the current async context.
109
+ *
110
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
111
+ */
112
+ static getAll(): Store | undefined;
113
+ /**
114
+ * Initializes a new async context and executes a callback within it.
115
+ * This must be called at the beginning of a request or logical async flow.
116
+ *
117
+ * @typeParam T - The callback's return type.
118
+ * @param {Store} store - The initial key-value store object.
119
+ * @param {() => T} callback - The function to run within the new context.
120
+ * @returns {T} The result of the callback function.
121
+ */
122
+ static run<T>(store: Store, callback: () => T): T;
123
+ /**
124
+ * Checks if a key exists in the current context store.
125
+ *
126
+ * @param {symbol} key - The symbol key to check.
127
+ * @returns {boolean} True if the key exists, false otherwise.
128
+ */
129
+ static has(key: symbol): boolean;
130
+ /**
131
+ * Removes a value from the current context store by symbol key.
132
+ *
133
+ * @param {symbol} key - The symbol key to delete.
134
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
135
+ * @throws {Error} If called outside an active context.
136
+ */
137
+ static delete(key: symbol): boolean;
138
+ /**
139
+ * Updates multiple values in the current context store at once.
140
+ *
141
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
142
+ * @throws {Error} If called outside an active context.
143
+ */
144
+ static patch(values: Partial<Record<symbol, unknown>>): void;
145
+ /**
146
+ * Executes a callback with a temporary store value that only exists during execution.
147
+ * Original store is restored after callback completes.
148
+ *
149
+ * @typeParam T - The callback's return type.
150
+ * @param {symbol} key - The symbol key to temporarily set.
151
+ * @param {unknown} value - The temporary value.
152
+ * @param {() => T} callback - The function to execute with the temporary value.
153
+ * @returns {T} The result of the callback function.
154
+ * @throws {Error} If called outside an active context.
155
+ */
156
+ static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
157
+ /**
158
+ * Creates a new context that inherits values from the current context.
159
+ *
160
+ * @typeParam T - The callback's return type.
161
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
162
+ * @param {() => T} callback - The function to execute in the new context.
163
+ * @returns {T} The result of the callback function.
164
+ */
165
+ static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
166
+ /**
167
+ * Creates Express middleware that initializes a context for each request.
168
+ *
169
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
170
+ * @returns Express middleware function.
171
+ */
172
+ static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, _res: any, next: any) => void;
173
+ }
174
+ /**
175
+ * Type-safe wrapper for accessing and modifying context values with specific types.
176
+ *
177
+ * @typeParam T - The value type.
178
+ */
179
+ declare class TypedContextKey<T> {
180
+ private readonly symbol;
181
+ private readonly defaultValue?;
182
+ /**
183
+ * Creates a new typed context key.
184
+ *
185
+ * @param symbol - The unique symbol for this key
186
+ * @param defaultValue - Optional default value if key is not found
187
+ */
188
+ constructor(symbol: symbol, defaultValue?: T | undefined);
189
+ /**
190
+ * Gets the current value for this key.
191
+ *
192
+ * @returns The value or defaultValue if not found
193
+ */
194
+ get(): T | undefined;
195
+ /**
196
+ * Sets the value for this key.
197
+ *
198
+ * @param value The value to set
199
+ */
200
+ set(value: T): void;
201
+ /**
202
+ * Checks if this key exists in the context.
203
+ *
204
+ * @returns True if the key exists
205
+ */
206
+ exists(): boolean;
207
+ /**
208
+ * Deletes this key from the context.
209
+ *
210
+ * @returns True if the key was deleted
211
+ */
212
+ delete(): boolean;
213
+ }
214
+
215
+ export { ContextStore, StoreKeys, TypedContextKey, getFromContext, getRequestId };
216
+ export type { Store };