@catbee/utils 0.0.1 → 0.0.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 (197) hide show
  1. package/README.md +303 -107
  2. package/build/esm/config.d.ts +12 -0
  3. package/build/esm/config.js +12 -0
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +1 -0
  6. package/build/esm/index.js +1 -0
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/types/api-response.d.ts +82 -0
  9. package/build/esm/types/api-response.js.map +1 -1
  10. package/build/esm/utils/array.utils.d.ts +64 -1
  11. package/build/esm/utils/array.utils.js +139 -2
  12. package/build/esm/utils/array.utils.js.map +1 -1
  13. package/build/esm/utils/async.utils.d.ts +60 -1
  14. package/build/esm/utils/async.utils.js +160 -2
  15. package/build/esm/utils/async.utils.js.map +1 -1
  16. package/build/esm/utils/cache.utils.d.ts +67 -4
  17. package/build/esm/utils/cache.utils.js +210 -28
  18. package/build/esm/utils/cache.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +101 -0
  20. package/build/esm/utils/context-store.utils.js +182 -0
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/crypto.utils.d.ts +110 -8
  23. package/build/esm/utils/crypto.utils.js +298 -15
  24. package/build/esm/utils/crypto.utils.js.map +1 -1
  25. package/build/esm/utils/decorators.utils.d.ts +40 -0
  26. package/build/esm/utils/decorators.utils.js +312 -0
  27. package/build/esm/utils/decorators.utils.js.map +1 -0
  28. package/build/esm/utils/dir.utils.d.ts +121 -0
  29. package/build/esm/utils/dir.utils.js +577 -0
  30. package/build/esm/utils/dir.utils.js.map +1 -1
  31. package/build/esm/utils/env.utils.d.ts +83 -0
  32. package/build/esm/utils/env.utils.js +233 -0
  33. package/build/esm/utils/env.utils.js.map +1 -1
  34. package/build/esm/utils/exception.utils.d.ts +116 -0
  35. package/build/esm/utils/exception.utils.js +322 -0
  36. package/build/esm/utils/exception.utils.js.map +1 -1
  37. package/build/esm/utils/fs.utils.d.ts +132 -0
  38. package/build/esm/utils/fs.utils.js +421 -0
  39. package/build/esm/utils/fs.utils.js.map +1 -1
  40. package/build/esm/utils/http-status-codes.d.ts +87 -178
  41. package/build/esm/utils/http-status-codes.js +92 -178
  42. package/build/esm/utils/http-status-codes.js.map +1 -1
  43. package/build/esm/utils/id.utils.d.ts +11 -10
  44. package/build/esm/utils/id.utils.js +29 -20
  45. package/build/esm/utils/id.utils.js.map +1 -1
  46. package/build/esm/utils/logger.utils.d.ts +24 -0
  47. package/build/esm/utils/logger.utils.js +54 -0
  48. package/build/esm/utils/logger.utils.js.map +1 -1
  49. package/build/esm/utils/middleware.utils.d.ts +72 -0
  50. package/build/esm/utils/middleware.utils.js +158 -0
  51. package/build/esm/utils/middleware.utils.js.map +1 -0
  52. package/build/esm/utils/obj.utils.d.ts +65 -3
  53. package/build/esm/utils/obj.utils.js +205 -6
  54. package/build/esm/utils/obj.utils.js.map +1 -1
  55. package/build/esm/utils/response.utils.d.ts +101 -0
  56. package/build/esm/utils/response.utils.js +153 -0
  57. package/build/esm/utils/response.utils.js.map +1 -1
  58. package/build/esm/utils/string.utils.d.ts +61 -5
  59. package/build/esm/utils/string.utils.js +101 -11
  60. package/build/esm/utils/string.utils.js.map +1 -1
  61. package/build/esm/utils/url.utils.d.ts +117 -0
  62. package/build/esm/utils/url.utils.js +287 -0
  63. package/build/esm/utils/url.utils.js.map +1 -1
  64. package/build/esm/utils/validate.utils.d.ts +110 -0
  65. package/build/esm/utils/validate.utils.js +186 -0
  66. package/build/esm/utils/validate.utils.js.map +1 -1
  67. package/build/esnext/config.d.ts +12 -0
  68. package/build/esnext/config.js +12 -0
  69. package/build/esnext/config.js.map +1 -1
  70. package/build/esnext/index.d.ts +1 -0
  71. package/build/esnext/index.js +1 -0
  72. package/build/esnext/index.js.map +1 -1
  73. package/build/esnext/types/api-response.d.ts +82 -0
  74. package/build/esnext/types/api-response.js.map +1 -1
  75. package/build/esnext/utils/array.utils.d.ts +64 -1
  76. package/build/esnext/utils/array.utils.js +129 -2
  77. package/build/esnext/utils/array.utils.js.map +1 -1
  78. package/build/esnext/utils/async.utils.d.ts +60 -1
  79. package/build/esnext/utils/async.utils.js +117 -1
  80. package/build/esnext/utils/async.utils.js.map +1 -1
  81. package/build/esnext/utils/cache.utils.d.ts +67 -4
  82. package/build/esnext/utils/cache.utils.js +137 -9
  83. package/build/esnext/utils/cache.utils.js.map +1 -1
  84. package/build/esnext/utils/context-store.utils.d.ts +101 -0
  85. package/build/esnext/utils/context-store.utils.js +168 -0
  86. package/build/esnext/utils/context-store.utils.js.map +1 -1
  87. package/build/esnext/utils/crypto.utils.d.ts +110 -8
  88. package/build/esnext/utils/crypto.utils.js +205 -15
  89. package/build/esnext/utils/crypto.utils.js.map +1 -1
  90. package/build/esnext/utils/decorators.utils.d.ts +40 -0
  91. package/build/esnext/utils/decorators.utils.js +155 -0
  92. package/build/esnext/utils/decorators.utils.js.map +1 -0
  93. package/build/esnext/utils/dir.utils.d.ts +121 -0
  94. package/build/esnext/utils/dir.utils.js +306 -0
  95. package/build/esnext/utils/dir.utils.js.map +1 -1
  96. package/build/esnext/utils/env.utils.d.ts +83 -0
  97. package/build/esnext/utils/env.utils.js +185 -0
  98. package/build/esnext/utils/env.utils.js.map +1 -1
  99. package/build/esnext/utils/exception.utils.d.ts +116 -0
  100. package/build/esnext/utils/exception.utils.js +213 -0
  101. package/build/esnext/utils/exception.utils.js.map +1 -1
  102. package/build/esnext/utils/fs.utils.d.ts +132 -0
  103. package/build/esnext/utils/fs.utils.js +268 -0
  104. package/build/esnext/utils/fs.utils.js.map +1 -1
  105. package/build/esnext/utils/http-status-codes.d.ts +87 -178
  106. package/build/esnext/utils/http-status-codes.js +92 -178
  107. package/build/esnext/utils/http-status-codes.js.map +1 -1
  108. package/build/esnext/utils/id.utils.d.ts +11 -10
  109. package/build/esnext/utils/id.utils.js +27 -19
  110. package/build/esnext/utils/id.utils.js.map +1 -1
  111. package/build/esnext/utils/logger.utils.d.ts +24 -0
  112. package/build/esnext/utils/logger.utils.js +42 -0
  113. package/build/esnext/utils/logger.utils.js.map +1 -1
  114. package/build/esnext/utils/middleware.utils.d.ts +72 -0
  115. package/build/esnext/utils/middleware.utils.js +157 -0
  116. package/build/esnext/utils/middleware.utils.js.map +1 -0
  117. package/build/esnext/utils/obj.utils.d.ts +65 -3
  118. package/build/esnext/utils/obj.utils.js +167 -3
  119. package/build/esnext/utils/obj.utils.js.map +1 -1
  120. package/build/esnext/utils/response.utils.d.ts +101 -0
  121. package/build/esnext/utils/response.utils.js +138 -0
  122. package/build/esnext/utils/response.utils.js.map +1 -1
  123. package/build/esnext/utils/string.utils.d.ts +61 -5
  124. package/build/esnext/utils/string.utils.js +110 -14
  125. package/build/esnext/utils/string.utils.js.map +1 -1
  126. package/build/esnext/utils/url.utils.d.ts +117 -0
  127. package/build/esnext/utils/url.utils.js +248 -0
  128. package/build/esnext/utils/url.utils.js.map +1 -1
  129. package/build/esnext/utils/validate.utils.d.ts +110 -0
  130. package/build/esnext/utils/validate.utils.js +184 -0
  131. package/build/esnext/utils/validate.utils.js.map +1 -1
  132. package/build/src/config.d.ts +12 -0
  133. package/build/src/config.js +12 -0
  134. package/build/src/config.js.map +1 -1
  135. package/build/src/index.d.ts +1 -0
  136. package/build/src/index.js +1 -0
  137. package/build/src/index.js.map +1 -1
  138. package/build/src/types/api-response.d.ts +82 -0
  139. package/build/src/types/api-response.js.map +1 -1
  140. package/build/src/utils/array.utils.d.ts +64 -1
  141. package/build/src/utils/array.utils.js +137 -4
  142. package/build/src/utils/array.utils.js.map +1 -1
  143. package/build/src/utils/async.utils.d.ts +60 -1
  144. package/build/src/utils/async.utils.js +124 -4
  145. package/build/src/utils/async.utils.js.map +1 -1
  146. package/build/src/utils/cache.utils.d.ts +67 -4
  147. package/build/src/utils/cache.utils.js +137 -9
  148. package/build/src/utils/cache.utils.js.map +1 -1
  149. package/build/src/utils/context-store.utils.d.ts +101 -0
  150. package/build/src/utils/context-store.utils.js +171 -1
  151. package/build/src/utils/context-store.utils.js.map +1 -1
  152. package/build/src/utils/crypto.utils.d.ts +110 -8
  153. package/build/src/utils/crypto.utils.js +224 -27
  154. package/build/src/utils/crypto.utils.js.map +1 -1
  155. package/build/src/utils/decorators.utils.d.ts +40 -0
  156. package/build/src/utils/decorators.utils.js +165 -0
  157. package/build/src/utils/decorators.utils.js.map +1 -0
  158. package/build/src/utils/dir.utils.d.ts +121 -0
  159. package/build/src/utils/dir.utils.js +316 -0
  160. package/build/src/utils/dir.utils.js.map +1 -1
  161. package/build/src/utils/env.utils.d.ts +83 -0
  162. package/build/src/utils/env.utils.js +186 -1
  163. package/build/src/utils/env.utils.js.map +1 -1
  164. package/build/src/utils/exception.utils.d.ts +116 -0
  165. package/build/src/utils/exception.utils.js +226 -1
  166. package/build/src/utils/exception.utils.js.map +1 -1
  167. package/build/src/utils/fs.utils.d.ts +132 -0
  168. package/build/src/utils/fs.utils.js +282 -0
  169. package/build/src/utils/fs.utils.js.map +1 -1
  170. package/build/src/utils/http-status-codes.d.ts +87 -178
  171. package/build/src/utils/http-status-codes.js +92 -178
  172. package/build/src/utils/http-status-codes.js.map +1 -1
  173. package/build/src/utils/id.utils.d.ts +11 -10
  174. package/build/src/utils/id.utils.js +27 -19
  175. package/build/src/utils/id.utils.js.map +1 -1
  176. package/build/src/utils/logger.utils.d.ts +24 -0
  177. package/build/src/utils/logger.utils.js +45 -0
  178. package/build/src/utils/logger.utils.js.map +1 -1
  179. package/build/src/utils/middleware.utils.d.ts +72 -0
  180. package/build/src/utils/middleware.utils.js +163 -0
  181. package/build/src/utils/middleware.utils.js.map +1 -0
  182. package/build/src/utils/obj.utils.d.ts +65 -3
  183. package/build/src/utils/obj.utils.js +177 -7
  184. package/build/src/utils/obj.utils.js.map +1 -1
  185. package/build/src/utils/response.utils.d.ts +101 -0
  186. package/build/src/utils/response.utils.js +146 -1
  187. package/build/src/utils/response.utils.js.map +1 -1
  188. package/build/src/utils/string.utils.d.ts +61 -5
  189. package/build/src/utils/string.utils.js +122 -20
  190. package/build/src/utils/string.utils.js.map +1 -1
  191. package/build/src/utils/url.utils.d.ts +117 -0
  192. package/build/src/utils/url.utils.js +257 -0
  193. package/build/src/utils/url.utils.js.map +1 -1
  194. package/build/src/utils/validate.utils.d.ts +110 -0
  195. package/build/src/utils/validate.utils.js +198 -0
  196. package/build/src/utils/validate.utils.js.map +1 -1
  197. package/package.json +20 -12
@@ -1,3 +1,4 @@
1
+ import fs from "fs";
1
2
  /**
2
3
  * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
3
4
  *
@@ -72,4 +73,124 @@ export declare function getDirSize(dirPath: string): Promise<number>;
72
73
  * @returns {() => void} A function to stop watching the directory.
73
74
  */
74
75
  export declare function watchDir(dirPath: string, callback: (eventType: "rename" | "change", filename: string | null) => void): () => void;
76
+ /**
77
+ * Finds files matching a glob pattern.
78
+ *
79
+ * @param {string} pattern - Glob pattern to match files.
80
+ * @param {object} [options] - Options for glob pattern matching.
81
+ * @param {string} [options.cwd] - Current working directory for relative patterns.
82
+ * @param {boolean} [options.dot=false] - Include dotfiles in matches.
83
+ * @param {boolean} [options.nodir=true] - Only match files, not directories.
84
+ * @returns {Promise<string[]>} Array of matched file paths.
85
+ * @throws {Error} If pattern matching fails.
86
+ */
87
+ export declare function findFilesByPattern(pattern: string, options?: {
88
+ cwd?: string;
89
+ dot?: boolean;
90
+ nodir?: boolean;
91
+ }): Promise<string[]>;
92
+ /**
93
+ * Gets all subdirectories in a directory.
94
+ *
95
+ * @param {string} dirPath - The directory to search in.
96
+ * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.
97
+ * @returns {Promise<string[]>} Array of absolute subdirectory paths.
98
+ * @throws {Error} If directory cannot be read.
99
+ */
100
+ export declare function getSubdirectories(dirPath: string, recursive?: boolean): Promise<string[]>;
101
+ /**
102
+ * Ensures a directory exists and is empty.
103
+ *
104
+ * @param {string} dirPath - Path to the directory.
105
+ * @returns {Promise<void>} Resolves when the directory exists and is empty.
106
+ * @throws {Error} If directory cannot be created or emptied.
107
+ */
108
+ export declare function ensureEmptyDir(dirPath: string): Promise<void>;
109
+ /**
110
+ * Creates a temporary directory with optional auto-cleanup.
111
+ *
112
+ * @param {object} [options] - Options for the temporary directory.
113
+ * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.
114
+ * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.
115
+ * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.
116
+ * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.
117
+ * @throws {Error} If directory cannot be created.
118
+ */
119
+ export declare function createTempDir(options?: {
120
+ prefix?: string;
121
+ parentDir?: string;
122
+ cleanup?: boolean;
123
+ }): Promise<{
124
+ path: string;
125
+ cleanup: () => Promise<void>;
126
+ }>;
127
+ /**
128
+ * Finds the newest file in a directory.
129
+ *
130
+ * @param {string} dirPath - Directory to search.
131
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
132
+ * @returns {Promise<string | null>} Path to the newest file or null if no files.
133
+ * @throws {Error} If directory cannot be read.
134
+ */
135
+ export declare function findNewestFile(dirPath: string, recursive?: boolean): Promise<string | null>;
136
+ /**
137
+ * Finds the oldest file in a directory.
138
+ *
139
+ * @param {string} dirPath - Directory to search.
140
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
141
+ * @returns {Promise<string | null>} Path to the oldest file or null if no files.
142
+ * @throws {Error} If directory cannot be read.
143
+ */
144
+ export declare function findOldestFile(dirPath: string, recursive?: boolean): Promise<string | null>;
145
+ /**
146
+ * Finds files or directories in a directory matching a predicate function.
147
+ *
148
+ * @param {string} dirPath - Directory to search.
149
+ * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.
150
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
151
+ * @returns {Promise<string[]>} Array of matching paths.
152
+ * @throws {Error} If directory cannot be read.
153
+ */
154
+ export declare function findInDir(dirPath: string, predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>, recursive?: boolean): Promise<string[]>;
155
+ /**
156
+ * Watches a directory recursively for file changes.
157
+ *
158
+ * @param {string} dirPath - Base directory path to watch.
159
+ * @param {(eventType: "rename" | "change", filename: string) => void} callback - Callback for each change event.
160
+ * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.
161
+ * @returns {Promise<() => void>} A function to stop watching the directory.
162
+ * @throws {Error} If directory cannot be watched.
163
+ */
164
+ export declare function watchDirRecursive(dirPath: string, callback: (eventType: "rename" | "change", filename: string) => void, includeSubdirs?: boolean): Promise<() => void>;
165
+ /**
166
+ * Gets detailed directory statistics including file count, directory count, and size.
167
+ *
168
+ * @param {string} dirPath - Path to the directory.
169
+ * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.
170
+ * @throws {Error} If directory cannot be read.
171
+ */
172
+ export declare function getDirStats(dirPath: string): Promise<{
173
+ fileCount: number;
174
+ dirCount: number;
175
+ totalSize: number;
176
+ }>;
177
+ /**
178
+ * Walks through a directory hierarchy, calling a visitor function for each entry.
179
+ *
180
+ * @param {string} dirPath - Starting directory path.
181
+ * @param {object} options - Options for walking the directory.
182
+ * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -
183
+ * Function called for each file/directory. Return false to skip a directory.
184
+ * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.
185
+ * @throws {Error} If directory cannot be read.
186
+ */
187
+ export declare function walkDir(dirPath: string, options: {
188
+ visitorFn: (entry: {
189
+ path: string;
190
+ name: string;
191
+ isDirectory: boolean;
192
+ stats: fs.Stats;
193
+ }) => boolean | void | Promise<boolean | void>;
194
+ traversalOrder?: "pre" | "post";
195
+ }): Promise<void>;
75
196
  //# sourceMappingURL=dir.utils.d.ts.map
@@ -1,6 +1,9 @@
1
+ import os from "os";
1
2
  import fs from "fs";
2
3
  import fsp from "fs/promises";
3
4
  import path from "path";
5
+ import { glob } from "glob";
6
+ import { randomBytes } from "crypto";
4
7
  /**
5
8
  * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
6
9
  *
@@ -147,4 +150,307 @@ export function watchDir(dirPath, callback) {
147
150
  });
148
151
  return () => watcher.close();
149
152
  }
153
+ /**
154
+ * Finds files matching a glob pattern.
155
+ *
156
+ * @param {string} pattern - Glob pattern to match files.
157
+ * @param {object} [options] - Options for glob pattern matching.
158
+ * @param {string} [options.cwd] - Current working directory for relative patterns.
159
+ * @param {boolean} [options.dot=false] - Include dotfiles in matches.
160
+ * @param {boolean} [options.nodir=true] - Only match files, not directories.
161
+ * @returns {Promise<string[]>} Array of matched file paths.
162
+ * @throws {Error} If pattern matching fails.
163
+ */
164
+ export async function findFilesByPattern(pattern, options = {}) {
165
+ const defaultOptions = Object.assign({ nodir: true }, options);
166
+ return glob(pattern, defaultOptions);
167
+ }
168
+ /**
169
+ * Gets all subdirectories in a directory.
170
+ *
171
+ * @param {string} dirPath - The directory to search in.
172
+ * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.
173
+ * @returns {Promise<string[]>} Array of absolute subdirectory paths.
174
+ * @throws {Error} If directory cannot be read.
175
+ */
176
+ export async function getSubdirectories(dirPath, recursive = false) {
177
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
178
+ const dirs = entries
179
+ .filter((entry) => entry.isDirectory())
180
+ .map((entry) => path.join(dirPath, entry.name));
181
+ if (recursive && dirs.length > 0) {
182
+ const nestedDirs = await Promise.all(dirs.map((dir) => getSubdirectories(dir, true)));
183
+ return [...dirs, ...nestedDirs.flat()];
184
+ }
185
+ return dirs;
186
+ }
187
+ /**
188
+ * Ensures a directory exists and is empty.
189
+ *
190
+ * @param {string} dirPath - Path to the directory.
191
+ * @returns {Promise<void>} Resolves when the directory exists and is empty.
192
+ * @throws {Error} If directory cannot be created or emptied.
193
+ */
194
+ export async function ensureEmptyDir(dirPath) {
195
+ if (await isDirectory(dirPath)) {
196
+ await emptyDir(dirPath);
197
+ }
198
+ else {
199
+ try {
200
+ await fsp.unlink(dirPath);
201
+ }
202
+ catch (error) {
203
+ // Ignore if file doesn't exist
204
+ if (error.code !== "ENOENT") {
205
+ throw error;
206
+ }
207
+ }
208
+ await ensureDir(dirPath);
209
+ }
210
+ }
211
+ /**
212
+ * Creates a temporary directory with optional auto-cleanup.
213
+ *
214
+ * @param {object} [options] - Options for the temporary directory.
215
+ * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.
216
+ * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.
217
+ * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.
218
+ * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.
219
+ * @throws {Error} If directory cannot be created.
220
+ */
221
+ export async function createTempDir(options = {}) {
222
+ const prefix = options.prefix || "tmp-";
223
+ const parentDir = options.parentDir || os.tmpdir();
224
+ const dirName = `${prefix}${randomBytes(6).toString("hex")}`;
225
+ const tempDirPath = path.join(parentDir, dirName);
226
+ await ensureDir(tempDirPath);
227
+ const cleanup = async () => {
228
+ try {
229
+ await deleteDirRecursive(tempDirPath);
230
+ }
231
+ catch (_a) {
232
+ // Ignore cleanup errors
233
+ }
234
+ };
235
+ if (options.cleanup) {
236
+ process.once("exit", () => {
237
+ try {
238
+ fs.rmSync(tempDirPath, { recursive: true, force: true });
239
+ }
240
+ catch (_a) {
241
+ // Ignore cleanup errors on exit
242
+ }
243
+ });
244
+ // Handle signals for better cleanup
245
+ ["SIGINT", "SIGTERM", "SIGUSR1", "SIGUSR2"].forEach((signal) => {
246
+ process.once(signal, () => {
247
+ cleanup().then(() => process.exit());
248
+ });
249
+ });
250
+ }
251
+ return { path: tempDirPath, cleanup };
252
+ }
253
+ /**
254
+ * Finds the newest file in a directory.
255
+ *
256
+ * @param {string} dirPath - Directory to search.
257
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
258
+ * @returns {Promise<string | null>} Path to the newest file or null if no files.
259
+ * @throws {Error} If directory cannot be read.
260
+ */
261
+ export async function findNewestFile(dirPath, recursive = false) {
262
+ const files = await listFiles(dirPath, recursive);
263
+ if (files.length === 0)
264
+ return null;
265
+ const stats = await Promise.all(files.map(async (file) => ({
266
+ path: file,
267
+ mtime: (await fsp.stat(file)).mtime,
268
+ })));
269
+ return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;
270
+ }
271
+ /**
272
+ * Finds the oldest file in a directory.
273
+ *
274
+ * @param {string} dirPath - Directory to search.
275
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
276
+ * @returns {Promise<string | null>} Path to the oldest file or null if no files.
277
+ * @throws {Error} If directory cannot be read.
278
+ */
279
+ export async function findOldestFile(dirPath, recursive = false) {
280
+ const files = await listFiles(dirPath, recursive);
281
+ if (files.length === 0)
282
+ return null;
283
+ const stats = await Promise.all(files.map(async (file) => ({
284
+ path: file,
285
+ mtime: (await fsp.stat(file)).mtime,
286
+ })));
287
+ return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;
288
+ }
289
+ /**
290
+ * Finds files or directories in a directory matching a predicate function.
291
+ *
292
+ * @param {string} dirPath - Directory to search.
293
+ * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.
294
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
295
+ * @returns {Promise<string[]>} Array of matching paths.
296
+ * @throws {Error} If directory cannot be read.
297
+ */
298
+ export async function findInDir(dirPath, predicate, recursive = false) {
299
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
300
+ const results = [];
301
+ for (const entry of entries) {
302
+ const entryPath = path.join(dirPath, entry.name);
303
+ const stat = await fsp.stat(entryPath);
304
+ if (await predicate(entryPath, stat)) {
305
+ results.push(entryPath);
306
+ }
307
+ if (recursive && entry.isDirectory()) {
308
+ const nestedResults = await findInDir(entryPath, predicate, true);
309
+ results.push(...nestedResults);
310
+ }
311
+ }
312
+ return results;
313
+ }
314
+ /**
315
+ * Watches a directory recursively for file changes.
316
+ *
317
+ * @param {string} dirPath - Base directory path to watch.
318
+ * @param {(eventType: "rename" | "change", filename: string) => void} callback - Callback for each change event.
319
+ * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.
320
+ * @returns {Promise<() => void>} A function to stop watching the directory.
321
+ * @throws {Error} If directory cannot be watched.
322
+ */
323
+ export async function watchDirRecursive(dirPath, callback, includeSubdirs = true) {
324
+ // Normalize the path to ensure consistent path separators
325
+ const normalizedBasePath = path.normalize(dirPath);
326
+ // Create watchers for the base dir and all subdirectories
327
+ const watchers = [];
328
+ // Helper function to add a watcher for a directory
329
+ const addWatcher = (dir) => {
330
+ try {
331
+ const watcher = fs.watch(dir, (eventType, filename) => {
332
+ if (!filename)
333
+ return;
334
+ const fullPath = path.join(dir, filename);
335
+ // Make the path relative to the base directory
336
+ const relativePath = path.relative(normalizedBasePath, fullPath);
337
+ callback(eventType, relativePath);
338
+ // If a new directory is created, we should watch it
339
+ if (eventType === "rename" && includeSubdirs) {
340
+ setTimeout(async () => {
341
+ try {
342
+ if (await isDirectory(fullPath)) {
343
+ addWatcher(fullPath);
344
+ }
345
+ }
346
+ catch (_a) {
347
+ // Ignore errors checking newly created items
348
+ }
349
+ }, 100);
350
+ }
351
+ });
352
+ watchers.push(watcher);
353
+ }
354
+ catch (_a) {
355
+ // Silently ignore directories we can't watch
356
+ }
357
+ };
358
+ // Add watcher for the base directory
359
+ addWatcher(normalizedBasePath);
360
+ // If watching subdirectories, add watchers for all existing subdirectories
361
+ if (includeSubdirs) {
362
+ const subdirs = await getSubdirectories(normalizedBasePath, true);
363
+ for (const subdir of subdirs) {
364
+ addWatcher(subdir);
365
+ }
366
+ }
367
+ // Return a function to close all watchers
368
+ return () => {
369
+ watchers.forEach((watcher) => watcher.close());
370
+ };
371
+ }
372
+ /**
373
+ * Gets detailed directory statistics including file count, directory count, and size.
374
+ *
375
+ * @param {string} dirPath - Path to the directory.
376
+ * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.
377
+ * @throws {Error} If directory cannot be read.
378
+ */
379
+ export async function getDirStats(dirPath) {
380
+ let fileCount = 0;
381
+ let dirCount = 0;
382
+ let totalSize = 0;
383
+ async function processDir(currentPath) {
384
+ const entries = await fsp.readdir(currentPath, { withFileTypes: true });
385
+ for (const entry of entries) {
386
+ const entryPath = path.join(currentPath, entry.name);
387
+ if (entry.isDirectory()) {
388
+ dirCount++;
389
+ await processDir(entryPath);
390
+ }
391
+ else if (entry.isFile()) {
392
+ fileCount++;
393
+ const stat = await fsp.stat(entryPath);
394
+ totalSize += stat.size;
395
+ }
396
+ }
397
+ }
398
+ await processDir(dirPath);
399
+ return { fileCount, dirCount, totalSize };
400
+ }
401
+ /**
402
+ * Walks through a directory hierarchy, calling a visitor function for each entry.
403
+ *
404
+ * @param {string} dirPath - Starting directory path.
405
+ * @param {object} options - Options for walking the directory.
406
+ * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -
407
+ * Function called for each file/directory. Return false to skip a directory.
408
+ * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.
409
+ * @throws {Error} If directory cannot be read.
410
+ */
411
+ export async function walkDir(dirPath, options) {
412
+ const traversalOrder = options.traversalOrder || "pre";
413
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true });
414
+ for (const entry of entries) {
415
+ const entryPath = path.join(dirPath, entry.name);
416
+ const stats = await fsp.stat(entryPath);
417
+ const entryInfo = {
418
+ path: entryPath,
419
+ name: entry.name,
420
+ isDirectory: entry.isDirectory(),
421
+ stats,
422
+ };
423
+ if (entry.isDirectory()) {
424
+ // Pre-order: visit directory before its contents
425
+ if (traversalOrder === "pre") {
426
+ const shouldContinue = await options.visitorFn(entryInfo);
427
+ // If the visitor returns false, don't recurse into this directory
428
+ if (shouldContinue !== false) {
429
+ await walkDir(entryPath, options);
430
+ }
431
+ }
432
+ else {
433
+ // Post-order: visit directory after its contents
434
+ await walkDir(entryPath, options);
435
+ await options.visitorFn(entryInfo);
436
+ }
437
+ }
438
+ else {
439
+ // Files are always visited when encountered
440
+ await options.visitorFn(entryInfo);
441
+ }
442
+ }
443
+ if (traversalOrder === "post") {
444
+ // Only visit the root if this is the top-level call (not for subdirectories)
445
+ // But since this function is always called recursively, always visit after children
446
+ const stats = await fsp.stat(dirPath);
447
+ const entryInfo = {
448
+ path: dirPath,
449
+ name: path.basename(dirPath),
450
+ isDirectory: true,
451
+ stats,
452
+ };
453
+ await options.visitorFn(entryInfo);
454
+ }
455
+ }
150
456
  //# sourceMappingURL=dir.utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,aAAa,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAe;IAC7C,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,OAAe,EACf,SAAS,GAAG,KAAK;IAEjB,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IACpE,MAAM,KAAK,GAAa,EAAE,CAAC;IAE3B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAEhD,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;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MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QACjD,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;YACxB,KAAK,IAAI,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;QACvC,CAAC;aAAM,CAAC;YACN,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACvC,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC;QACrB,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CACtB,OAAe,EACf,QAA2E;IAE3E,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,SAAS,EAAE,QAAQ,EAAE,EAAE;QACxD,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import fs from \"fs\";\nimport fsp from \"fs/promises\";\nimport path from \"path\";\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(\n dirPath: string,\n recursive = false,\n): 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"]}
1
+ {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA,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,CAA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D,MAAM,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,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":["import 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(\n dirPath: string,\n recursive = false,\n): 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(\n dirPath: string,\n recursive = false,\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(\n dirs.map((dir) => getSubdirectories(dir, true)),\n );\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(\n dirPath: string,\n recursive = false,\n): 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(\n dirPath: string,\n recursive = false,\n): 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"]}
@@ -18,6 +18,24 @@ export declare class Env {
18
18
  * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.
19
19
  */
20
20
  static isDev(): boolean;
21
+ /**
22
+ * Checks if the current NODE_ENV is 'production'.
23
+ *
24
+ * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.
25
+ */
26
+ static isProd(): boolean;
27
+ /**
28
+ * Checks if the current NODE_ENV is 'testing'.
29
+ *
30
+ * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.
31
+ */
32
+ static isTest(): boolean;
33
+ /**
34
+ * Checks if the current NODE_ENV is 'staging'.
35
+ *
36
+ * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.
37
+ */
38
+ static isStaging(): boolean;
21
39
  /**
22
40
  * Sets an environment variable (only affects runtime memory).
23
41
  *
@@ -113,6 +131,71 @@ export declare class Env {
113
131
  * @throws {Error} If missing or invalid.
114
132
  */
115
133
  static getEnum<T extends string>(key: string, allowedValues: T[], defaultValue?: T): T;
134
+ /**
135
+ * Retrieves a URL environment variable and validates it.
136
+ *
137
+ * @param {string} key - The environment variable key.
138
+ * @param {string} [defaultValue] - Optional fallback value.
139
+ * @param {object} [options] - Validation options.
140
+ * @param {string[]} [options.protocols] - Allowed protocols.
141
+ * @param {boolean} [options.requireTld=true] - Whether TLD is required.
142
+ * @returns {string} The validated URL.
143
+ * @throws {Error} If URL is invalid.
144
+ */
145
+ static getUrl(key: string, defaultValue?: string, options?: {
146
+ protocols?: string[];
147
+ requireTld?: boolean;
148
+ }): string;
149
+ /**
150
+ * Retrieves an email environment variable and validates it.
151
+ *
152
+ * @param {string} key - The environment variable key.
153
+ * @param {string} [defaultValue] - Optional fallback value.
154
+ * @returns {string} The validated email address.
155
+ * @throws {Error} If email is invalid.
156
+ */
157
+ static getEmail(key: string, defaultValue?: string): string;
158
+ /**
159
+ * Retrieves a path environment variable and validates it exists.
160
+ *
161
+ * @param {string} key - The environment variable key.
162
+ * @param {string} [defaultValue] - Optional fallback value.
163
+ * @param {object} [options] - Validation options.
164
+ * @param {boolean} [options.mustExist=false] - Whether path must exist.
165
+ * @param {boolean} [options.makeAbsolute=true] - Convert relative paths to absolute.
166
+ * @returns {string} The validated path.
167
+ * @throws {Error} If path is invalid.
168
+ */
169
+ static getPath(key: string, defaultValue?: string, options?: {
170
+ mustExist?: boolean;
171
+ makeAbsolute?: boolean;
172
+ }): string;
173
+ /**
174
+ * Retrieves a port environment variable and validates it.
175
+ *
176
+ * @param {string} key - The environment variable key.
177
+ * @param {number} [defaultValue=3000] - Optional fallback value.
178
+ * @returns {number} The validated port number.
179
+ * @throws {Error} If port is invalid.
180
+ */
181
+ static getPort(key: string, defaultValue?: number): number;
182
+ /**
183
+ * Retrieves a duration string and converts to milliseconds.
184
+ * Supports formats like "1d", "2h", "30m", "45s", "100ms" or combinations like "1h30m".
185
+ *
186
+ * @param {string} key - The environment variable key.
187
+ * @param {string|number} [defaultValue='0'] - Optional fallback value.
188
+ * @returns {number} The duration in milliseconds.
189
+ * @throws {Error} If duration format is invalid.
190
+ */
191
+ static getDuration(key: string, defaultValue?: string | number): number;
192
+ /**
193
+ * Gets all environment variables with sensitive values masked for safe logging.
194
+ *
195
+ * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.
196
+ * @returns {Record<string, string>} Environment variables with sensitive values masked.
197
+ */
198
+ static getSafeEnv(sensitiveKeys?: string[]): Record<string, string>;
116
199
  /**
117
200
  * Checks whether the specified environment variable exists.
118
201
  *