@catbee/utils 0.0.2 → 0.0.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 (170) hide show
  1. package/README.md +1 -4
  2. package/build/esm/config.d.ts +1 -5
  3. package/build/esm/config.js +6 -10
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +20 -19
  6. package/build/esm/index.js +20 -19
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/types/api-response.d.ts +2 -2
  9. package/build/esm/types/api-response.js.map +1 -1
  10. package/build/esm/utils/array.utils.d.ts +1 -1
  11. package/build/esm/utils/array.utils.js +17 -27
  12. package/build/esm/utils/array.utils.js.map +1 -1
  13. package/build/esm/utils/async.utils.d.ts +1 -5
  14. package/build/esm/utils/async.utils.js +17 -20
  15. package/build/esm/utils/async.utils.js.map +1 -1
  16. package/build/esm/utils/cache.utils.js +2 -2
  17. package/build/esm/utils/cache.utils.js.map +1 -1
  18. package/build/esm/utils/context-store.utils.d.ts +1 -1
  19. package/build/esm/utils/context-store.utils.js +8 -8
  20. package/build/esm/utils/context-store.utils.js.map +1 -1
  21. package/build/esm/utils/crypto.utils.d.ts +2 -2
  22. package/build/esm/utils/crypto.utils.js +37 -45
  23. package/build/esm/utils/crypto.utils.js.map +1 -1
  24. package/build/esm/utils/decorators.utils.d.ts +2 -18
  25. package/build/esm/utils/decorators.utils.js +31 -31
  26. package/build/esm/utils/decorators.utils.js.map +1 -1
  27. package/build/esm/utils/dir.utils.d.ts +4 -4
  28. package/build/esm/utils/dir.utils.js +18 -20
  29. package/build/esm/utils/dir.utils.js.map +1 -1
  30. package/build/esm/utils/env.utils.js +22 -26
  31. package/build/esm/utils/env.utils.js.map +1 -1
  32. package/build/esm/utils/exception.utils.d.ts +1 -1
  33. package/build/esm/utils/exception.utils.js +26 -29
  34. package/build/esm/utils/exception.utils.js.map +1 -1
  35. package/build/esm/utils/fs.utils.d.ts +3 -3
  36. package/build/esm/utils/fs.utils.js +19 -23
  37. package/build/esm/utils/fs.utils.js.map +1 -1
  38. package/build/esm/utils/http-status-codes.js.map +1 -1
  39. package/build/esm/utils/id.utils.js +8 -8
  40. package/build/esm/utils/id.utils.js.map +1 -1
  41. package/build/esm/utils/logger.utils.d.ts +13 -4
  42. package/build/esm/utils/logger.utils.js +16 -18
  43. package/build/esm/utils/logger.utils.js.map +1 -1
  44. package/build/esm/utils/middleware.utils.d.ts +15 -26
  45. package/build/esm/utils/middleware.utils.js +80 -59
  46. package/build/esm/utils/middleware.utils.js.map +1 -1
  47. package/build/esm/utils/obj.utils.js +16 -27
  48. package/build/esm/utils/obj.utils.js.map +1 -1
  49. package/build/esm/utils/response.utils.d.ts +2 -2
  50. package/build/esm/utils/response.utils.js +11 -11
  51. package/build/esm/utils/response.utils.js.map +1 -1
  52. package/build/esm/utils/string.utils.js +17 -17
  53. package/build/esm/utils/string.utils.js.map +1 -1
  54. package/build/esm/utils/url.utils.js +20 -22
  55. package/build/esm/utils/url.utils.js.map +1 -1
  56. package/build/esm/utils/validate.utils.js +11 -15
  57. package/build/esm/utils/validate.utils.js.map +1 -1
  58. package/build/esnext/config.d.ts +1 -5
  59. package/build/esnext/config.js +6 -10
  60. package/build/esnext/config.js.map +1 -1
  61. package/build/esnext/index.d.ts +20 -19
  62. package/build/esnext/index.js +20 -19
  63. package/build/esnext/index.js.map +1 -1
  64. package/build/esnext/types/api-response.d.ts +2 -2
  65. package/build/esnext/types/api-response.js.map +1 -1
  66. package/build/esnext/utils/array.utils.d.ts +1 -1
  67. package/build/esnext/utils/array.utils.js +23 -31
  68. package/build/esnext/utils/array.utils.js.map +1 -1
  69. package/build/esnext/utils/async.utils.d.ts +1 -5
  70. package/build/esnext/utils/async.utils.js +22 -22
  71. package/build/esnext/utils/async.utils.js.map +1 -1
  72. package/build/esnext/utils/cache.utils.js +3 -3
  73. package/build/esnext/utils/cache.utils.js.map +1 -1
  74. package/build/esnext/utils/context-store.utils.d.ts +1 -1
  75. package/build/esnext/utils/context-store.utils.js +10 -10
  76. package/build/esnext/utils/context-store.utils.js.map +1 -1
  77. package/build/esnext/utils/crypto.utils.d.ts +2 -2
  78. package/build/esnext/utils/crypto.utils.js +37 -47
  79. package/build/esnext/utils/crypto.utils.js.map +1 -1
  80. package/build/esnext/utils/decorators.utils.d.ts +2 -18
  81. package/build/esnext/utils/decorators.utils.js +33 -33
  82. package/build/esnext/utils/decorators.utils.js.map +1 -1
  83. package/build/esnext/utils/dir.utils.d.ts +4 -4
  84. package/build/esnext/utils/dir.utils.js +22 -24
  85. package/build/esnext/utils/dir.utils.js.map +1 -1
  86. package/build/esnext/utils/env.utils.js +24 -26
  87. package/build/esnext/utils/env.utils.js.map +1 -1
  88. package/build/esnext/utils/exception.utils.d.ts +1 -1
  89. package/build/esnext/utils/exception.utils.js +26 -29
  90. package/build/esnext/utils/exception.utils.js.map +1 -1
  91. package/build/esnext/utils/fs.utils.d.ts +3 -3
  92. package/build/esnext/utils/fs.utils.js +21 -25
  93. package/build/esnext/utils/fs.utils.js.map +1 -1
  94. package/build/esnext/utils/http-status-codes.js.map +1 -1
  95. package/build/esnext/utils/id.utils.js +8 -8
  96. package/build/esnext/utils/id.utils.js.map +1 -1
  97. package/build/esnext/utils/logger.utils.d.ts +13 -4
  98. package/build/esnext/utils/logger.utils.js +16 -18
  99. package/build/esnext/utils/logger.utils.js.map +1 -1
  100. package/build/esnext/utils/middleware.utils.d.ts +15 -26
  101. package/build/esnext/utils/middleware.utils.js +78 -59
  102. package/build/esnext/utils/middleware.utils.js.map +1 -1
  103. package/build/esnext/utils/obj.utils.js +17 -26
  104. package/build/esnext/utils/obj.utils.js.map +1 -1
  105. package/build/esnext/utils/response.utils.d.ts +2 -2
  106. package/build/esnext/utils/response.utils.js +11 -11
  107. package/build/esnext/utils/response.utils.js.map +1 -1
  108. package/build/esnext/utils/string.utils.js +17 -17
  109. package/build/esnext/utils/string.utils.js.map +1 -1
  110. package/build/esnext/utils/url.utils.js +21 -23
  111. package/build/esnext/utils/url.utils.js.map +1 -1
  112. package/build/esnext/utils/validate.utils.js +14 -16
  113. package/build/esnext/utils/validate.utils.js.map +1 -1
  114. package/build/src/config.d.ts +1 -5
  115. package/build/src/config.js +5 -9
  116. package/build/src/config.js.map +1 -1
  117. package/build/src/index.d.ts +20 -19
  118. package/build/src/index.js +1 -0
  119. package/build/src/index.js.map +1 -1
  120. package/build/src/types/api-response.d.ts +2 -2
  121. package/build/src/types/api-response.js.map +1 -1
  122. package/build/src/utils/array.utils.d.ts +1 -1
  123. package/build/src/utils/array.utils.js +22 -30
  124. package/build/src/utils/array.utils.js.map +1 -1
  125. package/build/src/utils/async.utils.d.ts +1 -5
  126. package/build/src/utils/async.utils.js +22 -22
  127. package/build/src/utils/async.utils.js.map +1 -1
  128. package/build/src/utils/cache.utils.js +2 -2
  129. package/build/src/utils/cache.utils.js.map +1 -1
  130. package/build/src/utils/context-store.utils.d.ts +1 -1
  131. package/build/src/utils/context-store.utils.js +9 -9
  132. package/build/src/utils/context-store.utils.js.map +1 -1
  133. package/build/src/utils/crypto.utils.d.ts +2 -2
  134. package/build/src/utils/crypto.utils.js +35 -45
  135. package/build/src/utils/crypto.utils.js.map +1 -1
  136. package/build/src/utils/decorators.utils.d.ts +2 -18
  137. package/build/src/utils/decorators.utils.js +32 -32
  138. package/build/src/utils/decorators.utils.js.map +1 -1
  139. package/build/src/utils/dir.utils.d.ts +4 -4
  140. package/build/src/utils/dir.utils.js +16 -18
  141. package/build/src/utils/dir.utils.js.map +1 -1
  142. package/build/src/utils/env.utils.js +22 -24
  143. package/build/src/utils/env.utils.js.map +1 -1
  144. package/build/src/utils/exception.utils.d.ts +1 -1
  145. package/build/src/utils/exception.utils.js +23 -26
  146. package/build/src/utils/exception.utils.js.map +1 -1
  147. package/build/src/utils/fs.utils.d.ts +3 -3
  148. package/build/src/utils/fs.utils.js +15 -19
  149. package/build/src/utils/fs.utils.js.map +1 -1
  150. package/build/src/utils/http-status-codes.js.map +1 -1
  151. package/build/src/utils/id.utils.js +7 -7
  152. package/build/src/utils/id.utils.js.map +1 -1
  153. package/build/src/utils/logger.utils.d.ts +13 -4
  154. package/build/src/utils/logger.utils.js +13 -15
  155. package/build/src/utils/logger.utils.js.map +1 -1
  156. package/build/src/utils/middleware.utils.d.ts +15 -26
  157. package/build/src/utils/middleware.utils.js +72 -52
  158. package/build/src/utils/middleware.utils.js.map +1 -1
  159. package/build/src/utils/obj.utils.js +17 -26
  160. package/build/src/utils/obj.utils.js.map +1 -1
  161. package/build/src/utils/response.utils.d.ts +2 -2
  162. package/build/src/utils/response.utils.js +9 -9
  163. package/build/src/utils/response.utils.js.map +1 -1
  164. package/build/src/utils/string.utils.js +17 -17
  165. package/build/src/utils/string.utils.js.map +1 -1
  166. package/build/src/utils/url.utils.js +20 -22
  167. package/build/src/utils/url.utils.js.map +1 -1
  168. package/build/src/utils/validate.utils.js +14 -16
  169. package/build/src/utils/validate.utils.js.map +1 -1
  170. package/package.json +3 -3
@@ -1,26 +1,4 @@
1
- /**
2
- * Type definitions for Express-compatible middleware
3
- */
4
- export type Request = {
5
- headers: Record<string, string | string[] | undefined>;
6
- method: string;
7
- url: string;
8
- ip?: string;
9
- body?: any;
10
- query?: Record<string, any>;
11
- params?: Record<string, any>;
12
- [key: string]: any;
13
- };
14
- export type Response = {
15
- status: (code: number) => Response;
16
- json: (data: any) => void;
17
- send: (data: any) => void;
18
- setHeader: (name: string, value: string | string[]) => void;
19
- end: (data?: any) => void;
20
- on: (event: string, callback: (...args: any[]) => void) => void;
21
- [key: string]: any;
22
- };
23
- export type NextFunction = (err?: Error | any) => void;
1
+ import type { Request, Response, NextFunction } from 'express';
24
2
  export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
25
3
  /**
26
4
  * Attaches a unique request ID to each request.
@@ -46,7 +24,7 @@ export declare function requestId(options?: {
46
24
  export declare function responseTime(options?: {
47
25
  addHeader?: boolean;
48
26
  logOnComplete?: boolean;
49
- }): Middleware;
27
+ }): (req: Request, res: Response, next: NextFunction) => void;
50
28
  /**
51
29
  * Request timeout middleware.
52
30
  * Aborts requests that take too long to process.
@@ -55,6 +33,18 @@ export declare function responseTime(options?: {
55
33
  * @returns {Middleware} Express-compatible middleware
56
34
  */
57
35
  export declare function timeout(timeoutMs?: number): Middleware;
36
+ /**
37
+ * Creates an Express middleware that initializes a per-request context.
38
+ *
39
+ * @param {object} [options] - Optional configuration
40
+ * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
41
+ * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
42
+ * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
43
+ */
44
+ export declare function setupRequestContext(options?: {
45
+ headerName?: string;
46
+ autoLog?: boolean;
47
+ }): Middleware;
58
48
  /**
59
49
  * Global error handling middleware with enhanced features.
60
50
  *
@@ -67,6 +57,5 @@ export declare function timeout(timeoutMs?: number): Middleware;
67
57
  export declare function errorHandler(options?: {
68
58
  logErrors?: boolean;
69
59
  includeDetails?: boolean;
70
- logger?: (message: string, error: any) => void;
71
- }): (err: any, req: Request, res: Response, _next: NextFunction) => void;
60
+ }): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
72
61
  //# sourceMappingURL=middleware.utils.d.ts.map
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.requestId = requestId;
4
4
  exports.responseTime = responseTime;
5
5
  exports.timeout = timeout;
6
+ exports.setupRequestContext = setupRequestContext;
6
7
  exports.errorHandler = errorHandler;
7
8
  const crypto_1 = require("crypto");
8
9
  const config_1 = require("../config");
@@ -11,6 +12,7 @@ const http_status_codes_1 = require("./http-status-codes");
11
12
  const response_utils_1 = require("./response.utils");
12
13
  const env_utils_1 = require("./env.utils");
13
14
  const logger_utils_1 = require("./logger.utils");
15
+ const context_store_utils_1 = require("./context-store.utils");
14
16
  /**
15
17
  * Attaches a unique request ID to each request.
16
18
  * Useful for request tracing and correlation between logs.
@@ -21,7 +23,7 @@ const logger_utils_1 = require("./logger.utils");
21
23
  * @returns {Middleware} Express-compatible middleware
22
24
  */
23
25
  function requestId(options) {
24
- const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || "X-Request-ID";
26
+ const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
25
27
  const exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
26
28
  return (req, res, next) => {
27
29
  // Use existing request ID from header or generate a new one
@@ -49,22 +51,23 @@ function responseTime(options) {
49
51
  const logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
50
52
  return (req, res, next) => {
51
53
  const start = process.hrtime();
52
- // Function to calculate elapsed time
53
- const calculateDuration = () => {
54
- const diff = process.hrtime(start);
55
- return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms
56
- };
57
- // Handle response completion
58
- res.on("finish", () => {
59
- const duration = calculateDuration();
60
- if (addHeader) {
61
- res.setHeader("X-Response-Time", `${duration.toFixed(2)}ms`);
62
- }
63
- if (logOnComplete) {
64
- const { method, url } = req;
65
- (0, logger_utils_1.getLogger)().info(`${method} ${url} - ${duration.toFixed(2)}ms`);
66
- }
67
- });
54
+ if (addHeader) {
55
+ // Wrap res.end to set header just before sending response
56
+ const originalEnd = res.end;
57
+ res.end = function (chunk, encoding, cb) {
58
+ const diff = process.hrtime(start);
59
+ const duration = diff[0] * 1e3 + diff[1] * 1e-6;
60
+ res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);
61
+ return originalEnd.call(this, chunk, encoding, cb);
62
+ };
63
+ }
64
+ if (logOnComplete) {
65
+ res.on('finish', () => {
66
+ const diff = process.hrtime(start);
67
+ const duration = diff[0] * 1e3 + diff[1] * 1e-6;
68
+ (0, logger_utils_1.getLogger)().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);
69
+ });
70
+ }
68
71
  next();
69
72
  };
70
73
  }
@@ -81,48 +84,47 @@ function timeout(timeoutMs = config_1.Config.Http.timeout) {
81
84
  const timer = setTimeout(() => {
82
85
  res.status(408).json({
83
86
  error: true,
84
- message: "Request timeout",
87
+ message: 'Request timeout',
85
88
  status: 408,
86
- timestamp: new Date().toISOString(),
89
+ timestamp: new Date().toISOString()
87
90
  });
88
91
  }, timeoutMs);
89
92
  // Clear timeout when response is sent
90
- res.on("finish", () => {
93
+ res.on('finish', () => {
91
94
  clearTimeout(timer);
92
95
  });
93
96
  next();
94
97
  };
95
98
  }
96
99
  /**
97
- * Creates a standardized error response object for API errors.
100
+ * Creates an Express middleware that initializes a per-request context.
98
101
  *
99
- * @param {string} message - Error message
100
- * @param {Request} req - Express request object
101
- * @param {any} error - Original error object
102
- * @param {object} [options] - Additional options
103
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
104
- * @returns {object} Formatted error response
102
+ * @param {object} [options] - Optional configuration
103
+ * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
104
+ * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
105
+ * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
105
106
  */
106
- const createErrorResponse = (message, req, error, options) => {
107
- const isDev = env_utils_1.Env.isDev();
108
- const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
109
- const response = {
110
- error: true,
111
- message,
112
- timestamp: new Date().toISOString(),
113
- requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || (0, id_utils_1.uuid)(),
114
- path: req.originalUrl || req.url,
107
+ function setupRequestContext(options = {}) {
108
+ const { headerName = 'x-request-id', autoLog = true } = options;
109
+ return (req, _res, next) => {
110
+ // Generate or use existing request ID
111
+ const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || crypto.randomUUID();
112
+ context_store_utils_1.ContextStore.run({ [context_store_utils_1.StoreKeys.REQUEST_ID]: requestId }, () => {
113
+ // Create a child logger for this request
114
+ const childLogger = (0, logger_utils_1.getLogger)().child({
115
+ reqId: requestId,
116
+ method: req.method,
117
+ url: req.originalUrl || req.url
118
+ });
119
+ // Store logger in context
120
+ context_store_utils_1.ContextStore.set(context_store_utils_1.StoreKeys.LOGGER, childLogger);
121
+ if (autoLog) {
122
+ childLogger.info('Request context initialized');
123
+ }
124
+ next();
125
+ });
115
126
  };
116
- // Include error code if present
117
- if (error === null || error === void 0 ? void 0 : error.code) {
118
- response.code = error.code;
119
- }
120
- // Include stack trace in development mode if requested
121
- if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
122
- response.stack = error.stack.split("\n").map((line) => line.trim());
123
- }
124
- return response;
125
- };
127
+ }
126
128
  /**
127
129
  * Global error handling middleware with enhanced features.
128
130
  *
@@ -135,14 +137,12 @@ const createErrorResponse = (message, req, error, options) => {
135
137
  function errorHandler(options) {
136
138
  const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
137
139
  const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
138
- const logger = (options === null || options === void 0 ? void 0 : options.logger) || (0, logger_utils_1.getLogger)().error;
139
140
  return (err, req, res, _next) => {
140
141
  // Determine status code
141
142
  const status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR;
142
143
  // Log error if enabled
143
144
  if (logErrors) {
144
- const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || "Unknown error"}`;
145
- logger(logMessage, err);
145
+ (0, logger_utils_1.getLogger)().error({ error: err }, `${err.message || 'Unknown error'}`);
146
146
  }
147
147
  // Handle ErrorResponse instances (our custom error class)
148
148
  if (err instanceof response_utils_1.ErrorResponse) {
@@ -151,12 +151,32 @@ function errorHandler(options) {
151
151
  message: err.message,
152
152
  timestamp: err.timestamp,
153
153
  requestId: err.requestId || req.id || (0, id_utils_1.uuid)(),
154
- path: req.originalUrl || req.url,
154
+ path: req.originalUrl || req.url
155
155
  });
156
156
  }
157
+ const createErrorResponse = (message, req, error, options) => {
158
+ const isDev = env_utils_1.Env.isDev();
159
+ const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
160
+ const response = {
161
+ error: true,
162
+ message,
163
+ timestamp: new Date().toISOString(),
164
+ requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || (0, id_utils_1.uuid)(),
165
+ path: req.originalUrl || req.url
166
+ };
167
+ // Include error code if present
168
+ if (error === null || error === void 0 ? void 0 : error.code) {
169
+ response.code = error.code;
170
+ }
171
+ // Include stack trace in development mode if requested
172
+ if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
173
+ response.stack = error.stack.split('\n').map((line) => line.trim());
174
+ }
175
+ return response;
176
+ };
157
177
  // Handle any other errors
158
- return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || "Internal Server Error", req, err, {
159
- includeDetails,
178
+ return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
179
+ includeDetails
160
180
  }));
161
181
  };
162
182
  }
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":";;AAiDA,8BAsBC;AAUD,oCAgCC;AASD,0BAmBC;AAmDD,oCAsCC;AAtOD,mCAAoC;AACpC,sCAAmC;AACnC,yCAAkC;AAClC,2DAAsD;AACtD,qDAAiD;AACjD,2CAAkC;AAClC,iDAA2C;AAkC3C;;;;;;;;GAQG;AACH,SAAgB,SAAS,CAAC,OAGzB;IACC,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,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,GAAG,uBAAH,GAAG,CAAE,UAAU,CAAA,IAAI,mCAAe,CAAC,qBAAqB,CAAC;QAE1E,uBAAuB;QACvB,IAAI,SAAS,EAAE,CAAC;YACd,MAAM,UAAU,GAAG,WAAW,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,OAAO,IAAI,eAAe,EAAE,CAAC;YAC5G,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAC1B,CAAC;QAED,0DAA0D;QAC1D,IAAI,GAAG,YAAY,8BAAa,EAAE,CAAC;YACjC,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;gBAC7B,KAAK,EAAE,GAAG,CAAC,KAAK;gBAChB,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,SAAS,EAAE,GAAG,CAAC,SAAS,IAAI,GAAG,CAAC,EAAE,IAAI,IAAA,eAAI,GAAE;gBAC5C,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC,CAAC;QACL,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { Config } from \"../config\";\nimport { uuid } from \"./id.utils\";\nimport { HttpStatusCodes } from \"./http-status-codes\";\nimport { ErrorResponse } from \"./response.utils\";\nimport { Env } from \"./env.utils\";\nimport { getLogger } from \"./logger.utils\";\n\n/**\n * Type definitions for Express-compatible middleware\n */\nexport type Request = {\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n ip?: string;\n body?: any;\n query?: Record<string, any>;\n params?: Record<string, any>;\n [key: string]: any;\n};\n\nexport type Response = {\n status: (code: number) => Response;\n json: (data: any) => void;\n send: (data: any) => void;\n setHeader: (name: string, value: string | string[]) => void;\n end: (data?: any) => void;\n on: (event: string, callback: (...args: any[]) => void) => void;\n [key: string]: any;\n};\n\nexport type NextFunction = (err?: Error | any) => void;\n\nexport type Middleware = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n}): Middleware {\n const headerName = options?.headerName || \"X-Request-ID\";\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: {\n addHeader?: boolean;\n logOnComplete?: boolean;\n}): Middleware {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req, res, next) => {\n const start = process.hrtime();\n\n // Function to calculate elapsed time\n const calculateDuration = (): number => {\n const diff = process.hrtime(start);\n return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms\n };\n\n // Handle response completion\n res.on(\"finish\", () => {\n const duration = calculateDuration();\n\n if (addHeader) {\n res.setHeader(\"X-Response-Time\", `${duration.toFixed(2)}ms`);\n }\n\n if (logOnComplete) {\n const { method, url } = req;\n getLogger().info(`${method} ${url} - ${duration.toFixed(2)}ms`);\n }\n });\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: \"Request timeout\",\n status: 408,\n timestamp: new Date().toISOString(),\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on(\"finish\", () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates a standardized error response object for API errors.\n *\n * @param {string} message - Error message\n * @param {Request} req - Express request object\n * @param {any} error - Original error object\n * @param {object} [options] - Additional options\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns {object} Formatted error response\n */\nconst createErrorResponse = (\n message: string,\n req: Request,\n error: any,\n options?: { includeDetails?: boolean },\n) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req.id || uuid(),\n path: req.originalUrl || req.url,\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split(\"\\n\").map((line: string) => line.trim());\n }\n\n return response;\n};\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: {\n logErrors?: boolean;\n includeDetails?: boolean;\n logger?: (message: string, error: any) => void;\n}) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n const logger = options?.logger || getLogger().error;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status =\n err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || \"Unknown error\"}`;\n logger(logMessage, err);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || req.id || uuid(),\n path: req.originalUrl || req.url,\n });\n }\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || \"Internal Server Error\", req, err, {\n includeDetails,\n }),\n );\n };\n}\n"]}
1
+ {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":";;AAqBA,8BAmBC;AAUD,oCA4BC;AASD,0BAmBC;AAUD,kDAwBC;AAWD,oCAwDC;AA/MD,mCAAoC;AACpC,sCAAmC;AACnC,yCAAkC;AAClC,2DAAsD;AACtD,qDAAiD;AACjD,2CAAkC;AAClC,iDAA2C;AAE3C,+DAAgE;AAIhE;;;;;;;;GAQG;AACH,SAAgB,SAAS,CAAC,OAAyD;IACjF,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAA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,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,gCAAgC;YAChC,IAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE,CAAC;gBAChB,QAAQ,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;YAC7B,CAAC;YAED,uDAAuD;YACvD,IAAI,cAAc,KAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,CAAA,EAAE,CAAC;gBACnC,QAAQ,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC9E,CAAC;YAED,OAAO,QAAQ,CAAC;QAClB,CAAC,CAAC;QAEF,0BAA0B;QAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n (req as any).id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n if (addHeader) {\n // Wrap res.end to set header just before sending response\n const originalEnd = res.end;\n res.end = function (chunk?: any, encoding?: any, cb?: any) {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n return originalEnd.call(this, chunk, encoding, cb);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n getLogger().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || crypto.randomUUID();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n reqId: requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: { logErrors?: boolean; includeDetails?: boolean }) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ error: err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n const createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n };\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
@@ -20,7 +20,7 @@ exports.getAllPaths = getAllPaths;
20
20
  * @returns {boolean} True if the object is empty, false otherwise.
21
21
  */
22
22
  function isObjEmpty(obj) {
23
- return !!obj && typeof obj === "object" && Object.keys(obj).length === 0;
23
+ return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;
24
24
  }
25
25
  /**
26
26
  * Returns a new object with only the specified keys picked.
@@ -32,7 +32,7 @@ function isObjEmpty(obj) {
32
32
  * @returns {Pick<T, K>} New object with picked keys.
33
33
  */
34
34
  function pick(obj, keys) {
35
- return Object.fromEntries(keys.map((key) => [key, obj[key]]));
35
+ return Object.fromEntries(keys.map(key => [key, obj[key]]));
36
36
  }
37
37
  /**
38
38
  * Returns a new object with the specified keys omitted.
@@ -58,12 +58,8 @@ function deepObjMerge(target, source) {
58
58
  for (const key in source) {
59
59
  const sourceVal = source[key];
60
60
  const targetVal = target[key];
61
- if (sourceVal &&
62
- typeof sourceVal === "object" &&
63
- !Array.isArray(sourceVal)) {
64
- if (!targetVal ||
65
- typeof targetVal !== "object" ||
66
- Array.isArray(targetVal)) {
61
+ if (sourceVal && typeof sourceVal === 'object' && !Array.isArray(sourceVal)) {
62
+ if (!targetVal || typeof targetVal !== 'object' || Array.isArray(targetVal)) {
67
63
  target[key] = {};
68
64
  }
69
65
  deepObjMerge(target[key], sourceVal);
@@ -82,10 +78,10 @@ function deepObjMerge(target, source) {
82
78
  * @param {string} [prefix=""] - Optional prefix for nested keys (used internally).
83
79
  * @returns {Record<string, any>} A new object with flattened keys.
84
80
  */
85
- function flattenObject(obj, prefix = "") {
81
+ function flattenObject(obj, prefix = '') {
86
82
  return Object.entries(obj).reduce((acc, [key, value]) => {
87
83
  const newKey = prefix ? `${prefix}.${key}` : key;
88
- if (value && typeof value === "object" && !Array.isArray(value)) {
84
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
89
85
  Object.assign(acc, flattenObject(value, newKey));
90
86
  }
91
87
  else {
@@ -103,12 +99,12 @@ function flattenObject(obj, prefix = "") {
103
99
  * @returns {any} The value at the given path, or undefined if not found.
104
100
  */
105
101
  function getValueByPath(obj, path) {
106
- if (!obj || typeof obj !== "object")
102
+ if (!obj || typeof obj !== 'object')
107
103
  return undefined;
108
104
  // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
109
105
  const parts = path
110
- .replace(/\[(\d+)\]/g, ".$1") // convert [0] to .0
111
- .split(".")
106
+ .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
107
+ .split('.')
112
108
  .filter(Boolean); // remove empty strings
113
109
  return parts.reduce((acc, key) => acc === null || acc === void 0 ? void 0 : acc[key], obj);
114
110
  }
@@ -123,12 +119,12 @@ function getValueByPath(obj, path) {
123
119
  * @returns {T} The modified object.
124
120
  */
125
121
  function setValueByPath(obj, path, value) {
126
- if (!obj || typeof obj !== "object")
122
+ if (!obj || typeof obj !== 'object')
127
123
  return obj;
128
124
  // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
129
125
  const parts = path
130
- .replace(/\[(\d+)\]/g, ".$1") // convert [0] to .0
131
- .split(".")
126
+ .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
127
+ .split('.')
132
128
  .filter(Boolean); // remove empty strings
133
129
  // Handle empty path
134
130
  if (parts.length === 0)
@@ -161,10 +157,7 @@ function isEqual(a, b) {
161
157
  if (a === b)
162
158
  return true;
163
159
  // Check if either is null/undefined or not an object
164
- if (a == null ||
165
- b == null ||
166
- typeof a !== "object" ||
167
- typeof b !== "object") {
160
+ if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
168
161
  return false;
169
162
  }
170
163
  // Handle Date objects
@@ -196,7 +189,7 @@ function isEqual(a, b) {
196
189
  if (keysA.length !== keysB.length)
197
190
  return false;
198
191
  // Check if every key in A exists in B and has the same value
199
- return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
192
+ return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
200
193
  }
201
194
  /**
202
195
  * Filters object properties based on a predicate function.
@@ -235,9 +228,7 @@ function deepFreeze(obj) {
235
228
  // Recursively freeze nested objects
236
229
  for (const prop of Object.getOwnPropertyNames(obj)) {
237
230
  const value = obj[prop];
238
- if (value !== null &&
239
- typeof value === "object" &&
240
- !Object.isFrozen(value)) {
231
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
241
232
  deepFreeze(value);
242
233
  }
243
234
  }
@@ -250,7 +241,7 @@ function deepFreeze(obj) {
250
241
  * @returns {boolean} True if value is a non-null, non-array object.
251
242
  */
252
243
  function isObject(value) {
253
- return value !== null && typeof value === "object" && !Array.isArray(value);
244
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
254
245
  }
255
246
  /**
256
247
  * Gets all paths in an object using dot notation.
@@ -259,7 +250,7 @@ function isObject(value) {
259
250
  * @param {string} [parentPath=""] - Internal param for recursion.
260
251
  * @returns {string[]} Array of all paths in dot notation.
261
252
  */
262
- function getAllPaths(obj, parentPath = "") {
253
+ function getAllPaths(obj, parentPath = '') {
263
254
  if (!isObject(obj))
264
255
  return [];
265
256
  return Object.entries(obj).flatMap(([key, value]) => {
@@ -1 +1 @@
1
- {"version":3,"file":"obj.utils.js","sourceRoot":"","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C,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === \"object\" && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Pick<T, K> {\n return Object.fromEntries(keys.map((key) => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Omit<T, K> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key as K)),\n ) as Omit<T, K>;\n}\n\n/**\n * Deeply merges two objects (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {Partial<T>} source - The object to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends Record<string, any>>(\n target: T,\n source: Partial<T>,\n): T {\n for (const key in source) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (\n sourceVal &&\n typeof sourceVal === \"object\" &&\n !Array.isArray(sourceVal)\n ) {\n if (\n !targetVal ||\n typeof targetVal !== \"object\" ||\n Array.isArray(targetVal)\n ) {\n target[key] = {} as any;\n }\n deepObjMerge(target[key], sourceVal as any);\n } else {\n target[key] = sourceVal as T[Extract<keyof T, string>];\n }\n }\n return target;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(\n obj: T,\n prefix = \"\",\n): Record<string, any> {\n return Object.entries(obj).reduce(\n (acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n },\n {},\n );\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== \"object\") return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, \".$1\") // convert [0] to .0\n .split(\".\")\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(\n obj: T,\n path: string,\n value: any,\n): T {\n if (!obj || typeof obj !== \"object\") return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, \".$1\") // convert [0] to .0\n .split(\".\")\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (\n a == null ||\n b == null ||\n typeof a !== \"object\" ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]),\n );\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean,\n): Partial<T> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key, value]) => predicate(value, key, obj)),\n ) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U,\n): Record<keyof T, U> {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)]),\n ) as Record<keyof T, U>;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Object.isFrozen(value)\n ) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(\n obj: Record<string, any>,\n parentPath: string = \"\",\n): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
1
+ {"version":3,"file":"obj.utils.js","sourceRoot":"","sources":["../../../src/utils/obj.utils.ts"],"names":[],"mappings":";;A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AAC;AACL,CAAC","sourcesContent":["/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(keys.map(key => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key as K))) as Omit<T, K>;\n}\n\n/**\n * Deeply merges two objects (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {Partial<T>} source - The object to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T {\n for (const key in source) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (sourceVal && typeof sourceVal === 'object' && !Array.isArray(sourceVal)) {\n if (!targetVal || typeof targetVal !== 'object' || Array.isArray(targetVal)) {\n target[key] = {} as any;\n }\n deepObjMerge(target[key], sourceVal as any);\n } else {\n target[key] = sourceVal as T[Extract<keyof T, string>];\n }\n }\n return target;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(obj: T, prefix = ''): Record<string, any> {\n return Object.entries(obj).reduce((acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== 'object') return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(obj: T, path: string, value: any): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean\n): Partial<T> {\n return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj))) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U\n): Record<keyof T, U> {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)])) as Record<\n keyof T,\n U\n >;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(obj: Record<string, any>, parentPath: string = ''): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ApiResponse } from "../types/api-response";
1
+ import { ApiResponse } from '../types/api-response';
2
2
  /**
3
3
  * Standard HTTP response wrapper for successful responses.
4
4
  * Implements the `ApiResponse<T>` interface and sets default values.
@@ -28,7 +28,7 @@ export declare class SuccessResponse<T> implements ApiResponse<T> {
28
28
  * Wrapper for error responses that extends the native `Error` object.
29
29
  * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).
30
30
  */
31
- export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, "data"> {
31
+ export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {
32
32
  /** HTTP status code associated with the error (e.g., 404, 500). */
33
33
  status: number;
34
34
  /** Indicates that this is an error. Always true. */
@@ -23,7 +23,7 @@ class SuccessResponse {
23
23
  constructor(message, data) {
24
24
  var _a;
25
25
  /** Message describing the result of the operation. */
26
- this.message = "Success";
26
+ this.message = 'Success';
27
27
  /** Whether the response is an error. Always false in success responses. */
28
28
  this.error = false;
29
29
  /** The payload returned from the API. */
@@ -81,7 +81,7 @@ class PaginatedResponse extends SuccessResponse {
81
81
  * @param {number} pagination.pageSize - Number of items per page.
82
82
  * @param {string} [message="Success"] - Optional custom message.
83
83
  */
84
- constructor(items, pagination, message = "Success") {
84
+ constructor(items, pagination, message = 'Success') {
85
85
  super(message, items);
86
86
  this.total = pagination.total;
87
87
  this.page = pagination.page;
@@ -101,7 +101,7 @@ class NoContentResponse extends SuccessResponse {
101
101
  *
102
102
  * @param {string} [message="Operation completed successfully"] - Optional custom message.
103
103
  */
104
- constructor(message = "Operation completed successfully") {
104
+ constructor(message = 'Operation completed successfully') {
105
105
  super(message, null);
106
106
  }
107
107
  }
@@ -135,7 +135,7 @@ exports.RedirectResponse = RedirectResponse;
135
135
  * @param {string} [message="Success"] - Optional custom message.
136
136
  * @returns {SuccessResponse<T>} A properly formatted success response.
137
137
  */
138
- function createSuccessResponse(data, message = "Success") {
138
+ function createSuccessResponse(data, message = 'Success') {
139
139
  return new SuccessResponse(message, data);
140
140
  }
141
141
  /**
@@ -158,7 +158,7 @@ function createErrorResponse(message, statusCode = 500) {
158
158
  * @param {string} [message="Success"] - Optional custom message.
159
159
  * @returns {PaginatedResponse<T>} A properly formatted paginated response.
160
160
  */
161
- function createPaginatedResponse(allItems, page, pageSize, message = "Success") {
161
+ function createPaginatedResponse(allItems, page, pageSize, message = 'Success') {
162
162
  // Ensure valid pagination parameters
163
163
  const validPage = Math.max(1, page);
164
164
  const validPageSize = Math.max(1, pageSize);
@@ -170,7 +170,7 @@ function createPaginatedResponse(allItems, page, pageSize, message = "Success")
170
170
  return new PaginatedResponse(pageItems, {
171
171
  total: allItems.length,
172
172
  page: validPage,
173
- pageSize: validPageSize,
173
+ pageSize: validPageSize
174
174
  }, message);
175
175
  }
176
176
  /**
@@ -181,18 +181,18 @@ function createPaginatedResponse(allItems, page, pageSize, message = "Success")
181
181
  */
182
182
  function sendResponse(res, apiResponse) {
183
183
  // Handle redirects
184
- if ("redirectUrl" in apiResponse) {
184
+ if ('redirectUrl' in apiResponse) {
185
185
  res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);
186
186
  return;
187
187
  }
188
188
  // Handle errors
189
- if ("error" in apiResponse && apiResponse.error) {
189
+ if ('error' in apiResponse && apiResponse.error) {
190
190
  const errorResponse = apiResponse;
191
191
  res.status(errorResponse.status).json({
192
192
  error: true,
193
193
  message: errorResponse.message,
194
194
  timestamp: errorResponse.timestamp,
195
- requestId: errorResponse.requestId,
195
+ requestId: errorResponse.requestId
196
196
  });
197
197
  return;
198
198
  }