@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":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,UAAU,EAEV,UAAU,EACV,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,eAAe,GAEhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAgBjC;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAClB,SAAiB,EACjB,KAAa,EACb,MAAc,EACd,WAAiC,KAAK;IAEtC,OAAO,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAClB,SAAiB,EACjB,KAAa,EACb,WAAiC,KAAK;IAEtC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,MAAc;IACtD,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,IAAI,CAClB,KAAa,EACb,WAAiC,KAAK;IAEtC,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CACpB,KAAa,EAC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,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes,\n} from \"crypto\";\nimport { promisify } from \"util\";\n\nexport type BufferEncoding =\n | \"ascii\"\n | \"utf8\"\n | \"utf-8\"\n | \"utf16le\"\n | \"utf-16le\"\n | \"ucs2\"\n | \"ucs-2\"\n | \"base64\"\n | \"base64url\"\n | \"latin1\"\n | \"binary\"\n | \"hex\";\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(\n algorithm: string,\n input: string,\n secret: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(\n algorithm: string,\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac(\"sha256\", input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return hash(\"sha1\", input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return hash(\"sha256\", input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash(\"md5\", input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(randomUUID());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(\n byteLength: number = 32,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(\n prefix: string = \"\",\n byteLength: number = 24,\n): string {\n const randomString = generateRandomBytesAsString(byteLength, \"base64\");\n const key = randomString\n .replace(/[+/=]/g, \"\") // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(\n a: string | Buffer | Uint8Array,\n b: string | Buffer | Uint8Array,\n): boolean {\n if (typeof a === \"string\" && typeof b === \"string\") {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if (\n (a instanceof Buffer || a instanceof Uint8Array) &&\n (b instanceof Buffer || b instanceof Uint8Array)\n ) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(\n a instanceof Buffer ? a : Buffer.from(a),\n b instanceof Buffer ? b : Buffer.from(b),\n );\n }\n\n throw new Error(\n \"Cannot compare: inputs must be strings, Buffers, or Uint8Arrays\",\n );\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(\n scrypt,\n);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {},\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || \"aes-256-gcm\";\n const inputEncoding = options.inputEncoding || \"utf8\";\n const outputEncoding = options.outputEncoding || \"hex\";\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey =\n typeof key === \"string\" ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === \"string\") {\n ciphertext = cipher.update(\n data,\n inputEncoding,\n outputEncoding as BufferEncoding,\n );\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding\n ? encrypted.toString(outputEncoding)\n : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes(\"gcm\")\n ? (cipher as any).getAuthTag()\n : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm,\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {},\n): Promise<string | Buffer> {\n const algorithm =\n options.algorithm || encryptedData.algorithm || \"aes-256-gcm\";\n const inputEncoding = options.inputEncoding || \"hex\";\n const outputEncoding = options.outputEncoding || \"utf8\";\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey =\n typeof key === \"string\"\n ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32)\n : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes(\"gcm\")) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === \"string\") {\n decrypted = decipher.update(\n encryptedData.ciphertext,\n inputEncoding as BufferEncoding,\n outputEncoding,\n );\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([\n decipher.update(encryptedData.ciphertext),\n decipher.final(),\n ]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600,\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds,\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString(\"base64url\");\n\n // Create signature\n const signature = hmac(\"sha256\", base64Payload, secret, \"base64url\");\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(\n token: string,\n secret: string,\n): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split(\".\");\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac(\"sha256\", payloadB64, secret, \"base64url\");\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\");\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,UAAU,EAEV,UAAU,EACV,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,eAAe,EAEhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAgBjC;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,WAAiC,KAAK;IAC3G,OAAO,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,WAAiC,KAAK;IAC3F,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;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AAC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QAC1E,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,iBAAiB,CAAC;YAAE,OAAO,IAAI,CAAC;QAE5D,iBAAiB;QACjB,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(randomUUID());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|
|
@@ -1,21 +1,20 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
interface Request {
|
|
3
3
|
query: any;
|
|
4
4
|
params: any;
|
|
5
5
|
body?: any;
|
|
6
6
|
[key: string]: any;
|
|
7
7
|
}
|
|
8
|
-
|
|
8
|
+
interface Response {
|
|
9
9
|
json: (body: any) => void;
|
|
10
10
|
headersSent: boolean;
|
|
11
11
|
[key: string]: any;
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
type NextFunction = (err?: any) => void;
|
|
14
|
+
type RequestHandler = (req: Request, res: Response, next: NextFunction) => any;
|
|
15
|
+
interface Router {
|
|
16
16
|
[method: string]: (path: string, ...handlers: RequestHandler[]) => void;
|
|
17
17
|
}
|
|
18
|
-
export type HttpMethod = "get" | "post" | "put" | "patch" | "delete" | "options" | "head" | "trace" | "connect";
|
|
19
18
|
export declare const Get: (path: string) => MethodDecorator;
|
|
20
19
|
export declare const Post: (path: string) => MethodDecorator;
|
|
21
20
|
export declare const Put: (path: string) => MethodDecorator;
|
|
@@ -37,4 +36,5 @@ export declare function Header(name: string, value: string): MethodDecorator;
|
|
|
37
36
|
export declare function Before(fn: Function): MethodDecorator;
|
|
38
37
|
export declare function After(fn: Function): MethodDecorator;
|
|
39
38
|
export declare function registerControllers(router: Router, controllers: any[]): void;
|
|
39
|
+
export {};
|
|
40
40
|
//# sourceMappingURL=decorators.utils.d.ts.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
2
|
-
import
|
|
2
|
+
import 'reflect-metadata';
|
|
3
3
|
// --- End sample Express interfaces ---
|
|
4
|
-
const ROUTES_KEY = Symbol(
|
|
5
|
-
const MIDDLEWARE_KEY = Symbol(
|
|
6
|
-
const PARAMS_KEY = Symbol(
|
|
4
|
+
const ROUTES_KEY = Symbol('routes');
|
|
5
|
+
const MIDDLEWARE_KEY = Symbol('middlewares');
|
|
6
|
+
const PARAMS_KEY = Symbol('params');
|
|
7
7
|
// ---- Route Decorators ----
|
|
8
8
|
function createRouteDecorator(method) {
|
|
9
9
|
return (path) => {
|
|
@@ -12,25 +12,25 @@ function createRouteDecorator(method) {
|
|
|
12
12
|
routes.push({
|
|
13
13
|
path,
|
|
14
14
|
method,
|
|
15
|
-
handlerName: propertyKey
|
|
15
|
+
handlerName: propertyKey
|
|
16
16
|
});
|
|
17
17
|
Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);
|
|
18
18
|
};
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
|
-
export const Get = createRouteDecorator(
|
|
22
|
-
export const Post = createRouteDecorator(
|
|
23
|
-
export const Put = createRouteDecorator(
|
|
24
|
-
export const Patch = createRouteDecorator(
|
|
25
|
-
export const Delete = createRouteDecorator(
|
|
26
|
-
export const Options = createRouteDecorator(
|
|
27
|
-
export const Head = createRouteDecorator(
|
|
28
|
-
export const Trace = createRouteDecorator(
|
|
29
|
-
export const Connect = createRouteDecorator(
|
|
21
|
+
export const Get = createRouteDecorator('get');
|
|
22
|
+
export const Post = createRouteDecorator('post');
|
|
23
|
+
export const Put = createRouteDecorator('put');
|
|
24
|
+
export const Patch = createRouteDecorator('patch');
|
|
25
|
+
export const Delete = createRouteDecorator('delete');
|
|
26
|
+
export const Options = createRouteDecorator('options');
|
|
27
|
+
export const Head = createRouteDecorator('head');
|
|
28
|
+
export const Trace = createRouteDecorator('trace');
|
|
29
|
+
export const Connect = createRouteDecorator('connect');
|
|
30
30
|
// ---- Controller Decorator ----
|
|
31
31
|
export function Controller(basePath) {
|
|
32
|
-
return
|
|
33
|
-
Reflect.defineMetadata(
|
|
32
|
+
return target => {
|
|
33
|
+
Reflect.defineMetadata('basePath', basePath, target);
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
36
|
// ---- Middleware Decorator ----
|
|
@@ -52,20 +52,20 @@ function createParamDecorator(type, key) {
|
|
|
52
52
|
};
|
|
53
53
|
};
|
|
54
54
|
}
|
|
55
|
-
export const Query = createParamDecorator(
|
|
56
|
-
export const Param = createParamDecorator(
|
|
57
|
-
export const Body = createParamDecorator(
|
|
58
|
-
export const Req = createParamDecorator(
|
|
59
|
-
export const Res = createParamDecorator(
|
|
55
|
+
export const Query = createParamDecorator('query');
|
|
56
|
+
export const Param = createParamDecorator('param');
|
|
57
|
+
export const Body = createParamDecorator('body');
|
|
58
|
+
export const Req = createParamDecorator('req');
|
|
59
|
+
export const Res = createParamDecorator('res');
|
|
60
60
|
// Custom HTTP status code decorator
|
|
61
|
-
const HTTP_CODE_KEY = Symbol(
|
|
61
|
+
const HTTP_CODE_KEY = Symbol('httpCode');
|
|
62
62
|
export function HttpCode(status) {
|
|
63
63
|
return (target, propertyKey, descriptor) => {
|
|
64
64
|
Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey);
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
// Custom header decorator
|
|
68
|
-
const HEADER_KEY = Symbol(
|
|
68
|
+
const HEADER_KEY = Symbol('headers');
|
|
69
69
|
export function Header(name, value) {
|
|
70
70
|
return (target, propertyKey, descriptor) => {
|
|
71
71
|
const headers = Reflect.getMetadata(HEADER_KEY, target, propertyKey) || {};
|
|
@@ -74,8 +74,8 @@ export function Header(name, value) {
|
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
76
|
// Before/After hooks (not Express middleware, but can be used for logging, etc.)
|
|
77
|
-
const BEFORE_KEY = Symbol(
|
|
78
|
-
const AFTER_KEY = Symbol(
|
|
77
|
+
const BEFORE_KEY = Symbol('before');
|
|
78
|
+
const AFTER_KEY = Symbol('after');
|
|
79
79
|
export function Before(fn) {
|
|
80
80
|
return (target, propertyKey, descriptor) => {
|
|
81
81
|
const hooks = Reflect.getMetadata(BEFORE_KEY, target, propertyKey) || [];
|
|
@@ -92,9 +92,9 @@ export function After(fn) {
|
|
|
92
92
|
}
|
|
93
93
|
// ---- Register Controllers ----
|
|
94
94
|
export function registerControllers(router, controllers) {
|
|
95
|
-
controllers.forEach(
|
|
95
|
+
controllers.forEach(ControllerClass => {
|
|
96
96
|
const instance = new ControllerClass();
|
|
97
|
-
const basePath = Reflect.getMetadata(
|
|
97
|
+
const basePath = Reflect.getMetadata('basePath', ControllerClass) || '';
|
|
98
98
|
const routes = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];
|
|
99
99
|
routes.forEach(({ path, method, handlerName }) => {
|
|
100
100
|
const middlewares = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];
|
|
@@ -113,19 +113,19 @@ export function registerControllers(router, controllers) {
|
|
|
113
113
|
params.forEach(({ index, type, key }) => {
|
|
114
114
|
var _a;
|
|
115
115
|
switch (type) {
|
|
116
|
-
case
|
|
116
|
+
case 'query':
|
|
117
117
|
args[index] = key ? req.query[key] : req.query;
|
|
118
118
|
break;
|
|
119
|
-
case
|
|
119
|
+
case 'param':
|
|
120
120
|
args[index] = key ? req.params[key] : req.params;
|
|
121
121
|
break;
|
|
122
|
-
case
|
|
122
|
+
case 'body':
|
|
123
123
|
args[index] = key ? (_a = req.body) === null || _a === void 0 ? void 0 : _a[key] : req.body;
|
|
124
124
|
break;
|
|
125
|
-
case
|
|
125
|
+
case 'req':
|
|
126
126
|
args[index] = req;
|
|
127
127
|
break;
|
|
128
|
-
case
|
|
128
|
+
case 'res':
|
|
129
129
|
args[index] = res;
|
|
130
130
|
break;
|
|
131
131
|
}
|
|
@@ -134,7 +134,7 @@ export function registerControllers(router, controllers) {
|
|
|
134
134
|
const result = instance[handlerName](...args);
|
|
135
135
|
// Support both sync and async handlers
|
|
136
136
|
const awaited = result instanceof Promise ? await result : result;
|
|
137
|
-
if (!res.headersSent && typeof awaited !==
|
|
137
|
+
if (!res.headersSent && typeof awaited !== 'undefined') {
|
|
138
138
|
if (httpCode)
|
|
139
139
|
(_a = res.status) === null || _a === void 0 ? void 0 : _a.call(res, httpCode);
|
|
140
140
|
for (const [k, v] of Object.entries(headers))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAEtD,OAAO,kBAAkB,CAAC;AAuB1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAyBpC,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GACV,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;Y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ACD,MAAM,MAAM,GAAI,QAAgB,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;oBACvD,uCAAuC;oBACvC,MAAM,OAAO,GAAG,MAAM,YAAY,OAAO,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;oBAClE,IAAI,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;wBACvD,IAAI,QAAQ;4BAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;wBACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport \"reflect-metadata\";\n\n// --- Sample Express interfaces for type safety ---\nexport interface Request {\n query: any;\n params: any;\n body?: any;\n [key: string]: any;\n}\nexport interface Response {\n json: (body: any) => void;\n headersSent: boolean;\n [key: string]: any;\n}\nexport type NextFunction = (err?: any) => void;\nexport type RequestHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => any;\nexport interface Router {\n [method: string]: (path: string, ...handlers: RequestHandler[]) => void;\n}\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol(\"routes\");\nconst MIDDLEWARE_KEY = Symbol(\"middlewares\");\nconst PARAMS_KEY = Symbol(\"params\");\n\nexport type HttpMethod =\n | \"get\"\n | \"post\"\n | \"put\"\n | \"patch\"\n | \"delete\"\n | \"options\"\n | \"head\"\n | \"trace\"\n | \"connect\";\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: \"query\" | \"param\" | \"body\" | \"req\" | \"res\";\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] =\n Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string,\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator(\"get\");\nexport const Post = createRouteDecorator(\"post\");\nexport const Put = createRouteDecorator(\"put\");\nexport const Patch = createRouteDecorator(\"patch\");\nexport const Delete = createRouteDecorator(\"delete\");\nexport const Options = createRouteDecorator(\"options\");\nexport const Head = createRouteDecorator(\"head\");\nexport const Trace = createRouteDecorator(\"trace\");\nexport const Connect = createRouteDecorator(\"connect\");\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(\"basePath\", basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] =\n Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(\n MIDDLEWARE_KEY,\n [...existing, ...middlewares],\n target,\n propertyKey as string,\n );\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition[\"type\"], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] =\n Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator(\"query\");\nexport const Param = createParamDecorator(\"param\");\nexport const Body = createParamDecorator(\"body\");\nexport const Req = createParamDecorator(\"req\");\nexport const Res = createParamDecorator(\"res\");\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol(\"httpCode\");\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(\n HTTP_CODE_KEY,\n status,\n target,\n propertyKey as string,\n );\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol(\"headers\");\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> =\n Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol(\"before\");\nconst AFTER_KEY = Symbol(\"after\");\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] =\n Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] =\n Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach((ControllerClass) => {\n const instance = new ControllerClass();\n const basePath: string =\n Reflect.getMetadata(\"basePath\", ControllerClass) || \"\";\n const routes: RouteDefinition[] =\n Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] =\n Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] =\n Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(\n HTTP_CODE_KEY,\n instance,\n handlerName,\n );\n const headers: Record<string, string> =\n Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] =\n Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] =\n Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case \"query\":\n args[index] = key ? req.query[key] : req.query;\n break;\n case \"param\":\n args[index] = key ? req.params[key] : req.params;\n break;\n case \"body\":\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case \"req\":\n args[index] = req;\n break;\n case \"res\":\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== \"undefined\") {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decorators.utils.js","sourceRoot":"","s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AC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport 'reflect-metadata';\n\n// --- Sample Express interfaces for type safety ---\ninterface Request {\n query: any;\n params: any;\n body?: any;\n [key: string]: any;\n}\ninterface Response {\n json: (body: any) => void;\n headersSent: boolean;\n [key: string]: any;\n}\ntype NextFunction = (err?: any) => void;\ntype RequestHandler = (req: Request, res: Response, next: NextFunction) => any;\ninterface Router {\n [method: string]: (path: string, ...handlers: RequestHandler[]) => void;\n}\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import fs from
|
|
1
|
+
import fs from 'fs';
|
|
2
2
|
/**
|
|
3
3
|
* Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
|
|
4
4
|
*
|
|
@@ -72,7 +72,7 @@ export declare function getDirSize(dirPath: string): Promise<number>;
|
|
|
72
72
|
* @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
|
|
73
73
|
* @returns {() => void} A function to stop watching the directory.
|
|
74
74
|
*/
|
|
75
|
-
export declare function watchDir(dirPath: string, callback: (eventType:
|
|
75
|
+
export declare function watchDir(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string | null) => void): () => void;
|
|
76
76
|
/**
|
|
77
77
|
* Finds files matching a glob pattern.
|
|
78
78
|
*
|
|
@@ -161,7 +161,7 @@ export declare function findInDir(dirPath: string, predicate: (path: string, sta
|
|
|
161
161
|
* @returns {Promise<() => void>} A function to stop watching the directory.
|
|
162
162
|
* @throws {Error} If directory cannot be watched.
|
|
163
163
|
*/
|
|
164
|
-
export declare function watchDirRecursive(dirPath: string, callback: (eventType:
|
|
164
|
+
export declare function watchDirRecursive(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string) => void, includeSubdirs?: boolean): Promise<() => void>;
|
|
165
165
|
/**
|
|
166
166
|
* Gets detailed directory statistics including file count, directory count, and size.
|
|
167
167
|
*
|
|
@@ -191,6 +191,6 @@ export declare function walkDir(dirPath: string, options: {
|
|
|
191
191
|
isDirectory: boolean;
|
|
192
192
|
stats: fs.Stats;
|
|
193
193
|
}) => boolean | void | Promise<boolean | void>;
|
|
194
|
-
traversalOrder?:
|
|
194
|
+
traversalOrder?: 'pre' | 'post';
|
|
195
195
|
}): Promise<void>;
|
|
196
196
|
//# sourceMappingURL=dir.utils.d.ts.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import os from
|
|
2
|
-
import fs from
|
|
3
|
-
import fsp from
|
|
4
|
-
import path from
|
|
5
|
-
import { glob } from
|
|
6
|
-
import { randomBytes } from
|
|
1
|
+
import os from 'os';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import fsp from 'fs/promises';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { glob } from 'glob';
|
|
6
|
+
import { randomBytes } from 'crypto';
|
|
7
7
|
/**
|
|
8
8
|
* Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
|
|
9
9
|
*
|
|
@@ -175,11 +175,9 @@ export async function findFilesByPattern(pattern, options = {}) {
|
|
|
175
175
|
*/
|
|
176
176
|
export async function getSubdirectories(dirPath, recursive = false) {
|
|
177
177
|
const entries = await fsp.readdir(dirPath, { withFileTypes: true });
|
|
178
|
-
const dirs = entries
|
|
179
|
-
.filter((entry) => entry.isDirectory())
|
|
180
|
-
.map((entry) => path.join(dirPath, entry.name));
|
|
178
|
+
const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));
|
|
181
179
|
if (recursive && dirs.length > 0) {
|
|
182
|
-
const nestedDirs = await Promise.all(dirs.map(
|
|
180
|
+
const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));
|
|
183
181
|
return [...dirs, ...nestedDirs.flat()];
|
|
184
182
|
}
|
|
185
183
|
return dirs;
|
|
@@ -201,7 +199,7 @@ export async function ensureEmptyDir(dirPath) {
|
|
|
201
199
|
}
|
|
202
200
|
catch (error) {
|
|
203
201
|
// Ignore if file doesn't exist
|
|
204
|
-
if (error.code !==
|
|
202
|
+
if (error.code !== 'ENOENT') {
|
|
205
203
|
throw error;
|
|
206
204
|
}
|
|
207
205
|
}
|
|
@@ -219,9 +217,9 @@ export async function ensureEmptyDir(dirPath) {
|
|
|
219
217
|
* @throws {Error} If directory cannot be created.
|
|
220
218
|
*/
|
|
221
219
|
export async function createTempDir(options = {}) {
|
|
222
|
-
const prefix = options.prefix ||
|
|
220
|
+
const prefix = options.prefix || 'tmp-';
|
|
223
221
|
const parentDir = options.parentDir || os.tmpdir();
|
|
224
|
-
const dirName = `${prefix}${randomBytes(6).toString(
|
|
222
|
+
const dirName = `${prefix}${randomBytes(6).toString('hex')}`;
|
|
225
223
|
const tempDirPath = path.join(parentDir, dirName);
|
|
226
224
|
await ensureDir(tempDirPath);
|
|
227
225
|
const cleanup = async () => {
|
|
@@ -233,7 +231,7 @@ export async function createTempDir(options = {}) {
|
|
|
233
231
|
}
|
|
234
232
|
};
|
|
235
233
|
if (options.cleanup) {
|
|
236
|
-
process.once(
|
|
234
|
+
process.once('exit', () => {
|
|
237
235
|
try {
|
|
238
236
|
fs.rmSync(tempDirPath, { recursive: true, force: true });
|
|
239
237
|
}
|
|
@@ -242,7 +240,7 @@ export async function createTempDir(options = {}) {
|
|
|
242
240
|
}
|
|
243
241
|
});
|
|
244
242
|
// Handle signals for better cleanup
|
|
245
|
-
[
|
|
243
|
+
['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {
|
|
246
244
|
process.once(signal, () => {
|
|
247
245
|
cleanup().then(() => process.exit());
|
|
248
246
|
});
|
|
@@ -264,7 +262,7 @@ export async function findNewestFile(dirPath, recursive = false) {
|
|
|
264
262
|
return null;
|
|
265
263
|
const stats = await Promise.all(files.map(async (file) => ({
|
|
266
264
|
path: file,
|
|
267
|
-
mtime: (await fsp.stat(file)).mtime
|
|
265
|
+
mtime: (await fsp.stat(file)).mtime
|
|
268
266
|
})));
|
|
269
267
|
return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;
|
|
270
268
|
}
|
|
@@ -282,7 +280,7 @@ export async function findOldestFile(dirPath, recursive = false) {
|
|
|
282
280
|
return null;
|
|
283
281
|
const stats = await Promise.all(files.map(async (file) => ({
|
|
284
282
|
path: file,
|
|
285
|
-
mtime: (await fsp.stat(file)).mtime
|
|
283
|
+
mtime: (await fsp.stat(file)).mtime
|
|
286
284
|
})));
|
|
287
285
|
return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;
|
|
288
286
|
}
|
|
@@ -336,7 +334,7 @@ export async function watchDirRecursive(dirPath, callback, includeSubdirs = true
|
|
|
336
334
|
const relativePath = path.relative(normalizedBasePath, fullPath);
|
|
337
335
|
callback(eventType, relativePath);
|
|
338
336
|
// If a new directory is created, we should watch it
|
|
339
|
-
if (eventType ===
|
|
337
|
+
if (eventType === 'rename' && includeSubdirs) {
|
|
340
338
|
setTimeout(async () => {
|
|
341
339
|
try {
|
|
342
340
|
if (await isDirectory(fullPath)) {
|
|
@@ -366,7 +364,7 @@ export async function watchDirRecursive(dirPath, callback, includeSubdirs = true
|
|
|
366
364
|
}
|
|
367
365
|
// Return a function to close all watchers
|
|
368
366
|
return () => {
|
|
369
|
-
watchers.forEach(
|
|
367
|
+
watchers.forEach(watcher => watcher.close());
|
|
370
368
|
};
|
|
371
369
|
}
|
|
372
370
|
/**
|
|
@@ -409,7 +407,7 @@ export async function getDirStats(dirPath) {
|
|
|
409
407
|
* @throws {Error} If directory cannot be read.
|
|
410
408
|
*/
|
|
411
409
|
export async function walkDir(dirPath, options) {
|
|
412
|
-
const traversalOrder = options.traversalOrder ||
|
|
410
|
+
const traversalOrder = options.traversalOrder || 'pre';
|
|
413
411
|
const entries = await fsp.readdir(dirPath, { withFileTypes: true });
|
|
414
412
|
for (const entry of entries) {
|
|
415
413
|
const entryPath = path.join(dirPath, entry.name);
|
|
@@ -418,11 +416,11 @@ export async function walkDir(dirPath, options) {
|
|
|
418
416
|
path: entryPath,
|
|
419
417
|
name: entry.name,
|
|
420
418
|
isDirectory: entry.isDirectory(),
|
|
421
|
-
stats
|
|
419
|
+
stats
|
|
422
420
|
};
|
|
423
421
|
if (entry.isDirectory()) {
|
|
424
422
|
// Pre-order: visit directory before its contents
|
|
425
|
-
if (traversalOrder ===
|
|
423
|
+
if (traversalOrder === 'pre') {
|
|
426
424
|
const shouldContinue = await options.visitorFn(entryInfo);
|
|
427
425
|
// If the visitor returns false, don't recurse into this directory
|
|
428
426
|
if (shouldContinue !== false) {
|
|
@@ -440,7 +438,7 @@ export async function walkDir(dirPath, options) {
|
|
|
440
438
|
await options.visitorFn(entryInfo);
|
|
441
439
|
}
|
|
442
440
|
}
|
|
443
|
-
if (traversalOrder ===
|
|
441
|
+
if (traversalOrder === 'post') {
|
|
444
442
|
// Only visit the root if this is the top-level call (not for subdirectories)
|
|
445
443
|
// But since this function is always called recursively, always visit after children
|
|
446
444
|
const stats = await fsp.stat(dirPath);
|
|
@@ -448,7 +446,7 @@ export async function walkDir(dirPath, options) {
|
|
|
448
446
|
path: dirPath,
|
|
449
447
|
name: path.basename(dirPath),
|
|
450
448
|
isDirectory: true,
|
|
451
|
-
stats
|
|
449
|
+
stats
|
|
452
450
|
};
|
|
453
451
|
await options.visitorFn(entryInfo);
|
|
454
452
|
}
|