@catbee/utils 0.0.2 → 0.0.3
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.
- package/build/esm/config.d.ts +1 -1
- package/build/esm/config.js +7 -7
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +20 -19
- package/build/esm/index.js +20 -19
- package/build/esm/index.js.map +1 -1
- package/build/esm/types/api-response.d.ts +2 -2
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/utils/array.utils.d.ts +1 -1
- package/build/esm/utils/array.utils.js +17 -27
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +1 -5
- package/build/esm/utils/async.utils.js +17 -20
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +2 -2
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +8 -8
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.d.ts +2 -2
- package/build/esm/utils/crypto.utils.js +37 -45
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +7 -7
- package/build/esm/utils/decorators.utils.js +31 -31
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.d.ts +4 -4
- package/build/esm/utils/dir.utils.js +18 -20
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.js +22 -26
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.d.ts +1 -1
- package/build/esm/utils/exception.utils.js +26 -29
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.d.ts +3 -3
- package/build/esm/utils/fs.utils.js +19 -23
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +8 -8
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +13 -4
- package/build/esm/utils/logger.utils.js +15 -15
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +5 -4
- package/build/esm/utils/middleware.utils.js +19 -19
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.js +16 -27
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +2 -2
- package/build/esm/utils/response.utils.js +11 -11
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +17 -17
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +20 -22
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.js +11 -15
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +1 -1
- package/build/esnext/config.js +7 -7
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +20 -19
- package/build/esnext/index.js +20 -19
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/types/api-response.d.ts +2 -2
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/utils/array.utils.d.ts +1 -1
- package/build/esnext/utils/array.utils.js +23 -31
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +1 -5
- package/build/esnext/utils/async.utils.js +22 -22
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +3 -3
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +10 -10
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.d.ts +2 -2
- package/build/esnext/utils/crypto.utils.js +37 -47
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +7 -7
- package/build/esnext/utils/decorators.utils.js +33 -33
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.d.ts +4 -4
- package/build/esnext/utils/dir.utils.js +22 -24
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.js +24 -26
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.d.ts +1 -1
- package/build/esnext/utils/exception.utils.js +26 -29
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.d.ts +3 -3
- package/build/esnext/utils/fs.utils.js +21 -25
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +8 -8
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +13 -4
- package/build/esnext/utils/logger.utils.js +15 -15
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +5 -4
- package/build/esnext/utils/middleware.utils.js +19 -19
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.js +17 -26
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +2 -2
- package/build/esnext/utils/response.utils.js +11 -11
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +17 -17
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +21 -23
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.js +14 -16
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +1 -1
- package/build/src/config.js +6 -6
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +20 -19
- package/build/src/index.js +1 -0
- package/build/src/index.js.map +1 -1
- package/build/src/types/api-response.d.ts +2 -2
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/utils/array.utils.d.ts +1 -1
- package/build/src/utils/array.utils.js +22 -30
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +1 -5
- package/build/src/utils/async.utils.js +22 -22
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +2 -2
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +9 -9
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.d.ts +2 -2
- package/build/src/utils/crypto.utils.js +35 -45
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +7 -7
- package/build/src/utils/decorators.utils.js +32 -32
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.d.ts +4 -4
- package/build/src/utils/dir.utils.js +16 -18
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.js +22 -24
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.d.ts +1 -1
- package/build/src/utils/exception.utils.js +23 -26
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.d.ts +3 -3
- package/build/src/utils/fs.utils.js +15 -19
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +7 -7
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +13 -4
- package/build/src/utils/logger.utils.js +12 -12
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +5 -4
- package/build/src/utils/middleware.utils.js +12 -12
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.js +17 -26
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +2 -2
- package/build/src/utils/response.utils.js +9 -9
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +17 -17
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +20 -22
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.js +14 -16
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +1 -1
|
@@ -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,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;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;YACnB,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACvB,CAAC;aAAM,IAAI,SAAS,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC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\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"]}
|
|
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,MA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,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;gBAC1D,kEAAkE;gBAClE,IAAI,cAAc,KAAK,KAAK,EAAE,CAAC;oBAC7B,MAAM,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;gBACpC,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,iDAAiD;gBACjD,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(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"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/* eslint-disable n/no-process-env */
|
|
2
|
-
import { existsSync } from
|
|
3
|
-
import { isAbsolute, resolve } from
|
|
2
|
+
import { existsSync } from 'fs';
|
|
3
|
+
import { isAbsolute, resolve } from 'path';
|
|
4
4
|
/**
|
|
5
5
|
* Enum representing valid application environments.
|
|
6
6
|
*/
|
|
@@ -22,7 +22,7 @@ export class Env {
|
|
|
22
22
|
* @returns {boolean} `true` if NODE_ENV is 'development', else `false`.
|
|
23
23
|
*/
|
|
24
24
|
static isDev() {
|
|
25
|
-
return
|
|
25
|
+
return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.DEVELOPMENT;
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
28
|
* Checks if the current NODE_ENV is 'production'.
|
|
@@ -30,7 +30,7 @@ export class Env {
|
|
|
30
30
|
* @returns {boolean} `true` if NODE_ENV is 'production', else `false`.
|
|
31
31
|
*/
|
|
32
32
|
static isProd() {
|
|
33
|
-
return Env.get(
|
|
33
|
+
return Env.get('NODE_ENV') === Environment.PRODUCTION;
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
36
|
* Checks if the current NODE_ENV is 'testing'.
|
|
@@ -38,7 +38,7 @@ export class Env {
|
|
|
38
38
|
* @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.
|
|
39
39
|
*/
|
|
40
40
|
static isTest() {
|
|
41
|
-
return Env.get(
|
|
41
|
+
return Env.get('NODE_ENV') === Environment.TESTING;
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
44
44
|
* Checks if the current NODE_ENV is 'staging'.
|
|
@@ -46,7 +46,7 @@ export class Env {
|
|
|
46
46
|
* @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.
|
|
47
47
|
*/
|
|
48
48
|
static isStaging() {
|
|
49
|
-
return Env.get(
|
|
49
|
+
return Env.get('NODE_ENV') === Environment.STAGING;
|
|
50
50
|
}
|
|
51
51
|
/**
|
|
52
52
|
* Sets an environment variable (only affects runtime memory).
|
|
@@ -137,9 +137,9 @@ export class Env {
|
|
|
137
137
|
static getBoolean(key, defaultValue = false) {
|
|
138
138
|
var _a;
|
|
139
139
|
const value = ((_a = process.env[key]) !== null && _a !== void 0 ? _a : defaultValue).toString().toLowerCase();
|
|
140
|
-
if ([
|
|
140
|
+
if (['true', '1', 'yes', 'on'].includes(value))
|
|
141
141
|
return true;
|
|
142
|
-
if ([
|
|
142
|
+
if (['false', '0', 'no', 'off'].includes(value))
|
|
143
143
|
return false;
|
|
144
144
|
throw new Error(`Env variable ${key} is not a boolean`);
|
|
145
145
|
}
|
|
@@ -187,15 +187,15 @@ export class Env {
|
|
|
187
187
|
* @param {string} [splitter=','] - Delimiter to split on.
|
|
188
188
|
* @returns {string[] | T[]} An array of strings.
|
|
189
189
|
*/
|
|
190
|
-
static getArray(key, defaultValue = [], splitter =
|
|
190
|
+
static getArray(key, defaultValue = [], splitter = ',') {
|
|
191
191
|
const value = process.env[key];
|
|
192
|
-
if (!value || value.trim() ===
|
|
192
|
+
if (!value || value.trim() === '') {
|
|
193
193
|
return defaultValue;
|
|
194
194
|
}
|
|
195
195
|
return value
|
|
196
196
|
.split(splitter)
|
|
197
|
-
.map(
|
|
198
|
-
.filter(
|
|
197
|
+
.map(item => item.trim())
|
|
198
|
+
.filter(item => item.length > 0);
|
|
199
199
|
}
|
|
200
200
|
/**
|
|
201
201
|
* Retrieves an enum-like environment variable value, validating against allowed values.
|
|
@@ -211,7 +211,7 @@ export class Env {
|
|
|
211
211
|
var _a;
|
|
212
212
|
const value = (_a = process.env[key]) !== null && _a !== void 0 ? _a : defaultValue;
|
|
213
213
|
if (!value || !allowedValues.includes(value)) {
|
|
214
|
-
throw new Error(`Env ${key} must be one of ${allowedValues.join(
|
|
214
|
+
throw new Error(`Env ${key} must be one of ${allowedValues.join(', ')}. Received: ${value}`);
|
|
215
215
|
}
|
|
216
216
|
return value;
|
|
217
217
|
}
|
|
@@ -239,19 +239,19 @@ export class Env {
|
|
|
239
239
|
throw new Error(`Env ${key} is not a valid URL`);
|
|
240
240
|
}
|
|
241
241
|
if (options.protocols && options.protocols.length > 0) {
|
|
242
|
-
const protocol = url.protocol.replace(
|
|
242
|
+
const protocol = url.protocol.replace(':', '');
|
|
243
243
|
if (!options.protocols.includes(protocol)) {
|
|
244
|
-
throw new Error(`Env ${key} must use one of the protocols: ${options.protocols.join(
|
|
244
|
+
throw new Error(`Env ${key} must use one of the protocols: ${options.protocols.join(', ')}`);
|
|
245
245
|
}
|
|
246
246
|
}
|
|
247
247
|
if (options.requireTld === true) {
|
|
248
248
|
// Check if hostname has a TLD (contains at least one dot and doesn't end with a dot)
|
|
249
249
|
// localhost, 127.0.0.1, etc. don't have TLDs
|
|
250
250
|
const hostname = url.hostname;
|
|
251
|
-
if (!hostname.includes(
|
|
252
|
-
hostname ===
|
|
251
|
+
if (!hostname.includes('.') ||
|
|
252
|
+
hostname === 'localhost' ||
|
|
253
253
|
/^[\d.]+$/.test(hostname) || // IP address
|
|
254
|
-
hostname.endsWith(
|
|
254
|
+
hostname.endsWith('.')) {
|
|
255
255
|
throw new Error(`Env ${key} must have a valid host with TLD`);
|
|
256
256
|
}
|
|
257
257
|
}
|
|
@@ -299,9 +299,7 @@ export class Env {
|
|
|
299
299
|
}
|
|
300
300
|
return defaultValue;
|
|
301
301
|
}
|
|
302
|
-
const path = options.makeAbsolute !== false && !isAbsolute(value)
|
|
303
|
-
? resolve(process.cwd(), value)
|
|
304
|
-
: value;
|
|
302
|
+
const path = options.makeAbsolute !== false && !isAbsolute(value) ? resolve(process.cwd(), value) : value;
|
|
305
303
|
if (options.mustExist && !existsSync(path)) {
|
|
306
304
|
throw new Error(`Path in env ${key} does not exist: ${path}`);
|
|
307
305
|
}
|
|
@@ -331,7 +329,7 @@ export class Env {
|
|
|
331
329
|
* @returns {number} The duration in milliseconds.
|
|
332
330
|
* @throws {Error} If duration format is invalid.
|
|
333
331
|
*/
|
|
334
|
-
static getDuration(key, defaultValue =
|
|
332
|
+
static getDuration(key, defaultValue = '0') {
|
|
335
333
|
const value = Env.get(key, String(defaultValue));
|
|
336
334
|
if (!value)
|
|
337
335
|
return 0;
|
|
@@ -342,7 +340,7 @@ export class Env {
|
|
|
342
340
|
// Parse duration string like "1d2h30m15s"
|
|
343
341
|
const durationRegex = /(\d+d)?(\d+h)?(\d+m)?(\d+s)?(\d+ms)?/;
|
|
344
342
|
const matches = value.match(durationRegex);
|
|
345
|
-
if (!matches || matches[0] ===
|
|
343
|
+
if (!matches || matches[0] === '') {
|
|
346
344
|
throw new Error(`Env ${key} has invalid duration format. Use 1d, 2h, 30m, 45s, or 100ms.`);
|
|
347
345
|
}
|
|
348
346
|
let ms = 0;
|
|
@@ -364,13 +362,13 @@ export class Env {
|
|
|
364
362
|
* @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.
|
|
365
363
|
* @returns {Record<string, string>} Environment variables with sensitive values masked.
|
|
366
364
|
*/
|
|
367
|
-
static getSafeEnv(sensitiveKeys = [
|
|
365
|
+
static getSafeEnv(sensitiveKeys = ['password', 'secret', 'key', 'token', 'auth']) {
|
|
368
366
|
const safeEnv = {};
|
|
369
367
|
for (const [key, value] of Object.entries(process.env)) {
|
|
370
368
|
if (!value)
|
|
371
369
|
continue;
|
|
372
|
-
const isSensitive = sensitiveKeys.some(
|
|
373
|
-
safeEnv[key] = isSensitive ?
|
|
370
|
+
const isSensitive = sensitiveKeys.some(sensitiveKey => key.toLowerCase().includes(sensitiveKey.toLowerCase()));
|
|
371
|
+
safeEnv[key] = isSensitive ? '******' : value;
|
|
374
372
|
}
|
|
375
373
|
return safeEnv;
|
|
376
374
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env.utils.js","sourceRoot":"","sources":["../../../src/utils/env.utils.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC3C;;GAEG;AACH,MAAM,CAAN,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,wCAAyB,CAAA;IACzB,0CAA2B,CAAA;IAC3B,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;AACrB,CAAC,EALW,WAAW,KAAX,WAAW,QAKtB;AAED;;;GAGG;AACH,MAAM,OAAO,GAAG;IACd;;;;OAIG;IACH,MAAM,CAAC,KAAK;QACV,OAAO,CACL,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,KAAK,WAAW,CAAC,WAAW,CACzE,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,UAAU,CAAC;IACxD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,GA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,QAAQ,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CACvD,CAAC;YAEF,OAAO,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC;QAChD,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,GAAG,CAAC,GAAW;QACpB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;IACxC,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,MAAM,CAAC,GAAW;QACvB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF","sourcesContent":["/* eslint-disable n/no-process-env */\nimport { existsSync } from \"fs\";\nimport { isAbsolute, resolve } from \"path\";\n/**\n * Enum representing valid application environments.\n */\nexport enum Environment {\n PRODUCTION = \"production\",\n DEVELOPMENT = \"development\",\n STAGING = \"staging\",\n TESTING = \"testing\",\n}\n\n/**\n * Utility class for accessing and managing environment variables.\n * Provides typed getters with fallback defaults and validation.\n */\nexport class Env {\n /**\n * Checks if the current NODE_ENV is 'development'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.\n */\n static isDev(): boolean {\n return (\n Env.get(\"NODE_ENV\", Environment.DEVELOPMENT) === Environment.DEVELOPMENT\n );\n }\n\n /**\n * Checks if the current NODE_ENV is 'production'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.\n */\n static isProd(): boolean {\n return Env.get(\"NODE_ENV\") === Environment.PRODUCTION;\n }\n\n /**\n * Checks if the current NODE_ENV is 'testing'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.\n */\n static isTest(): boolean {\n return Env.get(\"NODE_ENV\") === Environment.TESTING;\n }\n\n /**\n * Checks if the current NODE_ENV is 'staging'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.\n */\n static isStaging(): boolean {\n return Env.get(\"NODE_ENV\") === Environment.STAGING;\n }\n\n /**\n * Sets an environment variable (only affects runtime memory).\n *\n * @param {string} key - The environment variable key.\n * @param {string} value - The value to set.\n */\n static set(key: string, value: string): void {\n process.env[key] = value;\n }\n\n /**\n * Returns all environment variables as an object.\n *\n * @returns {object} The current `process.env` object.\n */\n static getAll(): object {\n return process.env;\n }\n\n /**\n * Retrieves a string environment variable with a fallback default.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Value to return if the key is missing.\n * @returns {string | undefined} The env value or the fallback.\n */\n static get(key: string, defaultValue?: string): string | undefined {\n return process.env[key] ?? defaultValue;\n }\n\n /**\n * Retrieves a string environment variable and throws if it's missing.\n *\n * @param {string} key - The environment variable key.\n * @returns {string} The environment variable's value.\n * @throws {Error} If the variable is not defined.\n */\n static getRequired(key: string): string {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return value;\n }\n\n /**\n * Retrieves an environment variable as a number, or returns a default.\n *\n * @param {string} key - The environment variable key.\n * @param {number} defaultValue - Fallback number if key is not present.\n * @returns {number} Parsed numeric value or default.\n * @throws {Error} If the value is not a valid number.\n */\n static getNumber(key: string, defaultValue: number): number {\n const value = process.env[key] ?? defaultValue;\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves a required environment variable as a number.\n *\n * @param {string} key - The environment variable key.\n * @returns {number} Parsed number.\n * @throws {Error} If the value is missing or not a number.\n */\n static getNumberRequired(key: string): number {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Required env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves an environment variable as a boolean.\n * Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.\n *\n * @param {string} key - The environment variable key.\n * @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.\n * @returns {boolean} Parsed boolean.\n * @throws {Error} If the value is not a recognized boolean string.\n */\n static getBoolean(key: string, defaultValue = false): boolean {\n const value = (process.env[key] ?? defaultValue).toString().toLowerCase();\n if ([\"true\", \"1\", \"yes\", \"on\"].includes(value)) return true;\n if ([\"false\", \"0\", \"no\", \"off\"].includes(value)) return false;\n throw new Error(`Env variable ${key} is not a boolean`);\n }\n\n /**\n * Retrieves a required environment variable as a boolean.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} Parsed boolean value.\n * @throws {Error} If missing or invalid.\n */\n static getBooleanRequired(key: string): boolean {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return this.getBoolean(key); // reuse logic\n }\n\n /**\n * Parses a stringified JSON object from an environment variable.\n *\n * @typeParam T - The type to parse as (defaults to `object`).\n * @param {string} key - The environment variable key.\n * @param {T} defaultValue - Value to return if key is missing.\n * @returns {T} Parsed object or default.\n * @throws {Error} If the value is not valid JSON.\n */\n static getJSON<T extends object = object>(key: string, defaultValue: T): T {\n const v = process.env[key];\n if (v !== undefined) {\n try {\n return JSON.parse(v);\n } catch {\n throw new Error(`Env variable ${key} is not a valid JSON string`);\n }\n }\n return defaultValue;\n }\n\n /**\n * Parses a comma-separated string as an array.\n *\n * @typeParam T - The item type (optional, defaults to string).\n * @param {string} key - The environment variable key.\n * @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.\n * @param {string} [splitter=','] - Delimiter to split on.\n * @returns {string[] | T[]} An array of strings.\n */\n static getArray<T = string>(\n key: string,\n defaultValue: T[] = [],\n splitter = \",\",\n ): string[] | T[] {\n const value = process.env[key];\n if (!value || value.trim() === \"\") {\n return defaultValue;\n }\n return value\n .split(splitter)\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n }\n\n /**\n * Retrieves an enum-like environment variable value, validating against allowed values.\n *\n * @typeParam T - The allowed value type (string literal types).\n * @param {string} key - The environment variable key.\n * @param {T[]} allowedValues - Array of accepted string values.\n * @param {T} [defaultValue] - Optional fallback value.\n * @returns {T} The validated environment value.\n * @throws {Error} If missing or invalid.\n */\n static getEnum<T extends string>(\n key: string,\n allowedValues: T[],\n defaultValue?: T,\n ): T {\n const value = process.env[key] ?? defaultValue;\n if (!value || !allowedValues.includes(value as T)) {\n throw new Error(\n `Env ${key} must be one of ${allowedValues.join(\", \")}. Received: ${value}`,\n );\n }\n return value as T;\n }\n\n /**\n * Retrieves a URL environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {string[]} [options.protocols] - Allowed protocols.\n * @param {boolean} [options.requireTld=true] - Whether TLD is required.\n * @returns {string} The validated URL.\n * @throws {Error} If URL is invalid.\n */\n static getUrl(\n key: string,\n defaultValue?: string,\n options: { protocols?: string[]; requireTld?: boolean } = {},\n ): string {\n const value = Env.get(key, defaultValue);\n if (!value) {\n throw new Error(`Env ${key} is missing or empty`);\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Env ${key} is not a valid URL`);\n }\n\n if (options.protocols && options.protocols.length > 0) {\n const protocol = url.protocol.replace(\":\", \"\");\n if (!options.protocols.includes(protocol)) {\n throw new Error(\n `Env ${key} must use one of the protocols: ${options.protocols.join(\", \")}`,\n );\n }\n }\n\n if (options.requireTld === true) {\n // Check if hostname has a TLD (contains at least one dot and doesn't end with a dot)\n // localhost, 127.0.0.1, etc. don't have TLDs\n const hostname = url.hostname;\n if (\n !hostname.includes(\".\") ||\n hostname === \"localhost\" ||\n /^[\\d.]+$/.test(hostname) || // IP address\n hostname.endsWith(\".\")\n ) {\n throw new Error(`Env ${key} must have a valid host with TLD`);\n }\n }\n\n return value;\n }\n\n /**\n * Retrieves an email environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @returns {string} The validated email address.\n * @throws {Error} If email is invalid.\n */\n static getEmail(key: string, defaultValue?: string): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Email env ${key} is missing`);\n }\n return defaultValue;\n }\n\n // Simple email validation regex\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n if (!emailRegex.test(value)) {\n throw new Error(`Env ${key} is not a valid email address`);\n }\n\n return value;\n }\n\n /**\n * Retrieves a path environment variable and validates it exists.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {boolean} [options.mustExist=false] - Whether path must exist.\n * @param {boolean} [options.makeAbsolute=true] - Convert relative paths to absolute.\n * @returns {string} The validated path.\n * @throws {Error} If path is invalid.\n */\n static getPath(\n key: string,\n defaultValue?: string,\n options: { mustExist?: boolean; makeAbsolute?: boolean } = {},\n ): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Path env ${key} is missing`);\n }\n return defaultValue;\n }\n\n const path =\n options.makeAbsolute !== false && !isAbsolute(value)\n ? resolve(process.cwd(), value)\n : value;\n\n if (options.mustExist && !existsSync(path)) {\n throw new Error(`Path in env ${key} does not exist: ${path}`);\n }\n\n return path;\n }\n\n /**\n * Retrieves a port environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {number} [defaultValue=3000] - Optional fallback value.\n * @returns {number} The validated port number.\n * @throws {Error} If port is invalid.\n */\n static getPort(key: string, defaultValue: number = 3000): number {\n const port = Env.getNumber(key, defaultValue);\n\n if (port < 0 || port > 65535) {\n throw new Error(`Env ${key} must be a valid port number (0-65535)`);\n }\n\n return port;\n }\n\n /**\n * Retrieves a duration string and converts to milliseconds.\n * Supports formats like \"1d\", \"2h\", \"30m\", \"45s\", \"100ms\" or combinations like \"1h30m\".\n *\n * @param {string} key - The environment variable key.\n * @param {string|number} [defaultValue='0'] - Optional fallback value.\n * @returns {number} The duration in milliseconds.\n * @throws {Error} If duration format is invalid.\n */\n static getDuration(key: string, defaultValue: string | number = \"0\"): number {\n const value = Env.get(key, String(defaultValue));\n\n if (!value) return 0;\n\n // Handle plain number input (assume milliseconds)\n if (/^\\d+$/.test(value)) {\n return parseInt(value, 10);\n }\n\n // Parse duration string like \"1d2h30m15s\"\n const durationRegex = /(\\d+d)?(\\d+h)?(\\d+m)?(\\d+s)?(\\d+ms)?/;\n const matches = value.match(durationRegex);\n\n if (!matches || matches[0] === \"\") {\n throw new Error(\n `Env ${key} has invalid duration format. Use 1d, 2h, 30m, 45s, or 100ms.`,\n );\n }\n\n let ms = 0;\n\n if (matches[1]) ms += parseInt(matches[1], 10) * 86400000; // days\n if (matches[2]) ms += parseInt(matches[2], 10) * 3600000; // hours\n if (matches[3]) ms += parseInt(matches[3], 10) * 60000; // minutes\n if (matches[4]) ms += parseInt(matches[4], 10) * 1000; // seconds\n if (matches[5]) ms += parseInt(matches[5], 10); // milliseconds\n\n return ms;\n }\n\n /**\n * Gets all environment variables with sensitive values masked for safe logging.\n *\n * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.\n * @returns {Record<string, string>} Environment variables with sensitive values masked.\n */\n static getSafeEnv(\n sensitiveKeys: string[] = [\"password\", \"secret\", \"key\", \"token\", \"auth\"],\n ): Record<string, string> {\n const safeEnv: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(process.env)) {\n if (!value) continue;\n\n const isSensitive = sensitiveKeys.some((sensitiveKey) =>\n key.toLowerCase().includes(sensitiveKey.toLowerCase()),\n );\n\n safeEnv[key] = isSensitive ? \"******\" : value;\n }\n\n return safeEnv;\n }\n\n /**\n * Checks whether the specified environment variable exists.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} `true` if the variable is defined, otherwise `false`.\n */\n static has(key: string): boolean {\n return process.env[key] !== undefined;\n }\n\n /**\n * Deletes the given environment variable (useful in tests).\n *\n * @param {string} key - The environment variable key to delete.\n * @returns {void}\n */\n static delete(key: string): void {\n delete process.env[key];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"env.utils.js","sourceRoot":"","sources":["../../../src/utils/env.utils.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC3C;;GAEG;AACH,MAAM,CAAN,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,wCAAyB,CAAA;IACzB,0CAA2B,CAAA;IAC3B,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;AACrB,CAAC,EALW,WAAW,KAAX,WAAW,QAKtB;AAED;;;GAGG;AACH,MAAM,OAAO,GAAG;IACd;;;;OAIG;IACH,MAAM,CAAC,KAAK;QACV,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,KAAK,WAAW,CAAC,WAAW,CAAC;IAClF,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,UAAU,CAAC;IACxD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,OAAO,CAAC;IACrD,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,SAAS;QACd,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,OAAO,CAAC;IACrD,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,GAAG,CAAC,GAAW,EAAE,KAAa;QACnC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAC3B,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,OAAO,CAAC,GAAG,CAAC;IACrB,CAAC;IA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;IAC1B,CAAC;CACF","sourcesContent":["/* eslint-disable n/no-process-env */\nimport { existsSync } from 'fs';\nimport { isAbsolute, resolve } from 'path';\n/**\n * Enum representing valid application environments.\n */\nexport enum Environment {\n PRODUCTION = 'production',\n DEVELOPMENT = 'development',\n STAGING = 'staging',\n TESTING = 'testing'\n}\n\n/**\n * Utility class for accessing and managing environment variables.\n * Provides typed getters with fallback defaults and validation.\n */\nexport class Env {\n /**\n * Checks if the current NODE_ENV is 'development'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.\n */\n static isDev(): boolean {\n return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.DEVELOPMENT;\n }\n\n /**\n * Checks if the current NODE_ENV is 'production'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.\n */\n static isProd(): boolean {\n return Env.get('NODE_ENV') === Environment.PRODUCTION;\n }\n\n /**\n * Checks if the current NODE_ENV is 'testing'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.\n */\n static isTest(): boolean {\n return Env.get('NODE_ENV') === Environment.TESTING;\n }\n\n /**\n * Checks if the current NODE_ENV is 'staging'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.\n */\n static isStaging(): boolean {\n return Env.get('NODE_ENV') === Environment.STAGING;\n }\n\n /**\n * Sets an environment variable (only affects runtime memory).\n *\n * @param {string} key - The environment variable key.\n * @param {string} value - The value to set.\n */\n static set(key: string, value: string): void {\n process.env[key] = value;\n }\n\n /**\n * Returns all environment variables as an object.\n *\n * @returns {object} The current `process.env` object.\n */\n static getAll(): object {\n return process.env;\n }\n\n /**\n * Retrieves a string environment variable with a fallback default.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Value to return if the key is missing.\n * @returns {string | undefined} The env value or the fallback.\n */\n static get(key: string, defaultValue?: string): string | undefined {\n return process.env[key] ?? defaultValue;\n }\n\n /**\n * Retrieves a string environment variable and throws if it's missing.\n *\n * @param {string} key - The environment variable key.\n * @returns {string} The environment variable's value.\n * @throws {Error} If the variable is not defined.\n */\n static getRequired(key: string): string {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return value;\n }\n\n /**\n * Retrieves an environment variable as a number, or returns a default.\n *\n * @param {string} key - The environment variable key.\n * @param {number} defaultValue - Fallback number if key is not present.\n * @returns {number} Parsed numeric value or default.\n * @throws {Error} If the value is not a valid number.\n */\n static getNumber(key: string, defaultValue: number): number {\n const value = process.env[key] ?? defaultValue;\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves a required environment variable as a number.\n *\n * @param {string} key - The environment variable key.\n * @returns {number} Parsed number.\n * @throws {Error} If the value is missing or not a number.\n */\n static getNumberRequired(key: string): number {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Required env ${key} is not a number`);\n }\n return numberValue;\n }\n\n /**\n * Retrieves an environment variable as a boolean.\n * Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.\n *\n * @param {string} key - The environment variable key.\n * @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.\n * @returns {boolean} Parsed boolean.\n * @throws {Error} If the value is not a recognized boolean string.\n */\n static getBoolean(key: string, defaultValue = false): boolean {\n const value = (process.env[key] ?? defaultValue).toString().toLowerCase();\n if (['true', '1', 'yes', 'on'].includes(value)) return true;\n if (['false', '0', 'no', 'off'].includes(value)) return false;\n throw new Error(`Env variable ${key} is not a boolean`);\n }\n\n /**\n * Retrieves a required environment variable as a boolean.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} Parsed boolean value.\n * @throws {Error} If missing or invalid.\n */\n static getBooleanRequired(key: string): boolean {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required env ${key} is missing`);\n }\n return this.getBoolean(key); // reuse logic\n }\n\n /**\n * Parses a stringified JSON object from an environment variable.\n *\n * @typeParam T - The type to parse as (defaults to `object`).\n * @param {string} key - The environment variable key.\n * @param {T} defaultValue - Value to return if key is missing.\n * @returns {T} Parsed object or default.\n * @throws {Error} If the value is not valid JSON.\n */\n static getJSON<T extends object = object>(key: string, defaultValue: T): T {\n const v = process.env[key];\n if (v !== undefined) {\n try {\n return JSON.parse(v);\n } catch {\n throw new Error(`Env variable ${key} is not a valid JSON string`);\n }\n }\n return defaultValue;\n }\n\n /**\n * Parses a comma-separated string as an array.\n *\n * @typeParam T - The item type (optional, defaults to string).\n * @param {string} key - The environment variable key.\n * @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.\n * @param {string} [splitter=','] - Delimiter to split on.\n * @returns {string[] | T[]} An array of strings.\n */\n static getArray<T = string>(key: string, defaultValue: T[] = [], splitter = ','): string[] | T[] {\n const value = process.env[key];\n if (!value || value.trim() === '') {\n return defaultValue;\n }\n return value\n .split(splitter)\n .map(item => item.trim())\n .filter(item => item.length > 0);\n }\n\n /**\n * Retrieves an enum-like environment variable value, validating against allowed values.\n *\n * @typeParam T - The allowed value type (string literal types).\n * @param {string} key - The environment variable key.\n * @param {T[]} allowedValues - Array of accepted string values.\n * @param {T} [defaultValue] - Optional fallback value.\n * @returns {T} The validated environment value.\n * @throws {Error} If missing or invalid.\n */\n static getEnum<T extends string>(key: string, allowedValues: T[], defaultValue?: T): T {\n const value = process.env[key] ?? defaultValue;\n if (!value || !allowedValues.includes(value as T)) {\n throw new Error(`Env ${key} must be one of ${allowedValues.join(', ')}. Received: ${value}`);\n }\n return value as T;\n }\n\n /**\n * Retrieves a URL environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {string[]} [options.protocols] - Allowed protocols.\n * @param {boolean} [options.requireTld=true] - Whether TLD is required.\n * @returns {string} The validated URL.\n * @throws {Error} If URL is invalid.\n */\n static getUrl(\n key: string,\n defaultValue?: string,\n options: { protocols?: string[]; requireTld?: boolean } = {}\n ): string {\n const value = Env.get(key, defaultValue);\n if (!value) {\n throw new Error(`Env ${key} is missing or empty`);\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Env ${key} is not a valid URL`);\n }\n\n if (options.protocols && options.protocols.length > 0) {\n const protocol = url.protocol.replace(':', '');\n if (!options.protocols.includes(protocol)) {\n throw new Error(`Env ${key} must use one of the protocols: ${options.protocols.join(', ')}`);\n }\n }\n\n if (options.requireTld === true) {\n // Check if hostname has a TLD (contains at least one dot and doesn't end with a dot)\n // localhost, 127.0.0.1, etc. don't have TLDs\n const hostname = url.hostname;\n if (\n !hostname.includes('.') ||\n hostname === 'localhost' ||\n /^[\\d.]+$/.test(hostname) || // IP address\n hostname.endsWith('.')\n ) {\n throw new Error(`Env ${key} must have a valid host with TLD`);\n }\n }\n\n return value;\n }\n\n /**\n * Retrieves an email environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @returns {string} The validated email address.\n * @throws {Error} If email is invalid.\n */\n static getEmail(key: string, defaultValue?: string): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Email env ${key} is missing`);\n }\n return defaultValue;\n }\n\n // Simple email validation regex\n const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n if (!emailRegex.test(value)) {\n throw new Error(`Env ${key} is not a valid email address`);\n }\n\n return value;\n }\n\n /**\n * Retrieves a path environment variable and validates it exists.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {object} [options] - Validation options.\n * @param {boolean} [options.mustExist=false] - Whether path must exist.\n * @param {boolean} [options.makeAbsolute=true] - Convert relative paths to absolute.\n * @returns {string} The validated path.\n * @throws {Error} If path is invalid.\n */\n static getPath(\n key: string,\n defaultValue?: string,\n options: { mustExist?: boolean; makeAbsolute?: boolean } = {}\n ): string {\n const value = Env.get(key, defaultValue);\n\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Path env ${key} is missing`);\n }\n return defaultValue;\n }\n\n const path = options.makeAbsolute !== false && !isAbsolute(value) ? resolve(process.cwd(), value) : value;\n\n if (options.mustExist && !existsSync(path)) {\n throw new Error(`Path in env ${key} does not exist: ${path}`);\n }\n\n return path;\n }\n\n /**\n * Retrieves a port environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {number} [defaultValue=3000] - Optional fallback value.\n * @returns {number} The validated port number.\n * @throws {Error} If port is invalid.\n */\n static getPort(key: string, defaultValue: number = 3000): number {\n const port = Env.getNumber(key, defaultValue);\n\n if (port < 0 || port > 65535) {\n throw new Error(`Env ${key} must be a valid port number (0-65535)`);\n }\n\n return port;\n }\n\n /**\n * Retrieves a duration string and converts to milliseconds.\n * Supports formats like \"1d\", \"2h\", \"30m\", \"45s\", \"100ms\" or combinations like \"1h30m\".\n *\n * @param {string} key - The environment variable key.\n * @param {string|number} [defaultValue='0'] - Optional fallback value.\n * @returns {number} The duration in milliseconds.\n * @throws {Error} If duration format is invalid.\n */\n static getDuration(key: string, defaultValue: string | number = '0'): number {\n const value = Env.get(key, String(defaultValue));\n\n if (!value) return 0;\n\n // Handle plain number input (assume milliseconds)\n if (/^\\d+$/.test(value)) {\n return parseInt(value, 10);\n }\n\n // Parse duration string like \"1d2h30m15s\"\n const durationRegex = /(\\d+d)?(\\d+h)?(\\d+m)?(\\d+s)?(\\d+ms)?/;\n const matches = value.match(durationRegex);\n\n if (!matches || matches[0] === '') {\n throw new Error(`Env ${key} has invalid duration format. Use 1d, 2h, 30m, 45s, or 100ms.`);\n }\n\n let ms = 0;\n\n if (matches[1]) ms += parseInt(matches[1], 10) * 86400000; // days\n if (matches[2]) ms += parseInt(matches[2], 10) * 3600000; // hours\n if (matches[3]) ms += parseInt(matches[3], 10) * 60000; // minutes\n if (matches[4]) ms += parseInt(matches[4], 10) * 1000; // seconds\n if (matches[5]) ms += parseInt(matches[5], 10); // milliseconds\n\n return ms;\n }\n\n /**\n * Gets all environment variables with sensitive values masked for safe logging.\n *\n * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.\n * @returns {Record<string, string>} Environment variables with sensitive values masked.\n */\n static getSafeEnv(sensitiveKeys: string[] = ['password', 'secret', 'key', 'token', 'auth']): Record<string, string> {\n const safeEnv: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(process.env)) {\n if (!value) continue;\n\n const isSensitive = sensitiveKeys.some(sensitiveKey => key.toLowerCase().includes(sensitiveKey.toLowerCase()));\n\n safeEnv[key] = isSensitive ? '******' : value;\n }\n\n return safeEnv;\n }\n\n /**\n * Checks whether the specified environment variable exists.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} `true` if the variable is defined, otherwise `false`.\n */\n static has(key: string): boolean {\n return process.env[key] !== undefined;\n }\n\n /**\n * Deletes the given environment variable (useful in tests).\n *\n * @param {string} key - The environment variable key to delete.\n * @returns {void}\n */\n static delete(key: string): void {\n delete process.env[key];\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { HttpStatusCodes } from
|
|
2
|
-
import { getLogger } from
|
|
3
|
-
import { ErrorResponse } from
|
|
1
|
+
import { HttpStatusCodes } from './http-status-codes';
|
|
2
|
+
import { getLogger } from './logger.utils';
|
|
3
|
+
import { ErrorResponse } from './response.utils';
|
|
4
4
|
/**
|
|
5
5
|
* Generic HTTP error class used for custom exceptions with any status code.
|
|
6
6
|
* Inherit this when you need to throw errors dynamically at runtime.
|
|
@@ -24,7 +24,7 @@ export class InternalServerErrorException extends ErrorResponse {
|
|
|
24
24
|
/**
|
|
25
25
|
* @param message - Optional custom message. Defaults to "Internal server error".
|
|
26
26
|
*/
|
|
27
|
-
constructor(message =
|
|
27
|
+
constructor(message = 'Internal server error') {
|
|
28
28
|
super(message);
|
|
29
29
|
this.status = HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
30
30
|
}
|
|
@@ -37,7 +37,7 @@ export class UnauthorizedException extends ErrorResponse {
|
|
|
37
37
|
/**
|
|
38
38
|
* @param message - Optional custom message. Defaults to "Unauthorized".
|
|
39
39
|
*/
|
|
40
|
-
constructor(message =
|
|
40
|
+
constructor(message = 'Unauthorized') {
|
|
41
41
|
super(message);
|
|
42
42
|
this.status = HttpStatusCodes.UNAUTHORIZED;
|
|
43
43
|
}
|
|
@@ -50,7 +50,7 @@ export class BadRequestException extends ErrorResponse {
|
|
|
50
50
|
/**
|
|
51
51
|
* @param message - Optional custom message. Defaults to "Bad request".
|
|
52
52
|
*/
|
|
53
|
-
constructor(message =
|
|
53
|
+
constructor(message = 'Bad request') {
|
|
54
54
|
super(message);
|
|
55
55
|
this.status = HttpStatusCodes.BAD_REQUEST;
|
|
56
56
|
}
|
|
@@ -63,7 +63,7 @@ export class NotFoundException extends ErrorResponse {
|
|
|
63
63
|
/**
|
|
64
64
|
* @param message - Optional custom message. Defaults to "Resource not found".
|
|
65
65
|
*/
|
|
66
|
-
constructor(message =
|
|
66
|
+
constructor(message = 'Resource not found') {
|
|
67
67
|
super(message);
|
|
68
68
|
this.status = HttpStatusCodes.NOT_FOUND;
|
|
69
69
|
}
|
|
@@ -76,7 +76,7 @@ export class ForbiddenException extends ErrorResponse {
|
|
|
76
76
|
/**
|
|
77
77
|
* @param message - Optional custom message. Defaults to "Forbidden".
|
|
78
78
|
*/
|
|
79
|
-
constructor(message =
|
|
79
|
+
constructor(message = 'Forbidden') {
|
|
80
80
|
super(message);
|
|
81
81
|
this.status = HttpStatusCodes.FORBIDDEN;
|
|
82
82
|
}
|
|
@@ -89,7 +89,7 @@ export class ConflictException extends ErrorResponse {
|
|
|
89
89
|
/**
|
|
90
90
|
* @param message - Optional custom message. Defaults to "Conflict".
|
|
91
91
|
*/
|
|
92
|
-
constructor(message =
|
|
92
|
+
constructor(message = 'Conflict') {
|
|
93
93
|
super(message);
|
|
94
94
|
this.status = HttpStatusCodes.CONFLICT;
|
|
95
95
|
}
|
|
@@ -102,7 +102,7 @@ export class BadGatewayException extends ErrorResponse {
|
|
|
102
102
|
/**
|
|
103
103
|
* @param message - Optional custom message. Defaults to "Bad Gateway".
|
|
104
104
|
*/
|
|
105
|
-
constructor(message =
|
|
105
|
+
constructor(message = 'Bad Gateway') {
|
|
106
106
|
super(message);
|
|
107
107
|
this.status = HttpStatusCodes.BAD_GATEWAY;
|
|
108
108
|
}
|
|
@@ -115,7 +115,7 @@ export class TooManyRequestsException extends ErrorResponse {
|
|
|
115
115
|
/**
|
|
116
116
|
* @param message - Optional custom message. Defaults to "Too many requests".
|
|
117
117
|
*/
|
|
118
|
-
constructor(message =
|
|
118
|
+
constructor(message = 'Too many requests') {
|
|
119
119
|
super(message);
|
|
120
120
|
this.status = HttpStatusCodes.TOO_MANY_REQUESTS;
|
|
121
121
|
}
|
|
@@ -128,7 +128,7 @@ export class ServiceUnavailableException extends ErrorResponse {
|
|
|
128
128
|
/**
|
|
129
129
|
* @param message - Optional custom message. Defaults to "Service Unavailable".
|
|
130
130
|
*/
|
|
131
|
-
constructor(message =
|
|
131
|
+
constructor(message = 'Service Unavailable') {
|
|
132
132
|
super(message);
|
|
133
133
|
this.status = HttpStatusCodes.SERVICE_UNAVAILABLE;
|
|
134
134
|
}
|
|
@@ -141,7 +141,7 @@ export class GatewayTimeoutException extends ErrorResponse {
|
|
|
141
141
|
/**
|
|
142
142
|
* @param message - Optional custom message. Defaults to "Gateway Timeout".
|
|
143
143
|
*/
|
|
144
|
-
constructor(message =
|
|
144
|
+
constructor(message = 'Gateway Timeout') {
|
|
145
145
|
super(message);
|
|
146
146
|
this.status = HttpStatusCodes.GATEWAY_TIMEOUT;
|
|
147
147
|
}
|
|
@@ -155,7 +155,7 @@ export class UnprocessableEntityException extends ErrorResponse {
|
|
|
155
155
|
* @param message - Optional custom message. Defaults to "Unprocessable Entity".
|
|
156
156
|
* @param details - Optional validation details or additional error context.
|
|
157
157
|
*/
|
|
158
|
-
constructor(message =
|
|
158
|
+
constructor(message = 'Unprocessable Entity', details) {
|
|
159
159
|
super(message);
|
|
160
160
|
this.details = details;
|
|
161
161
|
this.status = HttpStatusCodes.UNPROCESSABLE_ENTITY;
|
|
@@ -170,7 +170,7 @@ export class MethodNotAllowedException extends ErrorResponse {
|
|
|
170
170
|
* @param message - Optional custom message. Defaults to "Method Not Allowed".
|
|
171
171
|
* @param allowedMethods - Optional array of allowed HTTP methods.
|
|
172
172
|
*/
|
|
173
|
-
constructor(message =
|
|
173
|
+
constructor(message = 'Method Not Allowed', allowedMethods) {
|
|
174
174
|
super(message);
|
|
175
175
|
this.allowedMethods = allowedMethods;
|
|
176
176
|
this.status = HttpStatusCodes.METHOD_NOT_ALLOWED;
|
|
@@ -184,7 +184,7 @@ export class NotAcceptableException extends ErrorResponse {
|
|
|
184
184
|
/**
|
|
185
185
|
* @param message - Optional custom message. Defaults to "Not Acceptable".
|
|
186
186
|
*/
|
|
187
|
-
constructor(message =
|
|
187
|
+
constructor(message = 'Not Acceptable') {
|
|
188
188
|
super(message);
|
|
189
189
|
this.status = HttpStatusCodes.NOT_ACCEPTABLE;
|
|
190
190
|
}
|
|
@@ -197,7 +197,7 @@ export class RequestTimeoutException extends ErrorResponse {
|
|
|
197
197
|
/**
|
|
198
198
|
* @param message - Optional custom message. Defaults to "Request Timeout".
|
|
199
199
|
*/
|
|
200
|
-
constructor(message =
|
|
200
|
+
constructor(message = 'Request Timeout') {
|
|
201
201
|
super(message);
|
|
202
202
|
this.status = HttpStatusCodes.REQUEST_TIMEOUT;
|
|
203
203
|
}
|
|
@@ -210,7 +210,7 @@ export class UnsupportedMediaTypeException extends ErrorResponse {
|
|
|
210
210
|
/**
|
|
211
211
|
* @param message - Optional custom message. Defaults to "Unsupported Media Type".
|
|
212
212
|
*/
|
|
213
|
-
constructor(message =
|
|
213
|
+
constructor(message = 'Unsupported Media Type') {
|
|
214
214
|
super(message);
|
|
215
215
|
this.status = HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;
|
|
216
216
|
}
|
|
@@ -223,7 +223,7 @@ export class PayloadTooLargeException extends ErrorResponse {
|
|
|
223
223
|
/**
|
|
224
224
|
* @param message - Optional custom message. Defaults to "Payload Too Large".
|
|
225
225
|
*/
|
|
226
|
-
constructor(message =
|
|
226
|
+
constructor(message = 'Payload Too Large') {
|
|
227
227
|
super(message);
|
|
228
228
|
this.status = HttpStatusCodes.PAYLOAD_TOO_LARGE;
|
|
229
229
|
}
|
|
@@ -236,7 +236,7 @@ export class InsufficientStorageException extends ErrorResponse {
|
|
|
236
236
|
/**
|
|
237
237
|
* @param message - Optional custom message. Defaults to "Insufficient Storage".
|
|
238
238
|
*/
|
|
239
|
-
constructor(message =
|
|
239
|
+
constructor(message = 'Insufficient Storage') {
|
|
240
240
|
super(message);
|
|
241
241
|
this.status = HttpStatusCodes.INSUFFICIENT_STORAGE;
|
|
242
242
|
}
|
|
@@ -277,7 +277,7 @@ export function createHttpError(status, message) {
|
|
|
277
277
|
case HttpStatusCodes.CONFLICT:
|
|
278
278
|
return new ConflictException(message);
|
|
279
279
|
case HttpStatusCodes.GONE:
|
|
280
|
-
return new HttpError(HttpStatusCodes.GONE, message ||
|
|
280
|
+
return new HttpError(HttpStatusCodes.GONE, message || 'Gone');
|
|
281
281
|
case HttpStatusCodes.PAYLOAD_TOO_LARGE:
|
|
282
282
|
return new PayloadTooLargeException(message);
|
|
283
283
|
case HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:
|
|
@@ -307,10 +307,7 @@ export function createHttpError(status, message) {
|
|
|
307
307
|
* @returns True if object has error-like structure.
|
|
308
308
|
*/
|
|
309
309
|
export function hasErrorShape(error) {
|
|
310
|
-
return (typeof error ===
|
|
311
|
-
error !== null &&
|
|
312
|
-
"message" in error &&
|
|
313
|
-
typeof error.message === "string");
|
|
310
|
+
return (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string');
|
|
314
311
|
}
|
|
315
312
|
/**
|
|
316
313
|
* Safely extracts message from any error type.
|
|
@@ -319,7 +316,7 @@ export function hasErrorShape(error) {
|
|
|
319
316
|
* @returns A string error message.
|
|
320
317
|
*/
|
|
321
318
|
export function getErrorMessage(error) {
|
|
322
|
-
if (typeof error ===
|
|
319
|
+
if (typeof error === 'string') {
|
|
323
320
|
return error;
|
|
324
321
|
}
|
|
325
322
|
if (error instanceof Error) {
|
|
@@ -328,7 +325,7 @@ export function getErrorMessage(error) {
|
|
|
328
325
|
if (hasErrorShape(error)) {
|
|
329
326
|
return error.message;
|
|
330
327
|
}
|
|
331
|
-
return
|
|
328
|
+
return 'Unknown error occurred';
|
|
332
329
|
}
|
|
333
330
|
/**
|
|
334
331
|
* Wraps a function and transforms any errors into HTTP errors.
|
|
@@ -347,10 +344,10 @@ export function withErrorHandling(handler) {
|
|
|
347
344
|
throw error;
|
|
348
345
|
}
|
|
349
346
|
// Log the original error (consider using a proper logger)
|
|
350
|
-
getLogger().error(
|
|
347
|
+
getLogger().error('Caught error in handler:', error);
|
|
351
348
|
// Extract status code if it exists, otherwise use 500
|
|
352
349
|
let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
353
|
-
if (hasErrorShape(error) && typeof error.status ===
|
|
350
|
+
if (hasErrorShape(error) && typeof error.status === 'number') {
|
|
354
351
|
status = error.status;
|
|
355
352
|
}
|
|
356
353
|
// Create appropriate HTTP error
|