UNPKG

@catbee/utils

Version:

A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.

214 lines (210 loc) 8.67 kB
/* * The MIT License * * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import pino, { Logger as Logger$1 } from 'pino'; /** * Logger type for application-wide logging. */ type Logger = Logger$1; /** * Logger levels for application-wide logging. */ type LoggerLevels = pino.Level; declare const defaultSensitiveFields: string[]; /** * Sets the global redaction censor function used throughout the application for log redaction. * * Use this function to customize how sensitive data is redacted in logs. The provided function * will replace the default censor implementation. * * @example * ```typescript * // Custom censor that redacts only specific values * setRedactCensor((value, path, sensitiveFields) => { * if (path.includes('password')) return '***'; * return value; * }); * ``` * * @param fn - The redaction censor function to use globally. This function receives: * - value: The data value to potentially redact * - path: Array of strings representing the path to the value in the object * - sensitiveFields: Optional array of field names to consider sensitive * @returns void */ declare function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string): void; /** * Gets the current global redaction censor function used for log redaction. * * This function is called internally by the logger when determining how to redact * sensitive information. It can also be used to access the current censor implementation * for composition or extension. * * @example * ```typescript * const currentCensor = getRedactCensor(); * // Create an enhanced censor that extends the current one * setRedactCensor((value, path, fields) => { * // Add custom logic before delegating to current censor * if (someCondition) return customHandling(); * return currentCensor(value, path, fields); * }); * ``` * * @returns The current redaction censor function */ declare function getRedactCensor(): (value: unknown, path: string[], sensitiveFields?: string[]) => string; /** * Convenience function to redact sensitive data using the current global redact censor. * * This is a direct wrapper around the global censor function that simplifies usage * in application code without needing to access the censor function directly. * * @example * ```typescript * // Redact a potential sensitive value * const safeValue = redact(value, ['user', 'apiKey']); * ``` * * @param value - The value to potentially redact * @param path - Array of strings representing the path to the value in the object * @param sensitiveFields - Optional array of field names to consider sensitive * @returns The redacted string value or "***" for redacted content */ declare function redact(value: unknown, path: string[], sensitiveFields?: string[]): string; /** * @deprecated Use addSensitiveFields instead. * * Extends the current redaction function with additional fields to redact. * * This function wraps the existing censor while adding more fields to be considered * sensitive without replacing the entire redaction logic. * * @example * ```typescript * // Add custom fields to be redacted in all future redaction operations * addRedactFields(['customerId', 'accountNumber']); * ``` * * @param fields - Array of additional field names to redact */ declare function addRedactFields(fields: string[]): void; /** * Retrieves the expanded list of sensitive fields. * * This function expands the default sensitive fields into their various naming * conventions (e.g., camelCase, snake_case) and caches the result for efficiency. * * @returns Array of expanded sensitive field names */ declare function getExpandedSensitiveFields(): string[]; /** * Replaces the default list of sensitive fields with a new list. * * This is useful when you want complete control over what fields are considered * sensitive by default, rather than using the library's built-in list. * * @example * ```typescript * // Replace default sensitive fields with a custom list * setSensitiveFields(['password', 'ssn', 'creditCard']); * ``` * * @param fields - Array of field names to set as the new default sensitive fields */ declare function setSensitiveFields(fields: string[]): void; /** * Adds additional field names to the default sensitive fields list. * * This preserves the existing sensitive fields while adding new ones for * application-specific sensitive data. * * @example * ```typescript * // Add domain-specific sensitive fields to the default list * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']); * ``` * * @param fields - Array of additional field names to add to the sensitive fields list */ declare function addSensitiveFields(fields: string[]): void; /** * Use an object compatible with either modern or legacy global scopes. */ declare const _globalThis: typeof globalThis; /** * Retrieves the current logger instance: * - Returns a request-scoped logger from AsyncLocalStorage if available * - Falls back to the global (singleton) logger * - Initializes the global logger if not created yet * - If newInstance is true, returns a fresh logger without any context * * @param {boolean} newInstance - If true, returns a fresh logger without any context * @returns {Logger} The logger instance (request-bound or global root logger or fresh instance) */ declare function getLogger(newInstance?: boolean): Logger$1; /** * Creates a child logger with additional context. * * @param {Record<string, any>} bindings - Properties to attach to all log records * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global) * @returns {Logger} Child logger with merged context */ declare function createChildLogger(bindings: Record<string, any>, parentLogger?: Logger$1): Logger$1; /** * Creates a request-scoped logger with request ID and stores it in context * * @param {string} requestId - Unique request identifier * @param {object} [additionalContext] - Additional context to include in logs * @returns {Logger} Request-scoped logger instance */ declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): Logger$1; /** * Utility to safely log errors with proper stack trace extraction * * @param {Error|unknown} error - Error object to log * @param {string} [message] - Optional message to include * @param {Record<string, any>} [context] - Additional context properties */ declare function logError(error: Error | string, message?: string, context?: Record<string, any>): void; /** * Expands multiple sensitive field names into their variants. * Useful to match fields like `api_key`, `apiKey`, `apikey`, `APIKEY`, etc. */ declare function expandSensitiveFields(fields: string[]): string[]; /** * Generates multiple variants of a sensitive field name. * Useful to match fields like `api_key`, `apiKey`, `apikey`, `APIKEY`, etc. */ declare function expandSensitiveField(field: string): string[]; /** * Generates wildcard paths up to the given depth. * * depth = 2 -> * password * *.password * *.*.password */ declare function generateDeepPaths(field: string, depth: number): string[]; export { _globalThis, addRedactFields, addSensitiveFields, createChildLogger, createRequestLogger, defaultSensitiveFields, expandSensitiveField, expandSensitiveFields, generateDeepPaths, getExpandedSensitiveFields, getLogger, getRedactCensor, logError, redact, setRedactCensor, setSensitiveFields }; export type { Logger, LoggerLevels };