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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/README.md +1 -26
  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 +315 -0
  42. package/build/esm/utils/decorators.utils.js +666 -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 +315 -0
  135. package/build/esnext/utils/decorators.utils.js +504 -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 +315 -0
  228. package/build/src/utils/decorators.utils.js +516 -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,375 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __generator = (this && this.__generator) || function (thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
46
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
+ }
70
+ };
71
+ var __read = (this && this.__read) || function (o, n) {
72
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
73
+ if (!m) return o;
74
+ var i = m.call(o), r, ar = [], e;
75
+ try {
76
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
77
+ }
78
+ catch (error) { e = { error: error }; }
79
+ finally {
80
+ try {
81
+ if (r && !r.done && (m = i["return"])) m.call(i);
82
+ }
83
+ finally { if (e) throw e.error; }
84
+ }
85
+ return ar;
86
+ };
87
+ import { createHmac, createHash, randomBytes, createCipheriv, createDecipheriv, scrypt, timingSafeEqual } from 'crypto';
88
+ import { promisify } from 'util';
89
+ import { uuid } from './id.utils';
90
+ /**
91
+ * Generates an HMAC digest using the specified algorithm and secret key.
92
+ *
93
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
94
+ * @param {string} input - The string to hash.
95
+ * @param {string} secret - The secret key for HMAC.
96
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
97
+ * @returns {string} HMAC digest as a string.
98
+ */
99
+ export function hmac(algorithm, input, secret, encoding) {
100
+ if (encoding === void 0) { encoding = 'hex'; }
101
+ return createHmac(algorithm, secret).update(input).digest(encoding);
102
+ }
103
+ /**
104
+ * Generates a hash digest using the specified algorithm.
105
+ *
106
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
107
+ * @param {string} input - The string to hash.
108
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
109
+ * @returns {string} Hash digest as a string.
110
+ */
111
+ export function hash(algorithm, input, encoding) {
112
+ if (encoding === void 0) { encoding = 'hex'; }
113
+ return createHash(algorithm).update(input).digest(encoding);
114
+ }
115
+ /**
116
+ * Generates an HMAC-SHA256 digest.
117
+ *
118
+ * @param {string} input - The string to hash.
119
+ * @param {string} secret - The secret key.
120
+ * @returns {string} SHA-256 HMAC digest as a string.
121
+ */
122
+ export function sha256Hmac(input, secret) {
123
+ return hmac('sha256', input, secret);
124
+ }
125
+ /**
126
+ * Generates a SHA1 hash digest.
127
+ *
128
+ * @param {string} input - The string to hash.
129
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
130
+ * @returns {string} SHA-1 hash as a string.
131
+ */
132
+ export function sha1(input, encoding) {
133
+ if (encoding === void 0) { encoding = 'hex'; }
134
+ return hash('sha1', input, encoding);
135
+ }
136
+ /**
137
+ * Generates a SHA256 hash digest.
138
+ *
139
+ * @param {string} input - The string to hash.
140
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
141
+ * @returns {string} SHA-256 hash as a string.
142
+ */
143
+ export function sha256(input, encoding) {
144
+ if (encoding === void 0) { encoding = 'hex'; }
145
+ return hash('sha256', input, encoding);
146
+ }
147
+ /**
148
+ * Generates an MD5 hash digest.
149
+ *
150
+ * @param {string} input - The string to hash.
151
+ * @returns {string} MD5 hash as a string.
152
+ */
153
+ export function md5(input) {
154
+ return hash('md5', input);
155
+ }
156
+ /**
157
+ * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
158
+ *
159
+ * @returns {string} Random string hashed with SHA-256 (hex encoding).
160
+ */
161
+ export function randomString() {
162
+ return sha256(uuid());
163
+ }
164
+ /**
165
+ * Generates a secure random buffer of specified byte length.
166
+ *
167
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
168
+ * @returns {Buffer} Buffer containing random bytes.
169
+ */
170
+ export function generateRandomBytes(byteLength) {
171
+ if (byteLength === void 0) { byteLength = 32; }
172
+ return randomBytes(byteLength);
173
+ }
174
+ /**
175
+ * Generates a secure random string of specified byte length with specified encoding.
176
+ *
177
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
178
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
179
+ * @returns {string} Random string in specified encoding.
180
+ */
181
+ export function generateRandomBytesAsString(byteLength, encoding) {
182
+ if (byteLength === void 0) { byteLength = 32; }
183
+ if (encoding === void 0) { encoding = 'hex'; }
184
+ return randomBytes(byteLength).toString(encoding);
185
+ }
186
+ /**
187
+ * Generates a secure API key with a specified format.
188
+ *
189
+ * @param {string} [prefix=''] - Optional prefix for the key.
190
+ * @param {number} [byteLength=24] - Number of random bytes to generate.
191
+ * @returns {string} Formatted API key.
192
+ */
193
+ export function generateApiKey(prefix, byteLength) {
194
+ if (prefix === void 0) { prefix = ''; }
195
+ if (byteLength === void 0) { byteLength = 24; }
196
+ var randomString = generateRandomBytesAsString(byteLength, 'base64');
197
+ var key = randomString
198
+ .replace(/[+/=]/g, '') // Remove non-URL-safe characters
199
+ .substring(0, 32); // Limit length
200
+ return prefix ? "".concat(prefix, "_").concat(key) : key;
201
+ }
202
+ /**
203
+ * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
204
+ *
205
+ * @param {string | Buffer | Uint8Array} a - First value to compare
206
+ * @param {string | Buffer | Uint8Array} b - Second value to compare
207
+ * @returns {boolean} True if values are equal
208
+ */
209
+ export function safeCompare(a, b) {
210
+ if (typeof a === 'string' && typeof b === 'string') {
211
+ // Convert strings to buffers
212
+ var bufA = Buffer.from(a);
213
+ var bufB = Buffer.from(b);
214
+ // Compare lengths first (not constant time, but prevents timing attack on contents)
215
+ if (bufA.length !== bufB.length)
216
+ return false;
217
+ return timingSafeEqual(bufA, bufB);
218
+ }
219
+ else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
220
+ // Compare lengths first
221
+ if (a.length !== b.length)
222
+ return false;
223
+ return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
224
+ }
225
+ throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
226
+ }
227
+ // Promisified version of scrypt for key derivation
228
+ var scryptAsync = promisify(scrypt);
229
+ /**
230
+ * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
231
+ *
232
+ * @param {string | Buffer} data - Data to encrypt
233
+ * @param {string | Buffer} key - Encryption key or passphrase
234
+ * @param {EncryptionOptions} [options] - Encryption options
235
+ * @returns {Promise<EncryptionResult>} Encrypted data with metadata
236
+ */
237
+ export function encrypt(data_1, key_1) {
238
+ return __awaiter(this, arguments, void 0, function (data, key, options) {
239
+ var algorithm, inputEncoding, outputEncoding, iv, derivedKey, _a, cipher, ciphertext, encrypted, authTag;
240
+ if (options === void 0) { options = {}; }
241
+ return __generator(this, function (_b) {
242
+ switch (_b.label) {
243
+ case 0:
244
+ algorithm = options.algorithm || 'aes-256-gcm';
245
+ inputEncoding = options.inputEncoding || 'utf8';
246
+ outputEncoding = options.outputEncoding || 'hex';
247
+ iv = randomBytes(16);
248
+ if (!(typeof key === 'string')) return [3 /*break*/, 2];
249
+ return [4 /*yield*/, scryptAsync(key, iv.slice(0, 8), 32)];
250
+ case 1:
251
+ _a = _b.sent();
252
+ return [3 /*break*/, 3];
253
+ case 2:
254
+ _a = key;
255
+ _b.label = 3;
256
+ case 3:
257
+ derivedKey = _a;
258
+ cipher = createCipheriv(algorithm, derivedKey, iv);
259
+ if (typeof data === 'string') {
260
+ ciphertext = cipher.update(data, inputEncoding, outputEncoding);
261
+ ciphertext += cipher.final(outputEncoding);
262
+ }
263
+ else {
264
+ encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
265
+ ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
266
+ }
267
+ authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
268
+ return [2 /*return*/, {
269
+ ciphertext: ciphertext,
270
+ iv: iv,
271
+ authTag: authTag,
272
+ algorithm: algorithm
273
+ }];
274
+ }
275
+ });
276
+ });
277
+ }
278
+ /**
279
+ * Decrypts data that was encrypted with the encrypt function.
280
+ *
281
+ * @param {EncryptionResult} encryptedData - The encrypted data and metadata
282
+ * @param {string | Buffer} key - Decryption key or passphrase
283
+ * @param {DecryptionOptions} [options] - Decryption options
284
+ * @returns {Promise<string | Buffer>} Decrypted data
285
+ */
286
+ export function decrypt(encryptedData_1, key_1) {
287
+ return __awaiter(this, arguments, void 0, function (encryptedData, key, options) {
288
+ var algorithm, inputEncoding, outputEncoding, derivedKey, _a, decipher, decrypted, result;
289
+ if (options === void 0) { options = {}; }
290
+ return __generator(this, function (_b) {
291
+ switch (_b.label) {
292
+ case 0:
293
+ algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
294
+ inputEncoding = options.inputEncoding || 'hex';
295
+ outputEncoding = options.outputEncoding || 'utf8';
296
+ if (!(typeof key === 'string')) return [3 /*break*/, 2];
297
+ return [4 /*yield*/, scryptAsync(key, encryptedData.iv.slice(0, 8), 32)];
298
+ case 1:
299
+ _a = _b.sent();
300
+ return [3 /*break*/, 3];
301
+ case 2:
302
+ _a = key;
303
+ _b.label = 3;
304
+ case 3:
305
+ derivedKey = _a;
306
+ decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);
307
+ // Set auth tag if using GCM mode
308
+ if (encryptedData.authTag && algorithm.includes('gcm')) {
309
+ decipher.setAuthTag(encryptedData.authTag);
310
+ }
311
+ if (typeof encryptedData.ciphertext === 'string') {
312
+ decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
313
+ decrypted += decipher.final(outputEncoding);
314
+ }
315
+ else {
316
+ result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
317
+ decrypted = outputEncoding ? result.toString(outputEncoding) : result;
318
+ }
319
+ return [2 /*return*/, decrypted];
320
+ }
321
+ });
322
+ });
323
+ }
324
+ /**
325
+ * Creates a signed token with an expiration time and payload.
326
+ *
327
+ * @param {object} payload - Data to include in the token
328
+ * @param {string} secret - Secret key for signing
329
+ * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
330
+ * @returns {string} Signed token string
331
+ */
332
+ export function createSignedToken(payload, secret, expiresInSeconds) {
333
+ if (expiresInSeconds === void 0) { expiresInSeconds = 3600; }
334
+ // Create payload with expiration
335
+ var tokenPayload = __assign(__assign({}, payload), { exp: Math.floor(Date.now() / 1000) + expiresInSeconds });
336
+ // Convert to string
337
+ var payloadStr = JSON.stringify(tokenPayload);
338
+ // Base64 encode the payload
339
+ var base64Payload = Buffer.from(payloadStr).toString('base64url');
340
+ // Create signature
341
+ var signature = hmac('sha256', base64Payload, secret, 'base64url');
342
+ // Combine payload and signature
343
+ return "".concat(base64Payload, ".").concat(signature);
344
+ }
345
+ /**
346
+ * Verifies and decodes a signed token.
347
+ *
348
+ * @param {string} token - The token to verify
349
+ * @param {string} secret - Secret key for verification
350
+ * @returns {object | null} Decoded payload if valid, null if invalid
351
+ */
352
+ export function verifySignedToken(token, secret) {
353
+ try {
354
+ // Split token into parts
355
+ var _a = __read(token.split('.'), 2), payloadB64 = _a[0], signature = _a[1];
356
+ if (!payloadB64 || !signature)
357
+ return null;
358
+ // Verify signature
359
+ var expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
360
+ if (!safeCompare(signature, expectedSignature))
361
+ return null;
362
+ // Decode payload
363
+ var payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
364
+ var payload = JSON.parse(payloadStr);
365
+ // Check expiration
366
+ if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
367
+ return null;
368
+ }
369
+ return payload;
370
+ }
371
+ catch (_b) {
372
+ return null;
373
+ }
374
+ }
375
+ //# sourceMappingURL=crypto.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EACL,UAAU,EACV,UAAU,EAEV,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,eAAe,EAEhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAgBlC;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,QAAsC;IAAtC,yBAAA,EAAA,gBAAsC;IAC3G,OAAO,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,QAAsC;IAAtC,yBAAA,EAAA,gBAAsC;IAC3F,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,MAAc;IACtD,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAAC,KAAa,EAAE,QAAsC;IAAtC,yBAAA,EAAA,gBAAsC;IACxE,OAAO,IAAI,CAAC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W,CAAC,SAAS,EAAE,iBAAiB,CAAC;YAAE,OAAO,IAAI,CAAC;QAE5D,iBAAiB;QACjB,IAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzE,IAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,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 {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\nimport { uuid } from './id.utils';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(uuid());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Format options for the formatDate function
3
+ */
4
+ export interface DateFormatOptions {
5
+ /** Date format pattern (default: 'yyyy-MM-dd') */
6
+ format?: string;
7
+ /** Locale to use for formatting (default: system locale) */
8
+ locale?: string | string[];
9
+ /** Time zone to use (default: system time zone) */
10
+ timeZone?: string;
11
+ }
12
+ /**
13
+ * Format a date according to the specified format pattern.
14
+ *
15
+ * @param date - Date to format
16
+ * @param options - Formatting options
17
+ * @returns Formatted date string
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // Format as ISO date
22
+ * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
23
+ *
24
+ * // Format with time
25
+ * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
26
+ *
27
+ * // Format with locale
28
+ * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
29
+ * ```
30
+ */
31
+ export declare function formatDate(date: Date | number, options?: DateFormatOptions): string;
32
+ /**
33
+ * Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
34
+ *
35
+ * @param date - Date to format
36
+ * @param now - Reference date (default: current time)
37
+ * @param locale - Locale to use for formatting
38
+ * @returns Formatted relative time string
39
+ */
40
+ export declare function formatRelativeTime(date: Date | number, now?: Date | number, locale?: string | string[]): string;
41
+ /**
42
+ * Parse a date string or timestamp into a Date object.
43
+ *
44
+ * @param input - Date string or timestamp to parse
45
+ * @param fallback - Fallback date if parsing fails
46
+ * @returns Parsed Date object or fallback
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * parseDate('2023-05-15'); // Date object for May 15, 2023
51
+ * parseDate('invalid', new Date()); // Returns current date as fallback
52
+ * ```
53
+ */
54
+ export declare function parseDate(input: string | number, fallback?: Date): Date | null;
55
+ /**
56
+ * Calculate the difference between two dates in the specified unit.
57
+ *
58
+ * @param date1 - First date
59
+ * @param date2 - Second date (default: current time)
60
+ * @param unit - Unit of time for the difference
61
+ * @returns Difference in the specified unit
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * // Get difference in days
66
+ * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
67
+ *
68
+ * // Get difference in hours
69
+ * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
70
+ * ```
71
+ */
72
+ export declare function dateDiff(date1: Date | number, date2?: Date | number, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number;
73
+ /**
74
+ * Add a specified amount of time to a date.
75
+ *
76
+ * @param date - Base date
77
+ * @param amount - Amount to add (can be negative)
78
+ * @param unit - Unit of time to add
79
+ * @returns New date with the addition
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * // Add 5 days
84
+ * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
85
+ *
86
+ * // Subtract 2 hours
87
+ * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
88
+ * ```
89
+ */
90
+ export declare function addToDate(date: Date | number, amount: number, unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): Date;
91
+ /**
92
+ * Get the start of a time period containing the specified date.
93
+ *
94
+ * @param date - Date to get the start from
95
+ * @param unit - Time unit
96
+ * @returns Date object representing the start of the time unit
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * // Get start of day (midnight)
101
+ * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
102
+ *
103
+ * // Get start of month
104
+ * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
105
+ * ```
106
+ */
107
+ export declare function startOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
108
+ /**
109
+ * Get the end of a time period containing the specified date.
110
+ *
111
+ * @param date - Date to get the end from
112
+ * @param unit - Time unit
113
+ * @returns Date object representing the end of the time unit
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * // Get end of day (23:59:59.999)
118
+ * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
119
+ *
120
+ * // Get end of month
121
+ * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
122
+ * ```
123
+ */
124
+ export declare function endOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
125
+ /**
126
+ * Check if a date is between two other dates.
127
+ *
128
+ * @param date - Date to check
129
+ * @param start - Start date of the range
130
+ * @param end - End date of the range
131
+ * @param inclusive - Whether the comparison should be inclusive of start/end
132
+ * @returns True if the date is within the range
133
+ *
134
+ * @example
135
+ * ```typescript
136
+ * const date = new Date('2023-05-15');
137
+ * const start = new Date('2023-05-10');
138
+ * const end = new Date('2023-05-20');
139
+ *
140
+ * isBetween(date, start, end); // true
141
+ * ```
142
+ */
143
+ export declare function isBetween(date: Date | number, start: Date | number, end: Date | number, inclusive?: boolean): boolean;
144
+ /**
145
+ * Check if a year is a leap year.
146
+ *
147
+ * @param year - Year to check (or date object)
148
+ * @returns True if the year is a leap year
149
+ */
150
+ export declare function isLeapYear(year: number | Date): boolean;
151
+ /**
152
+ * Get the number of days in a month.
153
+ *
154
+ * @param year - Year
155
+ * @param month - Month (0-11)
156
+ * @returns Number of days in the month
157
+ */
158
+ export declare function daysInMonth(year: number | Date, month?: number): number;
159
+ //# sourceMappingURL=date.utils.d.ts.map