@catbee/utils 0.0.6 → 0.0.8-next.0

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 (249) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +77 -1107
  3. package/build/index.cjs +6888 -0
  4. package/build/index.d.ts +5242 -0
  5. package/build/index.mjs +6615 -0
  6. package/package.json +26 -95
  7. package/build/esm/config.d.ts +0 -130
  8. package/build/esm/config.js +0 -145
  9. package/build/esm/config.js.map +0 -1
  10. package/build/esm/index.d.ts +0 -27
  11. package/build/esm/index.js +0 -50
  12. package/build/esm/index.js.map +0 -1
  13. package/build/esm/servers/server.builder.d.ts +0 -625
  14. package/build/esm/servers/server.builder.js +0 -722
  15. package/build/esm/servers/server.builder.js.map +0 -1
  16. package/build/esm/servers/server.d.ts +0 -256
  17. package/build/esm/servers/server.js +0 -1211
  18. package/build/esm/servers/server.js.map +0 -1
  19. package/build/esm/types/api-response.d.ts +0 -124
  20. package/build/esm/types/api-response.js +0 -25
  21. package/build/esm/types/api-response.js.map +0 -1
  22. package/build/esm/types/index.d.ts +0 -125
  23. package/build/esm/types/index.js +0 -25
  24. package/build/esm/types/index.js.map +0 -1
  25. package/build/esm/types/server.d.ts +0 -285
  26. package/build/esm/types/server.js +0 -25
  27. package/build/esm/types/server.js.map +0 -1
  28. package/build/esm/utils/array.utils.d.ts +0 -168
  29. package/build/esm/utils/array.utils.js +0 -382
  30. package/build/esm/utils/array.utils.js.map +0 -1
  31. package/build/esm/utils/async.utils.d.ts +0 -174
  32. package/build/esm/utils/async.utils.js +0 -652
  33. package/build/esm/utils/async.utils.js.map +0 -1
  34. package/build/esm/utils/cache.utils.d.ts +0 -153
  35. package/build/esm/utils/cache.utils.js +0 -499
  36. package/build/esm/utils/cache.utils.js.map +0 -1
  37. package/build/esm/utils/context-store.utils.d.ts +0 -186
  38. package/build/esm/utils/context-store.utils.js +0 -304
  39. package/build/esm/utils/context-store.utils.js.map +0 -1
  40. package/build/esm/utils/crypto.utils.d.ts +0 -160
  41. package/build/esm/utils/crypto.utils.js +0 -375
  42. package/build/esm/utils/crypto.utils.js.map +0 -1
  43. package/build/esm/utils/decorators.utils.d.ts +0 -315
  44. package/build/esm/utils/decorators.utils.js +0 -666
  45. package/build/esm/utils/decorators.utils.js.map +0 -1
  46. package/build/esm/utils/dir.utils.d.ts +0 -196
  47. package/build/esm/utils/dir.utils.js +0 -998
  48. package/build/esm/utils/dir.utils.js.map +0 -1
  49. package/build/esm/utils/env.utils.d.ts +0 -377
  50. package/build/esm/utils/env.utils.js +0 -873
  51. package/build/esm/utils/env.utils.js.map +0 -1
  52. package/build/esm/utils/exception.utils.d.ts +0 -230
  53. package/build/esm/utils/exception.utils.js +0 -559
  54. package/build/esm/utils/exception.utils.js.map +0 -1
  55. package/build/esm/utils/fs.utils.d.ts +0 -164
  56. package/build/esm/utils/fs.utils.js +0 -580
  57. package/build/esm/utils/fs.utils.js.map +0 -1
  58. package/build/esm/utils/http-status-codes.d.ts +0 -266
  59. package/build/esm/utils/http-status-codes.js +0 -295
  60. package/build/esm/utils/http-status-codes.js.map +0 -1
  61. package/build/esm/utils/id.utils.d.ts +0 -36
  62. package/build/esm/utils/id.utils.js +0 -87
  63. package/build/esm/utils/id.utils.js.map +0 -1
  64. package/build/esm/utils/logger.utils.d.ts +0 -166
  65. package/build/esm/utils/logger.utils.js +0 -347
  66. package/build/esm/utils/logger.utils.js.map +0 -1
  67. package/build/esm/utils/middleware.utils.d.ts +0 -83
  68. package/build/esm/utils/middleware.utils.js +0 -205
  69. package/build/esm/utils/middleware.utils.js.map +0 -1
  70. package/build/esm/utils/obj.utils.d.ts +0 -124
  71. package/build/esm/utils/obj.utils.js +0 -519
  72. package/build/esm/utils/obj.utils.js.map +0 -1
  73. package/build/esm/utils/request.utils.d.ts +0 -77
  74. package/build/esm/utils/request.utils.js +0 -196
  75. package/build/esm/utils/request.utils.js.map +0 -1
  76. package/build/esm/utils/response.utils.d.ts +0 -163
  77. package/build/esm/utils/response.utils.js +0 -284
  78. package/build/esm/utils/response.utils.js.map +0 -1
  79. package/build/esm/utils/string.utils.d.ts +0 -93
  80. package/build/esm/utils/string.utils.js +0 -169
  81. package/build/esm/utils/string.utils.js.map +0 -1
  82. package/build/esm/utils/url.utils.d.ts +0 -141
  83. package/build/esm/utils/url.utils.js +0 -381
  84. package/build/esm/utils/url.utils.js.map +0 -1
  85. package/build/esm/utils/validate.utils.d.ts +0 -177
  86. package/build/esm/utils/validate.utils.js +0 -336
  87. package/build/esm/utils/validate.utils.js.map +0 -1
  88. package/build/esnext/config.d.ts +0 -130
  89. package/build/esnext/config.js +0 -145
  90. package/build/esnext/config.js.map +0 -1
  91. package/build/esnext/index.d.ts +0 -27
  92. package/build/esnext/index.js +0 -50
  93. package/build/esnext/index.js.map +0 -1
  94. package/build/esnext/servers/server.builder.d.ts +0 -625
  95. package/build/esnext/servers/server.builder.js +0 -677
  96. package/build/esnext/servers/server.builder.js.map +0 -1
  97. package/build/esnext/servers/server.d.ts +0 -256
  98. package/build/esnext/servers/server.js +0 -918
  99. package/build/esnext/servers/server.js.map +0 -1
  100. package/build/esnext/types/api-response.d.ts +0 -124
  101. package/build/esnext/types/api-response.js +0 -25
  102. package/build/esnext/types/api-response.js.map +0 -1
  103. package/build/esnext/types/index.d.ts +0 -125
  104. package/build/esnext/types/index.js +0 -25
  105. package/build/esnext/types/index.js.map +0 -1
  106. package/build/esnext/types/server.d.ts +0 -285
  107. package/build/esnext/types/server.js +0 -25
  108. package/build/esnext/types/server.js.map +0 -1
  109. package/build/esnext/utils/array.utils.d.ts +0 -168
  110. package/build/esnext/utils/array.utils.js +0 -345
  111. package/build/esnext/utils/array.utils.js.map +0 -1
  112. package/build/esnext/utils/async.utils.d.ts +0 -174
  113. package/build/esnext/utils/async.utils.js +0 -430
  114. package/build/esnext/utils/async.utils.js.map +0 -1
  115. package/build/esnext/utils/cache.utils.d.ts +0 -153
  116. package/build/esnext/utils/cache.utils.js +0 -293
  117. package/build/esnext/utils/cache.utils.js.map +0 -1
  118. package/build/esnext/utils/context-store.utils.d.ts +0 -186
  119. package/build/esnext/utils/context-store.utils.js +0 -286
  120. package/build/esnext/utils/context-store.utils.js.map +0 -1
  121. package/build/esnext/utils/crypto.utils.d.ts +0 -160
  122. package/build/esnext/utils/crypto.utils.js +0 -276
  123. package/build/esnext/utils/crypto.utils.js.map +0 -1
  124. package/build/esnext/utils/decorators.utils.d.ts +0 -315
  125. package/build/esnext/utils/decorators.utils.js +0 -504
  126. package/build/esnext/utils/decorators.utils.js.map +0 -1
  127. package/build/esnext/utils/dir.utils.d.ts +0 -196
  128. package/build/esnext/utils/dir.utils.js +0 -477
  129. package/build/esnext/utils/dir.utils.js.map +0 -1
  130. package/build/esnext/utils/env.utils.d.ts +0 -377
  131. package/build/esnext/utils/env.utils.js +0 -785
  132. package/build/esnext/utils/env.utils.js.map +0 -1
  133. package/build/esnext/utils/exception.utils.d.ts +0 -230
  134. package/build/esnext/utils/exception.utils.js +0 -381
  135. package/build/esnext/utils/exception.utils.js.map +0 -1
  136. package/build/esnext/utils/fs.utils.d.ts +0 -164
  137. package/build/esnext/utils/fs.utils.js +0 -349
  138. package/build/esnext/utils/fs.utils.js.map +0 -1
  139. package/build/esnext/utils/http-status-codes.d.ts +0 -266
  140. package/build/esnext/utils/http-status-codes.js +0 -295
  141. package/build/esnext/utils/http-status-codes.js.map +0 -1
  142. package/build/esnext/utils/id.utils.d.ts +0 -36
  143. package/build/esnext/utils/id.utils.js +0 -84
  144. package/build/esnext/utils/id.utils.js.map +0 -1
  145. package/build/esnext/utils/logger.utils.d.ts +0 -166
  146. package/build/esnext/utils/logger.utils.js +0 -306
  147. package/build/esnext/utils/logger.utils.js.map +0 -1
  148. package/build/esnext/utils/middleware.utils.d.ts +0 -83
  149. package/build/esnext/utils/middleware.utils.js +0 -198
  150. package/build/esnext/utils/middleware.utils.js.map +0 -1
  151. package/build/esnext/utils/obj.utils.d.ts +0 -124
  152. package/build/esnext/utils/obj.utils.js +0 -413
  153. package/build/esnext/utils/obj.utils.js.map +0 -1
  154. package/build/esnext/utils/request.utils.d.ts +0 -77
  155. package/build/esnext/utils/request.utils.js +0 -168
  156. package/build/esnext/utils/request.utils.js.map +0 -1
  157. package/build/esnext/utils/response.utils.d.ts +0 -163
  158. package/build/esnext/utils/response.utils.js +0 -247
  159. package/build/esnext/utils/response.utils.js.map +0 -1
  160. package/build/esnext/utils/string.utils.d.ts +0 -93
  161. package/build/esnext/utils/string.utils.js +0 -165
  162. package/build/esnext/utils/string.utils.js.map +0 -1
  163. package/build/esnext/utils/url.utils.d.ts +0 -141
  164. package/build/esnext/utils/url.utils.js +0 -304
  165. package/build/esnext/utils/url.utils.js.map +0 -1
  166. package/build/esnext/utils/validate.utils.d.ts +0 -177
  167. package/build/esnext/utils/validate.utils.js +0 -320
  168. package/build/esnext/utils/validate.utils.js.map +0 -1
  169. package/build/src/config.d.ts +0 -130
  170. package/build/src/config.js +0 -150
  171. package/build/src/config.js.map +0 -1
  172. package/build/src/index.d.ts +0 -27
  173. package/build/src/index.js +0 -69
  174. package/build/src/index.js.map +0 -1
  175. package/build/src/servers/server.builder.d.ts +0 -625
  176. package/build/src/servers/server.builder.js +0 -681
  177. package/build/src/servers/server.builder.js.map +0 -1
  178. package/build/src/servers/server.d.ts +0 -256
  179. package/build/src/servers/server.js +0 -958
  180. package/build/src/servers/server.js.map +0 -1
  181. package/build/src/types/api-response.d.ts +0 -124
  182. package/build/src/types/api-response.js +0 -26
  183. package/build/src/types/api-response.js.map +0 -1
  184. package/build/src/types/index.d.ts +0 -125
  185. package/build/src/types/index.js +0 -26
  186. package/build/src/types/index.js.map +0 -1
  187. package/build/src/types/server.d.ts +0 -285
  188. package/build/src/types/server.js +0 -26
  189. package/build/src/types/server.js.map +0 -1
  190. package/build/src/utils/array.utils.d.ts +0 -168
  191. package/build/src/utils/array.utils.js +0 -364
  192. package/build/src/utils/array.utils.js.map +0 -1
  193. package/build/src/utils/async.utils.d.ts +0 -174
  194. package/build/src/utils/async.utils.js +0 -447
  195. package/build/src/utils/async.utils.js.map +0 -1
  196. package/build/src/utils/cache.utils.d.ts +0 -153
  197. package/build/src/utils/cache.utils.js +0 -297
  198. package/build/src/utils/cache.utils.js.map +0 -1
  199. package/build/src/utils/context-store.utils.d.ts +0 -186
  200. package/build/src/utils/context-store.utils.js +0 -293
  201. package/build/src/utils/context-store.utils.js.map +0 -1
  202. package/build/src/utils/crypto.utils.d.ts +0 -160
  203. package/build/src/utils/crypto.utils.js +0 -293
  204. package/build/src/utils/crypto.utils.js.map +0 -1
  205. package/build/src/utils/decorators.utils.d.ts +0 -315
  206. package/build/src/utils/decorators.utils.js +0 -516
  207. package/build/src/utils/decorators.utils.js.map +0 -1
  208. package/build/src/utils/dir.utils.d.ts +0 -196
  209. package/build/src/utils/dir.utils.js +0 -501
  210. package/build/src/utils/dir.utils.js.map +0 -1
  211. package/build/src/utils/env.utils.d.ts +0 -377
  212. package/build/src/utils/env.utils.js +0 -789
  213. package/build/src/utils/env.utils.js.map +0 -1
  214. package/build/src/utils/exception.utils.d.ts +0 -230
  215. package/build/src/utils/exception.utils.js +0 -407
  216. package/build/src/utils/exception.utils.js.map +0 -1
  217. package/build/src/utils/fs.utils.d.ts +0 -164
  218. package/build/src/utils/fs.utils.js +0 -372
  219. package/build/src/utils/fs.utils.js.map +0 -1
  220. package/build/src/utils/http-status-codes.d.ts +0 -266
  221. package/build/src/utils/http-status-codes.js +0 -298
  222. package/build/src/utils/http-status-codes.js.map +0 -1
  223. package/build/src/utils/id.utils.d.ts +0 -36
  224. package/build/src/utils/id.utils.js +0 -91
  225. package/build/src/utils/id.utils.js.map +0 -1
  226. package/build/src/utils/logger.utils.d.ts +0 -166
  227. package/build/src/utils/logger.utils.js +0 -352
  228. package/build/src/utils/logger.utils.js.map +0 -1
  229. package/build/src/utils/middleware.utils.d.ts +0 -83
  230. package/build/src/utils/middleware.utils.js +0 -205
  231. package/build/src/utils/middleware.utils.js.map +0 -1
  232. package/build/src/utils/obj.utils.d.ts +0 -124
  233. package/build/src/utils/obj.utils.js +0 -429
  234. package/build/src/utils/obj.utils.js.map +0 -1
  235. package/build/src/utils/request.utils.d.ts +0 -77
  236. package/build/src/utils/request.utils.js +0 -175
  237. package/build/src/utils/request.utils.js.map +0 -1
  238. package/build/src/utils/response.utils.d.ts +0 -163
  239. package/build/src/utils/response.utils.js +0 -260
  240. package/build/src/utils/response.utils.js.map +0 -1
  241. package/build/src/utils/string.utils.d.ts +0 -93
  242. package/build/src/utils/string.utils.js +0 -179
  243. package/build/src/utils/string.utils.js.map +0 -1
  244. package/build/src/utils/url.utils.d.ts +0 -141
  245. package/build/src/utils/url.utils.js +0 -317
  246. package/build/src/utils/url.utils.js.map +0 -1
  247. package/build/src/utils/validate.utils.d.ts +0 -177
  248. package/build/src/utils/validate.utils.js +0 -345
  249. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1,352 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies
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
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
26
- if (k2 === undefined) k2 = k;
27
- var desc = Object.getOwnPropertyDescriptor(m, k);
28
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
29
- desc = { enumerable: true, get: function() { return m[k]; } };
30
- }
31
- Object.defineProperty(o, k2, desc);
32
- }) : (function(o, m, k, k2) {
33
- if (k2 === undefined) k2 = k;
34
- o[k2] = m[k];
35
- }));
36
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
37
- Object.defineProperty(o, "default", { enumerable: true, value: v });
38
- }) : function(o, v) {
39
- o["default"] = v;
40
- });
41
- var __importStar = (this && this.__importStar) || (function () {
42
- var ownKeys = function(o) {
43
- ownKeys = Object.getOwnPropertyNames || function (o) {
44
- var ar = [];
45
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
46
- return ar;
47
- };
48
- return ownKeys(o);
49
- };
50
- return function (mod) {
51
- if (mod && mod.__esModule) return mod;
52
- var result = {};
53
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
54
- __setModuleDefault(result, mod);
55
- return result;
56
- };
57
- })();
58
- Object.defineProperty(exports, "__esModule", { value: true });
59
- exports.globalLogger = exports.logger = exports._globalThis = exports.defaultSensitiveFields = void 0;
60
- exports.setRedactCensor = setRedactCensor;
61
- exports.getRedactCensor = getRedactCensor;
62
- exports.redact = redact;
63
- exports.addRedactFields = addRedactFields;
64
- exports.setSensitiveFields = setSensitiveFields;
65
- exports.addSensitiveFields = addSensitiveFields;
66
- exports.getLogger = getLogger;
67
- exports.createChildLogger = createChildLogger;
68
- exports.createRequestLogger = createRequestLogger;
69
- exports.logError = logError;
70
- const pino_1 = __importStar(require("pino"));
71
- const config_1 = require("../config");
72
- const context_store_utils_1 = require("./context-store.utils");
73
- const env_utils_1 = require("./env.utils");
74
- /**
75
- * Symbol used to store the root logger in the Node.js global object.
76
- */
77
- const GLOBAL_LOGGER_KEY = Symbol.for('logger');
78
- // Default sensitive fields
79
- exports.defaultSensitiveFields = [
80
- 'password',
81
- 'secret',
82
- 'token',
83
- 'apiKey',
84
- 'api_key',
85
- 'auth',
86
- 'jwt',
87
- 'access_token',
88
- 'client_secret',
89
- 'session_token',
90
- 'refresh_token'
91
- ];
92
- /**
93
- * The global censor function used by the logger.
94
- */
95
- let globalRedactCensor = (value, path, sensitiveFields = exports.defaultSensitiveFields) => {
96
- if (typeof value !== 'string')
97
- return '***';
98
- const lowerPath = path.map(p => p.toLowerCase());
99
- const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());
100
- if (lowerPath.some(p => lowerSensitiveFields.includes(p)))
101
- return '***';
102
- // Redact URLs
103
- if (lowerPath[0] === 'url') {
104
- return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');
105
- }
106
- if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {
107
- return value.replace(/^(\S+)\s+.+$/, '$1 ***') || '***';
108
- }
109
- // Redact sensitive fields - check each path segment against each sensitive field
110
- if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {
111
- return '***';
112
- }
113
- if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {
114
- return value;
115
- }
116
- return value;
117
- };
118
- /**
119
- * Sets the global redaction censor function used throughout the application for log redaction.
120
- *
121
- * Use this function to customize how sensitive data is redacted in logs. The provided function
122
- * will replace the default censor implementation.
123
- *
124
- * @example
125
- * ```typescript
126
- * // Custom censor that redacts only specific values
127
- * setRedactCensor((value, path, sensitiveFields) => {
128
- * if (path.includes('password')) return '***';
129
- * return value;
130
- * });
131
- * ```
132
- *
133
- * @param fn - The redaction censor function to use globally. This function receives:
134
- * - value: The data value to potentially redact
135
- * - path: Array of strings representing the path to the value in the object
136
- * - sensitiveFields: Optional array of field names to consider sensitive
137
- * @returns void
138
- */
139
- function setRedactCensor(fn) {
140
- globalRedactCensor = fn;
141
- }
142
- /**
143
- * Gets the current global redaction censor function used for log redaction.
144
- *
145
- * This function is called internally by the logger when determining how to redact
146
- * sensitive information. It can also be used to access the current censor implementation
147
- * for composition or extension.
148
- *
149
- * @example
150
- * ```typescript
151
- * const currentCensor = getRedactCensor();
152
- * // Create an enhanced censor that extends the current one
153
- * setRedactCensor((value, path, fields) => {
154
- * // Add custom logic before delegating to current censor
155
- * if (someCondition) return customHandling();
156
- * return currentCensor(value, path, fields);
157
- * });
158
- * ```
159
- *
160
- * @returns The current redaction censor function
161
- */
162
- function getRedactCensor() {
163
- return globalRedactCensor;
164
- }
165
- /**
166
- * Convenience function to redact sensitive data using the current global redact censor.
167
- *
168
- * This is a direct wrapper around the global censor function that simplifies usage
169
- * in application code without needing to access the censor function directly.
170
- *
171
- * @example
172
- * ```typescript
173
- * // Redact a potential sensitive value
174
- * const safeValue = redact(value, ['user', 'apiKey']);
175
- * ```
176
- *
177
- * @param value - The value to potentially redact
178
- * @param path - Array of strings representing the path to the value in the object
179
- * @param sensitiveFields - Optional array of field names to consider sensitive
180
- * @returns The redacted string value or "***" for redacted content
181
- */
182
- function redact(value, path, sensitiveFields) {
183
- return globalRedactCensor(value, path, sensitiveFields);
184
- }
185
- /**
186
- * Extends the current redaction function with additional fields to redact.
187
- *
188
- * This function wraps the existing censor while adding more fields to be considered
189
- * sensitive without replacing the entire redaction logic.
190
- *
191
- * @example
192
- * ```typescript
193
- * // Add custom fields to be redacted in all future redaction operations
194
- * addRedactFields(['customerId', 'accountNumber']);
195
- * ```
196
- *
197
- * @param fields - Array of additional field names to redact
198
- */
199
- function addRedactFields(fields) {
200
- const prev = globalRedactCensor;
201
- globalRedactCensor = (value, path, sensitiveFields = exports.defaultSensitiveFields) => prev(value, path, [...(sensitiveFields || []), ...fields]);
202
- }
203
- /**
204
- * Replaces the default list of sensitive fields with a new list.
205
- *
206
- * This is useful when you want complete control over what fields are considered
207
- * sensitive by default, rather than using the library's built-in list.
208
- *
209
- * @example
210
- * ```typescript
211
- * // Replace default sensitive fields with a custom list
212
- * setSensitiveFields(['password', 'ssn', 'creditCard']);
213
- * ```
214
- *
215
- * @param fields - Array of field names to set as the new default sensitive fields
216
- */
217
- function setSensitiveFields(fields) {
218
- exports.defaultSensitiveFields.splice(0, exports.defaultSensitiveFields.length, ...fields);
219
- }
220
- /**
221
- * Adds additional field names to the default sensitive fields list.
222
- *
223
- * This preserves the existing sensitive fields while adding new ones for
224
- * application-specific sensitive data.
225
- *
226
- * @example
227
- * ```typescript
228
- * // Add domain-specific sensitive fields to the default list
229
- * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
230
- * ```
231
- *
232
- * @param fields - Array of additional field names to add to the sensitive fields list
233
- */
234
- function addSensitiveFields(fields) {
235
- exports.defaultSensitiveFields.push(...fields);
236
- }
237
- /**
238
- * Use an object compatible with either modern or legacy global scopes.
239
- */
240
- exports._globalThis = typeof globalThis === 'object' ? globalThis : global;
241
- const _global = exports._globalThis;
242
- /**
243
- * Initializes the global root logger according to app configuration.
244
- *
245
- * - Sets log name, level, timestamp, and redaction for sensitive fields.
246
- * - Uses singleton in global symbol registry.
247
- */
248
- function setupLogger() {
249
- var _a;
250
- const logParams = {
251
- name: config_1.config.logger.name || '@catbee/utils',
252
- level: config_1.config.logger.level || 'info',
253
- redact: {
254
- paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],
255
- censor: (value, path) => redact(value, path)
256
- },
257
- // serializers: {
258
- // req: pino.stdSerializers.req,
259
- // request: pino.stdSerializers.req,
260
- // res: pino.stdSerializers.res,
261
- // response: pino.stdSerializers.res,
262
- // err: pino.stdSerializers.err,
263
- // error: pino.stdSerializers.err
264
- // },
265
- timestamp: pino_1.stdTimeFunctions.isoTime
266
- };
267
- const logger = config_1.config.logger.pretty && env_utils_1.Env.isDev()
268
- ? (0, pino_1.default)(logParams, pino_1.default.transport({
269
- target: 'pino-pretty',
270
- options: {
271
- colorize: true,
272
- translateTime: 'SYS:standard',
273
- ignore: 'pid,hostname',
274
- singleLine: config_1.config.logger.singleLine,
275
- levelFirst: true
276
- }
277
- }))
278
- : (0, pino_1.default)(logParams);
279
- _global[GLOBAL_LOGGER_KEY] = logger;
280
- (_a = _global[GLOBAL_LOGGER_KEY]) === null || _a === void 0 ? void 0 : _a.debug('Logger initialized');
281
- }
282
- /**
283
- * Retrieves the current logger instance:
284
- * - Returns a request-scoped logger from AsyncLocalStorage if available
285
- * - Falls back to the global (singleton) logger
286
- * - Initializes the global logger if not created yet
287
- *
288
- * @returns {Logger} The logger instance (request-bound or global root logger)
289
- */
290
- function getLogger() {
291
- const logger = context_store_utils_1.ContextStore.get(context_store_utils_1.StoreKeys.LOGGER);
292
- if (logger)
293
- return logger;
294
- if (!_global[GLOBAL_LOGGER_KEY]) {
295
- setupLogger();
296
- }
297
- return _global[GLOBAL_LOGGER_KEY];
298
- }
299
- /**
300
- * Alias for the current logger instance.
301
- * - Returns a request-scoped logger from AsyncLocalStorage if available
302
- * - Falls back to the global (singleton) logger
303
- * - Initializes the global logger if not created yet
304
- */
305
- exports.logger = getLogger;
306
- /**
307
- * Global logger instance.
308
- */
309
- exports.globalLogger = getLogger();
310
- /**
311
- * Creates a child logger with additional context.
312
- *
313
- * @param {Record<string, any>} bindings - Properties to attach to all log records
314
- * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
315
- * @returns {Logger} Child logger with merged context
316
- */
317
- function createChildLogger(bindings, parentLogger) {
318
- const logger = parentLogger || getLogger();
319
- return logger.child(bindings);
320
- }
321
- /**
322
- * Creates a request-scoped logger with request ID and stores it in context
323
- *
324
- * @param {string} requestId - Unique request identifier
325
- * @param {object} [additionalContext] - Additional context to include in logs
326
- * @returns {Logger} Request-scoped logger instance
327
- */
328
- function createRequestLogger(requestId, additionalContext = {}) {
329
- const logger = createChildLogger(Object.assign({ requestId }, additionalContext));
330
- try {
331
- context_store_utils_1.ContextStore.set(context_store_utils_1.StoreKeys.LOGGER, logger);
332
- }
333
- catch (_a) {
334
- // Context not initialized, can't store logger
335
- logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
336
- }
337
- return logger;
338
- }
339
- /**
340
- * Utility to safely log errors with proper stack trace extraction
341
- *
342
- * @param {Error|unknown} error - Error object to log
343
- * @param {string} [message] - Optional message to include
344
- * @param {Record<string, any>} [context] - Additional context properties
345
- */
346
- function logError(error, message, context) {
347
- const logger = getLogger();
348
- const errObj = error instanceof Error ? error : new Error(String(error));
349
- const logContext = Object.assign(Object.assign({}, context), { error: errObj });
350
- logger.error(logContext, message || errObj.message);
351
- }
352
- //# sourceMappingURL=logger.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FH,0CAEC;AAsBD,0CAEC;AAmBD,wBAEC;AAgBD,0CAIC;AAgBD,gDAEC;AAgBD,gDAEC;AA8DD,8BASC;AAsBD,8CAGC;AASD,kDAcC;AASD,4BAUC;AA9UD,6CAA6D;AAE7D,sCAAmC;AACnC,+DAAgE;AAChE,2CAAkC;AAElC;;GAEG;AACH,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C,2BAA2B;AACd,QAAA,sBAAsB,GAAG;IACpC,UAAU;IACV,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;IACT,MAAM;IACN,KAAK;IACL,cAAc;IACd,eAAe;IACf,eAAe;IACf,eAAe;CAChB,CAAC;AAEF;;GAEG;AACH,IAAI,kBAAkB,GAA2E,CAC/F,KAAK,EACL,IAAI,EACJ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AM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { Env } from './env.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n// Default sensitive fields\nexport const defaultSensitiveFields = [\n 'password',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'auth',\n 'jwt',\n 'access_token',\n 'client_secret',\n 'session_token',\n 'refresh_token'\n];\n\n/**\n * The global censor function used by the logger.\n */\nlet globalRedactCensor: (value: unknown, path: string[], sensitiveFields?: string[]) => string = (\n value,\n path,\n sensitiveFields = defaultSensitiveFields\n) => {\n if (typeof value !== 'string') return '***';\n\n const lowerPath = path.map(p => p.toLowerCase());\n const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());\n\n if (lowerPath.some(p => lowerSensitiveFields.includes(p))) return '***';\n\n // Redact URLs\n if (lowerPath[0] === 'url') {\n return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');\n }\n\n if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {\n return value.replace(/^(\\S+)\\s+.+$/, '$1 ***') || '***';\n }\n\n // Redact sensitive fields - check each path segment against each sensitive field\n if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {\n return '***';\n }\n\n if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {\n return value;\n }\n\n return value;\n};\n\n/**\n * Sets the global redaction censor function used throughout the application for log redaction.\n *\n * Use this function to customize how sensitive data is redacted in logs. The provided function\n * will replace the default censor implementation.\n *\n * @example\n * ```typescript\n * // Custom censor that redacts only specific values\n * setRedactCensor((value, path, sensitiveFields) => {\n * if (path.includes('password')) return '***';\n * return value;\n * });\n * ```\n *\n * @param fn - The redaction censor function to use globally. This function receives:\n * - value: The data value to potentially redact\n * - path: Array of strings representing the path to the value in the object\n * - sensitiveFields: Optional array of field names to consider sensitive\n * @returns void\n */\nexport function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string) {\n globalRedactCensor = fn;\n}\n\n/**\n * Gets the current global redaction censor function used for log redaction.\n *\n * This function is called internally by the logger when determining how to redact\n * sensitive information. It can also be used to access the current censor implementation\n * for composition or extension.\n *\n * @example\n * ```typescript\n * const currentCensor = getRedactCensor();\n * // Create an enhanced censor that extends the current one\n * setRedactCensor((value, path, fields) => {\n * // Add custom logic before delegating to current censor\n * if (someCondition) return customHandling();\n * return currentCensor(value, path, fields);\n * });\n * ```\n *\n * @returns The current redaction censor function\n */\nexport function getRedactCensor() {\n return globalRedactCensor;\n}\n\n/**\n * Convenience function to redact sensitive data using the current global redact censor.\n *\n * This is a direct wrapper around the global censor function that simplifies usage\n * in application code without needing to access the censor function directly.\n *\n * @example\n * ```typescript\n * // Redact a potential sensitive value\n * const safeValue = redact(value, ['user', 'apiKey']);\n * ```\n *\n * @param value - The value to potentially redact\n * @param path - Array of strings representing the path to the value in the object\n * @param sensitiveFields - Optional array of field names to consider sensitive\n * @returns The redacted string value or \"***\" for redacted content\n */\nexport function redact(value: unknown, path: string[], sensitiveFields?: string[]) {\n return globalRedactCensor(value, path, sensitiveFields);\n}\n\n/**\n * Extends the current redaction function with additional fields to redact.\n *\n * This function wraps the existing censor while adding more fields to be considered\n * sensitive without replacing the entire redaction logic.\n *\n * @example\n * ```typescript\n * // Add custom fields to be redacted in all future redaction operations\n * addRedactFields(['customerId', 'accountNumber']);\n * ```\n *\n * @param fields - Array of additional field names to redact\n */\nexport function addRedactFields(fields: string[]) {\n const prev = globalRedactCensor;\n globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) =>\n prev(value, path, [...(sensitiveFields || []), ...fields]);\n}\n\n/**\n * Replaces the default list of sensitive fields with a new list.\n *\n * This is useful when you want complete control over what fields are considered\n * sensitive by default, rather than using the library's built-in list.\n *\n * @example\n * ```typescript\n * // Replace default sensitive fields with a custom list\n * setSensitiveFields(['password', 'ssn', 'creditCard']);\n * ```\n *\n * @param fields - Array of field names to set as the new default sensitive fields\n */\nexport function setSensitiveFields(fields: string[]) {\n defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);\n}\n\n/**\n * Adds additional field names to the default sensitive fields list.\n *\n * This preserves the existing sensitive fields while adding new ones for\n * application-specific sensitive data.\n *\n * @example\n * ```typescript\n * // Add domain-specific sensitive fields to the default list\n * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);\n * ```\n *\n * @param fields - Array of additional field names to add to the sensitive fields list\n */\nexport function addSensitiveFields(fields: string[]) {\n defaultSensitiveFields.push(...fields);\n}\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: config.logger.name || '@catbee/utils',\n level: config.logger.level || 'info',\n redact: {\n paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],\n censor: (value, path) => redact(value, path)\n },\n // serializers: {\n // req: pino.stdSerializers.req,\n // request: pino.stdSerializers.req,\n // res: pino.stdSerializers.res,\n // response: pino.stdSerializers.res,\n // err: pino.stdSerializers.err,\n // error: pino.stdSerializers.err\n // },\n timestamp: stdTimeFunctions.isoTime\n };\n\n const logger =\n config.logger.pretty && Env.isDev()\n ? pino(\n logParams,\n pino.transport({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname',\n singleLine: config.logger.singleLine,\n levelFirst: true\n }\n })\n )\n : pino(logParams);\n\n _global[GLOBAL_LOGGER_KEY] = logger;\n _global[GLOBAL_LOGGER_KEY]?.debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Alias for the current logger instance.\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n */\nexport const logger = getLogger;\n\n/**\n * Global logger instance.\n */\nexport const globalLogger = getLogger();\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
@@ -1,83 +0,0 @@
1
- import type { Request, Response, NextFunction } from 'express';
2
- export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
3
- /**
4
- * Attaches a unique request ID to each request.
5
- * Useful for request tracing and correlation between logs.
6
- *
7
- * @param {object} [options] - Configuration options
8
- * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
9
- * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
10
- * @param {() => string} [options.generator] - Custom ID generator function
11
- * @returns {Middleware} Express-compatible middleware
12
- */
13
- export declare function requestId(options?: {
14
- headerName?: string;
15
- exposeHeader?: boolean;
16
- generator?: () => string;
17
- }): Middleware;
18
- /**
19
- * Measures request processing time and logs or adds it to response headers.
20
- *
21
- * @param {object} [options] - Configuration options
22
- * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
23
- * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
24
- * @returns {Middleware} Express-compatible middleware
25
- */
26
- export declare function responseTime(options?: {
27
- addHeader?: boolean;
28
- logOnComplete?: boolean;
29
- }): (req: Request, res: Response, next: NextFunction) => void;
30
- /**
31
- * Request timeout middleware.
32
- * Aborts requests that take too long to process.
33
- *
34
- * @param {number} [timeoutMs=30000] - Timeout in milliseconds
35
- * @returns {Middleware} Express-compatible middleware
36
- */
37
- export declare function timeout(timeoutMs?: number): Middleware;
38
- /**
39
- * Creates an Express middleware that initializes a per-request context.
40
- *
41
- * @param {object} [options] - Optional configuration
42
- * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
43
- * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
44
- * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
45
- */
46
- export declare function setupRequestContext(options?: {
47
- headerName?: string;
48
- autoLog?: boolean;
49
- }): Middleware;
50
- export interface ErrorHandlerOptions {
51
- /** Whether to log errors (default: true) */
52
- logErrors?: boolean;
53
- /** Whether to include error details in non-production (default: false) */
54
- includeDetails?: boolean;
55
- }
56
- /**
57
- * Global error handling middleware with enhanced features.
58
- *
59
- * @param {ErrorHandlerOptions} options - Error handler options
60
- * @param {boolean} [options.logErrors=true] - Whether to log errors
61
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
62
- * @returns Error middleware
63
- *
64
- * @example
65
- * import express from 'express';
66
- * import { errorHandler } from '@catbee/utils';
67
- *
68
- * const app = express();
69
- *
70
- * // Your routes
71
- * app.get('/ping', (req, res) => {
72
- * throw new Error('Something went wrong');
73
- * });
74
- *
75
- * // Error handler (must be last middleware)
76
- * app.use(errorHandler({ includeDetails: true }));
77
- *
78
- * app.listen(3000, () => {
79
- * console.log('Server running on port 3000');
80
- * });
81
- */
82
- export declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
83
- //# sourceMappingURL=middleware.utils.d.ts.map
@@ -1,205 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies
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
- const id_utils_1 = require("./id.utils");
32
- const http_status_codes_1 = require("./http-status-codes");
33
- const response_utils_1 = require("./response.utils");
34
- const logger_utils_1 = require("./logger.utils");
35
- const context_store_utils_1 = require("./context-store.utils");
36
- const exception_utils_1 = require("./exception.utils");
37
- /**
38
- * Attaches a unique request ID to each request.
39
- * Useful for request tracing and correlation between logs.
40
- *
41
- * @param {object} [options] - Configuration options
42
- * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
43
- * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
44
- * @param {() => string} [options.generator] - Custom ID generator function
45
- * @returns {Middleware} Express-compatible middleware
46
- */
47
- function requestId(options) {
48
- const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
49
- const exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
50
- const generateId = (options === null || options === void 0 ? void 0 : options.generator) || id_utils_1.uuid;
51
- return (req, res, next) => {
52
- // Use existing request ID from header or generate a new one
53
- const existingId = req.headers[headerName.toLowerCase()];
54
- const id = existingId || generateId();
55
- // Attach ID to request object
56
- req.id = id;
57
- // Add ID to response headers
58
- if (exposeHeader) {
59
- res.setHeader(headerName, id);
60
- }
61
- next();
62
- };
63
- }
64
- /**
65
- * Measures request processing time and logs or adds it to response headers.
66
- *
67
- * @param {object} [options] - Configuration options
68
- * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
69
- * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
70
- * @returns {Middleware} Express-compatible middleware
71
- */
72
- function responseTime(options) {
73
- const addHeader = (options === null || options === void 0 ? void 0 : options.addHeader) !== false;
74
- const logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
75
- return (req, res, next) => {
76
- const start = process.hrtime();
77
- // Function to calculate duration
78
- const getDuration = () => {
79
- const diff = process.hrtime(start);
80
- return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
81
- };
82
- if (addHeader) {
83
- // Ensure header is set before response is sent
84
- const originalWriteHead = res.writeHead;
85
- res.writeHead = function (...args) {
86
- res.setHeader('X-Response-Time', `${getDuration()}ms`);
87
- return originalWriteHead.apply(this, args);
88
- };
89
- }
90
- if (logOnComplete) {
91
- res.on('finish', () => {
92
- (0, logger_utils_1.getLogger)().info(`${req.method} ${req.url} - ${getDuration()}ms`);
93
- });
94
- }
95
- next();
96
- };
97
- }
98
- /**
99
- * Request timeout middleware.
100
- * Aborts requests that take too long to process.
101
- *
102
- * @param {number} [timeoutMs=30000] - Timeout in milliseconds
103
- * @returns {Middleware} Express-compatible middleware
104
- */
105
- function timeout(timeoutMs = 30000) {
106
- return (_req, res, next) => {
107
- // Set timeout for the request
108
- const timer = setTimeout(() => {
109
- const response = new exception_utils_1.RequestTimeoutException('Request timed out');
110
- res.status(http_status_codes_1.HttpStatusCodes.REQUEST_TIMEOUT).json(response);
111
- }, timeoutMs);
112
- // Clear timeout when response is sent
113
- res.on('finish', () => {
114
- clearTimeout(timer);
115
- });
116
- next();
117
- };
118
- }
119
- /**
120
- * Creates an Express middleware that initializes a per-request context.
121
- *
122
- * @param {object} [options] - Optional configuration
123
- * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
124
- * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
125
- * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
126
- */
127
- function setupRequestContext(options = {}) {
128
- const { headerName = 'x-request-id', autoLog = true } = options;
129
- return (req, _res, next) => {
130
- // Generate or use existing request ID
131
- const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || (0, id_utils_1.uuid)();
132
- context_store_utils_1.ContextStore.run({ [context_store_utils_1.StoreKeys.REQUEST_ID]: requestId }, () => {
133
- // Create a child logger for this request
134
- const childLogger = (0, logger_utils_1.getLogger)().child({
135
- requestId,
136
- method: req.method,
137
- url: req.originalUrl || req.url
138
- });
139
- // Store logger in context
140
- context_store_utils_1.ContextStore.set(context_store_utils_1.StoreKeys.LOGGER, childLogger);
141
- if (autoLog) {
142
- childLogger.info('Request context initialized');
143
- }
144
- next();
145
- });
146
- };
147
- }
148
- /**
149
- * Global error handling middleware with enhanced features.
150
- *
151
- * @param {ErrorHandlerOptions} options - Error handler options
152
- * @param {boolean} [options.logErrors=true] - Whether to log errors
153
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
154
- * @returns Error middleware
155
- *
156
- * @example
157
- * import express from 'express';
158
- * import { errorHandler } from '@catbee/utils';
159
- *
160
- * const app = express();
161
- *
162
- * // Your routes
163
- * app.get('/ping', (req, res) => {
164
- * throw new Error('Something went wrong');
165
- * });
166
- *
167
- * // Error handler (must be last middleware)
168
- * app.use(errorHandler({ includeDetails: true }));
169
- *
170
- * app.listen(3000, () => {
171
- * console.log('Server running on port 3000');
172
- * });
173
- */
174
- function errorHandler(options) {
175
- const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
176
- const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
177
- return (err, req, res, _next) => {
178
- // Determine status code
179
- 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;
180
- // Log error if enabled
181
- if (logErrors) {
182
- (0, logger_utils_1.getLogger)().error({ err }, `${err.message || 'Unknown error'}`);
183
- }
184
- // Handle ErrorResponse instances (our custom error class)
185
- if (err instanceof response_utils_1.ErrorResponse) {
186
- const result = {
187
- error: true,
188
- message: err.message,
189
- timestamp: err.timestamp,
190
- requestId: (err === null || err === void 0 ? void 0 : err.requestId) || (req === null || req === void 0 ? void 0 : req.id) || (0, id_utils_1.uuid)(),
191
- status,
192
- path: req.originalUrl || req.url
193
- };
194
- if (includeDetails && (err === null || err === void 0 ? void 0 : err.stack)) {
195
- result.stack = err.stack.split('\n').map((line) => line.trim());
196
- }
197
- return res.status(status).json(result);
198
- }
199
- // Handle any other errors
200
- return res
201
- .status(status)
202
- .json((0, response_utils_1.createFinalErrorResponse)(req, status, (err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', err, { includeDetails }));
203
- };
204
- }
205
- //# sourceMappingURL=middleware.utils.js.map