@catbee/utils 0.0.8-rc.2 → 0.0.8-rc.4

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 (66) hide show
  1. package/build/index.cjs +6591 -0
  2. package/build/index.d.ts +5131 -0
  3. package/build/index.mjs +6321 -0
  4. package/package.json +12 -36
  5. package/build/esm/config.d.ts +0 -121
  6. package/build/esm/config.js +0 -132
  7. package/build/esm/index.d.ts +0 -26
  8. package/build/esm/index.js +0 -49
  9. package/build/esm/servers/server.builder.d.ts +0 -507
  10. package/build/esm/servers/server.builder.js +0 -654
  11. package/build/esm/servers/server.d.ts +0 -255
  12. package/build/esm/servers/server.js +0 -963
  13. package/build/esm/types/api-response.d.ts +0 -151
  14. package/build/esm/types/api-response.js +0 -33
  15. package/build/esm/types/index.d.ts +0 -124
  16. package/build/esm/types/index.js +0 -24
  17. package/build/esm/types/server.d.ts +0 -267
  18. package/build/esm/types/server.js +0 -24
  19. package/build/esm/utils/array.utils.d.ts +0 -167
  20. package/build/esm/utils/array.utils.js +0 -344
  21. package/build/esm/utils/async.utils.d.ts +0 -264
  22. package/build/esm/utils/async.utils.js +0 -619
  23. package/build/esm/utils/cache.utils.d.ts +0 -152
  24. package/build/esm/utils/cache.utils.js +0 -294
  25. package/build/esm/utils/context-store.utils.d.ts +0 -188
  26. package/build/esm/utils/context-store.utils.js +0 -290
  27. package/build/esm/utils/crypto.utils.d.ts +0 -159
  28. package/build/esm/utils/crypto.utils.js +0 -278
  29. package/build/esm/utils/date.utils.d.ts +0 -158
  30. package/build/esm/utils/date.utils.js +0 -383
  31. package/build/esm/utils/decorators.utils.d.ts +0 -511
  32. package/build/esm/utils/decorators.utils.js +0 -1013
  33. package/build/esm/utils/dir.utils.d.ts +0 -195
  34. package/build/esm/utils/dir.utils.js +0 -476
  35. package/build/esm/utils/env.utils.d.ts +0 -376
  36. package/build/esm/utils/env.utils.js +0 -782
  37. package/build/esm/utils/exception.utils.d.ts +0 -229
  38. package/build/esm/utils/exception.utils.js +0 -382
  39. package/build/esm/utils/fs.utils.d.ts +0 -163
  40. package/build/esm/utils/fs.utils.js +0 -348
  41. package/build/esm/utils/http-status-codes.d.ts +0 -265
  42. package/build/esm/utils/http-status-codes.js +0 -294
  43. package/build/esm/utils/id.utils.d.ts +0 -35
  44. package/build/esm/utils/id.utils.js +0 -83
  45. package/build/esm/utils/logger.utils.d.ts +0 -159
  46. package/build/esm/utils/logger.utils.js +0 -304
  47. package/build/esm/utils/middleware.utils.d.ts +0 -99
  48. package/build/esm/utils/middleware.utils.js +0 -235
  49. package/build/esm/utils/obj.utils.d.ts +0 -123
  50. package/build/esm/utils/obj.utils.js +0 -412
  51. package/build/esm/utils/performance.utils.d.ts +0 -135
  52. package/build/esm/utils/performance.utils.js +0 -273
  53. package/build/esm/utils/request.utils.d.ts +0 -85
  54. package/build/esm/utils/request.utils.js +0 -190
  55. package/build/esm/utils/response.utils.d.ts +0 -162
  56. package/build/esm/utils/response.utils.js +0 -261
  57. package/build/esm/utils/stream.utils.d.ts +0 -87
  58. package/build/esm/utils/stream.utils.js +0 -209
  59. package/build/esm/utils/string.utils.d.ts +0 -92
  60. package/build/esm/utils/string.utils.js +0 -164
  61. package/build/esm/utils/type.utils.d.ts +0 -89
  62. package/build/esm/utils/type.utils.js +0 -186
  63. package/build/esm/utils/url.utils.d.ts +0 -140
  64. package/build/esm/utils/url.utils.js +0 -303
  65. package/build/esm/utils/validate.utils.d.ts +0 -176
  66. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,235 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/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
- import { uuid } from './id.utils';
25
- import { HttpStatusCodes } from './http-status-codes';
26
- import { createFinalErrorResponse, ErrorResponse } from './response.utils';
27
- import { getLogger } from './logger.utils';
28
- import { ContextStore, StoreKeys } from './context-store.utils';
29
- import { RequestTimeoutException } from './exception.utils';
30
- /**
31
- * Attaches a unique request ID to each request.
32
- * Useful for request tracing and correlation between logs.
33
- *
34
- * @param {object} [options] - Configuration options
35
- * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
36
- * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
37
- * @param {() => string} [options.generator] - Custom ID generator function
38
- * @returns {Middleware} Express-compatible middleware
39
- */
40
- export function requestId(options) {
41
- const headerName = options?.headerName || 'X-Request-ID';
42
- const exposeHeader = options?.exposeHeader !== false;
43
- const generateId = options?.generator || uuid;
44
- return (req, res, next) => {
45
- // Use existing request ID from header or generate a new one
46
- const existingId = req.headers[headerName.toLowerCase()];
47
- const id = existingId || generateId();
48
- // Attach ID to request object
49
- req.id = id;
50
- // Add ID to response headers
51
- if (exposeHeader) {
52
- res.setHeader(headerName, id);
53
- }
54
- next();
55
- };
56
- }
57
- /**
58
- * Measures request processing time and logs or adds it to response headers.
59
- *
60
- * @param {object} [options] - Configuration options
61
- * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
62
- * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
63
- * @returns {Middleware} Express-compatible middleware
64
- */
65
- export function responseTime(options) {
66
- const addHeader = options?.addHeader !== false;
67
- const logOnComplete = options?.logOnComplete === true;
68
- return (req, res, next) => {
69
- const start = process.hrtime();
70
- // Function to calculate duration
71
- const getDuration = () => {
72
- const diff = process.hrtime(start);
73
- return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
74
- };
75
- if (addHeader) {
76
- // Ensure header is set before response is sent
77
- const originalWriteHead = res.writeHead;
78
- res.writeHead = function (...args) {
79
- res.setHeader('X-Response-Time', `${getDuration()}ms`);
80
- return originalWriteHead.apply(this, args);
81
- };
82
- }
83
- if (logOnComplete) {
84
- res.on('finish', () => {
85
- getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);
86
- });
87
- }
88
- next();
89
- };
90
- }
91
- /**
92
- * Request timeout middleware.
93
- * Aborts requests that take too long to process.
94
- *
95
- * @param {number} [timeoutMs=30000] - Timeout in milliseconds
96
- * @returns {Middleware} Express-compatible middleware
97
- */
98
- export function timeout(timeoutMs = 30000) {
99
- return (_req, res, next) => {
100
- // Set timeout for the request
101
- const timer = setTimeout(() => {
102
- const response = new RequestTimeoutException('Request timed out');
103
- res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);
104
- }, timeoutMs);
105
- // Clear timeout when response is sent
106
- res.on('finish', () => {
107
- clearTimeout(timer);
108
- });
109
- next();
110
- };
111
- }
112
- /**
113
- * Creates an Express middleware that initializes a per-request context.
114
- *
115
- * @param {object} [options] - Optional configuration
116
- * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
117
- * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
118
- * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
119
- */
120
- export function setupRequestContext(options = {}) {
121
- const { headerName = 'x-request-id', autoLog = true } = options;
122
- return (req, _res, next) => {
123
- // Generate or use existing request ID
124
- const requestId = req.headers[headerName] || req?.['id'] || uuid();
125
- ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
126
- // Create a child logger for this request
127
- const childLogger = getLogger().child({
128
- requestId,
129
- method: req.method,
130
- url: req.originalUrl || req.url
131
- });
132
- req.logger = childLogger;
133
- // Store logger in context
134
- ContextStore.set(StoreKeys.LOGGER, childLogger);
135
- if (autoLog) {
136
- req.logger.info('Request context initialized');
137
- }
138
- next();
139
- });
140
- };
141
- }
142
- /**
143
- * Global error handling middleware with enhanced features.
144
- *
145
- * @param {ErrorHandlerOptions} options - Error handler options
146
- * @param {boolean} [options.logErrors=true] - Whether to log errors
147
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
148
- * @returns Error middleware
149
- *
150
- * @example
151
- * import express from 'express';
152
- * import { errorHandler } from '@catbee/utils';
153
- *
154
- * const app = express();
155
- *
156
- * // Your routes
157
- * app.get('/ping', (req, res) => {
158
- * throw new Error('Something went wrong');
159
- * });
160
- *
161
- * // Error handler (must be last middleware)
162
- * app.use(errorHandler({ includeDetails: true }));
163
- *
164
- * app.listen(3000, () => {
165
- * console.log('Server running on port 3000');
166
- * });
167
- */
168
- export function errorHandler(options) {
169
- const logErrors = options?.logErrors !== false;
170
- const includeDetails = options?.includeDetails === true;
171
- return (err, req, res, _next) => {
172
- // Determine status code
173
- const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;
174
- // Log error if enabled
175
- if (logErrors) {
176
- getLogger().error({ err }, `${err.message || 'Unknown error'}`);
177
- }
178
- // Handle ErrorResponse instances (our custom error class)
179
- if (err instanceof ErrorResponse) {
180
- const result = {
181
- error: true,
182
- message: err.message,
183
- timestamp: err.timestamp,
184
- requestId: err?.requestId || req?.id || uuid(),
185
- status,
186
- path: req.originalUrl || req.url
187
- };
188
- if (includeDetails && err?.stack) {
189
- result.stack = err.stack.split('\n').map((line) => line.trim());
190
- }
191
- return res.status(status).json(result);
192
- }
193
- // Handle any other errors
194
- return res
195
- .status(status)
196
- .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));
197
- };
198
- }
199
- /**
200
- * Health check middleware for service status and custom checks.
201
- *
202
- * @param {object} [options] - Health check options
203
- * @param {string} [options.path='/healthz'] - Health check endpoint path
204
- * @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
205
- * @param {boolean} [options.detailed=true] - Show detailed check results
206
- * @returns {Middleware} Express-compatible middleware
207
- */
208
- export function healthCheck(options) {
209
- const path = options?.path || '/healthz';
210
- const checks = options?.checks || [];
211
- const detailed = options?.detailed !== false;
212
- return async (req, res, next) => {
213
- if (req.path !== path)
214
- return next();
215
- const results = {};
216
- let allHealthy = true;
217
- for (const check of checks) {
218
- try {
219
- const result = await Promise.resolve(check.check());
220
- results[check.name] = !!result;
221
- if (!result)
222
- allHealthy = false;
223
- }
224
- catch {
225
- results[check.name] = false;
226
- allHealthy = false;
227
- }
228
- }
229
- const status = allHealthy ? HttpStatusCodes.OK : HttpStatusCodes.SERVICE_UNAVAILABLE;
230
- const response = detailed
231
- ? { status: allHealthy ? 'ok' : 'unhealthy', checks: results, timestamp: new Date().toISOString() }
232
- : { status: allHealthy ? 'ok' : 'unhealthy' };
233
- res.status(status).json(response);
234
- };
235
- }
@@ -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[];