@catbee/utils 0.0.3 → 0.0.5

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 (98) hide show
  1. package/README.md +693 -245
  2. package/build/esm/config.d.ts +18 -7
  3. package/build/esm/config.js +23 -7
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +2 -0
  6. package/build/esm/index.js +2 -0
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/utils/cache.utils.js +16 -16
  9. package/build/esm/utils/cache.utils.js.map +1 -1
  10. package/build/esm/utils/context-store.utils.d.ts +1 -1
  11. package/build/esm/utils/context-store.utils.js +1 -1
  12. package/build/esm/utils/context-store.utils.js.map +1 -1
  13. package/build/esm/utils/crypto.utils.js +3 -2
  14. package/build/esm/utils/crypto.utils.js.map +1 -1
  15. package/build/esm/utils/decorators.utils.d.ts +292 -17
  16. package/build/esm/utils/decorators.utils.js +372 -40
  17. package/build/esm/utils/decorators.utils.js.map +1 -1
  18. package/build/esm/utils/env.utils.d.ts +186 -23
  19. package/build/esm/utils/env.utils.js +494 -91
  20. package/build/esm/utils/env.utils.js.map +1 -1
  21. package/build/esm/utils/exception.utils.js +1 -1
  22. package/build/esm/utils/exception.utils.js.map +1 -1
  23. package/build/esm/utils/logger.utils.d.ts +107 -0
  24. package/build/esm/utils/logger.utils.js +210 -19
  25. package/build/esm/utils/logger.utils.js.map +1 -1
  26. package/build/esm/utils/middleware.utils.d.ts +42 -34
  27. package/build/esm/utils/middleware.utils.js +88 -51
  28. package/build/esm/utils/middleware.utils.js.map +1 -1
  29. package/build/esm/utils/request.utils.d.ts +77 -0
  30. package/build/esm/utils/request.utils.js +173 -0
  31. package/build/esm/utils/request.utils.js.map +1 -0
  32. package/build/esm/utils/response.utils.js +4 -4
  33. package/build/esm/utils/response.utils.js.map +1 -1
  34. package/build/esnext/config.d.ts +18 -7
  35. package/build/esnext/config.js +23 -7
  36. package/build/esnext/config.js.map +1 -1
  37. package/build/esnext/index.d.ts +2 -0
  38. package/build/esnext/index.js +2 -0
  39. package/build/esnext/index.js.map +1 -1
  40. package/build/esnext/utils/cache.utils.js +16 -16
  41. package/build/esnext/utils/cache.utils.js.map +1 -1
  42. package/build/esnext/utils/context-store.utils.d.ts +1 -1
  43. package/build/esnext/utils/context-store.utils.js +1 -1
  44. package/build/esnext/utils/context-store.utils.js.map +1 -1
  45. package/build/esnext/utils/crypto.utils.js +3 -2
  46. package/build/esnext/utils/crypto.utils.js.map +1 -1
  47. package/build/esnext/utils/decorators.utils.d.ts +292 -17
  48. package/build/esnext/utils/decorators.utils.js +348 -21
  49. package/build/esnext/utils/decorators.utils.js.map +1 -1
  50. package/build/esnext/utils/env.utils.d.ts +186 -23
  51. package/build/esnext/utils/env.utils.js +445 -77
  52. package/build/esnext/utils/env.utils.js.map +1 -1
  53. package/build/esnext/utils/exception.utils.js +1 -1
  54. package/build/esnext/utils/exception.utils.js.map +1 -1
  55. package/build/esnext/utils/logger.utils.d.ts +107 -0
  56. package/build/esnext/utils/logger.utils.js +181 -19
  57. package/build/esnext/utils/logger.utils.js.map +1 -1
  58. package/build/esnext/utils/middleware.utils.d.ts +42 -34
  59. package/build/esnext/utils/middleware.utils.js +86 -51
  60. package/build/esnext/utils/middleware.utils.js.map +1 -1
  61. package/build/esnext/utils/request.utils.d.ts +77 -0
  62. package/build/esnext/utils/request.utils.js +145 -0
  63. package/build/esnext/utils/request.utils.js.map +1 -0
  64. package/build/esnext/utils/response.utils.js +4 -4
  65. package/build/esnext/utils/response.utils.js.map +1 -1
  66. package/build/src/config.d.ts +18 -7
  67. package/build/src/config.js +26 -8
  68. package/build/src/config.js.map +1 -1
  69. package/build/src/index.d.ts +2 -0
  70. package/build/src/index.js +5 -0
  71. package/build/src/index.js.map +1 -1
  72. package/build/src/utils/cache.utils.js +15 -15
  73. package/build/src/utils/cache.utils.js.map +1 -1
  74. package/build/src/utils/context-store.utils.d.ts +1 -1
  75. package/build/src/utils/context-store.utils.js +1 -1
  76. package/build/src/utils/context-store.utils.js.map +1 -1
  77. package/build/src/utils/crypto.utils.js +2 -1
  78. package/build/src/utils/crypto.utils.js.map +1 -1
  79. package/build/src/utils/decorators.utils.d.ts +292 -17
  80. package/build/src/utils/decorators.utils.js +350 -21
  81. package/build/src/utils/decorators.utils.js.map +1 -1
  82. package/build/src/utils/env.utils.d.ts +186 -23
  83. package/build/src/utils/env.utils.js +444 -76
  84. package/build/src/utils/env.utils.js.map +1 -1
  85. package/build/src/utils/exception.utils.js +1 -1
  86. package/build/src/utils/exception.utils.js.map +1 -1
  87. package/build/src/utils/logger.utils.d.ts +107 -0
  88. package/build/src/utils/logger.utils.js +187 -19
  89. package/build/src/utils/logger.utils.js.map +1 -1
  90. package/build/src/utils/middleware.utils.d.ts +42 -34
  91. package/build/src/utils/middleware.utils.js +86 -50
  92. package/build/src/utils/middleware.utils.js.map +1 -1
  93. package/build/src/utils/request.utils.d.ts +77 -0
  94. package/build/src/utils/request.utils.js +152 -0
  95. package/build/src/utils/request.utils.js.map +1 -0
  96. package/build/src/utils/response.utils.js +4 -4
  97. package/build/src/utils/response.utils.js.map +1 -1
  98. package/package.json +11 -6
@@ -9,13 +9,202 @@ var __assign = (this && this.__assign) || function () {
9
9
  };
10
10
  return __assign.apply(this, arguments);
11
11
  };
12
+ var __read = (this && this.__read) || function (o, n) {
13
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
14
+ if (!m) return o;
15
+ var i = m.call(o), r, ar = [], e;
16
+ try {
17
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
18
+ }
19
+ catch (error) { e = { error: error }; }
20
+ finally {
21
+ try {
22
+ if (r && !r.done && (m = i["return"])) m.call(i);
23
+ }
24
+ finally { if (e) throw e.error; }
25
+ }
26
+ return ar;
27
+ };
28
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
29
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
30
+ if (ar || !(i in from)) {
31
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
32
+ ar[i] = from[i];
33
+ }
34
+ }
35
+ return to.concat(ar || Array.prototype.slice.call(from));
36
+ };
12
37
  import pino, { stdTimeFunctions } from 'pino';
13
- import { Config } from '../config';
38
+ import { config } from '../config';
14
39
  import { ContextStore, StoreKeys } from './context-store.utils';
40
+ import { Env } from './env.utils';
15
41
  /**
16
42
  * Symbol used to store the root logger in the Node.js global object.
17
43
  */
18
44
  var GLOBAL_LOGGER_KEY = Symbol.for('logger');
45
+ // Default sensitive fields
46
+ export var defaultSensitiveFields = [
47
+ 'password',
48
+ 'secret',
49
+ 'token',
50
+ 'apiKey',
51
+ 'api_key',
52
+ 'auth',
53
+ 'jwt',
54
+ 'access_token',
55
+ 'client_secret',
56
+ 'session_token',
57
+ 'refresh_token'
58
+ ];
59
+ /**
60
+ * The global censor function used by the logger.
61
+ */
62
+ var globalRedactCensor = function (value, path, sensitiveFields) {
63
+ if (sensitiveFields === void 0) { sensitiveFields = defaultSensitiveFields; }
64
+ if (typeof value !== 'string')
65
+ return '***';
66
+ var lowerPath = path.map(function (p) { return p.toLowerCase(); });
67
+ var lowerSensitiveFields = sensitiveFields.map(function (f) { return f.toLowerCase(); });
68
+ if (lowerPath.some(function (p) { return lowerSensitiveFields.includes(p); }))
69
+ return '***';
70
+ // Redact URLs
71
+ if (lowerPath[0] === 'url') {
72
+ return value.replace(new RegExp("([?&](".concat(lowerSensitiveFields.join('|'), ")=)[^&#]*"), 'gi'), '$1***');
73
+ }
74
+ if (lowerPath.some(function (p) { return p.includes('authorization') || p.includes('auth'); })) {
75
+ return value.replace(/^(\S+)\s+.+$/, '$1 ***') || '***';
76
+ }
77
+ // Redact sensitive fields - check each path segment against each sensitive field
78
+ if (lowerPath.some(function (pathPart) { return lowerSensitiveFields.some(function (field) { return pathPart.includes(field); }); })) {
79
+ return '***';
80
+ }
81
+ if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {
82
+ return value;
83
+ }
84
+ return value;
85
+ };
86
+ /**
87
+ * Sets the global redaction censor function used throughout the application for log redaction.
88
+ *
89
+ * Use this function to customize how sensitive data is redacted in logs. The provided function
90
+ * will replace the default censor implementation.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * // Custom censor that redacts only specific values
95
+ * setRedactCensor((value, path, sensitiveFields) => {
96
+ * if (path.includes('password')) return '***';
97
+ * return value;
98
+ * });
99
+ * ```
100
+ *
101
+ * @param fn - The redaction censor function to use globally. This function receives:
102
+ * - value: The data value to potentially redact
103
+ * - path: Array of strings representing the path to the value in the object
104
+ * - sensitiveFields: Optional array of field names to consider sensitive
105
+ * @returns void
106
+ */
107
+ export function setRedactCensor(fn) {
108
+ globalRedactCensor = fn;
109
+ }
110
+ /**
111
+ * Gets the current global redaction censor function used for log redaction.
112
+ *
113
+ * This function is called internally by the logger when determining how to redact
114
+ * sensitive information. It can also be used to access the current censor implementation
115
+ * for composition or extension.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * const currentCensor = getRedactCensor();
120
+ * // Create an enhanced censor that extends the current one
121
+ * setRedactCensor((value, path, fields) => {
122
+ * // Add custom logic before delegating to current censor
123
+ * if (someCondition) return customHandling();
124
+ * return currentCensor(value, path, fields);
125
+ * });
126
+ * ```
127
+ *
128
+ * @returns The current redaction censor function
129
+ */
130
+ export function getRedactCensor() {
131
+ return globalRedactCensor;
132
+ }
133
+ /**
134
+ * Convenience function to redact sensitive data using the current global redact censor.
135
+ *
136
+ * This is a direct wrapper around the global censor function that simplifies usage
137
+ * in application code without needing to access the censor function directly.
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * // Redact a potential sensitive value
142
+ * const safeValue = redact(value, ['user', 'apiKey']);
143
+ * ```
144
+ *
145
+ * @param value - The value to potentially redact
146
+ * @param path - Array of strings representing the path to the value in the object
147
+ * @param sensitiveFields - Optional array of field names to consider sensitive
148
+ * @returns The redacted string value or "***" for redacted content
149
+ */
150
+ export function redact(value, path, sensitiveFields) {
151
+ return globalRedactCensor(value, path, sensitiveFields);
152
+ }
153
+ /**
154
+ * Extends the current redaction function with additional fields to redact.
155
+ *
156
+ * This function wraps the existing censor while adding more fields to be considered
157
+ * sensitive without replacing the entire redaction logic.
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * // Add custom fields to be redacted in all future redaction operations
162
+ * addRedactFields(['customerId', 'accountNumber']);
163
+ * ```
164
+ *
165
+ * @param fields - Array of additional field names to redact
166
+ */
167
+ export function addRedactFields(fields) {
168
+ var prev = globalRedactCensor;
169
+ globalRedactCensor = function (value, path, sensitiveFields) {
170
+ if (sensitiveFields === void 0) { sensitiveFields = defaultSensitiveFields; }
171
+ return prev(value, path, __spreadArray(__spreadArray([], __read((sensitiveFields || [])), false), __read(fields), false));
172
+ };
173
+ }
174
+ /**
175
+ * Replaces the default list of sensitive fields with a new list.
176
+ *
177
+ * This is useful when you want complete control over what fields are considered
178
+ * sensitive by default, rather than using the library's built-in list.
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * // Replace default sensitive fields with a custom list
183
+ * setSensitiveFields(['password', 'ssn', 'creditCard']);
184
+ * ```
185
+ *
186
+ * @param fields - Array of field names to set as the new default sensitive fields
187
+ */
188
+ export function setSensitiveFields(fields) {
189
+ defaultSensitiveFields.splice.apply(defaultSensitiveFields, __spreadArray([0, defaultSensitiveFields.length], __read(fields), false));
190
+ }
191
+ /**
192
+ * Adds additional field names to the default sensitive fields list.
193
+ *
194
+ * This preserves the existing sensitive fields while adding new ones for
195
+ * application-specific sensitive data.
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * // Add domain-specific sensitive fields to the default list
200
+ * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
201
+ * ```
202
+ *
203
+ * @param fields - Array of additional field names to add to the sensitive fields list
204
+ */
205
+ export function addSensitiveFields(fields) {
206
+ defaultSensitiveFields.push.apply(defaultSensitiveFields, __spreadArray([], __read(fields), false));
207
+ }
19
208
  /**
20
209
  * Use an object compatible with either modern or legacy global scopes.
21
210
  */
@@ -29,25 +218,27 @@ var _global = _globalThis;
29
218
  */
30
219
  function setupLogger() {
31
220
  var logParams = {
32
- name: Config.Logger.name,
33
- level: Config.Logger.level,
221
+ name: config.logger.name || '@catbee/utils',
222
+ level: config.logger.level || 'info',
34
223
  redact: {
35
- paths: ['req.authorization', 'url'],
36
- censor: function (value, path) {
37
- if (path[0] === 'url') {
38
- return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');
39
- }
40
- else if (path[1] === 'authorization') {
41
- return value.replace(/\s+(\S+)$/, ' ***');
42
- }
43
- return '***';
44
- }
45
- }
224
+ paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization'],
225
+ censor: function (value, path) { return redact(value, path); }
226
+ },
227
+ timestamp: stdTimeFunctions.isoTime
46
228
  };
47
- if (Config.Logger.isoTimestamp) {
48
- logParams.timestamp = stdTimeFunctions.isoTime;
49
- }
50
- _global[GLOBAL_LOGGER_KEY] = pino(logParams);
229
+ var logger = config.logger.pretty && Env.isDev()
230
+ ? pino(logParams, pino.transport({
231
+ target: 'pino-pretty',
232
+ options: {
233
+ colorize: true,
234
+ translateTime: 'SYS:standard',
235
+ ignore: 'pid,hostname',
236
+ singleLine: false, // multi-line errors
237
+ levelFirst: true
238
+ }
239
+ }))
240
+ : pino(logParams);
241
+ _global[GLOBAL_LOGGER_KEY] = logger;
51
242
  _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');
52
243
  }
53
244
  /**
@@ -107,7 +298,7 @@ export function createRequestLogger(requestId, additionalContext) {
107
298
  export function logError(error, message, context) {
108
299
  var logger = getLogger();
109
300
  var errObj = error instanceof Error ? error : new Error(String(error));
110
- var logContext = __assign(__assign({}, context), { err: errObj });
301
+ var logContext = __assign(__assign({}, context), { error: errObj });
111
302
  logger.error(logContext, message || errObj.message);
112
303
  }
113
304
  //# sourceMappingURL=logger.utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.utils.js","sourceRoot":"","sources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AC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,IAAM,UAAU,yBACX,OAAO,KACV,GAAG,EAAE,MAAM,GACZ,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import 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';\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/**\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,\n level: Config.Logger.level,\n redact: {\n paths: ['req.authorization', 'url'],\n censor(value, path) {\n if (path[0] === 'url') {\n return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');\n } else if (path[1] === 'authorization') {\n return value.replace(/\\s+(\\S+)$/, ' ***');\n }\n return '***';\n }\n }\n };\n\n if (Config.Logger.isoTimestamp) {\n logParams.timestamp = stdTimeFunctions.isoTime;\n }\n\n _global[GLOBAL_LOGGER_KEY] = pino(logParams);\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 * 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 err: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
1
+ {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,E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QAC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,IAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,IAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,IAAM,UAAU,yBACX,OAAO,KACV,KAAK,EAAE,MAAM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import 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'],\n censor: (value, path) => redact(value, path)\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: false, // multi-line errors\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 * 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,27 +1,5 @@
1
- /**
2
- * Type definitions for Express-compatible middleware
3
- */
4
- 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
- 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
- type NextFunction = (err?: Error | any) => void;
24
- type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
1
+ import type { Request, Response, NextFunction } from 'express';
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.
27
5
  * Useful for request tracing and correlation between logs.
@@ -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,19 +33,49 @@ 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;
48
+ export interface ErrorHandlerOptions {
49
+ /** Whether to log errors (default: true) */
50
+ logErrors?: boolean;
51
+ /** Whether to include error details in non-production (default: false) */
52
+ includeDetails?: boolean;
53
+ }
58
54
  /**
59
55
  * Global error handling middleware with enhanced features.
60
56
  *
61
- * @param {object} [options] - Error handler options
57
+ * @param {ErrorHandlerOptions} options - Error handler options
62
58
  * @param {boolean} [options.logErrors=true] - Whether to log errors
63
59
  * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
64
- * @param {Function} [options.logger=getLogger().error] - Custom logging function
65
- * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware
60
+ * @returns Error middleware
61
+ *
62
+ * @example
63
+ * import express from 'express';
64
+ * import { errorHandler } from '@catbee/utils';
65
+ *
66
+ * const app = express();
67
+ *
68
+ * // Your routes
69
+ * app.get('/ping', (req, res) => {
70
+ * throw new Error('Something went wrong');
71
+ * });
72
+ *
73
+ * // Error handler (must be last middleware)
74
+ * app.use(errorHandler({ includeDetails: true }));
75
+ *
76
+ * app.listen(3000, () => {
77
+ * console.log('Server running on port 3000');
78
+ * });
66
79
  */
67
- export declare function errorHandler(options?: {
68
- logErrors?: boolean;
69
- includeDetails?: boolean;
70
- logger?: (message: string, error: any) => void;
71
- }): (err: any, req: Request, res: Response, _next: NextFunction) => void;
72
- export {};
80
+ export declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
73
81
  //# sourceMappingURL=middleware.utils.d.ts.map
@@ -1,10 +1,10 @@
1
- import { randomUUID } from 'crypto';
2
- import { Config } from '../config';
1
+ import { config } from '../config';
3
2
  import { uuid } from './id.utils';
4
3
  import { HttpStatusCodes } from './http-status-codes';
5
4
  import { ErrorResponse } from './response.utils';
6
5
  import { Env } from './env.utils';
7
6
  import { getLogger } from './logger.utils';
7
+ import { ContextStore, StoreKeys } from './context-store.utils';
8
8
  /**
9
9
  * Attaches a unique request ID to each request.
10
10
  * Useful for request tracing and correlation between logs.
@@ -20,7 +20,7 @@ export function requestId(options) {
20
20
  return function (req, res, next) {
21
21
  // Use existing request ID from header or generate a new one
22
22
  var existingId = req.headers[headerName.toLowerCase()];
23
- var id = existingId || randomUUID();
23
+ var id = existingId || uuid();
24
24
  // Attach ID to request object
25
25
  req.id = id;
26
26
  // Add ID to response headers
@@ -43,22 +43,23 @@ export function responseTime(options) {
43
43
  var logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
44
44
  return function (req, res, next) {
45
45
  var start = process.hrtime();
46
- // Function to calculate elapsed time
47
- var calculateDuration = function () {
48
- var diff = process.hrtime(start);
49
- return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms
50
- };
51
- // Handle response completion
52
- res.on('finish', function () {
53
- var duration = calculateDuration();
54
- if (addHeader) {
46
+ if (addHeader) {
47
+ // Wrap res.end to set header just before sending response
48
+ var originalEnd_1 = res.end;
49
+ res.end = function (chunk, encoding, cb) {
50
+ var diff = process.hrtime(start);
51
+ var duration = diff[0] * 1e3 + diff[1] * 1e-6;
55
52
  res.setHeader('X-Response-Time', "".concat(duration.toFixed(2), "ms"));
56
- }
57
- if (logOnComplete) {
58
- var method = req.method, url = req.url;
59
- getLogger().info("".concat(method, " ").concat(url, " - ").concat(duration.toFixed(2), "ms"));
60
- }
61
- });
53
+ return originalEnd_1.call(this, chunk, encoding, cb);
54
+ };
55
+ }
56
+ if (logOnComplete) {
57
+ res.on('finish', function () {
58
+ var diff = process.hrtime(start);
59
+ var duration = diff[0] * 1e3 + diff[1] * 1e-6;
60
+ getLogger().info("".concat(req.method, " ").concat(req.url, " - ").concat(duration.toFixed(2), "ms"));
61
+ });
62
+ }
62
63
  next();
63
64
  };
64
65
  }
@@ -70,7 +71,7 @@ export function responseTime(options) {
70
71
  * @returns {Middleware} Express-compatible middleware
71
72
  */
72
73
  export function timeout(timeoutMs) {
73
- if (timeoutMs === void 0) { timeoutMs = Config.Http.timeout; }
74
+ if (timeoutMs === void 0) { timeoutMs = config.http.timeout; }
74
75
  return function (req, res, next) {
75
76
  // Set timeout for the request
76
77
  var timer = setTimeout(function () {
@@ -89,55 +90,71 @@ export function timeout(timeoutMs) {
89
90
  };
90
91
  }
91
92
  /**
92
- * Creates a standardized error response object for API errors.
93
+ * Creates an Express middleware that initializes a per-request context.
93
94
  *
94
- * @param {string} message - Error message
95
- * @param {Request} req - Express request object
96
- * @param {any} error - Original error object
97
- * @param {object} [options] - Additional options
98
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
99
- * @returns {object} Formatted error response
95
+ * @param {object} [options] - Optional configuration
96
+ * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
97
+ * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
98
+ * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
100
99
  */
101
- var createErrorResponse = function (message, req, error, options) {
102
- var isDev = Env.isDev();
103
- var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
104
- var response = {
105
- error: true,
106
- message: message,
107
- timestamp: new Date().toISOString(),
108
- requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
109
- path: req.originalUrl || req.url
100
+ export function setupRequestContext(options) {
101
+ if (options === void 0) { options = {}; }
102
+ var _a = options.headerName, headerName = _a === void 0 ? 'x-request-id' : _a, _b = options.autoLog, autoLog = _b === void 0 ? true : _b;
103
+ return function (req, _res, next) {
104
+ var _a;
105
+ // Generate or use existing request ID
106
+ var requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || uuid();
107
+ ContextStore.run((_a = {}, _a[StoreKeys.REQUEST_ID] = requestId, _a), function () {
108
+ // Create a child logger for this request
109
+ var childLogger = getLogger().child({
110
+ requestId: requestId,
111
+ method: req.method,
112
+ url: req.originalUrl || req.url
113
+ });
114
+ // Store logger in context
115
+ ContextStore.set(StoreKeys.LOGGER, childLogger);
116
+ if (autoLog) {
117
+ childLogger.info('Request context initialized');
118
+ }
119
+ next();
120
+ });
110
121
  };
111
- // Include error code if present
112
- if (error === null || error === void 0 ? void 0 : error.code) {
113
- response.code = error.code;
114
- }
115
- // Include stack trace in development mode if requested
116
- if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
117
- response.stack = error.stack.split('\n').map(function (line) { return line.trim(); });
118
- }
119
- return response;
120
- };
122
+ }
121
123
  /**
122
124
  * Global error handling middleware with enhanced features.
123
125
  *
124
- * @param {object} [options] - Error handler options
126
+ * @param {ErrorHandlerOptions} options - Error handler options
125
127
  * @param {boolean} [options.logErrors=true] - Whether to log errors
126
128
  * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
127
- * @param {Function} [options.logger=getLogger().error] - Custom logging function
128
- * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware
129
+ * @returns Error middleware
130
+ *
131
+ * @example
132
+ * import express from 'express';
133
+ * import { errorHandler } from '@catbee/utils';
134
+ *
135
+ * const app = express();
136
+ *
137
+ * // Your routes
138
+ * app.get('/ping', (req, res) => {
139
+ * throw new Error('Something went wrong');
140
+ * });
141
+ *
142
+ * // Error handler (must be last middleware)
143
+ * app.use(errorHandler({ includeDetails: true }));
144
+ *
145
+ * app.listen(3000, () => {
146
+ * console.log('Server running on port 3000');
147
+ * });
129
148
  */
130
149
  export function errorHandler(options) {
131
150
  var logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
132
151
  var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
133
- var logger = (options === null || options === void 0 ? void 0 : options.logger) || getLogger().error;
134
152
  return function (err, req, res, _next) {
135
153
  // Determine status code
136
154
  var status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
137
155
  // Log error if enabled
138
156
  if (logErrors) {
139
- var logMessage = "[ERROR] ".concat(req.method, " ").concat(req.originalUrl || req.url, ": ").concat(err.message || 'Unknown error');
140
- logger(logMessage, err);
157
+ getLogger().error({ error: err }, "".concat(err.message || 'Unknown error'));
141
158
  }
142
159
  // Handle ErrorResponse instances (our custom error class)
143
160
  if (err instanceof ErrorResponse) {
@@ -149,6 +166,26 @@ export function errorHandler(options) {
149
166
  path: req.originalUrl || req.url
150
167
  });
151
168
  }
169
+ var createErrorResponse = function (message, req, error, options) {
170
+ var isDev = Env.isDev();
171
+ var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
172
+ var response = {
173
+ error: true,
174
+ message: message,
175
+ timestamp: new Date().toISOString(),
176
+ requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
177
+ path: req.originalUrl || req.url
178
+ };
179
+ // Include error code if present
180
+ if (error === null || error === void 0 ? void 0 : error.code) {
181
+ response.code = error.code;
182
+ }
183
+ // Include stack trace in development mode if requested
184
+ if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
185
+ response.stack = error.stack.split('\n').map(function (line) { return line.trim(); });
186
+ }
187
+ return response;
188
+ };
152
189
  // Handle any other errors
153
190
  return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
154
191
  includeDetails: includeDetails