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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/README.md +1 -2
  2. package/build/esm/config.d.ts +122 -0
  3. package/build/esm/config.js +133 -0
  4. package/build/esm/config.js.map +1 -0
  5. package/build/esm/index.d.ts +27 -0
  6. package/build/esm/index.js +50 -0
  7. package/build/esm/index.js.map +1 -0
  8. package/build/esm/servers/server.builder.d.ts +508 -0
  9. package/build/esm/servers/server.builder.js +702 -0
  10. package/build/esm/servers/server.builder.js.map +1 -0
  11. package/build/esm/servers/server.d.ts +256 -0
  12. package/build/esm/servers/server.js +1248 -0
  13. package/build/esm/servers/server.js.map +1 -0
  14. package/build/esm/types/api-response.d.ts +152 -0
  15. package/build/esm/types/api-response.js +34 -0
  16. package/build/esm/types/api-response.js.map +1 -0
  17. package/build/esm/types/index.d.ts +125 -0
  18. package/build/esm/types/index.js +25 -0
  19. package/build/esm/types/index.js.map +1 -0
  20. package/build/esm/types/server.d.ts +268 -0
  21. package/build/esm/types/server.js +25 -0
  22. package/build/esm/types/server.js.map +1 -0
  23. package/build/esm/utils/array.utils.d.ts +168 -0
  24. package/build/esm/utils/array.utils.js +382 -0
  25. package/build/esm/utils/array.utils.js.map +1 -0
  26. package/build/esm/utils/async.utils.d.ts +265 -0
  27. package/build/esm/utils/async.utils.js +896 -0
  28. package/build/esm/utils/async.utils.js.map +1 -0
  29. package/build/esm/utils/cache.utils.d.ts +153 -0
  30. package/build/esm/utils/cache.utils.js +499 -0
  31. package/build/esm/utils/cache.utils.js.map +1 -0
  32. package/build/esm/utils/context-store.utils.d.ts +189 -0
  33. package/build/esm/utils/context-store.utils.js +307 -0
  34. package/build/esm/utils/context-store.utils.js.map +1 -0
  35. package/build/esm/utils/crypto.utils.d.ts +160 -0
  36. package/build/esm/utils/crypto.utils.js +375 -0
  37. package/build/esm/utils/crypto.utils.js.map +1 -0
  38. package/build/esm/utils/date.utils.d.ts +159 -0
  39. package/build/esm/utils/date.utils.js +389 -0
  40. package/build/esm/utils/date.utils.js.map +1 -0
  41. package/build/esm/utils/decorators.utils.d.ts +508 -0
  42. package/build/esm/utils/decorators.utils.js +1057 -0
  43. package/build/esm/utils/decorators.utils.js.map +1 -0
  44. package/build/esm/utils/dir.utils.d.ts +196 -0
  45. package/build/esm/utils/dir.utils.js +998 -0
  46. package/build/esm/utils/dir.utils.js.map +1 -0
  47. package/build/esm/utils/env.utils.d.ts +377 -0
  48. package/build/esm/utils/env.utils.js +873 -0
  49. package/build/esm/utils/env.utils.js.map +1 -0
  50. package/build/esm/utils/exception.utils.d.ts +230 -0
  51. package/build/esm/utils/exception.utils.js +559 -0
  52. package/build/esm/utils/exception.utils.js.map +1 -0
  53. package/build/esm/utils/fs.utils.d.ts +164 -0
  54. package/build/esm/utils/fs.utils.js +580 -0
  55. package/build/esm/utils/fs.utils.js.map +1 -0
  56. package/build/esm/utils/http-status-codes.d.ts +266 -0
  57. package/build/esm/utils/http-status-codes.js +295 -0
  58. package/build/esm/utils/http-status-codes.js.map +1 -0
  59. package/build/esm/utils/id.utils.d.ts +36 -0
  60. package/build/esm/utils/id.utils.js +87 -0
  61. package/build/esm/utils/id.utils.js.map +1 -0
  62. package/build/esm/utils/logger.utils.d.ts +160 -0
  63. package/build/esm/utils/logger.utils.js +341 -0
  64. package/build/esm/utils/logger.utils.js.map +1 -0
  65. package/build/esm/utils/middleware.utils.d.ts +100 -0
  66. package/build/esm/utils/middleware.utils.js +325 -0
  67. package/build/esm/utils/middleware.utils.js.map +1 -0
  68. package/build/esm/utils/obj.utils.d.ts +124 -0
  69. package/build/esm/utils/obj.utils.js +519 -0
  70. package/build/esm/utils/obj.utils.js.map +1 -0
  71. package/build/esm/utils/performance.utils.d.ts +136 -0
  72. package/build/esm/utils/performance.utils.js +376 -0
  73. package/build/esm/utils/performance.utils.js.map +1 -0
  74. package/build/esm/utils/request.utils.d.ts +86 -0
  75. package/build/esm/utils/request.utils.js +223 -0
  76. package/build/esm/utils/request.utils.js.map +1 -0
  77. package/build/esm/utils/response.utils.d.ts +163 -0
  78. package/build/esm/utils/response.utils.js +284 -0
  79. package/build/esm/utils/response.utils.js.map +1 -0
  80. package/build/esm/utils/stream.utils.d.ts +88 -0
  81. package/build/esm/utils/stream.utils.js +284 -0
  82. package/build/esm/utils/stream.utils.js.map +1 -0
  83. package/build/esm/utils/string.utils.d.ts +93 -0
  84. package/build/esm/utils/string.utils.js +169 -0
  85. package/build/esm/utils/string.utils.js.map +1 -0
  86. package/build/esm/utils/type.utils.d.ts +90 -0
  87. package/build/esm/utils/type.utils.js +190 -0
  88. package/build/esm/utils/type.utils.js.map +1 -0
  89. package/build/esm/utils/url.utils.d.ts +141 -0
  90. package/build/esm/utils/url.utils.js +381 -0
  91. package/build/esm/utils/url.utils.js.map +1 -0
  92. package/build/esm/utils/validate.utils.d.ts +177 -0
  93. package/build/esm/utils/validate.utils.js +336 -0
  94. package/build/esm/utils/validate.utils.js.map +1 -0
  95. package/build/esnext/config.d.ts +122 -0
  96. package/build/esnext/config.js +133 -0
  97. package/build/esnext/config.js.map +1 -0
  98. package/build/esnext/index.d.ts +27 -0
  99. package/build/esnext/index.js +50 -0
  100. package/build/esnext/index.js.map +1 -0
  101. package/build/esnext/servers/server.builder.d.ts +508 -0
  102. package/build/esnext/servers/server.builder.js +657 -0
  103. package/build/esnext/servers/server.builder.js.map +1 -0
  104. package/build/esnext/servers/server.d.ts +256 -0
  105. package/build/esnext/servers/server.js +955 -0
  106. package/build/esnext/servers/server.js.map +1 -0
  107. package/build/esnext/types/api-response.d.ts +152 -0
  108. package/build/esnext/types/api-response.js +34 -0
  109. package/build/esnext/types/api-response.js.map +1 -0
  110. package/build/esnext/types/index.d.ts +125 -0
  111. package/build/esnext/types/index.js +25 -0
  112. package/build/esnext/types/index.js.map +1 -0
  113. package/build/esnext/types/server.d.ts +268 -0
  114. package/build/esnext/types/server.js +25 -0
  115. package/build/esnext/types/server.js.map +1 -0
  116. package/build/esnext/utils/array.utils.d.ts +168 -0
  117. package/build/esnext/utils/array.utils.js +345 -0
  118. package/build/esnext/utils/array.utils.js.map +1 -0
  119. package/build/esnext/utils/async.utils.d.ts +265 -0
  120. package/build/esnext/utils/async.utils.js +620 -0
  121. package/build/esnext/utils/async.utils.js.map +1 -0
  122. package/build/esnext/utils/cache.utils.d.ts +153 -0
  123. package/build/esnext/utils/cache.utils.js +293 -0
  124. package/build/esnext/utils/cache.utils.js.map +1 -0
  125. package/build/esnext/utils/context-store.utils.d.ts +189 -0
  126. package/build/esnext/utils/context-store.utils.js +289 -0
  127. package/build/esnext/utils/context-store.utils.js.map +1 -0
  128. package/build/esnext/utils/crypto.utils.d.ts +160 -0
  129. package/build/esnext/utils/crypto.utils.js +276 -0
  130. package/build/esnext/utils/crypto.utils.js.map +1 -0
  131. package/build/esnext/utils/date.utils.d.ts +159 -0
  132. package/build/esnext/utils/date.utils.js +384 -0
  133. package/build/esnext/utils/date.utils.js.map +1 -0
  134. package/build/esnext/utils/decorators.utils.d.ts +508 -0
  135. package/build/esnext/utils/decorators.utils.js +877 -0
  136. package/build/esnext/utils/decorators.utils.js.map +1 -0
  137. package/build/esnext/utils/dir.utils.d.ts +196 -0
  138. package/build/esnext/utils/dir.utils.js +477 -0
  139. package/build/esnext/utils/dir.utils.js.map +1 -0
  140. package/build/esnext/utils/env.utils.d.ts +377 -0
  141. package/build/esnext/utils/env.utils.js +785 -0
  142. package/build/esnext/utils/env.utils.js.map +1 -0
  143. package/build/esnext/utils/exception.utils.d.ts +230 -0
  144. package/build/esnext/utils/exception.utils.js +381 -0
  145. package/build/esnext/utils/exception.utils.js.map +1 -0
  146. package/build/esnext/utils/fs.utils.d.ts +164 -0
  147. package/build/esnext/utils/fs.utils.js +349 -0
  148. package/build/esnext/utils/fs.utils.js.map +1 -0
  149. package/build/esnext/utils/http-status-codes.d.ts +266 -0
  150. package/build/esnext/utils/http-status-codes.js +295 -0
  151. package/build/esnext/utils/http-status-codes.js.map +1 -0
  152. package/build/esnext/utils/id.utils.d.ts +36 -0
  153. package/build/esnext/utils/id.utils.js +84 -0
  154. package/build/esnext/utils/id.utils.js.map +1 -0
  155. package/build/esnext/utils/logger.utils.d.ts +160 -0
  156. package/build/esnext/utils/logger.utils.js +300 -0
  157. package/build/esnext/utils/logger.utils.js.map +1 -0
  158. package/build/esnext/utils/middleware.utils.d.ts +100 -0
  159. package/build/esnext/utils/middleware.utils.js +236 -0
  160. package/build/esnext/utils/middleware.utils.js.map +1 -0
  161. package/build/esnext/utils/obj.utils.d.ts +124 -0
  162. package/build/esnext/utils/obj.utils.js +413 -0
  163. package/build/esnext/utils/obj.utils.js.map +1 -0
  164. package/build/esnext/utils/performance.utils.d.ts +136 -0
  165. package/build/esnext/utils/performance.utils.js +271 -0
  166. package/build/esnext/utils/performance.utils.js.map +1 -0
  167. package/build/esnext/utils/request.utils.d.ts +86 -0
  168. package/build/esnext/utils/request.utils.js +186 -0
  169. package/build/esnext/utils/request.utils.js.map +1 -0
  170. package/build/esnext/utils/response.utils.d.ts +163 -0
  171. package/build/esnext/utils/response.utils.js +247 -0
  172. package/build/esnext/utils/response.utils.js.map +1 -0
  173. package/build/esnext/utils/stream.utils.d.ts +88 -0
  174. package/build/esnext/utils/stream.utils.js +210 -0
  175. package/build/esnext/utils/stream.utils.js.map +1 -0
  176. package/build/esnext/utils/string.utils.d.ts +93 -0
  177. package/build/esnext/utils/string.utils.js +165 -0
  178. package/build/esnext/utils/string.utils.js.map +1 -0
  179. package/build/esnext/utils/type.utils.d.ts +90 -0
  180. package/build/esnext/utils/type.utils.js +187 -0
  181. package/build/esnext/utils/type.utils.js.map +1 -0
  182. package/build/esnext/utils/url.utils.d.ts +141 -0
  183. package/build/esnext/utils/url.utils.js +304 -0
  184. package/build/esnext/utils/url.utils.js.map +1 -0
  185. package/build/esnext/utils/validate.utils.d.ts +177 -0
  186. package/build/esnext/utils/validate.utils.js +320 -0
  187. package/build/esnext/utils/validate.utils.js.map +1 -0
  188. package/build/src/config.d.ts +122 -0
  189. package/build/src/config.js +138 -0
  190. package/build/src/config.js.map +1 -0
  191. package/build/src/index.d.ts +27 -0
  192. package/build/src/index.js +69 -0
  193. package/build/src/index.js.map +1 -0
  194. package/build/src/servers/server.builder.d.ts +508 -0
  195. package/build/src/servers/server.builder.js +661 -0
  196. package/build/src/servers/server.builder.js.map +1 -0
  197. package/build/src/servers/server.d.ts +256 -0
  198. package/build/src/servers/server.js +962 -0
  199. package/build/src/servers/server.js.map +1 -0
  200. package/build/src/types/api-response.d.ts +152 -0
  201. package/build/src/types/api-response.js +37 -0
  202. package/build/src/types/api-response.js.map +1 -0
  203. package/build/src/types/index.d.ts +125 -0
  204. package/build/src/types/index.js +26 -0
  205. package/build/src/types/index.js.map +1 -0
  206. package/build/src/types/server.d.ts +268 -0
  207. package/build/src/types/server.js +26 -0
  208. package/build/src/types/server.js.map +1 -0
  209. package/build/src/utils/array.utils.d.ts +168 -0
  210. package/build/src/utils/array.utils.js +364 -0
  211. package/build/src/utils/array.utils.js.map +1 -0
  212. package/build/src/utils/async.utils.d.ts +265 -0
  213. package/build/src/utils/async.utils.js +641 -0
  214. package/build/src/utils/async.utils.js.map +1 -0
  215. package/build/src/utils/cache.utils.d.ts +153 -0
  216. package/build/src/utils/cache.utils.js +297 -0
  217. package/build/src/utils/cache.utils.js.map +1 -0
  218. package/build/src/utils/context-store.utils.d.ts +189 -0
  219. package/build/src/utils/context-store.utils.js +296 -0
  220. package/build/src/utils/context-store.utils.js.map +1 -0
  221. package/build/src/utils/crypto.utils.d.ts +160 -0
  222. package/build/src/utils/crypto.utils.js +293 -0
  223. package/build/src/utils/crypto.utils.js.map +1 -0
  224. package/build/src/utils/date.utils.d.ts +159 -0
  225. package/build/src/utils/date.utils.js +396 -0
  226. package/build/src/utils/date.utils.js.map +1 -0
  227. package/build/src/utils/decorators.utils.d.ts +508 -0
  228. package/build/src/utils/decorators.utils.js +896 -0
  229. package/build/src/utils/decorators.utils.js.map +1 -0
  230. package/build/src/utils/dir.utils.d.ts +196 -0
  231. package/build/src/utils/dir.utils.js +501 -0
  232. package/build/src/utils/dir.utils.js.map +1 -0
  233. package/build/src/utils/env.utils.d.ts +377 -0
  234. package/build/src/utils/env.utils.js +789 -0
  235. package/build/src/utils/env.utils.js.map +1 -0
  236. package/build/src/utils/exception.utils.d.ts +230 -0
  237. package/build/src/utils/exception.utils.js +407 -0
  238. package/build/src/utils/exception.utils.js.map +1 -0
  239. package/build/src/utils/fs.utils.d.ts +164 -0
  240. package/build/src/utils/fs.utils.js +372 -0
  241. package/build/src/utils/fs.utils.js.map +1 -0
  242. package/build/src/utils/http-status-codes.d.ts +266 -0
  243. package/build/src/utils/http-status-codes.js +298 -0
  244. package/build/src/utils/http-status-codes.js.map +1 -0
  245. package/build/src/utils/id.utils.d.ts +36 -0
  246. package/build/src/utils/id.utils.js +91 -0
  247. package/build/src/utils/id.utils.js.map +1 -0
  248. package/build/src/utils/logger.utils.d.ts +160 -0
  249. package/build/src/utils/logger.utils.js +346 -0
  250. package/build/src/utils/logger.utils.js.map +1 -0
  251. package/build/src/utils/middleware.utils.d.ts +100 -0
  252. package/build/src/utils/middleware.utils.js +244 -0
  253. package/build/src/utils/middleware.utils.js.map +1 -0
  254. package/build/src/utils/obj.utils.d.ts +124 -0
  255. package/build/src/utils/obj.utils.js +429 -0
  256. package/build/src/utils/obj.utils.js.map +1 -0
  257. package/build/src/utils/performance.utils.d.ts +136 -0
  258. package/build/src/utils/performance.utils.js +278 -0
  259. package/build/src/utils/performance.utils.js.map +1 -0
  260. package/build/src/utils/request.utils.d.ts +86 -0
  261. package/build/src/utils/request.utils.js +195 -0
  262. package/build/src/utils/request.utils.js.map +1 -0
  263. package/build/src/utils/response.utils.d.ts +163 -0
  264. package/build/src/utils/response.utils.js +260 -0
  265. package/build/src/utils/response.utils.js.map +1 -0
  266. package/build/src/utils/stream.utils.d.ts +88 -0
  267. package/build/src/utils/stream.utils.js +218 -0
  268. package/build/src/utils/stream.utils.js.map +1 -0
  269. package/build/src/utils/string.utils.d.ts +93 -0
  270. package/build/src/utils/string.utils.js +179 -0
  271. package/build/src/utils/string.utils.js.map +1 -0
  272. package/build/src/utils/type.utils.d.ts +90 -0
  273. package/build/src/utils/type.utils.js +196 -0
  274. package/build/src/utils/type.utils.js.map +1 -0
  275. package/build/src/utils/url.utils.d.ts +141 -0
  276. package/build/src/utils/url.utils.js +317 -0
  277. package/build/src/utils/url.utils.js.map +1 -0
  278. package/build/src/utils/validate.utils.d.ts +177 -0
  279. package/build/src/utils/validate.utils.js +345 -0
  280. package/build/src/utils/validate.utils.js.map +1 -0
  281. package/package.json +66 -12
  282. package/build/index.cjs +0 -6888
  283. package/build/index.d.ts +0 -5242
  284. package/build/index.mjs +0 -6615
@@ -0,0 +1,477 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ import os from 'os';
25
+ import fs from 'fs';
26
+ import fsp from 'fs/promises';
27
+ import path from 'path';
28
+ import { glob } from 'glob';
29
+ import { randomBytes } from 'crypto';
30
+ /**
31
+ * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
32
+ *
33
+ * @param {string} dirPath - The directory path to ensure.
34
+ * @returns {Promise<void>} Resolves when the directory exists.
35
+ * @throws {Error} If directory cannot be created.
36
+ */
37
+ export async function ensureDir(dirPath) {
38
+ await fsp.mkdir(dirPath, { recursive: true });
39
+ }
40
+ /**
41
+ * Recursively lists all files in a directory.
42
+ *
43
+ * @param {string} dirPath - The base directory.
44
+ * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
45
+ * @returns {Promise<string[]>} Array of absolute file paths.
46
+ * @throws {Error} If the directory cannot be read.
47
+ */
48
+ export async function listFiles(dirPath, recursive = false) {
49
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
50
+ const files = [];
51
+ for (const entry of entries) {
52
+ const fullPath = path.join(dirPath, entry.name);
53
+ if (entry.isFile()) {
54
+ files.push(fullPath);
55
+ }
56
+ else if (recursive && entry.isDirectory()) {
57
+ const nestedFiles = await listFiles(fullPath, true);
58
+ files.push(...nestedFiles);
59
+ }
60
+ }
61
+ return files;
62
+ }
63
+ /**
64
+ * Deletes a directory and all its contents recursively (like `rm -rf`).
65
+ *
66
+ * @param {string} dirPath - Directory to delete.
67
+ * @returns {Promise<void>} Resolves when deletion is complete.
68
+ * @throws {Error} If deletion fails.
69
+ */
70
+ export async function deleteDirRecursive(dirPath) {
71
+ await fsp.rm(dirPath, { recursive: true, force: true });
72
+ }
73
+ /**
74
+ * Checks whether a given path is a directory.
75
+ *
76
+ * @param {string} pathStr - Path to check.
77
+ * @returns {Promise<boolean>} True if the path is a directory, else false.
78
+ */
79
+ export async function isDirectory(pathStr) {
80
+ try {
81
+ const stat = await fsp.stat(pathStr);
82
+ return stat.isDirectory();
83
+ }
84
+ catch (_a) {
85
+ return false;
86
+ }
87
+ }
88
+ /**
89
+ * Recursively copies a directory and all its contents to a destination.
90
+ *
91
+ * @param {string} src - Source directory path.
92
+ * @param {string} dest - Destination directory path.
93
+ * @returns {Promise<void>} Resolves when copy is complete.
94
+ * @throws {Error} If source does not exist or copy fails.
95
+ */
96
+ export async function copyDir(src, dest) {
97
+ await ensureDir(dest);
98
+ const entries = await fsp.readdir(src, { withFileTypes: true });
99
+ for (const entry of entries) {
100
+ const srcPath = path.join(src, entry.name);
101
+ const destPath = path.join(dest, entry.name);
102
+ if (entry.isDirectory()) {
103
+ await copyDir(srcPath, destPath);
104
+ }
105
+ else {
106
+ await fsp.copyFile(srcPath, destPath);
107
+ }
108
+ }
109
+ }
110
+ /**
111
+ * Moves a directory to a new location by copying and deleting the original.
112
+ *
113
+ * @param {string} src - Source directory path.
114
+ * @param {string} dest - Destination directory path.
115
+ * @returns {Promise<void>} Resolves when move is complete.
116
+ * @throws {Error} If copy or deletion fails.
117
+ */
118
+ export async function moveDir(src, dest) {
119
+ await copyDir(src, dest);
120
+ await deleteDirRecursive(src);
121
+ }
122
+ /**
123
+ * Empties a directory by deleting all files and subdirectories inside it.
124
+ *
125
+ * @param {string} dirPath - Path to the directory to empty.
126
+ * @returns {Promise<void>} Resolves when the directory has been emptied.
127
+ * @throws {Error} If files or subdirectories cannot be removed.
128
+ */
129
+ export async function emptyDir(dirPath) {
130
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
131
+ for (const entry of entries) {
132
+ const entryPath = path.join(dirPath, entry.name);
133
+ if (entry.isDirectory()) {
134
+ await fsp.rm(entryPath, { recursive: true, force: true });
135
+ }
136
+ else {
137
+ await fsp.unlink(entryPath);
138
+ }
139
+ }
140
+ }
141
+ /**
142
+ * Calculates the total size (in bytes) of all files in a directory (recursive).
143
+ *
144
+ * @param {string} dirPath - Path to the directory.
145
+ * @returns {Promise<number>} Total size in bytes.
146
+ * @throws {Error} If any file stats cannot be read.
147
+ */
148
+ export async function getDirSize(dirPath) {
149
+ let total = 0;
150
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
151
+ for (const entry of entries) {
152
+ const entryPath = path.join(dirPath, entry.name);
153
+ if (entry.isDirectory()) {
154
+ total += await getDirSize(entryPath);
155
+ }
156
+ else {
157
+ const stat = await fsp.stat(entryPath);
158
+ total += stat.size;
159
+ }
160
+ }
161
+ return total;
162
+ }
163
+ /**
164
+ * Watches a directory for file changes and calls a callback on each event.
165
+ *
166
+ * @param {string} dirPath - Directory path to watch.
167
+ * @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
168
+ * @returns {() => void} A function to stop watching the directory.
169
+ */
170
+ export function watchDir(dirPath, callback) {
171
+ const watcher = fs.watch(dirPath, (eventType, filename) => {
172
+ callback(eventType, filename);
173
+ });
174
+ return () => watcher.close();
175
+ }
176
+ /**
177
+ * Finds files matching a glob pattern.
178
+ *
179
+ * @param {string} pattern - Glob pattern to match files.
180
+ * @param {object} [options] - Options for glob pattern matching.
181
+ * @param {string} [options.cwd] - Current working directory for relative patterns.
182
+ * @param {boolean} [options.dot=false] - Include dotfiles in matches.
183
+ * @param {boolean} [options.nodir=true] - Only match files, not directories.
184
+ * @returns {Promise<string[]>} Array of matched file paths.
185
+ * @throws {Error} If pattern matching fails.
186
+ */
187
+ export async function findFilesByPattern(pattern, options = {}) {
188
+ const defaultOptions = Object.assign({ nodir: true }, options);
189
+ return glob(pattern, defaultOptions);
190
+ }
191
+ /**
192
+ * Gets all subdirectories in a directory.
193
+ *
194
+ * @param {string} dirPath - The directory to search in.
195
+ * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.
196
+ * @returns {Promise<string[]>} Array of absolute subdirectory paths.
197
+ * @throws {Error} If directory cannot be read.
198
+ */
199
+ export async function getSubdirectories(dirPath, recursive = false) {
200
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
201
+ const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));
202
+ if (recursive && dirs.length > 0) {
203
+ const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));
204
+ return [...dirs, ...nestedDirs.flat()];
205
+ }
206
+ return dirs;
207
+ }
208
+ /**
209
+ * Ensures a directory exists and is empty.
210
+ *
211
+ * @param {string} dirPath - Path to the directory.
212
+ * @returns {Promise<void>} Resolves when the directory exists and is empty.
213
+ * @throws {Error} If directory cannot be created or emptied.
214
+ */
215
+ export async function ensureEmptyDir(dirPath) {
216
+ if (await isDirectory(dirPath)) {
217
+ await emptyDir(dirPath);
218
+ }
219
+ else {
220
+ try {
221
+ await fsp.unlink(dirPath);
222
+ }
223
+ catch (error) {
224
+ // Ignore if file doesn't exist
225
+ if (error.code !== 'ENOENT') {
226
+ throw error;
227
+ }
228
+ }
229
+ await ensureDir(dirPath);
230
+ }
231
+ }
232
+ /**
233
+ * Creates a temporary directory with optional auto-cleanup.
234
+ *
235
+ * @param {object} [options] - Options for the temporary directory.
236
+ * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.
237
+ * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.
238
+ * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.
239
+ * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.
240
+ * @throws {Error} If directory cannot be created.
241
+ */
242
+ export async function createTempDir(options = {}) {
243
+ const prefix = options.prefix || 'tmp-';
244
+ const parentDir = options.parentDir || os.tmpdir();
245
+ const dirName = `${prefix}${randomBytes(6).toString('hex')}`;
246
+ const tempDirPath = path.join(parentDir, dirName);
247
+ await ensureDir(tempDirPath);
248
+ const cleanup = async () => {
249
+ try {
250
+ await deleteDirRecursive(tempDirPath);
251
+ }
252
+ catch (_a) {
253
+ // Ignore cleanup errors
254
+ }
255
+ };
256
+ if (options.cleanup) {
257
+ process.once('exit', () => {
258
+ try {
259
+ fs.rmSync(tempDirPath, { recursive: true, force: true });
260
+ }
261
+ catch (_a) {
262
+ // Ignore cleanup errors on exit
263
+ }
264
+ });
265
+ // Handle signals for better cleanup
266
+ ['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {
267
+ process.once(signal, () => {
268
+ cleanup().then(() => process.exit());
269
+ });
270
+ });
271
+ }
272
+ return { path: tempDirPath, cleanup };
273
+ }
274
+ /**
275
+ * Finds the newest file in a directory.
276
+ *
277
+ * @param {string} dirPath - Directory to search.
278
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
279
+ * @returns {Promise<string | null>} Path to the newest file or null if no files.
280
+ * @throws {Error} If directory cannot be read.
281
+ */
282
+ export async function findNewestFile(dirPath, recursive = false) {
283
+ const files = await listFiles(dirPath, recursive);
284
+ if (files.length === 0)
285
+ return null;
286
+ const stats = await Promise.all(files.map(async (file) => ({
287
+ path: file,
288
+ mtime: (await fsp.stat(file)).mtime
289
+ })));
290
+ return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;
291
+ }
292
+ /**
293
+ * Finds the oldest file in a directory.
294
+ *
295
+ * @param {string} dirPath - Directory to search.
296
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
297
+ * @returns {Promise<string | null>} Path to the oldest file or null if no files.
298
+ * @throws {Error} If directory cannot be read.
299
+ */
300
+ export async function findOldestFile(dirPath, recursive = false) {
301
+ const files = await listFiles(dirPath, recursive);
302
+ if (files.length === 0)
303
+ return null;
304
+ const stats = await Promise.all(files.map(async (file) => ({
305
+ path: file,
306
+ mtime: (await fsp.stat(file)).mtime
307
+ })));
308
+ return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;
309
+ }
310
+ /**
311
+ * Finds files or directories in a directory matching a predicate function.
312
+ *
313
+ * @param {string} dirPath - Directory to search.
314
+ * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.
315
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
316
+ * @returns {Promise<string[]>} Array of matching paths.
317
+ * @throws {Error} If directory cannot be read.
318
+ */
319
+ export async function findInDir(dirPath, predicate, recursive = false) {
320
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
321
+ const results = [];
322
+ for (const entry of entries) {
323
+ const entryPath = path.join(dirPath, entry.name);
324
+ const stat = await fsp.stat(entryPath);
325
+ if (await predicate(entryPath, stat)) {
326
+ results.push(entryPath);
327
+ }
328
+ if (recursive && entry.isDirectory()) {
329
+ const nestedResults = await findInDir(entryPath, predicate, true);
330
+ results.push(...nestedResults);
331
+ }
332
+ }
333
+ return results;
334
+ }
335
+ /**
336
+ * Watches a directory recursively for file changes.
337
+ *
338
+ * @param {string} dirPath - Base directory path to watch.
339
+ * @param {(eventType: "rename" | "change", filename: string) => void} callback - Callback for each change event.
340
+ * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.
341
+ * @returns {Promise<() => void>} A function to stop watching the directory.
342
+ * @throws {Error} If directory cannot be watched.
343
+ */
344
+ export async function watchDirRecursive(dirPath, callback, includeSubdirs = true) {
345
+ // Normalize the path to ensure consistent path separators
346
+ const normalizedBasePath = path.normalize(dirPath);
347
+ // Create watchers for the base dir and all subdirectories
348
+ const watchers = [];
349
+ // Helper function to add a watcher for a directory
350
+ const addWatcher = (dir) => {
351
+ try {
352
+ const watcher = fs.watch(dir, (eventType, filename) => {
353
+ if (!filename)
354
+ return;
355
+ const fullPath = path.join(dir, filename);
356
+ // Make the path relative to the base directory
357
+ const relativePath = path.relative(normalizedBasePath, fullPath);
358
+ callback(eventType, relativePath);
359
+ // If a new directory is created, we should watch it
360
+ if (eventType === 'rename' && includeSubdirs) {
361
+ setTimeout(async () => {
362
+ try {
363
+ if (await isDirectory(fullPath)) {
364
+ addWatcher(fullPath);
365
+ }
366
+ }
367
+ catch (_a) {
368
+ // Ignore errors checking newly created items
369
+ }
370
+ }, 100);
371
+ }
372
+ });
373
+ watchers.push(watcher);
374
+ }
375
+ catch (_a) {
376
+ // Silently ignore directories we can't watch
377
+ }
378
+ };
379
+ // Add watcher for the base directory
380
+ addWatcher(normalizedBasePath);
381
+ // If watching subdirectories, add watchers for all existing subdirectories
382
+ if (includeSubdirs) {
383
+ const subdirs = await getSubdirectories(normalizedBasePath, true);
384
+ for (const subdir of subdirs) {
385
+ addWatcher(subdir);
386
+ }
387
+ }
388
+ // Return a function to close all watchers
389
+ return () => {
390
+ watchers.forEach(watcher => watcher.close());
391
+ };
392
+ }
393
+ /**
394
+ * Gets detailed directory statistics including file count, directory count, and size.
395
+ *
396
+ * @param {string} dirPath - Path to the directory.
397
+ * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.
398
+ * @throws {Error} If directory cannot be read.
399
+ */
400
+ export async function getDirStats(dirPath) {
401
+ let fileCount = 0;
402
+ let dirCount = 0;
403
+ let totalSize = 0;
404
+ async function processDir(currentPath) {
405
+ const entries = await fsp.readdir(currentPath, { withFileTypes: true });
406
+ for (const entry of entries) {
407
+ const entryPath = path.join(currentPath, entry.name);
408
+ if (entry.isDirectory()) {
409
+ dirCount++;
410
+ await processDir(entryPath);
411
+ }
412
+ else if (entry.isFile()) {
413
+ fileCount++;
414
+ const stat = await fsp.stat(entryPath);
415
+ totalSize += stat.size;
416
+ }
417
+ }
418
+ }
419
+ await processDir(dirPath);
420
+ return { fileCount, dirCount, totalSize };
421
+ }
422
+ /**
423
+ * Walks through a directory hierarchy, calling a visitor function for each entry.
424
+ *
425
+ * @param {string} dirPath - Starting directory path.
426
+ * @param {object} options - Options for walking the directory.
427
+ * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -
428
+ * Function called for each file/directory. Return false to skip a directory.
429
+ * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.
430
+ * @throws {Error} If directory cannot be read.
431
+ */
432
+ export async function walkDir(dirPath, options) {
433
+ const traversalOrder = options.traversalOrder || 'pre';
434
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
435
+ for (const entry of entries) {
436
+ const entryPath = path.join(dirPath, entry.name);
437
+ const stats = await fsp.stat(entryPath);
438
+ const entryInfo = {
439
+ path: entryPath,
440
+ name: entry.name,
441
+ isDirectory: entry.isDirectory(),
442
+ stats
443
+ };
444
+ if (entry.isDirectory()) {
445
+ // Pre-order: visit directory before its contents
446
+ if (traversalOrder === 'pre') {
447
+ const shouldContinue = await options.visitorFn(entryInfo);
448
+ // If the visitor returns false, don't recurse into this directory
449
+ if (shouldContinue !== false) {
450
+ await walkDir(entryPath, options);
451
+ }
452
+ }
453
+ else {
454
+ // Post-order: visit directory after its contents
455
+ await walkDir(entryPath, options);
456
+ await options.visitorFn(entryInfo);
457
+ }
458
+ }
459
+ else {
460
+ // Files are always visited when encountered
461
+ await options.visitorFn(entryInfo);
462
+ }
463
+ }
464
+ if (traversalOrder === 'post') {
465
+ // Only visit the root if this is the top-level call (not for subdirectories)
466
+ // But since this function is always called recursively, always visit after children
467
+ const stats = await fsp.stat(dirPath);
468
+ const entryInfo = {
469
+ path: dirPath,
470
+ name: path.basename(dirPath),
471
+ isDirectory: true,
472
+ stats
473
+ };
474
+ await options.visitorFn(entryInfo);
475
+ }
476
+ }
477
+ //# sourceMappingURL=dir.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,aAAa,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAe;IAC7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AC,CAAC;gBAClC,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;YACrC,CAAC;QACH,CAAC;aAAM,CAAC;YACN,4CAA4C;YAC5C,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED,IAAI,cAAc,KAAK,MAAM,EAAE,CAAC;QAC9B,6EAA6E;QAC7E,oFAAoF;QACpF,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,MAAM,SAAS,GAAG;YAChB,IAAI,EAAE,OAAO;YACb,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YAC5B,WAAW,EAAE,IAAI;YACjB,KAAK;SACN,CAAC;QACF,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IACrC,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 os from 'os';\nimport fs from 'fs';\nimport fsp from 'fs/promises';\nimport path from 'path';\nimport { glob } from 'glob';\nimport { randomBytes } from 'crypto';\n\n/**\n * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).\n *\n * @param {string} dirPath - The directory path to ensure.\n * @returns {Promise<void>} Resolves when the directory exists.\n * @throws {Error} If directory cannot be created.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fsp.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Recursively lists all files in a directory.\n *\n * @param {string} dirPath - The base directory.\n * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.\n * @returns {Promise<string[]>} Array of absolute file paths.\n * @throws {Error} If the directory cannot be read.\n */\nexport async function listFiles(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const files: string[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isFile()) {\n files.push(fullPath);\n } else if (recursive && entry.isDirectory()) {\n const nestedFiles = await listFiles(fullPath, true);\n files.push(...nestedFiles);\n }\n }\n\n return files;\n}\n\n/**\n * Deletes a directory and all its contents recursively (like `rm -rf`).\n *\n * @param {string} dirPath - Directory to delete.\n * @returns {Promise<void>} Resolves when deletion is complete.\n * @throws {Error} If deletion fails.\n */\nexport async function deleteDirRecursive(dirPath: string): Promise<void> {\n await fsp.rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * Checks whether a given path is a directory.\n *\n * @param {string} pathStr - Path to check.\n * @returns {Promise<boolean>} True if the path is a directory, else false.\n */\nexport async function isDirectory(pathStr: string): Promise<boolean> {\n try {\n const stat = await fsp.stat(pathStr);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Recursively copies a directory and all its contents to a destination.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when copy is complete.\n * @throws {Error} If source does not exist or copy fails.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fsp.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fsp.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Moves a directory to a new location by copying and deleting the original.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when move is complete.\n * @throws {Error} If copy or deletion fails.\n */\nexport async function moveDir(src: string, dest: string): Promise<void> {\n await copyDir(src, dest);\n await deleteDirRecursive(src);\n}\n\n/**\n * Empties a directory by deleting all files and subdirectories inside it.\n *\n * @param {string} dirPath - Path to the directory to empty.\n * @returns {Promise<void>} Resolves when the directory has been emptied.\n * @throws {Error} If files or subdirectories cannot be removed.\n */\nexport async function emptyDir(dirPath: string): Promise<void> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n await fsp.rm(entryPath, { recursive: true, force: true });\n } else {\n await fsp.unlink(entryPath);\n }\n }\n}\n\n/**\n * Calculates the total size (in bytes) of all files in a directory (recursive).\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<number>} Total size in bytes.\n * @throws {Error} If any file stats cannot be read.\n */\nexport async function getDirSize(dirPath: string): Promise<number> {\n let total = 0;\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n if (entry.isDirectory()) {\n total += await getDirSize(entryPath);\n } else {\n const stat = await fsp.stat(entryPath);\n total += stat.size;\n }\n }\n\n return total;\n}\n\n/**\n * Watches a directory for file changes and calls a callback on each event.\n *\n * @param {string} dirPath - Directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string | null) => void} callback - Callback for each change event.\n * @returns {() => void} A function to stop watching the directory.\n */\nexport function watchDir(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string | null) => void\n): () => void {\n const watcher = fs.watch(dirPath, (eventType, filename) => {\n callback(eventType, filename);\n });\n\n return () => watcher.close();\n}\n\n/**\n * Finds files matching a glob pattern.\n *\n * @param {string} pattern - Glob pattern to match files.\n * @param {object} [options] - Options for glob pattern matching.\n * @param {string} [options.cwd] - Current working directory for relative patterns.\n * @param {boolean} [options.dot=false] - Include dotfiles in matches.\n * @param {boolean} [options.nodir=true] - Only match files, not directories.\n * @returns {Promise<string[]>} Array of matched file paths.\n * @throws {Error} If pattern matching fails.\n */\nexport async function findFilesByPattern(\n pattern: string,\n options: { cwd?: string; dot?: boolean; nodir?: boolean } = {}\n): Promise<string[]> {\n const defaultOptions = { nodir: true, ...options };\n return glob(pattern, defaultOptions);\n}\n\n/**\n * Gets all subdirectories in a directory.\n *\n * @param {string} dirPath - The directory to search in.\n * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.\n * @returns {Promise<string[]>} Array of absolute subdirectory paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getSubdirectories(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));\n return [...dirs, ...nestedDirs.flat()];\n }\n\n return dirs;\n}\n\n/**\n * Ensures a directory exists and is empty.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<void>} Resolves when the directory exists and is empty.\n * @throws {Error} If directory cannot be created or emptied.\n */\nexport async function ensureEmptyDir(dirPath: string): Promise<void> {\n if (await isDirectory(dirPath)) {\n await emptyDir(dirPath);\n } else {\n try {\n await fsp.unlink(dirPath);\n } catch (error) {\n // Ignore if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n await ensureDir(dirPath);\n }\n}\n\n/**\n * Creates a temporary directory with optional auto-cleanup.\n *\n * @param {object} [options] - Options for the temporary directory.\n * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.\n * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.\n * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.\n * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.\n * @throws {Error} If directory cannot be created.\n */\nexport async function createTempDir(\n options: { prefix?: string; parentDir?: string; cleanup?: boolean } = {}\n): Promise<{ path: string; cleanup: () => Promise<void> }> {\n const prefix = options.prefix || 'tmp-';\n const parentDir = options.parentDir || os.tmpdir();\n const dirName = `${prefix}${randomBytes(6).toString('hex')}`;\n const tempDirPath = path.join(parentDir, dirName);\n\n await ensureDir(tempDirPath);\n\n const cleanup = async () => {\n try {\n await deleteDirRecursive(tempDirPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n if (options.cleanup) {\n process.once('exit', () => {\n try {\n fs.rmSync(tempDirPath, { recursive: true, force: true });\n } catch {\n // Ignore cleanup errors on exit\n }\n });\n\n // Handle signals for better cleanup\n ['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {\n process.once(signal as NodeJS.Signals, () => {\n cleanup().then(() => process.exit());\n });\n });\n }\n\n return { path: tempDirPath, cleanup };\n}\n\n/**\n * Finds the newest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the newest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findNewestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;\n}\n\n/**\n * Finds the oldest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the oldest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findOldestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;\n}\n\n/**\n * Finds files or directories in a directory matching a predicate function.\n *\n * @param {string} dirPath - Directory to search.\n * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string[]>} Array of matching paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findInDir(\n dirPath: string,\n predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>,\n recursive = false\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const results: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stat = await fsp.stat(entryPath);\n\n if (await predicate(entryPath, stat)) {\n results.push(entryPath);\n }\n\n if (recursive && entry.isDirectory()) {\n const nestedResults = await findInDir(entryPath, predicate, true);\n results.push(...nestedResults);\n }\n }\n\n return results;\n}\n\n/**\n * Watches a directory recursively for file changes.\n *\n * @param {string} dirPath - Base directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string) => void} callback - Callback for each change event.\n * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.\n * @returns {Promise<() => void>} A function to stop watching the directory.\n * @throws {Error} If directory cannot be watched.\n */\nexport async function watchDirRecursive(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string) => void,\n includeSubdirs = true\n): Promise<() => void> {\n // Normalize the path to ensure consistent path separators\n const normalizedBasePath = path.normalize(dirPath);\n\n // Create watchers for the base dir and all subdirectories\n const watchers: fs.FSWatcher[] = [];\n\n // Helper function to add a watcher for a directory\n const addWatcher = (dir: string) => {\n try {\n const watcher = fs.watch(dir, (eventType, filename) => {\n if (!filename) return;\n\n const fullPath = path.join(dir, filename);\n // Make the path relative to the base directory\n const relativePath = path.relative(normalizedBasePath, fullPath);\n callback(eventType, relativePath);\n\n // If a new directory is created, we should watch it\n if (eventType === 'rename' && includeSubdirs) {\n setTimeout(async () => {\n try {\n if (await isDirectory(fullPath)) {\n addWatcher(fullPath);\n }\n } catch {\n // Ignore errors checking newly created items\n }\n }, 100);\n }\n });\n watchers.push(watcher);\n } catch {\n // Silently ignore directories we can't watch\n }\n };\n\n // Add watcher for the base directory\n addWatcher(normalizedBasePath);\n\n // If watching subdirectories, add watchers for all existing subdirectories\n if (includeSubdirs) {\n const subdirs = await getSubdirectories(normalizedBasePath, true);\n for (const subdir of subdirs) {\n addWatcher(subdir);\n }\n }\n\n // Return a function to close all watchers\n return () => {\n watchers.forEach(watcher => watcher.close());\n };\n}\n\n/**\n * Gets detailed directory statistics including file count, directory count, and size.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getDirStats(\n dirPath: string\n): Promise<{ fileCount: number; dirCount: number; totalSize: number }> {\n let fileCount = 0;\n let dirCount = 0;\n let totalSize = 0;\n\n async function processDir(currentPath: string): Promise<void> {\n const entries = await fsp.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n dirCount++;\n await processDir(entryPath);\n } else if (entry.isFile()) {\n fileCount++;\n const stat = await fsp.stat(entryPath);\n totalSize += stat.size;\n }\n }\n }\n\n await processDir(dirPath);\n\n return { fileCount, dirCount, totalSize };\n}\n\n/**\n * Walks through a directory hierarchy, calling a visitor function for each entry.\n *\n * @param {string} dirPath - Starting directory path.\n * @param {object} options - Options for walking the directory.\n * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -\n * Function called for each file/directory. Return false to skip a directory.\n * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.\n * @throws {Error} If directory cannot be read.\n */\nexport async function walkDir(\n dirPath: string,\n options: {\n visitorFn: (entry: {\n path: string;\n name: string;\n isDirectory: boolean;\n stats: fs.Stats;\n }) => boolean | void | Promise<boolean | void>;\n traversalOrder?: 'pre' | 'post';\n }\n): Promise<void> {\n const traversalOrder = options.traversalOrder || 'pre';\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stats = await fsp.stat(entryPath);\n const entryInfo = {\n path: entryPath,\n name: entry.name,\n isDirectory: entry.isDirectory(),\n stats\n };\n\n if (entry.isDirectory()) {\n // Pre-order: visit directory before its contents\n if (traversalOrder === 'pre') {\n const shouldContinue = await options.visitorFn(entryInfo);\n // If the visitor returns false, don't recurse into this directory\n if (shouldContinue !== false) {\n await walkDir(entryPath, options);\n }\n } else {\n // Post-order: visit directory after its contents\n await walkDir(entryPath, options);\n await options.visitorFn(entryInfo);\n }\n } else {\n // Files are always visited when encountered\n await options.visitorFn(entryInfo);\n }\n }\n\n if (traversalOrder === 'post') {\n // Only visit the root if this is the top-level call (not for subdirectories)\n // But since this function is always called recursively, always visit after children\n const stats = await fsp.stat(dirPath);\n const entryInfo = {\n path: dirPath,\n name: path.basename(dirPath),\n isDirectory: true,\n stats\n };\n await options.visitorFn(entryInfo);\n }\n}\n"]}