@catbee/utils 0.0.5 → 0.0.7
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/LICENSE +21 -201
- package/README.md +51 -888
- package/build/esm/config.d.ts +84 -7
- package/build/esm/config.js +89 -5
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +4 -0
- package/build/esm/index.js +27 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/servers/server.builder.d.ts +508 -0
- package/build/esm/servers/server.builder.js +702 -0
- package/build/esm/servers/server.builder.js.map +1 -0
- package/build/esm/servers/server.d.ts +256 -0
- package/build/esm/servers/server.js +1201 -0
- package/build/esm/servers/server.js.map +1 -0
- package/build/esm/types/api-response.d.ts +33 -7
- package/build/esm/types/api-response.js +33 -1
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/types/index.d.ts +125 -0
- package/build/esm/types/index.js +25 -0
- package/build/esm/types/index.js.map +1 -0
- package/build/esm/types/server.d.ts +268 -0
- package/build/esm/types/server.js +25 -0
- package/build/esm/types/server.js.map +1 -0
- package/build/esm/utils/array.utils.js +23 -0
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +91 -0
- package/build/esm/utils/async.utils.js +267 -0
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +23 -0
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +3 -0
- package/build/esm/utils/context-store.utils.js +32 -6
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +23 -0
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/date.utils.d.ts +159 -0
- package/build/esm/utils/date.utils.js +389 -0
- package/build/esm/utils/date.utils.js.map +1 -0
- package/build/esm/utils/decorators.utils.js +23 -1
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.js +23 -0
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.js +23 -0
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +31 -8
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.js +23 -0
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js +23 -0
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +23 -0
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +5 -0
- package/build/esm/utils/logger.utils.js +40 -3
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +2 -0
- package/build/esm/utils/middleware.utils.js +61 -50
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.d.ts +10 -3
- package/build/esm/utils/obj.utils.js +225 -15
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/performance.utils.d.ts +136 -0
- package/build/esm/utils/performance.utils.js +376 -0
- package/build/esm/utils/performance.utils.js.map +1 -0
- package/build/esm/utils/request.utils.d.ts +9 -0
- package/build/esm/utils/request.utils.js +55 -5
- package/build/esm/utils/request.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +15 -1
- package/build/esm/utils/response.utils.js +51 -0
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/stream.utils.d.ts +88 -0
- package/build/esm/utils/stream.utils.js +284 -0
- package/build/esm/utils/stream.utils.js.map +1 -0
- package/build/esm/utils/string.utils.js +23 -0
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/type.utils.d.ts +90 -0
- package/build/esm/utils/type.utils.js +190 -0
- package/build/esm/utils/type.utils.js.map +1 -0
- package/build/esm/utils/url.utils.js +23 -0
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +7 -0
- package/build/esm/utils/validate.utils.js +35 -2
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +84 -7
- package/build/esnext/config.js +89 -5
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +4 -0
- package/build/esnext/index.js +27 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/servers/server.builder.d.ts +508 -0
- package/build/esnext/servers/server.builder.js +657 -0
- package/build/esnext/servers/server.builder.js.map +1 -0
- package/build/esnext/servers/server.d.ts +256 -0
- package/build/esnext/servers/server.js +908 -0
- package/build/esnext/servers/server.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +33 -7
- package/build/esnext/types/api-response.js +33 -1
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/types/index.d.ts +125 -0
- package/build/esnext/types/index.js +25 -0
- package/build/esnext/types/index.js.map +1 -0
- package/build/esnext/types/server.d.ts +268 -0
- package/build/esnext/types/server.js +25 -0
- package/build/esnext/types/server.js.map +1 -0
- package/build/esnext/utils/array.utils.js +23 -0
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +91 -0
- package/build/esnext/utils/async.utils.js +213 -0
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +23 -0
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +3 -0
- package/build/esnext/utils/context-store.utils.js +32 -6
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +23 -0
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/date.utils.d.ts +159 -0
- package/build/esnext/utils/date.utils.js +384 -0
- package/build/esnext/utils/date.utils.js.map +1 -0
- package/build/esnext/utils/decorators.utils.js +23 -1
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.js +23 -0
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.js +23 -0
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +30 -7
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.js +23 -0
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js +23 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +23 -0
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +5 -0
- package/build/esnext/utils/logger.utils.js +40 -3
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +2 -0
- package/build/esnext/utils/middleware.utils.js +57 -50
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.d.ts +10 -3
- package/build/esnext/utils/obj.utils.js +176 -12
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/performance.utils.d.ts +136 -0
- package/build/esnext/utils/performance.utils.js +271 -0
- package/build/esnext/utils/performance.utils.js.map +1 -0
- package/build/esnext/utils/request.utils.d.ts +9 -0
- package/build/esnext/utils/request.utils.js +46 -5
- package/build/esnext/utils/request.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +15 -1
- package/build/esnext/utils/response.utils.js +51 -0
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/stream.utils.d.ts +88 -0
- package/build/esnext/utils/stream.utils.js +210 -0
- package/build/esnext/utils/stream.utils.js.map +1 -0
- package/build/esnext/utils/string.utils.js +23 -0
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/type.utils.d.ts +90 -0
- package/build/esnext/utils/type.utils.js +187 -0
- package/build/esnext/utils/type.utils.js.map +1 -0
- package/build/esnext/utils/url.utils.js +23 -0
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +7 -0
- package/build/esnext/utils/validate.utils.js +33 -0
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +84 -7
- package/build/src/config.js +90 -6
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +4 -0
- package/build/src/index.js +27 -0
- package/build/src/index.js.map +1 -1
- package/build/src/servers/server.builder.d.ts +508 -0
- package/build/src/servers/server.builder.js +661 -0
- package/build/src/servers/server.builder.js.map +1 -0
- package/build/src/servers/server.d.ts +256 -0
- package/build/src/servers/server.js +948 -0
- package/build/src/servers/server.js.map +1 -0
- package/build/src/types/api-response.d.ts +33 -7
- package/build/src/types/api-response.js +34 -0
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/types/index.d.ts +125 -0
- package/build/src/types/index.js +26 -0
- package/build/src/types/index.js.map +1 -0
- package/build/src/types/server.d.ts +268 -0
- package/build/src/types/server.js +26 -0
- package/build/src/types/server.js.map +1 -0
- package/build/src/utils/array.utils.js +23 -0
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +91 -0
- package/build/src/utils/async.utils.js +217 -0
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +23 -0
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +3 -0
- package/build/src/utils/context-store.utils.js +32 -6
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +23 -0
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/date.utils.d.ts +159 -0
- package/build/src/utils/date.utils.js +396 -0
- package/build/src/utils/date.utils.js.map +1 -0
- package/build/src/utils/decorators.utils.js +23 -1
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.js +23 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.js +23 -0
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +30 -7
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.js +23 -0
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js +23 -0
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +23 -0
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +5 -0
- package/build/src/utils/logger.utils.js +41 -4
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +2 -0
- package/build/src/utils/middleware.utils.js +56 -49
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.d.ts +10 -3
- package/build/src/utils/obj.utils.js +177 -12
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/performance.utils.d.ts +136 -0
- package/build/src/utils/performance.utils.js +278 -0
- package/build/src/utils/performance.utils.js.map +1 -0
- package/build/src/utils/request.utils.d.ts +9 -0
- package/build/src/utils/request.utils.js +48 -5
- package/build/src/utils/request.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +15 -1
- package/build/src/utils/response.utils.js +52 -0
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/stream.utils.d.ts +88 -0
- package/build/src/utils/stream.utils.js +218 -0
- package/build/src/utils/stream.utils.js.map +1 -0
- package/build/src/utils/string.utils.js +23 -0
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/type.utils.d.ts +90 -0
- package/build/src/utils/type.utils.js +196 -0
- package/build/src/utils/type.utils.js.map +1 -0
- package/build/src/utils/url.utils.js +23 -0
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +7 -0
- package/build/src/utils/validate.utils.js +36 -2
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +39 -9
|
@@ -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,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,M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ryToTextEncoding,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\nimport { uuid } from './id.utils';\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(uuid());\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
|
+
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AAI,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":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\nimport { uuid } from './id.utils';\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(uuid());\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"]}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Format options for the formatDate function
|
|
3
|
+
*/
|
|
4
|
+
export interface DateFormatOptions {
|
|
5
|
+
/** Date format pattern (default: 'yyyy-MM-dd') */
|
|
6
|
+
format?: string;
|
|
7
|
+
/** Locale to use for formatting (default: system locale) */
|
|
8
|
+
locale?: string | string[];
|
|
9
|
+
/** Time zone to use (default: system time zone) */
|
|
10
|
+
timeZone?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Format a date according to the specified format pattern.
|
|
14
|
+
*
|
|
15
|
+
* @param date - Date to format
|
|
16
|
+
* @param options - Formatting options
|
|
17
|
+
* @returns Formatted date string
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* // Format as ISO date
|
|
22
|
+
* formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
|
|
23
|
+
*
|
|
24
|
+
* // Format with time
|
|
25
|
+
* formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
|
|
26
|
+
*
|
|
27
|
+
* // Format with locale
|
|
28
|
+
* formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function formatDate(date: Date | number, options?: DateFormatOptions): string;
|
|
32
|
+
/**
|
|
33
|
+
* Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
|
|
34
|
+
*
|
|
35
|
+
* @param date - Date to format
|
|
36
|
+
* @param now - Reference date (default: current time)
|
|
37
|
+
* @param locale - Locale to use for formatting
|
|
38
|
+
* @returns Formatted relative time string
|
|
39
|
+
*/
|
|
40
|
+
export declare function formatRelativeTime(date: Date | number, now?: Date | number, locale?: string | string[]): string;
|
|
41
|
+
/**
|
|
42
|
+
* Parse a date string or timestamp into a Date object.
|
|
43
|
+
*
|
|
44
|
+
* @param input - Date string or timestamp to parse
|
|
45
|
+
* @param fallback - Fallback date if parsing fails
|
|
46
|
+
* @returns Parsed Date object or fallback
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```typescript
|
|
50
|
+
* parseDate('2023-05-15'); // Date object for May 15, 2023
|
|
51
|
+
* parseDate('invalid', new Date()); // Returns current date as fallback
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export declare function parseDate(input: string | number, fallback?: Date): Date | null;
|
|
55
|
+
/**
|
|
56
|
+
* Calculate the difference between two dates in the specified unit.
|
|
57
|
+
*
|
|
58
|
+
* @param date1 - First date
|
|
59
|
+
* @param date2 - Second date (default: current time)
|
|
60
|
+
* @param unit - Unit of time for the difference
|
|
61
|
+
* @returns Difference in the specified unit
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* // Get difference in days
|
|
66
|
+
* dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
|
|
67
|
+
*
|
|
68
|
+
* // Get difference in hours
|
|
69
|
+
* dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
export declare function dateDiff(date1: Date | number, date2?: Date | number, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number;
|
|
73
|
+
/**
|
|
74
|
+
* Add a specified amount of time to a date.
|
|
75
|
+
*
|
|
76
|
+
* @param date - Base date
|
|
77
|
+
* @param amount - Amount to add (can be negative)
|
|
78
|
+
* @param unit - Unit of time to add
|
|
79
|
+
* @returns New date with the addition
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```typescript
|
|
83
|
+
* // Add 5 days
|
|
84
|
+
* addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
|
|
85
|
+
*
|
|
86
|
+
* // Subtract 2 hours
|
|
87
|
+
* addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export declare function addToDate(date: Date | number, amount: number, unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): Date;
|
|
91
|
+
/**
|
|
92
|
+
* Get the start of a time period containing the specified date.
|
|
93
|
+
*
|
|
94
|
+
* @param date - Date to get the start from
|
|
95
|
+
* @param unit - Time unit
|
|
96
|
+
* @returns Date object representing the start of the time unit
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```typescript
|
|
100
|
+
* // Get start of day (midnight)
|
|
101
|
+
* startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
|
|
102
|
+
*
|
|
103
|
+
* // Get start of month
|
|
104
|
+
* startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
export declare function startOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
|
|
108
|
+
/**
|
|
109
|
+
* Get the end of a time period containing the specified date.
|
|
110
|
+
*
|
|
111
|
+
* @param date - Date to get the end from
|
|
112
|
+
* @param unit - Time unit
|
|
113
|
+
* @returns Date object representing the end of the time unit
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* // Get end of day (23:59:59.999)
|
|
118
|
+
* endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
|
|
119
|
+
*
|
|
120
|
+
* // Get end of month
|
|
121
|
+
* endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export declare function endOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
|
|
125
|
+
/**
|
|
126
|
+
* Check if a date is between two other dates.
|
|
127
|
+
*
|
|
128
|
+
* @param date - Date to check
|
|
129
|
+
* @param start - Start date of the range
|
|
130
|
+
* @param end - End date of the range
|
|
131
|
+
* @param inclusive - Whether the comparison should be inclusive of start/end
|
|
132
|
+
* @returns True if the date is within the range
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```typescript
|
|
136
|
+
* const date = new Date('2023-05-15');
|
|
137
|
+
* const start = new Date('2023-05-10');
|
|
138
|
+
* const end = new Date('2023-05-20');
|
|
139
|
+
*
|
|
140
|
+
* isBetween(date, start, end); // true
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
export declare function isBetween(date: Date | number, start: Date | number, end: Date | number, inclusive?: boolean): boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Check if a year is a leap year.
|
|
146
|
+
*
|
|
147
|
+
* @param year - Year to check (or date object)
|
|
148
|
+
* @returns True if the year is a leap year
|
|
149
|
+
*/
|
|
150
|
+
export declare function isLeapYear(year: number | Date): boolean;
|
|
151
|
+
/**
|
|
152
|
+
* Get the number of days in a month.
|
|
153
|
+
*
|
|
154
|
+
* @param year - Year
|
|
155
|
+
* @param month - Month (0-11)
|
|
156
|
+
* @returns Number of days in the month
|
|
157
|
+
*/
|
|
158
|
+
export declare function daysInMonth(year: number | Date, month?: number): number;
|
|
159
|
+
//# sourceMappingURL=date.utils.d.ts.map
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Format a date according to the specified format pattern.
|
|
26
|
+
*
|
|
27
|
+
* @param date - Date to format
|
|
28
|
+
* @param options - Formatting options
|
|
29
|
+
* @returns Formatted date string
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```typescript
|
|
33
|
+
* // Format as ISO date
|
|
34
|
+
* formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
|
|
35
|
+
*
|
|
36
|
+
* // Format with time
|
|
37
|
+
* formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
|
|
38
|
+
*
|
|
39
|
+
* // Format with locale
|
|
40
|
+
* formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function formatDate(date, options = {}) {
|
|
44
|
+
const { format = 'yyyy-MM-dd', locale, timeZone } = options;
|
|
45
|
+
const d = date instanceof Date ? date : new Date(date);
|
|
46
|
+
// Custom formatter for common patterns
|
|
47
|
+
if (format === 'yyyy-MM-dd') {
|
|
48
|
+
const yyyy = d.getFullYear();
|
|
49
|
+
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
50
|
+
const dd = String(d.getDate()).padStart(2, '0');
|
|
51
|
+
return `${yyyy}-${mm}-${dd}`;
|
|
52
|
+
}
|
|
53
|
+
if (format === 'yyyy-MM-dd HH:mm:ss') {
|
|
54
|
+
const yyyy = d.getFullYear();
|
|
55
|
+
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
56
|
+
const dd = String(d.getDate()).padStart(2, '0');
|
|
57
|
+
const HH = String(d.getHours()).padStart(2, '0');
|
|
58
|
+
const MM = String(d.getMinutes()).padStart(2, '0');
|
|
59
|
+
const SS = String(d.getSeconds()).padStart(2, '0');
|
|
60
|
+
return `${yyyy}-${mm}-${dd} ${HH}:${MM}:${SS}`;
|
|
61
|
+
}
|
|
62
|
+
if (format === 'relative') {
|
|
63
|
+
return formatRelativeTime(date);
|
|
64
|
+
}
|
|
65
|
+
// Fallback to Intl.DateTimeFormat for other formats
|
|
66
|
+
return new Intl.DateTimeFormat(locale, {
|
|
67
|
+
timeZone,
|
|
68
|
+
year: format.includes('yyyy') || format.includes('y') ? 'numeric' : undefined,
|
|
69
|
+
month: format.includes('MM') || format.includes('M') ? 'numeric' : undefined,
|
|
70
|
+
day: format.includes('dd') || format.includes('d') ? 'numeric' : undefined,
|
|
71
|
+
hour: format.includes('HH') || format.includes('H') ? 'numeric' : undefined,
|
|
72
|
+
minute: format.includes('mm') || format.includes('m') ? 'numeric' : undefined,
|
|
73
|
+
second: format.includes('ss') || format.includes('s') ? 'numeric' : undefined,
|
|
74
|
+
hour12: !format.includes('HH') && !format.includes('H')
|
|
75
|
+
}).format(d);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
|
|
79
|
+
*
|
|
80
|
+
* @param date - Date to format
|
|
81
|
+
* @param now - Reference date (default: current time)
|
|
82
|
+
* @param locale - Locale to use for formatting
|
|
83
|
+
* @returns Formatted relative time string
|
|
84
|
+
*/
|
|
85
|
+
export function formatRelativeTime(date, now = new Date(), locale) {
|
|
86
|
+
const d1 = date instanceof Date ? date : new Date(date);
|
|
87
|
+
const d2 = now instanceof Date ? now : new Date(now);
|
|
88
|
+
const diffMs = d1.getTime() - d2.getTime();
|
|
89
|
+
const diffSecs = Math.round(diffMs / 1000);
|
|
90
|
+
const diffMins = Math.round(diffSecs / 60);
|
|
91
|
+
const diffHours = Math.round(diffMins / 60);
|
|
92
|
+
const diffDays = Math.round(diffHours / 24);
|
|
93
|
+
const diffMonths = Math.round(diffDays / 30);
|
|
94
|
+
const diffYears = Math.round(diffDays / 365);
|
|
95
|
+
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
|
|
96
|
+
if (Math.abs(diffSecs) < 60)
|
|
97
|
+
return formatter.format(diffSecs, 'second');
|
|
98
|
+
if (Math.abs(diffMins) < 60)
|
|
99
|
+
return formatter.format(diffMins, 'minute');
|
|
100
|
+
if (Math.abs(diffHours) < 24)
|
|
101
|
+
return formatter.format(diffHours, 'hour');
|
|
102
|
+
if (Math.abs(diffDays) < 30)
|
|
103
|
+
return formatter.format(diffDays, 'day');
|
|
104
|
+
if (Math.abs(diffMonths) < 12)
|
|
105
|
+
return formatter.format(diffMonths, 'month');
|
|
106
|
+
return formatter.format(diffYears, 'year');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Parse a date string or timestamp into a Date object.
|
|
110
|
+
*
|
|
111
|
+
* @param input - Date string or timestamp to parse
|
|
112
|
+
* @param fallback - Fallback date if parsing fails
|
|
113
|
+
* @returns Parsed Date object or fallback
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* parseDate('2023-05-15'); // Date object for May 15, 2023
|
|
118
|
+
* parseDate('invalid', new Date()); // Returns current date as fallback
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
export function parseDate(input, fallback) {
|
|
122
|
+
if (typeof input === 'number') {
|
|
123
|
+
return new Date(input);
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
const date = new Date(input);
|
|
127
|
+
// Check if date is valid
|
|
128
|
+
if (isNaN(date.getTime())) {
|
|
129
|
+
return fallback || null;
|
|
130
|
+
}
|
|
131
|
+
return date;
|
|
132
|
+
}
|
|
133
|
+
catch (_a) {
|
|
134
|
+
return fallback || null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Calculate the difference between two dates in the specified unit.
|
|
139
|
+
*
|
|
140
|
+
* @param date1 - First date
|
|
141
|
+
* @param date2 - Second date (default: current time)
|
|
142
|
+
* @param unit - Unit of time for the difference
|
|
143
|
+
* @returns Difference in the specified unit
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```typescript
|
|
147
|
+
* // Get difference in days
|
|
148
|
+
* dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
|
|
149
|
+
*
|
|
150
|
+
* // Get difference in hours
|
|
151
|
+
* dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
export function dateDiff(date1, date2 = new Date(), unit = 'days') {
|
|
155
|
+
const d1 = date1 instanceof Date ? date1 : new Date(date1);
|
|
156
|
+
const d2 = date2 instanceof Date ? date2 : new Date(date2);
|
|
157
|
+
const diffMs = d1.getTime() - d2.getTime();
|
|
158
|
+
switch (unit) {
|
|
159
|
+
case 'milliseconds':
|
|
160
|
+
return diffMs;
|
|
161
|
+
case 'seconds':
|
|
162
|
+
return diffMs / 1000;
|
|
163
|
+
case 'minutes':
|
|
164
|
+
return diffMs / (1000 * 60);
|
|
165
|
+
case 'hours':
|
|
166
|
+
return diffMs / (1000 * 60 * 60);
|
|
167
|
+
case 'days':
|
|
168
|
+
return diffMs / (1000 * 60 * 60 * 24);
|
|
169
|
+
case 'months':
|
|
170
|
+
return (d1.getFullYear() - d2.getFullYear()) * 12 + d1.getMonth() - d2.getMonth();
|
|
171
|
+
case 'years':
|
|
172
|
+
return d1.getFullYear() - d2.getFullYear();
|
|
173
|
+
default:
|
|
174
|
+
throw new Error(`Unsupported unit: ${unit}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Add a specified amount of time to a date.
|
|
179
|
+
*
|
|
180
|
+
* @param date - Base date
|
|
181
|
+
* @param amount - Amount to add (can be negative)
|
|
182
|
+
* @param unit - Unit of time to add
|
|
183
|
+
* @returns New date with the addition
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```typescript
|
|
187
|
+
* // Add 5 days
|
|
188
|
+
* addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
|
|
189
|
+
*
|
|
190
|
+
* // Subtract 2 hours
|
|
191
|
+
* addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
export function addToDate(date, amount, unit) {
|
|
195
|
+
const d = date instanceof Date ? new Date(date) : new Date(date);
|
|
196
|
+
switch (unit) {
|
|
197
|
+
case 'milliseconds':
|
|
198
|
+
d.setMilliseconds(d.getMilliseconds() + amount);
|
|
199
|
+
break;
|
|
200
|
+
case 'seconds':
|
|
201
|
+
d.setSeconds(d.getSeconds() + amount);
|
|
202
|
+
break;
|
|
203
|
+
case 'minutes':
|
|
204
|
+
d.setMinutes(d.getMinutes() + amount);
|
|
205
|
+
break;
|
|
206
|
+
case 'hours':
|
|
207
|
+
d.setHours(d.getHours() + amount);
|
|
208
|
+
break;
|
|
209
|
+
case 'days':
|
|
210
|
+
d.setDate(d.getDate() + amount);
|
|
211
|
+
break;
|
|
212
|
+
case 'months': {
|
|
213
|
+
const origDate = d.getDate();
|
|
214
|
+
const origMonth = d.getMonth();
|
|
215
|
+
d.setDate(1); // Prevent overflow
|
|
216
|
+
d.setMonth(origMonth + amount);
|
|
217
|
+
const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
|
|
218
|
+
d.setDate(Math.min(origDate, lastDay));
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
case 'years':
|
|
222
|
+
d.setFullYear(d.getFullYear() + amount);
|
|
223
|
+
break;
|
|
224
|
+
default:
|
|
225
|
+
throw new Error(`Unsupported unit: ${unit}`);
|
|
226
|
+
}
|
|
227
|
+
return d;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Get the start of a time period containing the specified date.
|
|
231
|
+
*
|
|
232
|
+
* @param date - Date to get the start from
|
|
233
|
+
* @param unit - Time unit
|
|
234
|
+
* @returns Date object representing the start of the time unit
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* ```typescript
|
|
238
|
+
* // Get start of day (midnight)
|
|
239
|
+
* startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
|
|
240
|
+
*
|
|
241
|
+
* // Get start of month
|
|
242
|
+
* startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
|
|
243
|
+
* ```
|
|
244
|
+
*/
|
|
245
|
+
export function startOf(date, unit) {
|
|
246
|
+
const d = date instanceof Date ? new Date(date) : new Date(date);
|
|
247
|
+
switch (unit) {
|
|
248
|
+
case 'second':
|
|
249
|
+
d.setMilliseconds(0);
|
|
250
|
+
break;
|
|
251
|
+
case 'minute':
|
|
252
|
+
d.setSeconds(0, 0);
|
|
253
|
+
break;
|
|
254
|
+
case 'hour':
|
|
255
|
+
d.setMinutes(0, 0, 0);
|
|
256
|
+
break;
|
|
257
|
+
case 'day':
|
|
258
|
+
d.setHours(0, 0, 0, 0);
|
|
259
|
+
break;
|
|
260
|
+
case 'week':
|
|
261
|
+
d.setHours(0, 0, 0, 0);
|
|
262
|
+
d.setDate(d.getDate() - d.getDay());
|
|
263
|
+
break;
|
|
264
|
+
case 'month':
|
|
265
|
+
d.setDate(1);
|
|
266
|
+
d.setHours(0, 0, 0, 0);
|
|
267
|
+
break;
|
|
268
|
+
case 'quarter':
|
|
269
|
+
d.setMonth(Math.floor(d.getMonth() / 3) * 3, 1);
|
|
270
|
+
d.setHours(0, 0, 0, 0);
|
|
271
|
+
break;
|
|
272
|
+
case 'year':
|
|
273
|
+
d.setMonth(0, 1);
|
|
274
|
+
d.setHours(0, 0, 0, 0);
|
|
275
|
+
break;
|
|
276
|
+
default:
|
|
277
|
+
throw new Error(`Unsupported unit: ${unit}`);
|
|
278
|
+
}
|
|
279
|
+
return d;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Get the end of a time period containing the specified date.
|
|
283
|
+
*
|
|
284
|
+
* @param date - Date to get the end from
|
|
285
|
+
* @param unit - Time unit
|
|
286
|
+
* @returns Date object representing the end of the time unit
|
|
287
|
+
*
|
|
288
|
+
* @example
|
|
289
|
+
* ```typescript
|
|
290
|
+
* // Get end of day (23:59:59.999)
|
|
291
|
+
* endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
|
|
292
|
+
*
|
|
293
|
+
* // Get end of month
|
|
294
|
+
* endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
|
|
295
|
+
* ```
|
|
296
|
+
*/
|
|
297
|
+
export function endOf(date, unit) {
|
|
298
|
+
const d = date instanceof Date ? new Date(date) : new Date(date);
|
|
299
|
+
switch (unit) {
|
|
300
|
+
case 'second':
|
|
301
|
+
d.setMilliseconds(999);
|
|
302
|
+
break;
|
|
303
|
+
case 'minute':
|
|
304
|
+
d.setSeconds(59, 999);
|
|
305
|
+
break;
|
|
306
|
+
case 'hour':
|
|
307
|
+
d.setMinutes(59, 59, 999);
|
|
308
|
+
break;
|
|
309
|
+
case 'day':
|
|
310
|
+
d.setHours(23, 59, 59, 999);
|
|
311
|
+
break;
|
|
312
|
+
case 'week':
|
|
313
|
+
d.setDate(d.getDate() - d.getDay() + 6);
|
|
314
|
+
d.setHours(23, 59, 59, 999);
|
|
315
|
+
break;
|
|
316
|
+
case 'month':
|
|
317
|
+
d.setMonth(d.getMonth() + 1, 0);
|
|
318
|
+
d.setHours(23, 59, 59, 999);
|
|
319
|
+
break;
|
|
320
|
+
case 'quarter':
|
|
321
|
+
d.setMonth(Math.floor(d.getMonth() / 3) * 3 + 3, 0);
|
|
322
|
+
d.setHours(23, 59, 59, 999);
|
|
323
|
+
break;
|
|
324
|
+
case 'year':
|
|
325
|
+
d.setMonth(11, 31);
|
|
326
|
+
d.setHours(23, 59, 59, 999);
|
|
327
|
+
break;
|
|
328
|
+
default:
|
|
329
|
+
throw new Error(`Unsupported unit: ${unit}`);
|
|
330
|
+
}
|
|
331
|
+
return d;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Check if a date is between two other dates.
|
|
335
|
+
*
|
|
336
|
+
* @param date - Date to check
|
|
337
|
+
* @param start - Start date of the range
|
|
338
|
+
* @param end - End date of the range
|
|
339
|
+
* @param inclusive - Whether the comparison should be inclusive of start/end
|
|
340
|
+
* @returns True if the date is within the range
|
|
341
|
+
*
|
|
342
|
+
* @example
|
|
343
|
+
* ```typescript
|
|
344
|
+
* const date = new Date('2023-05-15');
|
|
345
|
+
* const start = new Date('2023-05-10');
|
|
346
|
+
* const end = new Date('2023-05-20');
|
|
347
|
+
*
|
|
348
|
+
* isBetween(date, start, end); // true
|
|
349
|
+
* ```
|
|
350
|
+
*/
|
|
351
|
+
export function isBetween(date, start, end, inclusive = true) {
|
|
352
|
+
const d = date instanceof Date ? date.getTime() : date;
|
|
353
|
+
const s = start instanceof Date ? start.getTime() : start;
|
|
354
|
+
const e = end instanceof Date ? end.getTime() : end;
|
|
355
|
+
return inclusive ? d >= s && d <= e : d > s && d < e;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Check if a year is a leap year.
|
|
359
|
+
*
|
|
360
|
+
* @param year - Year to check (or date object)
|
|
361
|
+
* @returns True if the year is a leap year
|
|
362
|
+
*/
|
|
363
|
+
export function isLeapYear(year) {
|
|
364
|
+
const y = year instanceof Date ? year.getFullYear() : year;
|
|
365
|
+
return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Get the number of days in a month.
|
|
369
|
+
*
|
|
370
|
+
* @param year - Year
|
|
371
|
+
* @param month - Month (0-11)
|
|
372
|
+
* @returns Number of days in the month
|
|
373
|
+
*/
|
|
374
|
+
export function daysInMonth(year, month) {
|
|
375
|
+
if (year instanceof Date) {
|
|
376
|
+
month = year.getMonth();
|
|
377
|
+
year = year.getFullYear();
|
|
378
|
+
}
|
|
379
|
+
if (month === undefined) {
|
|
380
|
+
throw new Error('Month is required when year is a number');
|
|
381
|
+
}
|
|
382
|
+
return new Date(year, month + 1, 0).getDate();
|
|
383
|
+
}
|
|
384
|
+
//# sourceMappingURL=date.utils.js.map
|