@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,243 +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.requestId = requestId;
27
- exports.responseTime = responseTime;
28
- exports.timeout = timeout;
29
- exports.setupRequestContext = setupRequestContext;
30
- exports.errorHandler = errorHandler;
31
- exports.healthCheck = healthCheck;
32
- const id_utils_1 = require("./id.utils");
33
- const http_status_codes_1 = require("./http-status-codes");
34
- const response_utils_1 = require("./response.utils");
35
- const logger_utils_1 = require("./logger.utils");
36
- const context_store_utils_1 = require("./context-store.utils");
37
- const exception_utils_1 = require("./exception.utils");
38
- /**
39
- * Attaches a unique request ID to each request.
40
- * Useful for request tracing and correlation between logs.
41
- *
42
- * @param {object} [options] - Configuration options
43
- * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
44
- * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
45
- * @param {() => string} [options.generator] - Custom ID generator function
46
- * @returns {Middleware} Express-compatible middleware
47
- */
48
- function requestId(options) {
49
- const headerName = options?.headerName || 'X-Request-ID';
50
- const exposeHeader = options?.exposeHeader !== false;
51
- const generateId = options?.generator || id_utils_1.uuid;
52
- return (req, res, next) => {
53
- // Use existing request ID from header or generate a new one
54
- const existingId = req.headers[headerName.toLowerCase()];
55
- const id = existingId || generateId();
56
- // Attach ID to request object
57
- req.id = id;
58
- // Add ID to response headers
59
- if (exposeHeader) {
60
- res.setHeader(headerName, id);
61
- }
62
- next();
63
- };
64
- }
65
- /**
66
- * Measures request processing time and logs or adds it to response headers.
67
- *
68
- * @param {object} [options] - Configuration options
69
- * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
70
- * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
71
- * @returns {Middleware} Express-compatible middleware
72
- */
73
- function responseTime(options) {
74
- const addHeader = options?.addHeader !== false;
75
- const logOnComplete = options?.logOnComplete === true;
76
- return (req, res, next) => {
77
- const start = process.hrtime();
78
- // Function to calculate duration
79
- const getDuration = () => {
80
- const diff = process.hrtime(start);
81
- return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
82
- };
83
- if (addHeader) {
84
- // Ensure header is set before response is sent
85
- const originalWriteHead = res.writeHead;
86
- res.writeHead = function (...args) {
87
- res.setHeader('X-Response-Time', `${getDuration()}ms`);
88
- return originalWriteHead.apply(this, args);
89
- };
90
- }
91
- if (logOnComplete) {
92
- res.on('finish', () => {
93
- (0, logger_utils_1.getLogger)().info(`${req.method} ${req.url} - ${getDuration()}ms`);
94
- });
95
- }
96
- next();
97
- };
98
- }
99
- /**
100
- * Request timeout middleware.
101
- * Aborts requests that take too long to process.
102
- *
103
- * @param {number} [timeoutMs=30000] - Timeout in milliseconds
104
- * @returns {Middleware} Express-compatible middleware
105
- */
106
- function timeout(timeoutMs = 30000) {
107
- return (_req, res, next) => {
108
- // Set timeout for the request
109
- const timer = setTimeout(() => {
110
- const response = new exception_utils_1.RequestTimeoutException('Request timed out');
111
- res.status(http_status_codes_1.HttpStatusCodes.REQUEST_TIMEOUT).json(response);
112
- }, timeoutMs);
113
- // Clear timeout when response is sent
114
- res.on('finish', () => {
115
- clearTimeout(timer);
116
- });
117
- next();
118
- };
119
- }
120
- /**
121
- * Creates an Express middleware that initializes a per-request context.
122
- *
123
- * @param {object} [options] - Optional configuration
124
- * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
125
- * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
126
- * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
127
- */
128
- function setupRequestContext(options = {}) {
129
- const { headerName = 'x-request-id', autoLog = true } = options;
130
- return (req, _res, next) => {
131
- // Generate or use existing request ID
132
- const requestId = req.headers[headerName] || req?.['id'] || (0, id_utils_1.uuid)();
133
- context_store_utils_1.ContextStore.run({ [context_store_utils_1.StoreKeys.REQUEST_ID]: requestId }, () => {
134
- // Create a child logger for this request
135
- const childLogger = (0, logger_utils_1.getLogger)().child({
136
- requestId,
137
- method: req.method,
138
- url: req.originalUrl || req.url
139
- });
140
- req.logger = childLogger;
141
- // Store logger in context
142
- context_store_utils_1.ContextStore.set(context_store_utils_1.StoreKeys.LOGGER, childLogger);
143
- if (autoLog) {
144
- req.logger.info('Request context initialized');
145
- }
146
- next();
147
- });
148
- };
149
- }
150
- /**
151
- * Global error handling middleware with enhanced features.
152
- *
153
- * @param {ErrorHandlerOptions} options - Error handler options
154
- * @param {boolean} [options.logErrors=true] - Whether to log errors
155
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
156
- * @returns Error middleware
157
- *
158
- * @example
159
- * import express from 'express';
160
- * import { errorHandler } from '@catbee/utils';
161
- *
162
- * const app = express();
163
- *
164
- * // Your routes
165
- * app.get('/ping', (req, res) => {
166
- * throw new Error('Something went wrong');
167
- * });
168
- *
169
- * // Error handler (must be last middleware)
170
- * app.use(errorHandler({ includeDetails: true }));
171
- *
172
- * app.listen(3000, () => {
173
- * console.log('Server running on port 3000');
174
- * });
175
- */
176
- function errorHandler(options) {
177
- const logErrors = options?.logErrors !== false;
178
- const includeDetails = options?.includeDetails === true;
179
- return (err, req, res, _next) => {
180
- // Determine status code
181
- const status = err?.status || err?.statusCode || http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR;
182
- // Log error if enabled
183
- if (logErrors) {
184
- (0, logger_utils_1.getLogger)().error({ err }, `${err.message || 'Unknown error'}`);
185
- }
186
- // Handle ErrorResponse instances (our custom error class)
187
- if (err instanceof response_utils_1.ErrorResponse) {
188
- const result = {
189
- error: true,
190
- message: err.message,
191
- timestamp: err.timestamp,
192
- requestId: err?.requestId || req?.id || (0, id_utils_1.uuid)(),
193
- status,
194
- path: req.originalUrl || req.url
195
- };
196
- if (includeDetails && err?.stack) {
197
- result.stack = err.stack.split('\n').map((line) => line.trim());
198
- }
199
- return res.status(status).json(result);
200
- }
201
- // Handle any other errors
202
- return res
203
- .status(status)
204
- .json((0, response_utils_1.createFinalErrorResponse)(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));
205
- };
206
- }
207
- /**
208
- * Health check middleware for service status and custom checks.
209
- *
210
- * @param {object} [options] - Health check options
211
- * @param {string} [options.path='/healthz'] - Health check endpoint path
212
- * @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
213
- * @param {boolean} [options.detailed=true] - Show detailed check results
214
- * @returns {Middleware} Express-compatible middleware
215
- */
216
- function healthCheck(options) {
217
- const path = options?.path || '/healthz';
218
- const checks = options?.checks || [];
219
- const detailed = options?.detailed !== false;
220
- return async (req, res, next) => {
221
- if (req.path !== path)
222
- return next();
223
- const results = {};
224
- let allHealthy = true;
225
- for (const check of checks) {
226
- try {
227
- const result = await Promise.resolve(check.check());
228
- results[check.name] = !!result;
229
- if (!result)
230
- allHealthy = false;
231
- }
232
- catch {
233
- results[check.name] = false;
234
- allHealthy = false;
235
- }
236
- }
237
- const status = allHealthy ? http_status_codes_1.HttpStatusCodes.OK : http_status_codes_1.HttpStatusCodes.SERVICE_UNAVAILABLE;
238
- const response = detailed
239
- ? { status: allHealthy ? 'ok' : 'unhealthy', checks: results, timestamp: new Date().toISOString() }
240
- : { status: allHealthy ? 'ok' : 'unhealthy' };
241
- res.status(status).json(response);
242
- };
243
- }
@@ -1,123 +0,0 @@
1
- /**
2
- * Checks whether the object has no own enumerable properties.
3
- *
4
- * @param {Record<any, any>} obj - The object to check.
5
- * @returns {boolean} True if the object is empty, false otherwise.
6
- */
7
- export declare function isObjEmpty(obj: Record<any, any>): boolean;
8
- /**
9
- * Returns a new object with only the specified keys picked.
10
- *
11
- * @template T
12
- * @template K
13
- * @param {T} obj - The source object.
14
- * @param {K[]} keys - Keys to pick from the object.
15
- * @returns {Pick<T, K>} New object with picked keys.
16
- */
17
- export declare function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
18
- /**
19
- * Returns a new object with the specified keys omitted.
20
- *
21
- * @template T
22
- * @template K
23
- * @param {T} obj - The source object.
24
- * @param {K[]} keys - Keys to omit from the object.
25
- * @returns {Omit<T, K>} New object without omitted keys.
26
- */
27
- export declare function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
28
- /**
29
- * Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).
30
- *
31
- * @template T
32
- * @param {T} target - The object to merge into (will be mutated).
33
- * @param {...any[]} sources - The objects to merge from.
34
- * @returns {T} The merged object (same as target).
35
- */
36
- export declare function deepObjMerge<T extends object>(target: T, ...sources: any[]): T;
37
- /**
38
- * Checks if a value is a plain object (i.e., not an array, null, or a built-in object).
39
- *
40
- * @param value - The value to check.
41
- * @returns True if the value is a plain object, false otherwise.
42
- */
43
- export declare function isPlainObject(value: any): value is Record<string, any>;
44
- /**
45
- * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ "a.b": 1 }`).
46
- *
47
- * @template T
48
- * @param {T} obj - The object to flatten.
49
- * @param {string} [prefix=""] - Optional prefix for nested keys (used internally).
50
- * @returns {Record<string, any>} A new object with flattened keys.
51
- */
52
- export declare function flattenObject<T extends Record<string, any>>(obj: T, prefix?: string): Record<string, any>;
53
- /**
54
- * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.
55
- *
56
- * @template T
57
- * @param {T} obj - The object to extract from.
58
- * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
59
- * @returns {any} The value at the given path, or undefined if not found.
60
- */
61
- export declare function getValueByPath<T extends object>(obj: T, path: string): any;
62
- /**
63
- * Sets a value at a deeply nested key in an object using dot/bracket notation path.
64
- * Creates intermediate objects and arrays as needed.
65
- *
66
- * @template T
67
- * @param {T} obj - The object to modify.
68
- * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
69
- * @param {any} value - The value to set at the path.
70
- * @returns {T} The modified object.
71
- */
72
- export declare function setValueByPath<T extends object>(obj: T, path: string, value: any): T;
73
- /**
74
- * Performs a deep equality check between two objects.
75
- *
76
- * @param {any} a - First value to compare.
77
- * @param {any} b - Second value to compare.
78
- * @returns {boolean} True if values are deeply equal.
79
- */
80
- export declare function isEqual(a: any, b: any): boolean;
81
- /**
82
- * Filters object properties based on a predicate function.
83
- *
84
- * @template T
85
- * @param {T} obj - The source object.
86
- * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.
87
- * @returns {Partial<T>} New object with filtered properties.
88
- */
89
- export declare function filterObject<T extends object>(obj: T, predicate: (value: any, key: string, obj: T) => boolean): Partial<T>;
90
- /**
91
- * Maps object values to new values using a mapping function.
92
- *
93
- * @template T
94
- * @template U
95
- * @param {T} obj - The source object.
96
- * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.
97
- * @returns {Record<keyof T, U>} New object with mapped values.
98
- */
99
- export declare function mapObject<T extends object, U>(obj: T, mapFn: (value: any, key: string, obj: T) => U): Record<keyof T, U>;
100
- /**
101
- * Recursively freezes an object and all its properties.
102
- * Makes an object immutable.
103
- *
104
- * @template T
105
- * @param {T} obj - The object to freeze.
106
- * @returns {Readonly<T>} The frozen object.
107
- */
108
- export declare function deepFreeze<T extends object>(obj: T): Readonly<T>;
109
- /**
110
- * Safely checks if a value is an object (not null, not array).
111
- *
112
- * @param {unknown} value - Value to check.
113
- * @returns {boolean} True if value is a non-null, non-array object.
114
- */
115
- export declare function isObject(value: unknown): value is Record<string, any>;
116
- /**
117
- * Gets all paths in an object using dot notation.
118
- *
119
- * @param {Record<string, any>} obj - Object to analyze.
120
- * @param {string} [parentPath=""] - Internal param for recursion.
121
- * @returns {string[]} Array of all paths in dot notation.
122
- */
123
- export declare function getAllPaths(obj: Record<string, any>, parentPath?: string): string[];