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

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 (281) hide show
  1. package/README.md +25 -1
  2. package/build/esm/config.d.ts +0 -1
  3. package/build/esm/config.js +6 -7
  4. package/build/esm/index.d.ts +0 -1
  5. package/build/esm/index.js +0 -1
  6. package/build/esm/servers/server.builder.d.ts +0 -1
  7. package/build/esm/servers/server.builder.js +99 -147
  8. package/build/esm/servers/server.d.ts +0 -1
  9. package/build/esm/servers/server.js +591 -876
  10. package/build/esm/types/api-response.d.ts +0 -1
  11. package/build/esm/types/api-response.js +0 -1
  12. package/build/esm/types/index.d.ts +0 -1
  13. package/build/esm/types/index.js +0 -1
  14. package/build/esm/types/server.d.ts +0 -1
  15. package/build/esm/types/server.js +0 -1
  16. package/build/esm/utils/array.utils.d.ts +0 -1
  17. package/build/esm/utils/array.utils.js +48 -86
  18. package/build/esm/utils/async.utils.d.ts +0 -1
  19. package/build/esm/utils/async.utils.js +247 -524
  20. package/build/esm/utils/cache.utils.d.ts +0 -1
  21. package/build/esm/utils/cache.utils.js +96 -301
  22. package/build/esm/utils/context-store.utils.d.ts +0 -1
  23. package/build/esm/utils/context-store.utils.js +62 -79
  24. package/build/esm/utils/crypto.utils.d.ts +0 -1
  25. package/build/esm/utils/crypto.utils.js +78 -175
  26. package/build/esm/utils/date.utils.d.ts +0 -1
  27. package/build/esm/utils/date.utils.js +47 -53
  28. package/build/esm/utils/decorators.utils.d.ts +201 -5
  29. package/build/esm/utils/decorators.utils.js +632 -285
  30. package/build/esm/utils/dir.utils.d.ts +0 -1
  31. package/build/esm/utils/dir.utils.js +264 -786
  32. package/build/esm/utils/env.utils.d.ts +0 -1
  33. package/build/esm/utils/env.utils.js +180 -271
  34. package/build/esm/utils/exception.utils.d.ts +0 -1
  35. package/build/esm/utils/exception.utils.js +112 -289
  36. package/build/esm/utils/fs.utils.d.ts +0 -1
  37. package/build/esm/utils/fs.utils.js +169 -401
  38. package/build/esm/utils/http-status-codes.d.ts +0 -1
  39. package/build/esm/utils/http-status-codes.js +0 -1
  40. package/build/esm/utils/id.utils.d.ts +0 -1
  41. package/build/esm/utils/id.utils.js +5 -9
  42. package/build/esm/utils/logger.utils.d.ts +0 -1
  43. package/build/esm/utils/logger.utils.js +34 -71
  44. package/build/esm/utils/middleware.utils.d.ts +0 -1
  45. package/build/esm/utils/middleware.utils.js +65 -155
  46. package/build/esm/utils/obj.utils.d.ts +0 -1
  47. package/build/esm/utils/obj.utils.js +69 -176
  48. package/build/esm/utils/performance.utils.d.ts +0 -1
  49. package/build/esm/utils/performance.utils.js +92 -195
  50. package/build/esm/utils/request.utils.d.ts +0 -1
  51. package/build/esm/utils/request.utils.js +41 -74
  52. package/build/esm/utils/response.utils.d.ts +0 -1
  53. package/build/esm/utils/response.utils.js +84 -107
  54. package/build/esm/utils/stream.utils.d.ts +0 -1
  55. package/build/esm/utils/stream.utils.js +38 -113
  56. package/build/esm/utils/string.utils.d.ts +0 -1
  57. package/build/esm/utils/string.utils.js +6 -11
  58. package/build/esm/utils/type.utils.d.ts +0 -1
  59. package/build/esm/utils/type.utils.js +8 -12
  60. package/build/esm/utils/url.utils.d.ts +0 -1
  61. package/build/esm/utils/url.utils.js +49 -127
  62. package/build/esm/utils/validate.utils.d.ts +0 -1
  63. package/build/esm/utils/validate.utils.js +23 -40
  64. package/package.json +3 -33
  65. package/build/esm/config.js.map +0 -1
  66. package/build/esm/index.js.map +0 -1
  67. package/build/esm/servers/server.builder.js.map +0 -1
  68. package/build/esm/servers/server.js.map +0 -1
  69. package/build/esm/types/api-response.js.map +0 -1
  70. package/build/esm/types/index.js.map +0 -1
  71. package/build/esm/types/server.js.map +0 -1
  72. package/build/esm/utils/array.utils.js.map +0 -1
  73. package/build/esm/utils/async.utils.js.map +0 -1
  74. package/build/esm/utils/cache.utils.js.map +0 -1
  75. package/build/esm/utils/context-store.utils.js.map +0 -1
  76. package/build/esm/utils/crypto.utils.js.map +0 -1
  77. package/build/esm/utils/date.utils.js.map +0 -1
  78. package/build/esm/utils/decorators.utils.js.map +0 -1
  79. package/build/esm/utils/dir.utils.js.map +0 -1
  80. package/build/esm/utils/env.utils.js.map +0 -1
  81. package/build/esm/utils/exception.utils.js.map +0 -1
  82. package/build/esm/utils/fs.utils.js.map +0 -1
  83. package/build/esm/utils/http-status-codes.js.map +0 -1
  84. package/build/esm/utils/id.utils.js.map +0 -1
  85. package/build/esm/utils/logger.utils.js.map +0 -1
  86. package/build/esm/utils/middleware.utils.js.map +0 -1
  87. package/build/esm/utils/obj.utils.js.map +0 -1
  88. package/build/esm/utils/performance.utils.js.map +0 -1
  89. package/build/esm/utils/request.utils.js.map +0 -1
  90. package/build/esm/utils/response.utils.js.map +0 -1
  91. package/build/esm/utils/stream.utils.js.map +0 -1
  92. package/build/esm/utils/string.utils.js.map +0 -1
  93. package/build/esm/utils/type.utils.js.map +0 -1
  94. package/build/esm/utils/url.utils.js.map +0 -1
  95. package/build/esm/utils/validate.utils.js.map +0 -1
  96. package/build/esnext/config.d.ts +0 -122
  97. package/build/esnext/config.js +0 -133
  98. package/build/esnext/config.js.map +0 -1
  99. package/build/esnext/index.d.ts +0 -27
  100. package/build/esnext/index.js +0 -50
  101. package/build/esnext/index.js.map +0 -1
  102. package/build/esnext/servers/server.builder.d.ts +0 -508
  103. package/build/esnext/servers/server.builder.js +0 -657
  104. package/build/esnext/servers/server.builder.js.map +0 -1
  105. package/build/esnext/servers/server.d.ts +0 -256
  106. package/build/esnext/servers/server.js +0 -955
  107. package/build/esnext/servers/server.js.map +0 -1
  108. package/build/esnext/types/api-response.d.ts +0 -152
  109. package/build/esnext/types/api-response.js +0 -34
  110. package/build/esnext/types/api-response.js.map +0 -1
  111. package/build/esnext/types/index.d.ts +0 -125
  112. package/build/esnext/types/index.js +0 -25
  113. package/build/esnext/types/index.js.map +0 -1
  114. package/build/esnext/types/server.d.ts +0 -268
  115. package/build/esnext/types/server.js +0 -25
  116. package/build/esnext/types/server.js.map +0 -1
  117. package/build/esnext/utils/array.utils.d.ts +0 -168
  118. package/build/esnext/utils/array.utils.js +0 -345
  119. package/build/esnext/utils/array.utils.js.map +0 -1
  120. package/build/esnext/utils/async.utils.d.ts +0 -265
  121. package/build/esnext/utils/async.utils.js +0 -620
  122. package/build/esnext/utils/async.utils.js.map +0 -1
  123. package/build/esnext/utils/cache.utils.d.ts +0 -153
  124. package/build/esnext/utils/cache.utils.js +0 -293
  125. package/build/esnext/utils/cache.utils.js.map +0 -1
  126. package/build/esnext/utils/context-store.utils.d.ts +0 -189
  127. package/build/esnext/utils/context-store.utils.js +0 -289
  128. package/build/esnext/utils/context-store.utils.js.map +0 -1
  129. package/build/esnext/utils/crypto.utils.d.ts +0 -160
  130. package/build/esnext/utils/crypto.utils.js +0 -276
  131. package/build/esnext/utils/crypto.utils.js.map +0 -1
  132. package/build/esnext/utils/date.utils.d.ts +0 -159
  133. package/build/esnext/utils/date.utils.js +0 -384
  134. package/build/esnext/utils/date.utils.js.map +0 -1
  135. package/build/esnext/utils/decorators.utils.d.ts +0 -315
  136. package/build/esnext/utils/decorators.utils.js +0 -504
  137. package/build/esnext/utils/decorators.utils.js.map +0 -1
  138. package/build/esnext/utils/dir.utils.d.ts +0 -196
  139. package/build/esnext/utils/dir.utils.js +0 -477
  140. package/build/esnext/utils/dir.utils.js.map +0 -1
  141. package/build/esnext/utils/env.utils.d.ts +0 -377
  142. package/build/esnext/utils/env.utils.js +0 -785
  143. package/build/esnext/utils/env.utils.js.map +0 -1
  144. package/build/esnext/utils/exception.utils.d.ts +0 -230
  145. package/build/esnext/utils/exception.utils.js +0 -381
  146. package/build/esnext/utils/exception.utils.js.map +0 -1
  147. package/build/esnext/utils/fs.utils.d.ts +0 -164
  148. package/build/esnext/utils/fs.utils.js +0 -349
  149. package/build/esnext/utils/fs.utils.js.map +0 -1
  150. package/build/esnext/utils/http-status-codes.d.ts +0 -266
  151. package/build/esnext/utils/http-status-codes.js +0 -295
  152. package/build/esnext/utils/http-status-codes.js.map +0 -1
  153. package/build/esnext/utils/id.utils.d.ts +0 -36
  154. package/build/esnext/utils/id.utils.js +0 -84
  155. package/build/esnext/utils/id.utils.js.map +0 -1
  156. package/build/esnext/utils/logger.utils.d.ts +0 -160
  157. package/build/esnext/utils/logger.utils.js +0 -300
  158. package/build/esnext/utils/logger.utils.js.map +0 -1
  159. package/build/esnext/utils/middleware.utils.d.ts +0 -100
  160. package/build/esnext/utils/middleware.utils.js +0 -236
  161. package/build/esnext/utils/middleware.utils.js.map +0 -1
  162. package/build/esnext/utils/obj.utils.d.ts +0 -124
  163. package/build/esnext/utils/obj.utils.js +0 -413
  164. package/build/esnext/utils/obj.utils.js.map +0 -1
  165. package/build/esnext/utils/performance.utils.d.ts +0 -136
  166. package/build/esnext/utils/performance.utils.js +0 -271
  167. package/build/esnext/utils/performance.utils.js.map +0 -1
  168. package/build/esnext/utils/request.utils.d.ts +0 -86
  169. package/build/esnext/utils/request.utils.js +0 -186
  170. package/build/esnext/utils/request.utils.js.map +0 -1
  171. package/build/esnext/utils/response.utils.d.ts +0 -163
  172. package/build/esnext/utils/response.utils.js +0 -247
  173. package/build/esnext/utils/response.utils.js.map +0 -1
  174. package/build/esnext/utils/stream.utils.d.ts +0 -88
  175. package/build/esnext/utils/stream.utils.js +0 -210
  176. package/build/esnext/utils/stream.utils.js.map +0 -1
  177. package/build/esnext/utils/string.utils.d.ts +0 -93
  178. package/build/esnext/utils/string.utils.js +0 -165
  179. package/build/esnext/utils/string.utils.js.map +0 -1
  180. package/build/esnext/utils/type.utils.d.ts +0 -90
  181. package/build/esnext/utils/type.utils.js +0 -187
  182. package/build/esnext/utils/type.utils.js.map +0 -1
  183. package/build/esnext/utils/url.utils.d.ts +0 -141
  184. package/build/esnext/utils/url.utils.js +0 -304
  185. package/build/esnext/utils/url.utils.js.map +0 -1
  186. package/build/esnext/utils/validate.utils.d.ts +0 -177
  187. package/build/esnext/utils/validate.utils.js +0 -320
  188. package/build/esnext/utils/validate.utils.js.map +0 -1
  189. package/build/src/config.d.ts +0 -122
  190. package/build/src/config.js +0 -138
  191. package/build/src/config.js.map +0 -1
  192. package/build/src/index.d.ts +0 -27
  193. package/build/src/index.js +0 -69
  194. package/build/src/index.js.map +0 -1
  195. package/build/src/servers/server.builder.d.ts +0 -508
  196. package/build/src/servers/server.builder.js +0 -661
  197. package/build/src/servers/server.builder.js.map +0 -1
  198. package/build/src/servers/server.d.ts +0 -256
  199. package/build/src/servers/server.js +0 -962
  200. package/build/src/servers/server.js.map +0 -1
  201. package/build/src/types/api-response.d.ts +0 -152
  202. package/build/src/types/api-response.js +0 -37
  203. package/build/src/types/api-response.js.map +0 -1
  204. package/build/src/types/index.d.ts +0 -125
  205. package/build/src/types/index.js +0 -26
  206. package/build/src/types/index.js.map +0 -1
  207. package/build/src/types/server.d.ts +0 -268
  208. package/build/src/types/server.js +0 -26
  209. package/build/src/types/server.js.map +0 -1
  210. package/build/src/utils/array.utils.d.ts +0 -168
  211. package/build/src/utils/array.utils.js +0 -364
  212. package/build/src/utils/array.utils.js.map +0 -1
  213. package/build/src/utils/async.utils.d.ts +0 -265
  214. package/build/src/utils/async.utils.js +0 -641
  215. package/build/src/utils/async.utils.js.map +0 -1
  216. package/build/src/utils/cache.utils.d.ts +0 -153
  217. package/build/src/utils/cache.utils.js +0 -297
  218. package/build/src/utils/cache.utils.js.map +0 -1
  219. package/build/src/utils/context-store.utils.d.ts +0 -189
  220. package/build/src/utils/context-store.utils.js +0 -296
  221. package/build/src/utils/context-store.utils.js.map +0 -1
  222. package/build/src/utils/crypto.utils.d.ts +0 -160
  223. package/build/src/utils/crypto.utils.js +0 -293
  224. package/build/src/utils/crypto.utils.js.map +0 -1
  225. package/build/src/utils/date.utils.d.ts +0 -159
  226. package/build/src/utils/date.utils.js +0 -396
  227. package/build/src/utils/date.utils.js.map +0 -1
  228. package/build/src/utils/decorators.utils.d.ts +0 -315
  229. package/build/src/utils/decorators.utils.js +0 -516
  230. package/build/src/utils/decorators.utils.js.map +0 -1
  231. package/build/src/utils/dir.utils.d.ts +0 -196
  232. package/build/src/utils/dir.utils.js +0 -501
  233. package/build/src/utils/dir.utils.js.map +0 -1
  234. package/build/src/utils/env.utils.d.ts +0 -377
  235. package/build/src/utils/env.utils.js +0 -789
  236. package/build/src/utils/env.utils.js.map +0 -1
  237. package/build/src/utils/exception.utils.d.ts +0 -230
  238. package/build/src/utils/exception.utils.js +0 -407
  239. package/build/src/utils/exception.utils.js.map +0 -1
  240. package/build/src/utils/fs.utils.d.ts +0 -164
  241. package/build/src/utils/fs.utils.js +0 -372
  242. package/build/src/utils/fs.utils.js.map +0 -1
  243. package/build/src/utils/http-status-codes.d.ts +0 -266
  244. package/build/src/utils/http-status-codes.js +0 -298
  245. package/build/src/utils/http-status-codes.js.map +0 -1
  246. package/build/src/utils/id.utils.d.ts +0 -36
  247. package/build/src/utils/id.utils.js +0 -91
  248. package/build/src/utils/id.utils.js.map +0 -1
  249. package/build/src/utils/logger.utils.d.ts +0 -160
  250. package/build/src/utils/logger.utils.js +0 -346
  251. package/build/src/utils/logger.utils.js.map +0 -1
  252. package/build/src/utils/middleware.utils.d.ts +0 -100
  253. package/build/src/utils/middleware.utils.js +0 -244
  254. package/build/src/utils/middleware.utils.js.map +0 -1
  255. package/build/src/utils/obj.utils.d.ts +0 -124
  256. package/build/src/utils/obj.utils.js +0 -429
  257. package/build/src/utils/obj.utils.js.map +0 -1
  258. package/build/src/utils/performance.utils.d.ts +0 -136
  259. package/build/src/utils/performance.utils.js +0 -278
  260. package/build/src/utils/performance.utils.js.map +0 -1
  261. package/build/src/utils/request.utils.d.ts +0 -86
  262. package/build/src/utils/request.utils.js +0 -195
  263. package/build/src/utils/request.utils.js.map +0 -1
  264. package/build/src/utils/response.utils.d.ts +0 -163
  265. package/build/src/utils/response.utils.js +0 -260
  266. package/build/src/utils/response.utils.js.map +0 -1
  267. package/build/src/utils/stream.utils.d.ts +0 -88
  268. package/build/src/utils/stream.utils.js +0 -218
  269. package/build/src/utils/stream.utils.js.map +0 -1
  270. package/build/src/utils/string.utils.d.ts +0 -93
  271. package/build/src/utils/string.utils.js +0 -179
  272. package/build/src/utils/string.utils.js.map +0 -1
  273. package/build/src/utils/type.utils.d.ts +0 -90
  274. package/build/src/utils/type.utils.js +0 -196
  275. package/build/src/utils/type.utils.js.map +0 -1
  276. package/build/src/utils/url.utils.d.ts +0 -141
  277. package/build/src/utils/url.utils.js +0 -317
  278. package/build/src/utils/url.utils.js.map +0 -1
  279. package/build/src/utils/validate.utils.d.ts +0 -177
  280. package/build/src/utils/validate.utils.js +0 -345
  281. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1,293 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in all
15
- * copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.
24
- */
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.hmac = hmac;
27
- exports.hash = hash;
28
- exports.sha256Hmac = sha256Hmac;
29
- exports.sha1 = sha1;
30
- exports.sha256 = sha256;
31
- exports.md5 = md5;
32
- exports.randomString = randomString;
33
- exports.generateRandomBytes = generateRandomBytes;
34
- exports.generateRandomBytesAsString = generateRandomBytesAsString;
35
- exports.generateApiKey = generateApiKey;
36
- exports.safeCompare = safeCompare;
37
- exports.encrypt = encrypt;
38
- exports.decrypt = decrypt;
39
- exports.createSignedToken = createSignedToken;
40
- exports.verifySignedToken = verifySignedToken;
41
- const crypto_1 = require("crypto");
42
- const util_1 = require("util");
43
- const id_utils_1 = require("./id.utils");
44
- /**
45
- * Generates an HMAC digest using the specified algorithm and secret key.
46
- *
47
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
48
- * @param {string} input - The string to hash.
49
- * @param {string} secret - The secret key for HMAC.
50
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
51
- * @returns {string} HMAC digest as a string.
52
- */
53
- function hmac(algorithm, input, secret, encoding = 'hex') {
54
- return (0, crypto_1.createHmac)(algorithm, secret).update(input).digest(encoding);
55
- }
56
- /**
57
- * Generates a hash digest using the specified algorithm.
58
- *
59
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
60
- * @param {string} input - The string to hash.
61
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
62
- * @returns {string} Hash digest as a string.
63
- */
64
- function hash(algorithm, input, encoding = 'hex') {
65
- return (0, crypto_1.createHash)(algorithm).update(input).digest(encoding);
66
- }
67
- /**
68
- * Generates an HMAC-SHA256 digest.
69
- *
70
- * @param {string} input - The string to hash.
71
- * @param {string} secret - The secret key.
72
- * @returns {string} SHA-256 HMAC digest as a string.
73
- */
74
- function sha256Hmac(input, secret) {
75
- return hmac('sha256', input, secret);
76
- }
77
- /**
78
- * Generates a SHA1 hash digest.
79
- *
80
- * @param {string} input - The string to hash.
81
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
82
- * @returns {string} SHA-1 hash as a string.
83
- */
84
- function sha1(input, encoding = 'hex') {
85
- return hash('sha1', input, encoding);
86
- }
87
- /**
88
- * Generates a SHA256 hash digest.
89
- *
90
- * @param {string} input - The string to hash.
91
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
92
- * @returns {string} SHA-256 hash as a string.
93
- */
94
- function sha256(input, encoding = 'hex') {
95
- return hash('sha256', input, encoding);
96
- }
97
- /**
98
- * Generates an MD5 hash digest.
99
- *
100
- * @param {string} input - The string to hash.
101
- * @returns {string} MD5 hash as a string.
102
- */
103
- function md5(input) {
104
- return hash('md5', input);
105
- }
106
- /**
107
- * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
108
- *
109
- * @returns {string} Random string hashed with SHA-256 (hex encoding).
110
- */
111
- function randomString() {
112
- return sha256((0, id_utils_1.uuid)());
113
- }
114
- /**
115
- * Generates a secure random buffer of specified byte length.
116
- *
117
- * @param {number} [byteLength=32] - Number of random bytes to generate.
118
- * @returns {Buffer} Buffer containing random bytes.
119
- */
120
- function generateRandomBytes(byteLength = 32) {
121
- return (0, crypto_1.randomBytes)(byteLength);
122
- }
123
- /**
124
- * Generates a secure random string of specified byte length with specified encoding.
125
- *
126
- * @param {number} [byteLength=32] - Number of random bytes to generate.
127
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
128
- * @returns {string} Random string in specified encoding.
129
- */
130
- function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
131
- return (0, crypto_1.randomBytes)(byteLength).toString(encoding);
132
- }
133
- /**
134
- * Generates a secure API key with a specified format.
135
- *
136
- * @param {string} [prefix=''] - Optional prefix for the key.
137
- * @param {number} [byteLength=24] - Number of random bytes to generate.
138
- * @returns {string} Formatted API key.
139
- */
140
- function generateApiKey(prefix = '', byteLength = 24) {
141
- const randomString = generateRandomBytesAsString(byteLength, 'base64');
142
- const key = randomString
143
- .replace(/[+/=]/g, '') // Remove non-URL-safe characters
144
- .substring(0, 32); // Limit length
145
- return prefix ? `${prefix}_${key}` : key;
146
- }
147
- /**
148
- * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
149
- *
150
- * @param {string | Buffer | Uint8Array} a - First value to compare
151
- * @param {string | Buffer | Uint8Array} b - Second value to compare
152
- * @returns {boolean} True if values are equal
153
- */
154
- function safeCompare(a, b) {
155
- if (typeof a === 'string' && typeof b === 'string') {
156
- // Convert strings to buffers
157
- const bufA = Buffer.from(a);
158
- const bufB = Buffer.from(b);
159
- // Compare lengths first (not constant time, but prevents timing attack on contents)
160
- if (bufA.length !== bufB.length)
161
- return false;
162
- return (0, crypto_1.timingSafeEqual)(bufA, bufB);
163
- }
164
- else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
165
- // Compare lengths first
166
- if (a.length !== b.length)
167
- return false;
168
- return (0, crypto_1.timingSafeEqual)(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
169
- }
170
- throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
171
- }
172
- // Promisified version of scrypt for key derivation
173
- const scryptAsync = (0, util_1.promisify)(crypto_1.scrypt);
174
- /**
175
- * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
176
- *
177
- * @param {string | Buffer} data - Data to encrypt
178
- * @param {string | Buffer} key - Encryption key or passphrase
179
- * @param {EncryptionOptions} [options] - Encryption options
180
- * @returns {Promise<EncryptionResult>} Encrypted data with metadata
181
- */
182
- async function encrypt(data, key, options = {}) {
183
- const algorithm = options.algorithm || 'aes-256-gcm';
184
- const inputEncoding = options.inputEncoding || 'utf8';
185
- const outputEncoding = options.outputEncoding || 'hex';
186
- // Generate a random IV
187
- const iv = (0, crypto_1.randomBytes)(16);
188
- // Derive key using scrypt if key is a string (passphrase)
189
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
190
- // Create cipher
191
- const cipher = (0, crypto_1.createCipheriv)(algorithm, derivedKey, iv);
192
- // Encrypt the data
193
- let ciphertext;
194
- if (typeof data === 'string') {
195
- ciphertext = cipher.update(data, inputEncoding, outputEncoding);
196
- ciphertext += cipher.final(outputEncoding);
197
- }
198
- else {
199
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
200
- ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
201
- }
202
- // Get authentication tag if using GCM mode
203
- const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
204
- return {
205
- ciphertext,
206
- iv,
207
- authTag,
208
- algorithm
209
- };
210
- }
211
- /**
212
- * Decrypts data that was encrypted with the encrypt function.
213
- *
214
- * @param {EncryptionResult} encryptedData - The encrypted data and metadata
215
- * @param {string | Buffer} key - Decryption key or passphrase
216
- * @param {DecryptionOptions} [options] - Decryption options
217
- * @returns {Promise<string | Buffer>} Decrypted data
218
- */
219
- async function decrypt(encryptedData, key, options = {}) {
220
- const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
221
- const inputEncoding = options.inputEncoding || 'hex';
222
- const outputEncoding = options.outputEncoding || 'utf8';
223
- // Derive key using scrypt if key is a string (passphrase)
224
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
225
- // Create decipher
226
- const decipher = (0, crypto_1.createDecipheriv)(algorithm, derivedKey, encryptedData.iv);
227
- // Set auth tag if using GCM mode
228
- if (encryptedData.authTag && algorithm.includes('gcm')) {
229
- decipher.setAuthTag(encryptedData.authTag);
230
- }
231
- // Decrypt the data
232
- let decrypted;
233
- if (typeof encryptedData.ciphertext === 'string') {
234
- decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
235
- decrypted += decipher.final(outputEncoding);
236
- }
237
- else {
238
- const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
239
- decrypted = outputEncoding ? result.toString(outputEncoding) : result;
240
- }
241
- return decrypted;
242
- }
243
- /**
244
- * Creates a signed token with an expiration time and payload.
245
- *
246
- * @param {object} payload - Data to include in the token
247
- * @param {string} secret - Secret key for signing
248
- * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
249
- * @returns {string} Signed token string
250
- */
251
- function createSignedToken(payload, secret, expiresInSeconds = 3600) {
252
- // Create payload with expiration
253
- const tokenPayload = Object.assign(Object.assign({}, payload), { exp: Math.floor(Date.now() / 1000) + expiresInSeconds });
254
- // Convert to string
255
- const payloadStr = JSON.stringify(tokenPayload);
256
- // Base64 encode the payload
257
- const base64Payload = Buffer.from(payloadStr).toString('base64url');
258
- // Create signature
259
- const signature = hmac('sha256', base64Payload, secret, 'base64url');
260
- // Combine payload and signature
261
- return `${base64Payload}.${signature}`;
262
- }
263
- /**
264
- * Verifies and decodes a signed token.
265
- *
266
- * @param {string} token - The token to verify
267
- * @param {string} secret - Secret key for verification
268
- * @returns {object | null} Decoded payload if valid, null if invalid
269
- */
270
- function verifySignedToken(token, secret) {
271
- try {
272
- // Split token into parts
273
- const [payloadB64, signature] = token.split('.');
274
- if (!payloadB64 || !signature)
275
- return null;
276
- // Verify signature
277
- const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
278
- if (!safeCompare(signature, expectedSignature))
279
- return null;
280
- // Decode payload
281
- const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
282
- const payload = JSON.parse(payloadStr);
283
- // Check expiration
284
- if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
285
- return null;
286
- }
287
- return payload;
288
- }
289
- catch (_a) {
290
- return null;
291
- }
292
- }
293
- //# sourceMappingURL=crypto.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAuCH,oBAEC;AAUD,oBAEC;AASD,gCAEC;AASD,oBAEC;AASD,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AAC","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"]}
@@ -1,159 +0,0 @@
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