@catbee/utils 0.0.8-next.0 → 0.0.8-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/README.md +1 -2
  2. package/build/esm/config.d.ts +122 -0
  3. package/build/esm/config.js +133 -0
  4. package/build/esm/config.js.map +1 -0
  5. package/build/esm/index.d.ts +27 -0
  6. package/build/esm/index.js +50 -0
  7. package/build/esm/index.js.map +1 -0
  8. package/build/esm/servers/server.builder.d.ts +508 -0
  9. package/build/esm/servers/server.builder.js +702 -0
  10. package/build/esm/servers/server.builder.js.map +1 -0
  11. package/build/esm/servers/server.d.ts +256 -0
  12. package/build/esm/servers/server.js +1248 -0
  13. package/build/esm/servers/server.js.map +1 -0
  14. package/build/esm/types/api-response.d.ts +152 -0
  15. package/build/esm/types/api-response.js +34 -0
  16. package/build/esm/types/api-response.js.map +1 -0
  17. package/build/esm/types/index.d.ts +125 -0
  18. package/build/esm/types/index.js +25 -0
  19. package/build/esm/types/index.js.map +1 -0
  20. package/build/esm/types/server.d.ts +268 -0
  21. package/build/esm/types/server.js +25 -0
  22. package/build/esm/types/server.js.map +1 -0
  23. package/build/esm/utils/array.utils.d.ts +168 -0
  24. package/build/esm/utils/array.utils.js +382 -0
  25. package/build/esm/utils/array.utils.js.map +1 -0
  26. package/build/esm/utils/async.utils.d.ts +265 -0
  27. package/build/esm/utils/async.utils.js +896 -0
  28. package/build/esm/utils/async.utils.js.map +1 -0
  29. package/build/esm/utils/cache.utils.d.ts +153 -0
  30. package/build/esm/utils/cache.utils.js +499 -0
  31. package/build/esm/utils/cache.utils.js.map +1 -0
  32. package/build/esm/utils/context-store.utils.d.ts +189 -0
  33. package/build/esm/utils/context-store.utils.js +307 -0
  34. package/build/esm/utils/context-store.utils.js.map +1 -0
  35. package/build/esm/utils/crypto.utils.d.ts +160 -0
  36. package/build/esm/utils/crypto.utils.js +375 -0
  37. package/build/esm/utils/crypto.utils.js.map +1 -0
  38. package/build/esm/utils/date.utils.d.ts +159 -0
  39. package/build/esm/utils/date.utils.js +389 -0
  40. package/build/esm/utils/date.utils.js.map +1 -0
  41. package/build/esm/utils/decorators.utils.d.ts +508 -0
  42. package/build/esm/utils/decorators.utils.js +1057 -0
  43. package/build/esm/utils/decorators.utils.js.map +1 -0
  44. package/build/esm/utils/dir.utils.d.ts +196 -0
  45. package/build/esm/utils/dir.utils.js +998 -0
  46. package/build/esm/utils/dir.utils.js.map +1 -0
  47. package/build/esm/utils/env.utils.d.ts +377 -0
  48. package/build/esm/utils/env.utils.js +873 -0
  49. package/build/esm/utils/env.utils.js.map +1 -0
  50. package/build/esm/utils/exception.utils.d.ts +230 -0
  51. package/build/esm/utils/exception.utils.js +559 -0
  52. package/build/esm/utils/exception.utils.js.map +1 -0
  53. package/build/esm/utils/fs.utils.d.ts +164 -0
  54. package/build/esm/utils/fs.utils.js +580 -0
  55. package/build/esm/utils/fs.utils.js.map +1 -0
  56. package/build/esm/utils/http-status-codes.d.ts +266 -0
  57. package/build/esm/utils/http-status-codes.js +295 -0
  58. package/build/esm/utils/http-status-codes.js.map +1 -0
  59. package/build/esm/utils/id.utils.d.ts +36 -0
  60. package/build/esm/utils/id.utils.js +87 -0
  61. package/build/esm/utils/id.utils.js.map +1 -0
  62. package/build/esm/utils/logger.utils.d.ts +160 -0
  63. package/build/esm/utils/logger.utils.js +341 -0
  64. package/build/esm/utils/logger.utils.js.map +1 -0
  65. package/build/esm/utils/middleware.utils.d.ts +100 -0
  66. package/build/esm/utils/middleware.utils.js +325 -0
  67. package/build/esm/utils/middleware.utils.js.map +1 -0
  68. package/build/esm/utils/obj.utils.d.ts +124 -0
  69. package/build/esm/utils/obj.utils.js +519 -0
  70. package/build/esm/utils/obj.utils.js.map +1 -0
  71. package/build/esm/utils/performance.utils.d.ts +136 -0
  72. package/build/esm/utils/performance.utils.js +376 -0
  73. package/build/esm/utils/performance.utils.js.map +1 -0
  74. package/build/esm/utils/request.utils.d.ts +86 -0
  75. package/build/esm/utils/request.utils.js +223 -0
  76. package/build/esm/utils/request.utils.js.map +1 -0
  77. package/build/esm/utils/response.utils.d.ts +163 -0
  78. package/build/esm/utils/response.utils.js +284 -0
  79. package/build/esm/utils/response.utils.js.map +1 -0
  80. package/build/esm/utils/stream.utils.d.ts +88 -0
  81. package/build/esm/utils/stream.utils.js +284 -0
  82. package/build/esm/utils/stream.utils.js.map +1 -0
  83. package/build/esm/utils/string.utils.d.ts +93 -0
  84. package/build/esm/utils/string.utils.js +169 -0
  85. package/build/esm/utils/string.utils.js.map +1 -0
  86. package/build/esm/utils/type.utils.d.ts +90 -0
  87. package/build/esm/utils/type.utils.js +190 -0
  88. package/build/esm/utils/type.utils.js.map +1 -0
  89. package/build/esm/utils/url.utils.d.ts +141 -0
  90. package/build/esm/utils/url.utils.js +381 -0
  91. package/build/esm/utils/url.utils.js.map +1 -0
  92. package/build/esm/utils/validate.utils.d.ts +177 -0
  93. package/build/esm/utils/validate.utils.js +336 -0
  94. package/build/esm/utils/validate.utils.js.map +1 -0
  95. package/build/esnext/config.d.ts +122 -0
  96. package/build/esnext/config.js +133 -0
  97. package/build/esnext/config.js.map +1 -0
  98. package/build/esnext/index.d.ts +27 -0
  99. package/build/esnext/index.js +50 -0
  100. package/build/esnext/index.js.map +1 -0
  101. package/build/esnext/servers/server.builder.d.ts +508 -0
  102. package/build/esnext/servers/server.builder.js +657 -0
  103. package/build/esnext/servers/server.builder.js.map +1 -0
  104. package/build/esnext/servers/server.d.ts +256 -0
  105. package/build/esnext/servers/server.js +955 -0
  106. package/build/esnext/servers/server.js.map +1 -0
  107. package/build/esnext/types/api-response.d.ts +152 -0
  108. package/build/esnext/types/api-response.js +34 -0
  109. package/build/esnext/types/api-response.js.map +1 -0
  110. package/build/esnext/types/index.d.ts +125 -0
  111. package/build/esnext/types/index.js +25 -0
  112. package/build/esnext/types/index.js.map +1 -0
  113. package/build/esnext/types/server.d.ts +268 -0
  114. package/build/esnext/types/server.js +25 -0
  115. package/build/esnext/types/server.js.map +1 -0
  116. package/build/esnext/utils/array.utils.d.ts +168 -0
  117. package/build/esnext/utils/array.utils.js +345 -0
  118. package/build/esnext/utils/array.utils.js.map +1 -0
  119. package/build/esnext/utils/async.utils.d.ts +265 -0
  120. package/build/esnext/utils/async.utils.js +620 -0
  121. package/build/esnext/utils/async.utils.js.map +1 -0
  122. package/build/esnext/utils/cache.utils.d.ts +153 -0
  123. package/build/esnext/utils/cache.utils.js +293 -0
  124. package/build/esnext/utils/cache.utils.js.map +1 -0
  125. package/build/esnext/utils/context-store.utils.d.ts +189 -0
  126. package/build/esnext/utils/context-store.utils.js +289 -0
  127. package/build/esnext/utils/context-store.utils.js.map +1 -0
  128. package/build/esnext/utils/crypto.utils.d.ts +160 -0
  129. package/build/esnext/utils/crypto.utils.js +276 -0
  130. package/build/esnext/utils/crypto.utils.js.map +1 -0
  131. package/build/esnext/utils/date.utils.d.ts +159 -0
  132. package/build/esnext/utils/date.utils.js +384 -0
  133. package/build/esnext/utils/date.utils.js.map +1 -0
  134. package/build/esnext/utils/decorators.utils.d.ts +508 -0
  135. package/build/esnext/utils/decorators.utils.js +877 -0
  136. package/build/esnext/utils/decorators.utils.js.map +1 -0
  137. package/build/esnext/utils/dir.utils.d.ts +196 -0
  138. package/build/esnext/utils/dir.utils.js +477 -0
  139. package/build/esnext/utils/dir.utils.js.map +1 -0
  140. package/build/esnext/utils/env.utils.d.ts +377 -0
  141. package/build/esnext/utils/env.utils.js +785 -0
  142. package/build/esnext/utils/env.utils.js.map +1 -0
  143. package/build/esnext/utils/exception.utils.d.ts +230 -0
  144. package/build/esnext/utils/exception.utils.js +381 -0
  145. package/build/esnext/utils/exception.utils.js.map +1 -0
  146. package/build/esnext/utils/fs.utils.d.ts +164 -0
  147. package/build/esnext/utils/fs.utils.js +349 -0
  148. package/build/esnext/utils/fs.utils.js.map +1 -0
  149. package/build/esnext/utils/http-status-codes.d.ts +266 -0
  150. package/build/esnext/utils/http-status-codes.js +295 -0
  151. package/build/esnext/utils/http-status-codes.js.map +1 -0
  152. package/build/esnext/utils/id.utils.d.ts +36 -0
  153. package/build/esnext/utils/id.utils.js +84 -0
  154. package/build/esnext/utils/id.utils.js.map +1 -0
  155. package/build/esnext/utils/logger.utils.d.ts +160 -0
  156. package/build/esnext/utils/logger.utils.js +300 -0
  157. package/build/esnext/utils/logger.utils.js.map +1 -0
  158. package/build/esnext/utils/middleware.utils.d.ts +100 -0
  159. package/build/esnext/utils/middleware.utils.js +236 -0
  160. package/build/esnext/utils/middleware.utils.js.map +1 -0
  161. package/build/esnext/utils/obj.utils.d.ts +124 -0
  162. package/build/esnext/utils/obj.utils.js +413 -0
  163. package/build/esnext/utils/obj.utils.js.map +1 -0
  164. package/build/esnext/utils/performance.utils.d.ts +136 -0
  165. package/build/esnext/utils/performance.utils.js +271 -0
  166. package/build/esnext/utils/performance.utils.js.map +1 -0
  167. package/build/esnext/utils/request.utils.d.ts +86 -0
  168. package/build/esnext/utils/request.utils.js +186 -0
  169. package/build/esnext/utils/request.utils.js.map +1 -0
  170. package/build/esnext/utils/response.utils.d.ts +163 -0
  171. package/build/esnext/utils/response.utils.js +247 -0
  172. package/build/esnext/utils/response.utils.js.map +1 -0
  173. package/build/esnext/utils/stream.utils.d.ts +88 -0
  174. package/build/esnext/utils/stream.utils.js +210 -0
  175. package/build/esnext/utils/stream.utils.js.map +1 -0
  176. package/build/esnext/utils/string.utils.d.ts +93 -0
  177. package/build/esnext/utils/string.utils.js +165 -0
  178. package/build/esnext/utils/string.utils.js.map +1 -0
  179. package/build/esnext/utils/type.utils.d.ts +90 -0
  180. package/build/esnext/utils/type.utils.js +187 -0
  181. package/build/esnext/utils/type.utils.js.map +1 -0
  182. package/build/esnext/utils/url.utils.d.ts +141 -0
  183. package/build/esnext/utils/url.utils.js +304 -0
  184. package/build/esnext/utils/url.utils.js.map +1 -0
  185. package/build/esnext/utils/validate.utils.d.ts +177 -0
  186. package/build/esnext/utils/validate.utils.js +320 -0
  187. package/build/esnext/utils/validate.utils.js.map +1 -0
  188. package/build/src/config.d.ts +122 -0
  189. package/build/src/config.js +138 -0
  190. package/build/src/config.js.map +1 -0
  191. package/build/src/index.d.ts +27 -0
  192. package/build/src/index.js +69 -0
  193. package/build/src/index.js.map +1 -0
  194. package/build/src/servers/server.builder.d.ts +508 -0
  195. package/build/src/servers/server.builder.js +661 -0
  196. package/build/src/servers/server.builder.js.map +1 -0
  197. package/build/src/servers/server.d.ts +256 -0
  198. package/build/src/servers/server.js +962 -0
  199. package/build/src/servers/server.js.map +1 -0
  200. package/build/src/types/api-response.d.ts +152 -0
  201. package/build/src/types/api-response.js +37 -0
  202. package/build/src/types/api-response.js.map +1 -0
  203. package/build/src/types/index.d.ts +125 -0
  204. package/build/src/types/index.js +26 -0
  205. package/build/src/types/index.js.map +1 -0
  206. package/build/src/types/server.d.ts +268 -0
  207. package/build/src/types/server.js +26 -0
  208. package/build/src/types/server.js.map +1 -0
  209. package/build/src/utils/array.utils.d.ts +168 -0
  210. package/build/src/utils/array.utils.js +364 -0
  211. package/build/src/utils/array.utils.js.map +1 -0
  212. package/build/src/utils/async.utils.d.ts +265 -0
  213. package/build/src/utils/async.utils.js +641 -0
  214. package/build/src/utils/async.utils.js.map +1 -0
  215. package/build/src/utils/cache.utils.d.ts +153 -0
  216. package/build/src/utils/cache.utils.js +297 -0
  217. package/build/src/utils/cache.utils.js.map +1 -0
  218. package/build/src/utils/context-store.utils.d.ts +189 -0
  219. package/build/src/utils/context-store.utils.js +296 -0
  220. package/build/src/utils/context-store.utils.js.map +1 -0
  221. package/build/src/utils/crypto.utils.d.ts +160 -0
  222. package/build/src/utils/crypto.utils.js +293 -0
  223. package/build/src/utils/crypto.utils.js.map +1 -0
  224. package/build/src/utils/date.utils.d.ts +159 -0
  225. package/build/src/utils/date.utils.js +396 -0
  226. package/build/src/utils/date.utils.js.map +1 -0
  227. package/build/src/utils/decorators.utils.d.ts +508 -0
  228. package/build/src/utils/decorators.utils.js +896 -0
  229. package/build/src/utils/decorators.utils.js.map +1 -0
  230. package/build/src/utils/dir.utils.d.ts +196 -0
  231. package/build/src/utils/dir.utils.js +501 -0
  232. package/build/src/utils/dir.utils.js.map +1 -0
  233. package/build/src/utils/env.utils.d.ts +377 -0
  234. package/build/src/utils/env.utils.js +789 -0
  235. package/build/src/utils/env.utils.js.map +1 -0
  236. package/build/src/utils/exception.utils.d.ts +230 -0
  237. package/build/src/utils/exception.utils.js +407 -0
  238. package/build/src/utils/exception.utils.js.map +1 -0
  239. package/build/src/utils/fs.utils.d.ts +164 -0
  240. package/build/src/utils/fs.utils.js +372 -0
  241. package/build/src/utils/fs.utils.js.map +1 -0
  242. package/build/src/utils/http-status-codes.d.ts +266 -0
  243. package/build/src/utils/http-status-codes.js +298 -0
  244. package/build/src/utils/http-status-codes.js.map +1 -0
  245. package/build/src/utils/id.utils.d.ts +36 -0
  246. package/build/src/utils/id.utils.js +91 -0
  247. package/build/src/utils/id.utils.js.map +1 -0
  248. package/build/src/utils/logger.utils.d.ts +160 -0
  249. package/build/src/utils/logger.utils.js +346 -0
  250. package/build/src/utils/logger.utils.js.map +1 -0
  251. package/build/src/utils/middleware.utils.d.ts +100 -0
  252. package/build/src/utils/middleware.utils.js +244 -0
  253. package/build/src/utils/middleware.utils.js.map +1 -0
  254. package/build/src/utils/obj.utils.d.ts +124 -0
  255. package/build/src/utils/obj.utils.js +429 -0
  256. package/build/src/utils/obj.utils.js.map +1 -0
  257. package/build/src/utils/performance.utils.d.ts +136 -0
  258. package/build/src/utils/performance.utils.js +278 -0
  259. package/build/src/utils/performance.utils.js.map +1 -0
  260. package/build/src/utils/request.utils.d.ts +86 -0
  261. package/build/src/utils/request.utils.js +195 -0
  262. package/build/src/utils/request.utils.js.map +1 -0
  263. package/build/src/utils/response.utils.d.ts +163 -0
  264. package/build/src/utils/response.utils.js +260 -0
  265. package/build/src/utils/response.utils.js.map +1 -0
  266. package/build/src/utils/stream.utils.d.ts +88 -0
  267. package/build/src/utils/stream.utils.js +218 -0
  268. package/build/src/utils/stream.utils.js.map +1 -0
  269. package/build/src/utils/string.utils.d.ts +93 -0
  270. package/build/src/utils/string.utils.js +179 -0
  271. package/build/src/utils/string.utils.js.map +1 -0
  272. package/build/src/utils/type.utils.d.ts +90 -0
  273. package/build/src/utils/type.utils.js +196 -0
  274. package/build/src/utils/type.utils.js.map +1 -0
  275. package/build/src/utils/url.utils.d.ts +141 -0
  276. package/build/src/utils/url.utils.js +317 -0
  277. package/build/src/utils/url.utils.js.map +1 -0
  278. package/build/src/utils/validate.utils.d.ts +177 -0
  279. package/build/src/utils/validate.utils.js +345 -0
  280. package/build/src/utils/validate.utils.js.map +1 -0
  281. package/package.json +66 -12
  282. package/build/index.cjs +0 -6888
  283. package/build/index.d.ts +0 -5242
  284. package/build/index.mjs +0 -6615
@@ -0,0 +1,87 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ import { randomUUID, randomBytes } from 'crypto';
25
+ /**
26
+ * Generates a UUID v4 string (RFC 4122).
27
+ *
28
+ * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')
29
+ */
30
+ export function uuid() {
31
+ return randomUUID();
32
+ }
33
+ /**
34
+ * Generates a nanoid-style random ID (URL-safe, customizable length).
35
+ *
36
+ * @param {number} length - Length of the ID (default: 21).
37
+ * @returns {string} Nanoid-style random string.
38
+ */
39
+ export function nanoId(length) {
40
+ if (length === void 0) { length = 21; }
41
+ if (length <= 0)
42
+ return '';
43
+ var id = '';
44
+ while (id.length < length) {
45
+ id += randomBytes(Math.ceil((length * 3) / 4))
46
+ .toString('base64url')
47
+ .replace(/[+/=]/g, '');
48
+ }
49
+ return id.slice(0, length);
50
+ }
51
+ /**
52
+ * Generates a cryptographically strong random hex string.
53
+ *
54
+ * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).
55
+ * @returns {string} Random hex string.
56
+ */
57
+ export function randomHex(byteLength) {
58
+ if (byteLength === void 0) { byteLength = 16; }
59
+ // Use Node.js crypto for both Node and browser compatibility
60
+ // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)
61
+ return randomBytes(byteLength)
62
+ .toString('hex')
63
+ .padStart(byteLength * 2, '0')
64
+ .slice(0, byteLength * 2);
65
+ }
66
+ /**
67
+ * Generates a random integer between min (inclusive) and max (inclusive).
68
+ *
69
+ * @param {number} min - Minimum value.
70
+ * @param {number} max - Maximum value.
71
+ * @returns {number} Random integer in range.
72
+ */
73
+ export function randomInt(min, max) {
74
+ var range = max - min + 1;
75
+ return Math.floor(Math.random() * range) + min;
76
+ }
77
+ /**
78
+ * Generates a cryptographically strong random base64 string.
79
+ *
80
+ * @param {number} byteLength - Number of random bytes (default: 16).
81
+ * @returns {string} Random base64 string (URL-safe, no padding).
82
+ */
83
+ export function randomBase64(byteLength) {
84
+ if (byteLength === void 0) { byteLength = 16; }
85
+ return randomBytes(byteLength).toString('base64url');
86
+ }
87
+ //# sourceMappingURL=id.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAEjD;;;;GAIG;AACH,MAAM,UAAU,IAAI;IAClB,OAAO,UAAU,EAAE,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,MAAmB;IAAnB,uBAAA,EAAA,WAAmB;IACxC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC3B,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,OAAO,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;QAC1B,EAAE,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;aAC3C,QAAQ,CAAC,WAAW,CAAC;aACrB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,UAAuB;IAAvB,2BAAA,EAAA,eAAuB;IAC/C,6DAA6D;IAC7D,kGAAkG;IAClG,OAAO,WAAW,CAAC,UAAU,CAAC;SAC3B,QAAQ,CAAC,KAAK,CAAC;SACf,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,GAAG,CAAC;SAC7B,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW,EAAE,GAAW;IAChD,IAAM,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,UAAuB;IAAvB,2BAAA,EAAA,eAAuB;IAClD,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\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 { randomUUID, randomBytes } from 'crypto';\n\n/**\n * Generates a UUID v4 string (RFC 4122).\n *\n * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')\n */\nexport function uuid(): string {\n return randomUUID();\n}\n\n/**\n * Generates a nanoid-style random ID (URL-safe, customizable length).\n *\n * @param {number} length - Length of the ID (default: 21).\n * @returns {string} Nanoid-style random string.\n */\nexport function nanoId(length: number = 21): string {\n if (length <= 0) return '';\n let id = '';\n while (id.length < length) {\n id += randomBytes(Math.ceil((length * 3) / 4))\n .toString('base64url')\n .replace(/[+/=]/g, '');\n }\n return id.slice(0, length);\n}\n\n/**\n * Generates a cryptographically strong random hex string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).\n * @returns {string} Random hex string.\n */\nexport function randomHex(byteLength: number = 16): string {\n // Use Node.js crypto for both Node and browser compatibility\n // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)\n return randomBytes(byteLength)\n .toString('hex')\n .padStart(byteLength * 2, '0')\n .slice(0, byteLength * 2);\n}\n\n/**\n * Generates a random integer between min (inclusive) and max (inclusive).\n *\n * @param {number} min - Minimum value.\n * @param {number} max - Maximum value.\n * @returns {number} Random integer in range.\n */\nexport function randomInt(min: number, max: number): number {\n const range = max - min + 1;\n return Math.floor(Math.random() * range) + min;\n}\n\n/**\n * Generates a cryptographically strong random base64 string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16).\n * @returns {string} Random base64 string (URL-safe, no padding).\n */\nexport function randomBase64(byteLength: number = 16): string {\n return randomBytes(byteLength).toString('base64url');\n}\n"]}
@@ -0,0 +1,160 @@
1
+ import pino from 'pino';
2
+ import type { Logger as PinoLogger } from 'pino';
3
+ /**
4
+ * Logger type for application-wide logging.
5
+ */
6
+ export type Logger = pino.Logger;
7
+ /**
8
+ * Logger levels for application-wide logging.
9
+ */
10
+ export type LoggerLevels = pino.Level;
11
+ export declare const defaultSensitiveFields: string[];
12
+ /**
13
+ * Sets the global redaction censor function used throughout the application for log redaction.
14
+ *
15
+ * Use this function to customize how sensitive data is redacted in logs. The provided function
16
+ * will replace the default censor implementation.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * // Custom censor that redacts only specific values
21
+ * setRedactCensor((value, path, sensitiveFields) => {
22
+ * if (path.includes('password')) return '***';
23
+ * return value;
24
+ * });
25
+ * ```
26
+ *
27
+ * @param fn - The redaction censor function to use globally. This function receives:
28
+ * - value: The data value to potentially redact
29
+ * - path: Array of strings representing the path to the value in the object
30
+ * - sensitiveFields: Optional array of field names to consider sensitive
31
+ * @returns void
32
+ */
33
+ export declare function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string): void;
34
+ /**
35
+ * Gets the current global redaction censor function used for log redaction.
36
+ *
37
+ * This function is called internally by the logger when determining how to redact
38
+ * sensitive information. It can also be used to access the current censor implementation
39
+ * for composition or extension.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const currentCensor = getRedactCensor();
44
+ * // Create an enhanced censor that extends the current one
45
+ * setRedactCensor((value, path, fields) => {
46
+ * // Add custom logic before delegating to current censor
47
+ * if (someCondition) return customHandling();
48
+ * return currentCensor(value, path, fields);
49
+ * });
50
+ * ```
51
+ *
52
+ * @returns The current redaction censor function
53
+ */
54
+ export declare function getRedactCensor(): (value: unknown, path: string[], sensitiveFields?: string[]) => string;
55
+ /**
56
+ * Convenience function to redact sensitive data using the current global redact censor.
57
+ *
58
+ * This is a direct wrapper around the global censor function that simplifies usage
59
+ * in application code without needing to access the censor function directly.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * // Redact a potential sensitive value
64
+ * const safeValue = redact(value, ['user', 'apiKey']);
65
+ * ```
66
+ *
67
+ * @param value - The value to potentially redact
68
+ * @param path - Array of strings representing the path to the value in the object
69
+ * @param sensitiveFields - Optional array of field names to consider sensitive
70
+ * @returns The redacted string value or "***" for redacted content
71
+ */
72
+ export declare function redact(value: unknown, path: string[], sensitiveFields?: string[]): string;
73
+ /**
74
+ * Extends the current redaction function with additional fields to redact.
75
+ *
76
+ * This function wraps the existing censor while adding more fields to be considered
77
+ * sensitive without replacing the entire redaction logic.
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * // Add custom fields to be redacted in all future redaction operations
82
+ * addRedactFields(['customerId', 'accountNumber']);
83
+ * ```
84
+ *
85
+ * @param fields - Array of additional field names to redact
86
+ */
87
+ export declare function addRedactFields(fields: string[]): void;
88
+ /**
89
+ * Replaces the default list of sensitive fields with a new list.
90
+ *
91
+ * This is useful when you want complete control over what fields are considered
92
+ * sensitive by default, rather than using the library's built-in list.
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * // Replace default sensitive fields with a custom list
97
+ * setSensitiveFields(['password', 'ssn', 'creditCard']);
98
+ * ```
99
+ *
100
+ * @param fields - Array of field names to set as the new default sensitive fields
101
+ */
102
+ export declare function setSensitiveFields(fields: string[]): void;
103
+ /**
104
+ * Adds additional field names to the default sensitive fields list.
105
+ *
106
+ * This preserves the existing sensitive fields while adding new ones for
107
+ * application-specific sensitive data.
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * // Add domain-specific sensitive fields to the default list
112
+ * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
113
+ * ```
114
+ *
115
+ * @param fields - Array of additional field names to add to the sensitive fields list
116
+ */
117
+ export declare function addSensitiveFields(fields: string[]): void;
118
+ /**
119
+ * Use an object compatible with either modern or legacy global scopes.
120
+ */
121
+ export declare const _globalThis: typeof globalThis;
122
+ /**
123
+ * Retrieves the current logger instance:
124
+ * - Returns a request-scoped logger from AsyncLocalStorage if available
125
+ * - Falls back to the global (singleton) logger
126
+ * - Initializes the global logger if not created yet
127
+ *
128
+ * @returns {Logger} The logger instance (request-bound or global root logger)
129
+ */
130
+ export declare function getLogger(): PinoLogger;
131
+ /**
132
+ * Logger instance for the global context.
133
+ * This logger is used for logging messages that are not tied to a specific request.
134
+ */
135
+ export declare const logger: pino.Logger;
136
+ /**
137
+ * Creates a child logger with additional context.
138
+ *
139
+ * @param {Record<string, any>} bindings - Properties to attach to all log records
140
+ * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
141
+ * @returns {Logger} Child logger with merged context
142
+ */
143
+ export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
144
+ /**
145
+ * Creates a request-scoped logger with request ID and stores it in context
146
+ *
147
+ * @param {string} requestId - Unique request identifier
148
+ * @param {object} [additionalContext] - Additional context to include in logs
149
+ * @returns {Logger} Request-scoped logger instance
150
+ */
151
+ export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
152
+ /**
153
+ * Utility to safely log errors with proper stack trace extraction
154
+ *
155
+ * @param {Error|unknown} error - Error object to log
156
+ * @param {string} [message] - Optional message to include
157
+ * @param {Record<string, any>} [context] - Additional context properties
158
+ */
159
+ export declare function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void;
160
+ //# sourceMappingURL=logger.utils.d.ts.map
@@ -0,0 +1,341 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ var __assign = (this && this.__assign) || function () {
25
+ __assign = Object.assign || function(t) {
26
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
27
+ s = arguments[i];
28
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
29
+ t[p] = s[p];
30
+ }
31
+ return t;
32
+ };
33
+ return __assign.apply(this, arguments);
34
+ };
35
+ var __read = (this && this.__read) || function (o, n) {
36
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
37
+ if (!m) return o;
38
+ var i = m.call(o), r, ar = [], e;
39
+ try {
40
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
41
+ }
42
+ catch (error) { e = { error: error }; }
43
+ finally {
44
+ try {
45
+ if (r && !r.done && (m = i["return"])) m.call(i);
46
+ }
47
+ finally { if (e) throw e.error; }
48
+ }
49
+ return ar;
50
+ };
51
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
52
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
53
+ if (ar || !(i in from)) {
54
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
55
+ ar[i] = from[i];
56
+ }
57
+ }
58
+ return to.concat(ar || Array.prototype.slice.call(from));
59
+ };
60
+ import pino, { stdTimeFunctions } from 'pino';
61
+ import { config } from '../config';
62
+ import { ContextStore, StoreKeys } from './context-store.utils';
63
+ import { Env } from './env.utils';
64
+ /**
65
+ * Symbol used to store the root logger in the Node.js global object.
66
+ */
67
+ var GLOBAL_LOGGER_KEY = Symbol.for('logger');
68
+ // Default sensitive fields
69
+ export var defaultSensitiveFields = [
70
+ 'password',
71
+ 'secret',
72
+ 'token',
73
+ 'apiKey',
74
+ 'api_key',
75
+ 'auth',
76
+ 'jwt',
77
+ 'access_token',
78
+ 'client_secret',
79
+ 'session_token',
80
+ 'refresh_token'
81
+ ];
82
+ /**
83
+ * The global censor function used by the logger.
84
+ */
85
+ var globalRedactCensor = function (value, path, sensitiveFields) {
86
+ if (sensitiveFields === void 0) { sensitiveFields = defaultSensitiveFields; }
87
+ if (typeof value !== 'string')
88
+ return '***';
89
+ var lowerPath = path.map(function (p) { return p.toLowerCase(); });
90
+ var lowerSensitiveFields = sensitiveFields.map(function (f) { return f.toLowerCase(); });
91
+ if (lowerPath.some(function (p) { return lowerSensitiveFields.includes(p); }))
92
+ return '***';
93
+ // Redact URLs
94
+ if (lowerPath[0] === 'url') {
95
+ return value.replace(new RegExp("([?&](".concat(lowerSensitiveFields.join('|'), ")=)[^&#]*"), 'gi'), '$1***');
96
+ }
97
+ if (lowerPath.some(function (p) { return p.includes('authorization') || p.includes('auth'); })) {
98
+ return value.replace(/^(\S+)\s+.+$/, '$1 ***') || '***';
99
+ }
100
+ // Redact sensitive fields - check each path segment against each sensitive field
101
+ if (lowerPath.some(function (pathPart) { return lowerSensitiveFields.some(function (field) { return pathPart.includes(field); }); })) {
102
+ return '***';
103
+ }
104
+ if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {
105
+ return value;
106
+ }
107
+ return value;
108
+ };
109
+ /**
110
+ * Sets the global redaction censor function used throughout the application for log redaction.
111
+ *
112
+ * Use this function to customize how sensitive data is redacted in logs. The provided function
113
+ * will replace the default censor implementation.
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * // Custom censor that redacts only specific values
118
+ * setRedactCensor((value, path, sensitiveFields) => {
119
+ * if (path.includes('password')) return '***';
120
+ * return value;
121
+ * });
122
+ * ```
123
+ *
124
+ * @param fn - The redaction censor function to use globally. This function receives:
125
+ * - value: The data value to potentially redact
126
+ * - path: Array of strings representing the path to the value in the object
127
+ * - sensitiveFields: Optional array of field names to consider sensitive
128
+ * @returns void
129
+ */
130
+ export function setRedactCensor(fn) {
131
+ globalRedactCensor = fn;
132
+ }
133
+ /**
134
+ * Gets the current global redaction censor function used for log redaction.
135
+ *
136
+ * This function is called internally by the logger when determining how to redact
137
+ * sensitive information. It can also be used to access the current censor implementation
138
+ * for composition or extension.
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * const currentCensor = getRedactCensor();
143
+ * // Create an enhanced censor that extends the current one
144
+ * setRedactCensor((value, path, fields) => {
145
+ * // Add custom logic before delegating to current censor
146
+ * if (someCondition) return customHandling();
147
+ * return currentCensor(value, path, fields);
148
+ * });
149
+ * ```
150
+ *
151
+ * @returns The current redaction censor function
152
+ */
153
+ export function getRedactCensor() {
154
+ return globalRedactCensor;
155
+ }
156
+ /**
157
+ * Convenience function to redact sensitive data using the current global redact censor.
158
+ *
159
+ * This is a direct wrapper around the global censor function that simplifies usage
160
+ * in application code without needing to access the censor function directly.
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * // Redact a potential sensitive value
165
+ * const safeValue = redact(value, ['user', 'apiKey']);
166
+ * ```
167
+ *
168
+ * @param value - The value to potentially redact
169
+ * @param path - Array of strings representing the path to the value in the object
170
+ * @param sensitiveFields - Optional array of field names to consider sensitive
171
+ * @returns The redacted string value or "***" for redacted content
172
+ */
173
+ export function redact(value, path, sensitiveFields) {
174
+ return globalRedactCensor(value, path, sensitiveFields);
175
+ }
176
+ /**
177
+ * Extends the current redaction function with additional fields to redact.
178
+ *
179
+ * This function wraps the existing censor while adding more fields to be considered
180
+ * sensitive without replacing the entire redaction logic.
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * // Add custom fields to be redacted in all future redaction operations
185
+ * addRedactFields(['customerId', 'accountNumber']);
186
+ * ```
187
+ *
188
+ * @param fields - Array of additional field names to redact
189
+ */
190
+ export function addRedactFields(fields) {
191
+ var prev = globalRedactCensor;
192
+ globalRedactCensor = function (value, path, sensitiveFields) {
193
+ if (sensitiveFields === void 0) { sensitiveFields = defaultSensitiveFields; }
194
+ return prev(value, path, __spreadArray(__spreadArray([], __read((sensitiveFields || [])), false), __read(fields), false));
195
+ };
196
+ }
197
+ /**
198
+ * Replaces the default list of sensitive fields with a new list.
199
+ *
200
+ * This is useful when you want complete control over what fields are considered
201
+ * sensitive by default, rather than using the library's built-in list.
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * // Replace default sensitive fields with a custom list
206
+ * setSensitiveFields(['password', 'ssn', 'creditCard']);
207
+ * ```
208
+ *
209
+ * @param fields - Array of field names to set as the new default sensitive fields
210
+ */
211
+ export function setSensitiveFields(fields) {
212
+ defaultSensitiveFields.splice.apply(defaultSensitiveFields, __spreadArray([0, defaultSensitiveFields.length], __read(fields), false));
213
+ }
214
+ /**
215
+ * Adds additional field names to the default sensitive fields list.
216
+ *
217
+ * This preserves the existing sensitive fields while adding new ones for
218
+ * application-specific sensitive data.
219
+ *
220
+ * @example
221
+ * ```typescript
222
+ * // Add domain-specific sensitive fields to the default list
223
+ * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
224
+ * ```
225
+ *
226
+ * @param fields - Array of additional field names to add to the sensitive fields list
227
+ */
228
+ export function addSensitiveFields(fields) {
229
+ defaultSensitiveFields.push.apply(defaultSensitiveFields, __spreadArray([], __read(fields), false));
230
+ }
231
+ /**
232
+ * Use an object compatible with either modern or legacy global scopes.
233
+ */
234
+ export var _globalThis = typeof globalThis === 'object' ? globalThis : global;
235
+ var _global = _globalThis;
236
+ /**
237
+ * Initializes the global root logger according to app configuration.
238
+ *
239
+ * - Sets log name, level, timestamp, and redaction for sensitive fields.
240
+ * - Uses singleton in global symbol registry.
241
+ */
242
+ function setupLogger() {
243
+ var _a;
244
+ var logParams = {
245
+ name: config.logger.name || '@catbee/utils',
246
+ level: config.logger.level || 'info',
247
+ redact: {
248
+ paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],
249
+ censor: function (value, path) { return redact(value, path); }
250
+ },
251
+ // serializers: {
252
+ // req: pino.stdSerializers.req,
253
+ // request: pino.stdSerializers.req,
254
+ // res: pino.stdSerializers.res,
255
+ // response: pino.stdSerializers.res,
256
+ // err: pino.stdSerializers.err,
257
+ // error: pino.stdSerializers.err
258
+ // },
259
+ timestamp: stdTimeFunctions.isoTime
260
+ };
261
+ var logger = config.logger.pretty && Env.isDev()
262
+ ? pino(logParams, pino.transport({
263
+ target: 'pino-pretty',
264
+ options: {
265
+ colorize: true,
266
+ translateTime: 'SYS:standard',
267
+ ignore: 'pid,hostname',
268
+ singleLine: config.logger.singleLine,
269
+ levelFirst: true
270
+ }
271
+ }))
272
+ : pino(logParams);
273
+ _global[GLOBAL_LOGGER_KEY] = logger;
274
+ (_a = _global[GLOBAL_LOGGER_KEY]) === null || _a === void 0 ? void 0 : _a.debug('Logger initialized');
275
+ }
276
+ /**
277
+ * Retrieves the current logger instance:
278
+ * - Returns a request-scoped logger from AsyncLocalStorage if available
279
+ * - Falls back to the global (singleton) logger
280
+ * - Initializes the global logger if not created yet
281
+ *
282
+ * @returns {Logger} The logger instance (request-bound or global root logger)
283
+ */
284
+ export function getLogger() {
285
+ var logger = ContextStore.get(StoreKeys.LOGGER);
286
+ if (logger)
287
+ return logger;
288
+ if (!_global[GLOBAL_LOGGER_KEY]) {
289
+ setupLogger();
290
+ }
291
+ return _global[GLOBAL_LOGGER_KEY];
292
+ }
293
+ /**
294
+ * Logger instance for the global context.
295
+ * This logger is used for logging messages that are not tied to a specific request.
296
+ */
297
+ export var logger = getLogger();
298
+ /**
299
+ * Creates a child logger with additional context.
300
+ *
301
+ * @param {Record<string, any>} bindings - Properties to attach to all log records
302
+ * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
303
+ * @returns {Logger} Child logger with merged context
304
+ */
305
+ export function createChildLogger(bindings, parentLogger) {
306
+ var logger = parentLogger || getLogger();
307
+ return logger.child(bindings);
308
+ }
309
+ /**
310
+ * Creates a request-scoped logger with request ID and stores it in context
311
+ *
312
+ * @param {string} requestId - Unique request identifier
313
+ * @param {object} [additionalContext] - Additional context to include in logs
314
+ * @returns {Logger} Request-scoped logger instance
315
+ */
316
+ export function createRequestLogger(requestId, additionalContext) {
317
+ if (additionalContext === void 0) { additionalContext = {}; }
318
+ var logger = createChildLogger(__assign({ requestId: requestId }, additionalContext));
319
+ try {
320
+ ContextStore.set(StoreKeys.LOGGER, logger);
321
+ }
322
+ catch (_a) {
323
+ // Context not initialized, can't store logger
324
+ logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
325
+ }
326
+ return logger;
327
+ }
328
+ /**
329
+ * Utility to safely log errors with proper stack trace extraction
330
+ *
331
+ * @param {Error|unknown} error - Error object to log
332
+ * @param {string} [message] - Optional message to include
333
+ * @param {Record<string, any>} [context] - Additional context properties
334
+ */
335
+ export function logError(error, message, context) {
336
+ var logger = getLogger();
337
+ var errObj = error instanceof Error ? error : new Error(String(error));
338
+ var logContext = __assign(__assign({}, context), { error: errObj });
339
+ logger.error(logContext, message || errObj.message);
340
+ }
341
+ //# sourceMappingURL=logger.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAElC;;GAEG;AACH,IAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C,2BAA2B;AAC3B,MAAM,CAAC,IAAM,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,UAC/F,KAAK,EACL,IAAI,EACJ,eAAwC;IAAxC,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,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":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\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 * Logger instance for the global context.\n * This logger is used for logging messages that are not tied to a specific request.\n */\nexport const logger = 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"]}