@vritti/api-sdk 0.0.7 → 0.0.9

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/dist/index.d.cts CHANGED
@@ -1,9 +1,11 @@
1
1
  import * as _nestjs_common from '@nestjs/common';
2
- import { DynamicModule, OnModuleDestroy, OnModuleInit, Logger, CanActivate, ExecutionContext, ExceptionFilter, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
2
+ import { DynamicModule, OnModuleDestroy, OnModuleInit, Logger, CanActivate, ExecutionContext, ExceptionFilter, ArgumentsHost, HttpException, HttpStatus, ModuleMetadata, Type, NestModule, MiddlewareConsumer, LoggerService as LoggerService$1, NestMiddleware, NestInterceptor, CallHandler } from '@nestjs/common';
3
3
  import { ConfigService } from '@nestjs/config';
4
4
  import { Reflector } from '@nestjs/core';
5
5
  import { JwtService } from '@nestjs/jwt';
6
- import { FastifyRequest } from 'fastify';
6
+ import { FastifyRequest, FastifyReply } from 'fastify';
7
+ import { Observable } from 'rxjs';
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
9
 
8
10
  /**
9
11
  * Global authentication configuration module
@@ -1299,32 +1301,6 @@ declare class CsrfGuard implements CanActivate {
1299
1301
  canActivate(context: ExecutionContext): Promise<boolean>;
1300
1302
  }
1301
1303
 
1302
- /**
1303
- * Global HTTP Exception Filter
1304
- *
1305
- * Standardizes all error responses in the format:
1306
- * {
1307
- * errors: [{ field: string, message: string }],
1308
- * message?: string,
1309
- * statusCode: number,
1310
- * timestamp: string,
1311
- * path: string
1312
- * }
1313
- *
1314
- * Handles:
1315
- * - Validation errors (class-validator) - Converts to field-specific errors
1316
- * - HTTP exceptions - Maps to standardized format
1317
- * - Unknown errors - Returns generic 500 error
1318
- */
1319
- declare class HttpExceptionFilter implements ExceptionFilter {
1320
- private readonly logger;
1321
- catch(exception: unknown, host: ArgumentsHost): void;
1322
- /**
1323
- * Parse class-validator error messages into field-specific errors
1324
- */
1325
- private parseValidationErrors;
1326
- }
1327
-
1328
1304
  /**
1329
1305
  * Converts an HTTP status code to its corresponding title string.
1330
1306
  * Uses the HttpStatus enum to map status codes to human-readable titles.
@@ -1338,6 +1314,27 @@ declare class HttpExceptionFilter implements ExceptionFilter {
1338
1314
  * getHttpStatusTitle(500) // Returns: "Internal Server Error"
1339
1315
  */
1340
1316
  declare function getHttpStatusTitle(status: number): string;
1317
+ /**
1318
+ * Global HTTP Exception Filter implementing RFC 7807 Problem Details
1319
+ *
1320
+ * Transforms all exceptions into a standardized RFC 7807 format:
1321
+ * {
1322
+ * title: string, // Human-readable status title
1323
+ * status: number, // HTTP status code
1324
+ * detail: string, // Detailed error description
1325
+ * errors: FieldError[] // Field-specific error messages
1326
+ * }
1327
+ *
1328
+ * Handles:
1329
+ * - Custom field exceptions from @vritti/api-sdk (BaseFieldException)
1330
+ * - Class-validator DTO validation errors
1331
+ * - Standard NestJS HTTP exceptions
1332
+ * - Unknown errors
1333
+ */
1334
+ declare class HttpExceptionFilter implements ExceptionFilter {
1335
+ private readonly logger;
1336
+ catch(exception: unknown, host: ArgumentsHost): void;
1337
+ }
1341
1338
 
1342
1339
  interface FieldError$1 {
1343
1340
  field?: string;
@@ -1769,4 +1766,405 @@ declare class BadGatewayException extends BaseFieldException {
1769
1766
  constructor(messageOrField: string | FieldError[], fieldMessageOrDetail?: string, detail?: string);
1770
1767
  }
1771
1768
 
1772
- export { type ApiErrorResponse, AuthConfigModule, BadGatewayException, BadRequestException, BaseFieldException, ConflictException, CsrfGuard, DatabaseModule, type DatabaseModuleOptions, type FieldError, ForbiddenException, GoneException, HttpExceptionFilter, HttpModule, InternalServerErrorException, MethodNotAllowedException, NotAcceptableException, NotFoundException, NotImplementedException, Onboarding, PayloadTooLargeException, PrimaryBaseRepository, PrimaryDatabaseService, type PrimaryDbConfig, type ProblemDetails, Public, RequestTimeoutException, ServiceUnavailableException, Tenant, TenantBaseRepository, TenantContextService, TenantDatabaseService, type TenantInfo, TooManyRequestsException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, ValidationException, VrittiAuthGuard, getHttpStatusTitle };
1769
+ /**
1770
+ * Supported log levels for the logging system.
1771
+ */
1772
+ type LogLevel = 'error' | 'warn' | 'log' | 'debug' | 'verbose';
1773
+ /**
1774
+ * Supported log output formats.
1775
+ */
1776
+ type LogFormat = 'json' | 'text';
1777
+ /**
1778
+ * Metadata that can be attached to log entries.
1779
+ */
1780
+ interface LogMetadata {
1781
+ correlationId?: string;
1782
+ method?: string;
1783
+ url?: string;
1784
+ statusCode?: number;
1785
+ duration?: number;
1786
+ ip?: string;
1787
+ userAgent?: string;
1788
+ [key: string]: unknown;
1789
+ }
1790
+ /**
1791
+ * Configuration options for the logger module.
1792
+ */
1793
+ interface LoggerModuleOptions {
1794
+ provider?: 'default' | 'winston';
1795
+ level?: LogLevel;
1796
+ format?: LogFormat;
1797
+ enableFileLogger?: boolean;
1798
+ filePath?: string;
1799
+ maxFiles?: string;
1800
+ enableCorrelationId?: boolean;
1801
+ enableHttpLogger?: boolean;
1802
+ httpLogger?: HttpLoggerOptions;
1803
+ appName?: string;
1804
+ environment?: string;
1805
+ defaultMeta?: Record<string, unknown>;
1806
+ }
1807
+ /**
1808
+ * Factory function for creating logger options asynchronously.
1809
+ */
1810
+ interface LoggerOptionsFactory {
1811
+ createLoggerOptions(): Promise<LoggerModuleOptions> | LoggerModuleOptions;
1812
+ }
1813
+ /**
1814
+ * Async configuration options for the logger module.
1815
+ */
1816
+ interface LoggerModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
1817
+ useExisting?: Type<LoggerOptionsFactory>;
1818
+ useClass?: Type<LoggerOptionsFactory>;
1819
+ useFactory?: (...args: unknown[]) => Promise<LoggerModuleOptions> | LoggerModuleOptions;
1820
+ inject?: unknown[];
1821
+ }
1822
+ /**
1823
+ * Context object for correlation tracking across async operations.
1824
+ */
1825
+ interface CorrelationContext {
1826
+ correlationId: string;
1827
+ [key: string]: unknown;
1828
+ }
1829
+ /**
1830
+ * Configuration options for HTTP request/response logger interceptor.
1831
+ */
1832
+ interface HttpLoggerOptions {
1833
+ enableRequestLog?: boolean;
1834
+ enableResponseLog?: boolean;
1835
+ enableRequestBodyLog?: boolean;
1836
+ enableResponseBodyLog?: boolean;
1837
+ slowRequestThreshold?: number;
1838
+ excludedRoutes?: string[];
1839
+ maskedHeaders?: string[];
1840
+ maxBodySize?: number;
1841
+ }
1842
+
1843
+ /**
1844
+ * Logger Module
1845
+ *
1846
+ * Dynamic NestJS module providing unified logging infrastructure with:
1847
+ * - Environment presets (development, staging, production, test)
1848
+ * - Transparent switching between default NestJS Logger and Winston
1849
+ * - Correlation ID tracking via middleware
1850
+ * - HTTP request/response logging via interceptor
1851
+ * - PII masking and file logging support
1852
+ *
1853
+ * @module logger/logger.module
1854
+ */
1855
+
1856
+ /**
1857
+ * Dependency injection token for logger module options
1858
+ */
1859
+ declare const LOGGER_MODULE_OPTIONS: unique symbol;
1860
+ /**
1861
+ * Global logger module providing unified logging infrastructure.
1862
+ *
1863
+ * Features:
1864
+ * - Environment presets (development, staging, production, test)
1865
+ * - Single `LoggerService` interface for all logging needs
1866
+ * - Transparent provider switching (default ↔ Winston)
1867
+ * - Correlation ID tracking across async operations
1868
+ * - HTTP request/response logging
1869
+ * - PII masking for GDPR compliance
1870
+ * - File-based logging with rotation
1871
+ *
1872
+ * @example
1873
+ * ```typescript
1874
+ * // Production environment with explicit config
1875
+ * @Module({
1876
+ * imports: [
1877
+ * LoggerModule.forRoot({
1878
+ * environment: 'production',
1879
+ * appName: 'my-service'
1880
+ * })
1881
+ * ],
1882
+ * })
1883
+ * export class AppModule {}
1884
+ *
1885
+ * // Development environment with custom override
1886
+ * @Module({
1887
+ * imports: [
1888
+ * LoggerModule.forRoot({
1889
+ * environment: 'development',
1890
+ * level: 'verbose' // Override preset's debug
1891
+ * })
1892
+ * ],
1893
+ * })
1894
+ * export class AppModule {}
1895
+ *
1896
+ * // Use default NestJS logger
1897
+ * @Module({
1898
+ * imports: [
1899
+ * LoggerModule.forRoot({
1900
+ * provider: 'default',
1901
+ * environment: 'development'
1902
+ * })
1903
+ * ],
1904
+ * })
1905
+ * export class AppModule {}
1906
+ *
1907
+ * // Dynamic configuration with ConfigService
1908
+ * @Module({
1909
+ * imports: [
1910
+ * LoggerModule.forRootAsync({
1911
+ * imports: [ConfigModule],
1912
+ * useFactory: (config: ConfigService) => ({
1913
+ * environment: config.get('NODE_ENV', 'development'),
1914
+ * provider: config.get('LOG_PROVIDER', 'winston'),
1915
+ * appName: config.get('APP_NAME')
1916
+ * }),
1917
+ * inject: [ConfigService]
1918
+ * })
1919
+ * ],
1920
+ * })
1921
+ * export class AppModule {}
1922
+ * ```
1923
+ */
1924
+ declare class LoggerModule implements NestModule {
1925
+ /**
1926
+ * Configures the logger module with static options.
1927
+ *
1928
+ * Users must explicitly pass `environment` to select a preset.
1929
+ * All preset values can be overridden by passing explicit options.
1930
+ *
1931
+ * @param options - Logger configuration options
1932
+ * @returns Dynamic module configuration
1933
+ *
1934
+ * @example
1935
+ * ```typescript
1936
+ * // Production preset with app name
1937
+ * LoggerModule.forRoot({
1938
+ * environment: 'production',
1939
+ * appName: 'my-service'
1940
+ * })
1941
+ *
1942
+ * // Development preset with custom level
1943
+ * LoggerModule.forRoot({
1944
+ * environment: 'development',
1945
+ * level: 'verbose',
1946
+ * enableFileLogger: true
1947
+ * })
1948
+ *
1949
+ * // Use default NestJS logger
1950
+ * LoggerModule.forRoot({
1951
+ * provider: 'default',
1952
+ * environment: 'development'
1953
+ * })
1954
+ * ```
1955
+ */
1956
+ static forRoot(options?: LoggerModuleOptions): DynamicModule;
1957
+ /**
1958
+ * Configures the logger module with async options.
1959
+ *
1960
+ * Supports dynamic configuration using:
1961
+ * - `useFactory`: Factory function with dependency injection
1962
+ * - `useClass`: Class implementing `LoggerOptionsFactory`
1963
+ * - `useExisting`: Existing provider implementing `LoggerOptionsFactory`
1964
+ *
1965
+ * Options from the factory/class are merged with environment preset defaults.
1966
+ *
1967
+ * @param options - Async configuration options
1968
+ * @returns Dynamic module configuration
1969
+ *
1970
+ * @example
1971
+ * ```typescript
1972
+ * // Factory with ConfigService
1973
+ * LoggerModule.forRootAsync({
1974
+ * imports: [ConfigModule],
1975
+ * useFactory: (config: ConfigService) => ({
1976
+ * environment: config.get('NODE_ENV', 'development'),
1977
+ * provider: config.get('LOG_PROVIDER', 'winston'),
1978
+ * level: config.get('LOG_LEVEL'),
1979
+ * appName: config.get('APP_NAME'),
1980
+ * }),
1981
+ * inject: [ConfigService]
1982
+ * })
1983
+ *
1984
+ * // Factory class
1985
+ * @Injectable()
1986
+ * class LoggerConfigService implements LoggerOptionsFactory {
1987
+ * createLoggerOptions(): LoggerModuleOptions {
1988
+ * return {
1989
+ * environment: 'production',
1990
+ * appName: 'my-service'
1991
+ * };
1992
+ * }
1993
+ * }
1994
+ *
1995
+ * LoggerModule.forRootAsync({
1996
+ * useClass: LoggerConfigService
1997
+ * })
1998
+ * ```
1999
+ */
2000
+ static forRootAsync(options: LoggerModuleAsyncOptions): DynamicModule;
2001
+ /**
2002
+ * Configures middleware for the module.
2003
+ * Middleware is registered globally in main.ts using Fastify hooks.
2004
+ */
2005
+ configure(consumer: MiddlewareConsumer): void;
2006
+ /**
2007
+ * Creates async providers for dynamic module configuration.
2008
+ */
2009
+ private static createAsyncProviders;
2010
+ /**
2011
+ * Creates the async options provider.
2012
+ */
2013
+ private static createAsyncOptionsProvider;
2014
+ }
2015
+
2016
+ /**
2017
+ * Unified Logger Service
2018
+ *
2019
+ * Single service that provides both default NestJS Logger and Winston logger implementations.
2020
+ * Automatically delegates to the configured provider (default or winston).
2021
+ * @module logger/logger.service
2022
+ */
2023
+
2024
+ /**
2025
+ * Unified logger service implementing NestJS LoggerService interface.
2026
+ * Supports both default NestJS Logger and Winston implementations via facade pattern.
2027
+ */
2028
+ declare class LoggerService implements LoggerService$1 {
2029
+ private readonly defaultLogger?;
2030
+ private readonly activeLogger;
2031
+ private readonly options;
2032
+ private context?;
2033
+ constructor(options?: LoggerModuleOptions, defaultLogger?: Logger | undefined);
2034
+ /**
2035
+ * Creates a Winston logger instance with inline configuration.
2036
+ * Consolidates winston-config.factory.ts logic.
2037
+ */
2038
+ private createWinstonLogger;
2039
+ log(message: any, context?: string): void;
2040
+ error(message: any, trace?: string, context?: string): void;
2041
+ warn(message: any, context?: string): void;
2042
+ debug(message: any, context?: string): void;
2043
+ verbose(message: any, context?: string): void;
2044
+ setContext(context: string): void;
2045
+ /**
2046
+ * Unified internal logging method that handles both Winston and NestJS Logger.
2047
+ */
2048
+ private _log;
2049
+ /**
2050
+ * Logs with custom metadata (Winston only).
2051
+ */
2052
+ logWithMetadata(level: LogLevel, message: any, metadata?: LogMetadata, context?: string): void;
2053
+ private formatMessage;
2054
+ /**
2055
+ * Enriches metadata with correlation context from AsyncLocalStorage.
2056
+ * Inline from winston-logger.service.ts
2057
+ */
2058
+ private enrichMetadata;
2059
+ child(context: string): LoggerService;
2060
+ }
2061
+
2062
+ /**
2063
+ * Correlation ID Middleware
2064
+ *
2065
+ * Generates unique correlation IDs for request tracking across async operations.
2066
+ * Stores correlation ID in AsyncLocalStorage for access throughout the request lifecycle.
2067
+ * @module logger/correlation-id.middleware
2068
+ */
2069
+
2070
+ /**
2071
+ * Configuration options for the Correlation ID middleware.
2072
+ */
2073
+ interface CorrelationIdMiddlewareOptions {
2074
+ /**
2075
+ * If true, adds the correlation ID to response headers.
2076
+ * @default true
2077
+ */
2078
+ includeInResponse?: boolean;
2079
+ /**
2080
+ * The header name to use when adding correlation ID to response.
2081
+ * @default 'x-correlation-id'
2082
+ */
2083
+ responseHeader?: string;
2084
+ }
2085
+ /**
2086
+ * Correlation ID Middleware for Fastify/NestJS applications.
2087
+ *
2088
+ * Generates a unique correlation ID for each request,
2089
+ * stores it in AsyncLocalStorage for access throughout the request lifecycle,
2090
+ * and optionally adds it to response headers.
2091
+ */
2092
+ declare class CorrelationIdMiddleware implements NestMiddleware {
2093
+ private readonly includeInResponse;
2094
+ private readonly responseHeader;
2095
+ constructor(options?: CorrelationIdMiddlewareOptions);
2096
+ /**
2097
+ * Middleware handler for processing requests.
2098
+ */
2099
+ use(req: FastifyRequest, reply: FastifyReply, next: () => void): void;
2100
+ /**
2101
+ * Fastify hook handler for onRequest.
2102
+ * This is an async function that returns a Promise, ensuring the AsyncLocalStorage
2103
+ * context persists throughout the entire request lifecycle.
2104
+ */
2105
+ onRequest(req: FastifyRequest, reply: FastifyReply): Promise<void>;
2106
+ }
2107
+
2108
+ /**
2109
+ * HTTP Logger Interceptor
2110
+ *
2111
+ * Automatically logs HTTP requests and responses with correlation tracking.
2112
+ * @module logger/http-logger.interceptor
2113
+ */
2114
+
2115
+ /**
2116
+ * HTTP Logger Interceptor for NestJS applications.
2117
+ *
2118
+ * Logs all HTTP requests and responses with metadata including
2119
+ * correlation IDs, performance metrics, and error details.
2120
+ */
2121
+ declare class HttpLoggerInterceptor implements NestInterceptor {
2122
+ private readonly logger;
2123
+ private readonly enableRequestLog;
2124
+ private readonly enableResponseLog;
2125
+ private readonly slowRequestThreshold;
2126
+ constructor(logger: LoggerService, options?: HttpLoggerOptions);
2127
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any>;
2128
+ private logRequest;
2129
+ private logResponse;
2130
+ private logError;
2131
+ }
2132
+
2133
+ /**
2134
+ * Logging Utilities
2135
+ *
2136
+ * Consolidated utilities for correlation tracking, PII masking, and async context management.
2137
+ * @module logging/utils
2138
+ */
2139
+
2140
+ /**
2141
+ * Async local storage for correlation context tracking across async operations.
2142
+ */
2143
+ declare const correlationStorage: AsyncLocalStorage<CorrelationContext>;
2144
+ /**
2145
+ * Gets the current correlation context from async local storage.
2146
+ */
2147
+ declare function getCorrelationContext(): CorrelationContext | undefined;
2148
+ /**
2149
+ * Runs a callback within a correlation context.
2150
+ */
2151
+ declare function runWithCorrelationContext<T>(context: CorrelationContext, callback: () => T): T;
2152
+ /**
2153
+ * Updates the current correlation context with new values.
2154
+ */
2155
+ declare function updateCorrelationContext(updates: Partial<CorrelationContext>): void;
2156
+ /**
2157
+ * Default header name for setting correlation ID in responses.
2158
+ */
2159
+ declare const DEFAULT_CORRELATION_HEADER = "x-correlation-id";
2160
+ /**
2161
+ * Generates a new correlation ID using UUID v4.
2162
+ * Always creates a fresh ID for each request.
2163
+ */
2164
+ declare function generateCorrelationId(): string;
2165
+ /**
2166
+ * Adds correlation ID to Fastify response headers.
2167
+ */
2168
+ declare function addCorrelationIdToResponse(reply: FastifyReply, correlationId: string, headerName?: string): void;
2169
+
2170
+ export { type ApiErrorResponse, AuthConfigModule, BadGatewayException, BadRequestException, BaseFieldException, ConflictException, type CorrelationContext, CorrelationIdMiddleware, CsrfGuard, DEFAULT_CORRELATION_HEADER, DatabaseModule, type DatabaseModuleOptions, type FieldError, ForbiddenException, GoneException, HttpExceptionFilter, HttpLoggerInterceptor, type HttpLoggerOptions, HttpModule, InternalServerErrorException, LOGGER_MODULE_OPTIONS, type LogFormat, type LogLevel, type LogMetadata, LoggerModule, type LoggerModuleAsyncOptions, type LoggerModuleOptions, type LoggerOptionsFactory, LoggerService, MethodNotAllowedException, NotAcceptableException, NotFoundException, NotImplementedException, Onboarding, PayloadTooLargeException, PrimaryBaseRepository, PrimaryDatabaseService, type PrimaryDbConfig, type ProblemDetails, Public, RequestTimeoutException, ServiceUnavailableException, Tenant, TenantBaseRepository, TenantContextService, TenantDatabaseService, type TenantInfo, TooManyRequestsException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, ValidationException, VrittiAuthGuard, addCorrelationIdToResponse, correlationStorage, generateCorrelationId, getCorrelationContext, getHttpStatusTitle, runWithCorrelationContext, updateCorrelationContext };