@catbee/utils 1.0.5 → 2.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +27 -27
  3. package/array/array.utils.d.ts +191 -0
  4. package/array/index.cjs +246 -0
  5. package/array/index.d.ts +25 -0
  6. package/array/index.mjs +228 -0
  7. package/async/async.utils.d.ts +296 -0
  8. package/async/index.cjs +428 -0
  9. package/async/index.d.ts +25 -0
  10. package/async/index.mjs +407 -0
  11. package/cache/cache.utils.d.ts +176 -0
  12. package/cache/index.cjs +292 -0
  13. package/cache/index.d.ts +25 -0
  14. package/cache/index.mjs +290 -0
  15. package/config/config.d.ts +57 -0
  16. package/config/index.cjs +136 -0
  17. package/config/index.d.ts +26 -0
  18. package/config/index.mjs +131 -0
  19. package/context-store/context-store.utils.d.ts +212 -0
  20. package/context-store/index.cjs +267 -0
  21. package/context-store/index.d.ts +25 -0
  22. package/context-store/index.mjs +261 -0
  23. package/crypto/crypto.utils.d.ts +183 -0
  24. package/crypto/index.cjs +182 -0
  25. package/crypto/index.d.ts +25 -0
  26. package/crypto/index.mjs +166 -0
  27. package/date/date.utils.d.ts +190 -0
  28. package/date/index.cjs +295 -0
  29. package/date/index.d.ts +25 -0
  30. package/date/index.mjs +283 -0
  31. package/decorators/decorators.utils.d.ts +705 -0
  32. package/decorators/index.cjs +913 -0
  33. package/decorators/index.d.ts +25 -0
  34. package/decorators/index.mjs +872 -0
  35. package/dir/dir.utils.d.ts +216 -0
  36. package/dir/index.cjs +416 -0
  37. package/dir/index.d.ts +25 -0
  38. package/dir/index.mjs +389 -0
  39. package/env/env.utils.d.ts +400 -0
  40. package/env/index.cjs +761 -0
  41. package/env/index.d.ts +25 -0
  42. package/env/index.mjs +758 -0
  43. package/exception/exception.utils.d.ts +253 -0
  44. package/exception/index.cjs +362 -0
  45. package/exception/index.d.ts +25 -0
  46. package/exception/index.mjs +338 -0
  47. package/fs/fs.utils.d.ts +196 -0
  48. package/fs/index.cjs +253 -0
  49. package/fs/index.d.ts +25 -0
  50. package/fs/index.mjs +228 -0
  51. package/http-status-codes/http-status-codes.d.ts +289 -0
  52. package/http-status-codes/index.cjs +96 -0
  53. package/http-status-codes/index.d.ts +25 -0
  54. package/http-status-codes/index.mjs +94 -0
  55. package/id/id.utils.d.ts +59 -0
  56. package/id/index.cjs +62 -0
  57. package/id/index.d.ts +25 -0
  58. package/id/index.mjs +56 -0
  59. package/index.cjs +218 -0
  60. package/index.d.ts +51 -0
  61. package/index.mjs +51 -0
  62. package/logger/index.cjs +334 -0
  63. package/logger/index.d.ts +25 -0
  64. package/logger/index.mjs +313 -0
  65. package/logger/logger.utils.d.ts +210 -0
  66. package/middleware/index.cjs +177 -0
  67. package/middleware/index.d.ts +25 -0
  68. package/middleware/index.mjs +170 -0
  69. package/middleware/middleware.utils.d.ts +123 -0
  70. package/obj/index.cjs +317 -0
  71. package/obj/index.d.ts +25 -0
  72. package/obj/index.mjs +301 -0
  73. package/obj/obj.utils.d.ts +156 -0
  74. package/package.json +172 -20
  75. package/performance/index.cjs +231 -0
  76. package/performance/index.d.ts +25 -0
  77. package/performance/index.mjs +225 -0
  78. package/performance/performance.utils.d.ts +159 -0
  79. package/request/index.cjs +202 -0
  80. package/request/index.d.ts +26 -0
  81. package/request/index.mjs +194 -0
  82. package/request/request.utils.d.ts +109 -0
  83. package/response/index.cjs +234 -0
  84. package/response/index.d.ts +26 -0
  85. package/response/index.mjs +222 -0
  86. package/response/response.utils.d.ts +186 -0
  87. package/server/index.cjs +1627 -0
  88. package/server/index.d.ts +28 -0
  89. package/server/index.mjs +1617 -0
  90. package/server/server.builder.d.ts +531 -0
  91. package/server/server.d.ts +303 -0
  92. package/stream/index.cjs +151 -0
  93. package/stream/index.d.ts +25 -0
  94. package/stream/index.mjs +144 -0
  95. package/stream/stream.utils.d.ts +111 -0
  96. package/string/index.cjs +109 -0
  97. package/string/index.d.ts +25 -0
  98. package/string/index.mjs +95 -0
  99. package/string/string.utils.d.ts +124 -0
  100. package/type/index.cjs +129 -0
  101. package/type/index.d.ts +25 -0
  102. package/type/index.mjs +119 -0
  103. package/type/type.utils.d.ts +129 -0
  104. package/types/api-response.d.ts +175 -0
  105. package/types/common.d.ts +148 -0
  106. package/types/config.d.ts +88 -0
  107. package/types/index.cjs +34 -0
  108. package/types/index.d.ts +28 -0
  109. package/types/index.mjs +32 -0
  110. package/types/server.d.ts +291 -0
  111. package/url/index.cjs +201 -0
  112. package/url/index.d.ts +25 -0
  113. package/url/index.mjs +189 -0
  114. package/url/url.utils.d.ts +164 -0
  115. package/validate/index.cjs +212 -0
  116. package/validate/index.d.ts +25 -0
  117. package/validate/index.mjs +188 -0
  118. package/validate/validate.utils.d.ts +200 -0
  119. package/build/index.cjs +0 -7579
  120. package/build/index.d.ts +0 -5774
  121. package/build/index.mjs +0 -7274
@@ -0,0 +1,216 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/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
+
25
+ import fs from 'fs';
26
+ /**
27
+ * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
28
+ *
29
+ * @param {string} dirPath - The directory path to ensure.
30
+ * @returns {Promise<void>} Resolves when the directory exists.
31
+ * @throws {Error} If directory cannot be created.
32
+ */
33
+ export declare function ensureDir(dirPath: string): Promise<void>;
34
+ /**
35
+ * Recursively lists all files in a directory.
36
+ *
37
+ * @param {string} dirPath - The base directory.
38
+ * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
39
+ * @returns {Promise<string[]>} Array of absolute file paths.
40
+ * @throws {Error} If the directory cannot be read.
41
+ */
42
+ export declare function listFiles(dirPath: string, recursive?: boolean): Promise<string[]>;
43
+ /**
44
+ * Deletes a directory and all its contents recursively (like `rm -rf`).
45
+ *
46
+ * @param {string} dirPath - Directory to delete.
47
+ * @returns {Promise<void>} Resolves when deletion is complete.
48
+ * @throws {Error} If deletion fails.
49
+ */
50
+ export declare function deleteDirRecursive(dirPath: string): Promise<void>;
51
+ /**
52
+ * Checks whether a given path is a directory.
53
+ *
54
+ * @param {string} pathStr - Path to check.
55
+ * @returns {Promise<boolean>} True if the path is a directory, else false.
56
+ */
57
+ export declare function isDirectory(pathStr: string): Promise<boolean>;
58
+ /**
59
+ * Recursively copies a directory and all its contents to a destination.
60
+ *
61
+ * @param {string} src - Source directory path.
62
+ * @param {string} dest - Destination directory path.
63
+ * @returns {Promise<void>} Resolves when copy is complete.
64
+ * @throws {Error} If source does not exist or copy fails.
65
+ */
66
+ export declare function copyDir(src: string, dest: string): Promise<void>;
67
+ /**
68
+ * Moves a directory to a new location by copying and deleting the original.
69
+ *
70
+ * @param {string} src - Source directory path.
71
+ * @param {string} dest - Destination directory path.
72
+ * @returns {Promise<void>} Resolves when move is complete.
73
+ * @throws {Error} If copy or deletion fails.
74
+ */
75
+ export declare function moveDir(src: string, dest: string): Promise<void>;
76
+ /**
77
+ * Empties a directory by deleting all files and subdirectories inside it.
78
+ *
79
+ * @param {string} dirPath - Path to the directory to empty.
80
+ * @returns {Promise<void>} Resolves when the directory has been emptied.
81
+ * @throws {Error} If files or subdirectories cannot be removed.
82
+ */
83
+ export declare function emptyDir(dirPath: string): Promise<void>;
84
+ /**
85
+ * Calculates the total size (in bytes) of all files in a directory (recursive).
86
+ *
87
+ * @param {string} dirPath - Path to the directory.
88
+ * @returns {Promise<number>} Total size in bytes.
89
+ * @throws {Error} If any file stats cannot be read.
90
+ */
91
+ export declare function getDirSize(dirPath: string): Promise<number>;
92
+ /**
93
+ * Watches a directory for file changes and calls a callback on each event.
94
+ *
95
+ * @param {string} dirPath - Directory path to watch.
96
+ * @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
97
+ * @returns {() => void} A function to stop watching the directory.
98
+ */
99
+ export declare function watchDir(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string | null) => void): () => void;
100
+ /**
101
+ * Recursively finds files matching a simple pattern (supports '*' and '?').
102
+ *
103
+ * @param {string} pattern - Simple pattern to match files (e.g., '*.ts', 'src/*.js').
104
+ * @param {object} [options] - Options for matching files.
105
+ * @param {string} [options.cwd=process.cwd()] - Base directory to start searching from.
106
+ * @param {boolean} [options.dot=false] - Include dotfiles in matches.
107
+ * @returns {Promise<string[]>} Array of matched file paths.
108
+ */
109
+ export declare function findFilesByPattern(pattern: string, options?: {
110
+ cwd?: string;
111
+ dot?: boolean;
112
+ }): Promise<string[]>;
113
+ /**
114
+ * Gets all subdirectories in a directory.
115
+ *
116
+ * @param {string} dirPath - The directory to search in.
117
+ * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.
118
+ * @returns {Promise<string[]>} Array of absolute subdirectory paths.
119
+ * @throws {Error} If directory cannot be read.
120
+ */
121
+ export declare function getSubdirectories(dirPath: string, recursive?: boolean): Promise<string[]>;
122
+ /**
123
+ * Ensures a directory exists and is empty.
124
+ *
125
+ * @param {string} dirPath - Path to the directory.
126
+ * @returns {Promise<void>} Resolves when the directory exists and is empty.
127
+ * @throws {Error} If directory cannot be created or emptied.
128
+ */
129
+ export declare function ensureEmptyDir(dirPath: string): Promise<void>;
130
+ /**
131
+ * Creates a temporary directory with optional auto-cleanup.
132
+ *
133
+ * @param {object} [options] - Options for the temporary directory.
134
+ * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.
135
+ * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.
136
+ * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.
137
+ * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.
138
+ * @throws {Error} If directory cannot be created.
139
+ */
140
+ export declare function createTempDir(options?: {
141
+ prefix?: string;
142
+ parentDir?: string;
143
+ cleanup?: boolean;
144
+ }): Promise<{
145
+ path: string;
146
+ cleanup: () => Promise<void>;
147
+ }>;
148
+ /**
149
+ * Finds the newest file in a directory.
150
+ *
151
+ * @param {string} dirPath - Directory to search.
152
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
153
+ * @returns {Promise<string | null>} Path to the newest file or null if no files.
154
+ * @throws {Error} If directory cannot be read.
155
+ */
156
+ export declare function findNewestFile(dirPath: string, recursive?: boolean): Promise<string | null>;
157
+ /**
158
+ * Finds the oldest file in a directory.
159
+ *
160
+ * @param {string} dirPath - Directory to search.
161
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
162
+ * @returns {Promise<string | null>} Path to the oldest file or null if no files.
163
+ * @throws {Error} If directory cannot be read.
164
+ */
165
+ export declare function findOldestFile(dirPath: string, recursive?: boolean): Promise<string | null>;
166
+ /**
167
+ * Finds files or directories in a directory matching a predicate function.
168
+ *
169
+ * @param {string} dirPath - Directory to search.
170
+ * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.
171
+ * @param {boolean} [recursive=false] - Whether to search subdirectories.
172
+ * @returns {Promise<string[]>} Array of matching paths.
173
+ * @throws {Error} If directory cannot be read.
174
+ */
175
+ export declare function findInDir(dirPath: string, predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>, recursive?: boolean): Promise<string[]>;
176
+ /**
177
+ * Watches a directory recursively for file changes.
178
+ *
179
+ * @param {string} dirPath - Base directory path to watch.
180
+ * @param {(eventType: "rename" | "change", filename: string) => void} callback - Callback for each change event.
181
+ * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.
182
+ * @returns {Promise<() => void>} A function to stop watching the directory.
183
+ * @throws {Error} If directory cannot be watched.
184
+ */
185
+ export declare function watchDirRecursive(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string) => void, includeSubdirs?: boolean): Promise<() => void>;
186
+ /**
187
+ * Gets detailed directory statistics including file count, directory count, and size.
188
+ *
189
+ * @param {string} dirPath - Path to the directory.
190
+ * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.
191
+ * @throws {Error} If directory cannot be read.
192
+ */
193
+ export declare function getDirStats(dirPath: string): Promise<{
194
+ fileCount: number;
195
+ dirCount: number;
196
+ totalSize: number;
197
+ }>;
198
+ /**
199
+ * Walks through a directory hierarchy, calling a visitor function for each entry.
200
+ *
201
+ * @param {string} dirPath - Starting directory path.
202
+ * @param {object} options - Options for walking the directory.
203
+ * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -
204
+ * Function called for each file/directory. Return false to skip a directory.
205
+ * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.
206
+ * @throws {Error} If directory cannot be read.
207
+ */
208
+ export declare function walkDir(dirPath: string, options: {
209
+ visitorFn: (entry: {
210
+ path: string;
211
+ name: string;
212
+ isDirectory: boolean;
213
+ stats: fs.Stats;
214
+ }) => boolean | void | Promise<boolean | void>;
215
+ traversalOrder?: 'pre' | 'post';
216
+ }): Promise<void>;
package/dir/index.cjs ADDED
@@ -0,0 +1,416 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/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
+
25
+ 'use strict';
26
+
27
+ var os = require('os');
28
+ var fs = require('fs');
29
+ var fsp = require('fs/promises');
30
+ var path = require('path');
31
+ var crypto = require('crypto');
32
+
33
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
34
+
35
+ var os__default = /*#__PURE__*/_interopDefault(os);
36
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
37
+ var fsp__default = /*#__PURE__*/_interopDefault(fsp);
38
+ var path__default = /*#__PURE__*/_interopDefault(path);
39
+
40
+ var __defProp = Object.defineProperty;
41
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
42
+ async function ensureDir(dirPath) {
43
+ await fsp__default.default.mkdir(dirPath, {
44
+ recursive: true
45
+ });
46
+ }
47
+ __name(ensureDir, "ensureDir");
48
+ async function listFiles(dirPath, recursive = false) {
49
+ const entries = await fsp__default.default.readdir(dirPath, {
50
+ withFileTypes: true
51
+ });
52
+ const files = [];
53
+ for (const entry of entries) {
54
+ const fullPath = path__default.default.join(dirPath, entry.name);
55
+ if (entry.isFile()) {
56
+ files.push(fullPath);
57
+ } else if (recursive && entry.isDirectory()) {
58
+ const nestedFiles = await listFiles(fullPath, true);
59
+ files.push(...nestedFiles);
60
+ }
61
+ }
62
+ return files;
63
+ }
64
+ __name(listFiles, "listFiles");
65
+ async function deleteDirRecursive(dirPath) {
66
+ await fsp__default.default.rm(dirPath, {
67
+ recursive: true,
68
+ force: true
69
+ });
70
+ }
71
+ __name(deleteDirRecursive, "deleteDirRecursive");
72
+ async function isDirectory(pathStr) {
73
+ try {
74
+ const stat = await fsp__default.default.stat(pathStr);
75
+ return stat.isDirectory();
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+ __name(isDirectory, "isDirectory");
81
+ async function copyDir(src, dest) {
82
+ await ensureDir(dest);
83
+ const entries = await fsp__default.default.readdir(src, {
84
+ withFileTypes: true
85
+ });
86
+ for (const entry of entries) {
87
+ const srcPath = path__default.default.join(src, entry.name);
88
+ const destPath = path__default.default.join(dest, entry.name);
89
+ if (entry.isDirectory()) {
90
+ await copyDir(srcPath, destPath);
91
+ } else {
92
+ await fsp__default.default.copyFile(srcPath, destPath);
93
+ }
94
+ }
95
+ }
96
+ __name(copyDir, "copyDir");
97
+ async function moveDir(src, dest) {
98
+ await copyDir(src, dest);
99
+ await deleteDirRecursive(src);
100
+ }
101
+ __name(moveDir, "moveDir");
102
+ async function emptyDir(dirPath) {
103
+ const entries = await fsp__default.default.readdir(dirPath, {
104
+ withFileTypes: true
105
+ });
106
+ for (const entry of entries) {
107
+ const entryPath = path__default.default.join(dirPath, entry.name);
108
+ if (entry.isDirectory()) {
109
+ await fsp__default.default.rm(entryPath, {
110
+ recursive: true,
111
+ force: true
112
+ });
113
+ } else {
114
+ await fsp__default.default.unlink(entryPath);
115
+ }
116
+ }
117
+ }
118
+ __name(emptyDir, "emptyDir");
119
+ async function getDirSize(dirPath) {
120
+ let total = 0;
121
+ const entries = await fsp__default.default.readdir(dirPath, {
122
+ withFileTypes: true
123
+ });
124
+ for (const entry of entries) {
125
+ const entryPath = path__default.default.join(dirPath, entry.name);
126
+ if (entry.isDirectory()) {
127
+ total += await getDirSize(entryPath);
128
+ } else {
129
+ const stat = await fsp__default.default.stat(entryPath);
130
+ total += stat.size;
131
+ }
132
+ }
133
+ return total;
134
+ }
135
+ __name(getDirSize, "getDirSize");
136
+ function watchDir(dirPath, callback) {
137
+ const watcher = fs__default.default.watch(dirPath, (eventType, filename) => {
138
+ callback(eventType, filename);
139
+ });
140
+ return () => watcher.close();
141
+ }
142
+ __name(watchDir, "watchDir");
143
+ async function findFilesByPattern(pattern, options = {}) {
144
+ const matchPattern = /* @__PURE__ */ __name((name, pattern2) => {
145
+ let escaped = pattern2.replaceAll(/[.+^${}()|[\]\\]/g, "\\$&");
146
+ escaped = escaped.replaceAll("*", ".*").replaceAll("?", ".");
147
+ const regex = new RegExp(`^${escaped}$`);
148
+ return regex.test(name);
149
+ }, "matchPattern");
150
+ const { cwd = process.cwd(), dot = false } = options;
151
+ const segments = pattern.split("/");
152
+ async function walk(dir, segIndex) {
153
+ if (segIndex >= segments.length) return [];
154
+ const segment = segments[segIndex];
155
+ const entries = await fs__default.default.promises.readdir(dir, {
156
+ withFileTypes: true
157
+ });
158
+ let matchedFiles = [];
159
+ for (const entry of entries) {
160
+ const entryName = entry.name;
161
+ if (!dot && entryName.startsWith(".")) continue;
162
+ const fullPath = path__default.default.join(dir, entryName);
163
+ const isLastSegment = segIndex === segments.length - 1;
164
+ if (isLastSegment) {
165
+ if (matchPattern(entryName, segment) && entry.isFile()) {
166
+ matchedFiles.push(fullPath);
167
+ }
168
+ } else if (entry.isDirectory()) {
169
+ if (matchPattern(entryName, segment)) {
170
+ matchedFiles.push(...await walk(fullPath, segIndex + 1));
171
+ }
172
+ }
173
+ }
174
+ return matchedFiles;
175
+ }
176
+ __name(walk, "walk");
177
+ return walk(cwd, 0);
178
+ }
179
+ __name(findFilesByPattern, "findFilesByPattern");
180
+ async function getSubdirectories(dirPath, recursive = false) {
181
+ const entries = await fsp__default.default.readdir(dirPath, {
182
+ withFileTypes: true
183
+ });
184
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => path__default.default.join(dirPath, entry.name));
185
+ if (recursive && dirs.length > 0) {
186
+ const nestedDirs = await Promise.all(dirs.map((dir) => getSubdirectories(dir, true)));
187
+ return [
188
+ ...dirs,
189
+ ...nestedDirs.flat()
190
+ ];
191
+ }
192
+ return dirs;
193
+ }
194
+ __name(getSubdirectories, "getSubdirectories");
195
+ async function ensureEmptyDir(dirPath) {
196
+ if (await isDirectory(dirPath)) {
197
+ await emptyDir(dirPath);
198
+ } else {
199
+ try {
200
+ await fsp__default.default.unlink(dirPath);
201
+ } catch (error) {
202
+ if (error.code !== "ENOENT") {
203
+ throw error;
204
+ }
205
+ }
206
+ await ensureDir(dirPath);
207
+ }
208
+ }
209
+ __name(ensureEmptyDir, "ensureEmptyDir");
210
+ async function createTempDir(options = {}) {
211
+ const prefix = options.prefix || "tmp-";
212
+ const parentDir = options.parentDir || os__default.default.tmpdir();
213
+ const dirName = `${prefix}${crypto.randomBytes(6).toString("hex")}`;
214
+ const tempDirPath = path__default.default.join(parentDir, dirName);
215
+ await ensureDir(tempDirPath);
216
+ const cleanup = /* @__PURE__ */ __name(async () => {
217
+ try {
218
+ await deleteDirRecursive(tempDirPath);
219
+ } catch {
220
+ }
221
+ }, "cleanup");
222
+ if (options.cleanup) {
223
+ process.once("exit", () => {
224
+ try {
225
+ fs__default.default.rmSync(tempDirPath, {
226
+ recursive: true,
227
+ force: true
228
+ });
229
+ } catch {
230
+ }
231
+ });
232
+ const signals = [
233
+ "SIGINT",
234
+ "SIGTERM",
235
+ "SIGUSR1",
236
+ "SIGUSR2"
237
+ ];
238
+ for (const signal of signals) {
239
+ process.once(signal, () => {
240
+ cleanup().then(() => process.exit());
241
+ });
242
+ }
243
+ }
244
+ return {
245
+ path: tempDirPath,
246
+ cleanup
247
+ };
248
+ }
249
+ __name(createTempDir, "createTempDir");
250
+ async function findNewestFile(dirPath, recursive = false) {
251
+ const files = await listFiles(dirPath, recursive);
252
+ if (files.length === 0) return null;
253
+ const stats = await Promise.all(files.map(async (file) => ({
254
+ path: file,
255
+ mtime: (await fsp__default.default.stat(file)).mtime
256
+ })));
257
+ return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;
258
+ }
259
+ __name(findNewestFile, "findNewestFile");
260
+ async function findOldestFile(dirPath, recursive = false) {
261
+ const files = await listFiles(dirPath, recursive);
262
+ if (files.length === 0) return null;
263
+ const stats = await Promise.all(files.map(async (file) => ({
264
+ path: file,
265
+ mtime: (await fsp__default.default.stat(file)).mtime
266
+ })));
267
+ return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;
268
+ }
269
+ __name(findOldestFile, "findOldestFile");
270
+ async function findInDir(dirPath, predicate, recursive = false) {
271
+ const entries = await fsp__default.default.readdir(dirPath, {
272
+ withFileTypes: true
273
+ });
274
+ const results = [];
275
+ for (const entry of entries) {
276
+ const entryPath = path__default.default.join(dirPath, entry.name);
277
+ const stat = await fsp__default.default.stat(entryPath);
278
+ if (await predicate(entryPath, stat)) {
279
+ results.push(entryPath);
280
+ }
281
+ if (recursive && entry.isDirectory()) {
282
+ const nestedResults = await findInDir(entryPath, predicate, true);
283
+ results.push(...nestedResults);
284
+ }
285
+ }
286
+ return results;
287
+ }
288
+ __name(findInDir, "findInDir");
289
+ async function watchDirRecursive(dirPath, callback, includeSubdirs = true) {
290
+ const normalizedBasePath = path__default.default.normalize(dirPath);
291
+ const watchers = [];
292
+ const addWatcher = /* @__PURE__ */ __name((dir) => {
293
+ try {
294
+ const watcher = fs__default.default.watch(dir, (eventType, filename) => {
295
+ if (!filename) return;
296
+ const fullPath = path__default.default.join(dir, filename);
297
+ const relativePath = path__default.default.relative(normalizedBasePath, fullPath);
298
+ callback(eventType, relativePath);
299
+ if (eventType === "rename" && includeSubdirs) {
300
+ setTimeout(async () => {
301
+ try {
302
+ if (await isDirectory(fullPath)) {
303
+ addWatcher(fullPath);
304
+ }
305
+ } catch {
306
+ }
307
+ }, 100);
308
+ }
309
+ });
310
+ watchers.push(watcher);
311
+ } catch {
312
+ }
313
+ }, "addWatcher");
314
+ addWatcher(normalizedBasePath);
315
+ if (includeSubdirs) {
316
+ const subdirs = await getSubdirectories(normalizedBasePath, true);
317
+ for (const subdir of subdirs) {
318
+ addWatcher(subdir);
319
+ }
320
+ }
321
+ return () => {
322
+ for (const watcher of watchers) {
323
+ watcher.close();
324
+ }
325
+ };
326
+ }
327
+ __name(watchDirRecursive, "watchDirRecursive");
328
+ async function getDirStats(dirPath) {
329
+ let fileCount = 0;
330
+ let dirCount = 0;
331
+ let totalSize = 0;
332
+ async function processDir(currentPath) {
333
+ const entries = await fsp__default.default.readdir(currentPath, {
334
+ withFileTypes: true
335
+ });
336
+ for (const entry of entries) {
337
+ const entryPath = path__default.default.join(currentPath, entry.name);
338
+ if (entry.isDirectory()) {
339
+ dirCount++;
340
+ await processDir(entryPath);
341
+ } else if (entry.isFile()) {
342
+ fileCount++;
343
+ const stat = await fsp__default.default.stat(entryPath);
344
+ totalSize += stat.size;
345
+ }
346
+ }
347
+ }
348
+ __name(processDir, "processDir");
349
+ await processDir(dirPath);
350
+ return {
351
+ fileCount,
352
+ dirCount,
353
+ totalSize
354
+ };
355
+ }
356
+ __name(getDirStats, "getDirStats");
357
+ async function walkDir(dirPath, options) {
358
+ const traversalOrder = options.traversalOrder || "pre";
359
+ const entries = await fsp__default.default.readdir(dirPath, {
360
+ withFileTypes: true
361
+ });
362
+ for (const entry of entries) {
363
+ const entryPath = path__default.default.join(dirPath, entry.name);
364
+ const stats = await fsp__default.default.stat(entryPath);
365
+ const entryInfo = {
366
+ path: entryPath,
367
+ name: entry.name,
368
+ isDirectory: entry.isDirectory(),
369
+ stats
370
+ };
371
+ if (entry.isDirectory()) {
372
+ if (traversalOrder === "pre") {
373
+ const shouldContinue = await options.visitorFn(entryInfo);
374
+ if (shouldContinue !== false) {
375
+ await walkDir(entryPath, options);
376
+ }
377
+ } else {
378
+ await walkDir(entryPath, options);
379
+ await options.visitorFn(entryInfo);
380
+ }
381
+ } else {
382
+ await options.visitorFn(entryInfo);
383
+ }
384
+ }
385
+ if (traversalOrder === "post") {
386
+ const stats = await fsp__default.default.stat(dirPath);
387
+ const entryInfo = {
388
+ path: dirPath,
389
+ name: path__default.default.basename(dirPath),
390
+ isDirectory: true,
391
+ stats
392
+ };
393
+ await options.visitorFn(entryInfo);
394
+ }
395
+ }
396
+ __name(walkDir, "walkDir");
397
+
398
+ exports.copyDir = copyDir;
399
+ exports.createTempDir = createTempDir;
400
+ exports.deleteDirRecursive = deleteDirRecursive;
401
+ exports.emptyDir = emptyDir;
402
+ exports.ensureDir = ensureDir;
403
+ exports.ensureEmptyDir = ensureEmptyDir;
404
+ exports.findFilesByPattern = findFilesByPattern;
405
+ exports.findInDir = findInDir;
406
+ exports.findNewestFile = findNewestFile;
407
+ exports.findOldestFile = findOldestFile;
408
+ exports.getDirSize = getDirSize;
409
+ exports.getDirStats = getDirStats;
410
+ exports.getSubdirectories = getSubdirectories;
411
+ exports.isDirectory = isDirectory;
412
+ exports.listFiles = listFiles;
413
+ exports.moveDir = moveDir;
414
+ exports.walkDir = walkDir;
415
+ exports.watchDir = watchDir;
416
+ exports.watchDirRecursive = watchDirRecursive;
package/dir/index.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/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
+
25
+ export * from './dir.utils';