import { Request, Response, NextFunction } from 'express'; import * as _nestjs_common from '@nestjs/common'; import { CanActivate, ExecutionContext, NestInterceptor, CallHandler, ClassSerializerInterceptor, ClassSerializerInterceptorOptions, PlainLiteralObject, HttpException, HttpStatus, Type, DynamicModule, RequestMethod, ExceptionFilter, ArgumentsHost, OnApplicationShutdown, ClassProvider } from '@nestjs/common'; import { Reflector, ModulesContainer } from '@nestjs/core'; import * as rxjs from 'rxjs'; import { Observable } from 'rxjs'; import { a as SmpWinstonLoggerService, S as SmpEnvironmentVariables } from './smp-winston-logger-service.class-CltMrgeM.js'; export { b as SmpWinstonLogger, s as smpEnvironmentVariablesSchema } from './smp-winston-logger-service.class-CltMrgeM.js'; import * as _nestjs_config from '@nestjs/config'; import { ConfigService } from '@nestjs/config'; import * as jsonwebtoken from 'jsonwebtoken'; import { verify, decode } from 'jsonwebtoken'; import { ConfidentialClientApplication } from '@azure/msal-node'; import { SmpAbstractRxjsTtlCacheStrategy } from '@tonysamperi/ts-mapi-core/rxjs'; import { S as SmpCacheInterceptorStrategy } from './smp-cache-interceptor-strategy.class-CMO0pOJC.js'; import { ClassTransformOptions } from 'class-transformer'; import * as _tonysamperi_ts_mapi_core from '@tonysamperi/ts-mapi-core'; import { SmpErrorResponseCreateOpts, SmpErrorResponse, SmpPrimitive } from '@tonysamperi/ts-mapi-core'; import { z } from 'zod'; export { SmpSendEmailOptions, SmpSmtpModule, SmpSmtpService } from './smtp.js'; import * as url from 'url'; import { SmpLoggerMethods } from '@tonysamperi/logger'; import { Knex } from 'knex'; import { ConnectConfig, Client, ClientChannel } from 'ssh2'; import { AxiosInstance, AxiosRequestHeaders, CancelTokenSource, Cancel } from 'axios'; import TransportStream from 'winston-transport'; import 'winston'; import 'nodemailer'; /** * Combines SmpBasicAuthGuard with SmpBasicAuthUsersForbidden to add basic auth to your route or controller with specified users. * It only makes sense in combination with SmpBasicAuthForbiddenTo. * e.g. When SmpBasicAuthForbiddenTo is applied to a controller, put this on specific endpoint to negate a user from the list above * @param users * @constructor */ declare const SmpBasicAuthForbiddenTo: (...users: string[]) => (target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor) => void; /** * Combines SmpBasicAuthGuard with SmpBasicAuthUsers to add basic auth to your route or controller with specified users. * Be aware that not passing users will cause the route not to be accessible. * * Can be combined with @SmpBasicAuthForbiddenTo to exclude specific users from a route. * Note that using @SmpBasicAuthForbiddenTo without @SmpBasicAuthRestrictedTo has no effect. * @param users * @constructor */ declare const SmpBasicAuthRestrictedTo: (...users: string[]) => (target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor) => void; declare const SMP_BASIC_AUTH_USERS_META_KEY = "smp:basic-auth-users"; declare const SmpBasicAuthUsers: (...users: string[]) => MethodDecorator & ClassDecorator; declare const SMP_BASIC_AUTH_USERS_FORBID_META_KEY = "smp:basic-auth-users-forbid"; declare const SmpBasicAuthUsersForbid: (...users: string[]) => MethodDecorator & ClassDecorator; declare const SMP_CACHEABLE_META_KEY = "smp:cacheable"; interface SmpCacheMetadata { ttl: number; keyFn?: (ctx: Request | any) => string; } /** * @param ttl time in seconds! * @param keyFn receives the request object * @constructor */ declare const SmpCacheable: (ttl?: number, keyFn?: (ctx: Request) => string) => MethodDecorator; declare const SMP_OIDC_GROUPS_META_KEY = "smp:oidcGroups"; declare const SmpOidcGroups: (...groups: string[]) => _nestjs_common.CustomDecorator; declare const SMP_OIDC_ROLES_META_KEY = "smp:oidcRoles"; declare const SmpOidcRoles: (...roles: string[]) => _nestjs_common.CustomDecorator; declare const SmpOidcUser: (...dataOrPipes: unknown[]) => ParameterDecorator; declare const SMP_GLOBAL_ERROR_LOGGER_META_KEY = "smp:globalErrorLogger"; declare const SmpGlobalErrorLogger: (name?: string) => _nestjs_common.CustomDecorator; declare const SMP_PUBLIC_KEY = "smp:public"; declare const SmpPublic: () => MethodDecorator; declare const SMP_SKIP_CLASS_SERIALIZER_KEY = "smp:skipClassSerializer"; declare const SmpSkipClassSerializer: () => _nestjs_common.CustomDecorator; declare const SMP_SKIP_REST_LOGGING_KEY = "smp:skipRestLogging"; declare const SmpSkipRestLogging: () => _nestjs_common.CustomDecorator; /** * A base implementation of a basic auth guard. * If SmpBasicAuthGuard or SmpJwtAuthGuard are not enough for you, you can implement this one! */ declare abstract class SmpAbstractAuthGuard implements CanActivate { protected readonly _loggerSrv: SmpWinstonLoggerService; protected readonly _reflector: Reflector; protected _basicRealm: string | undefined; constructor(_loggerSrv: SmpWinstonLoggerService, _reflector: Reflector); canActivate(context: ExecutionContext): Observable; protected _canActivate(_context_: ExecutionContext): Observable; protected _handleUnauthorized(req: Request, res: Response, credentials?: string): never; } declare abstract class SmpAbstractUserService { /** * @param credentials generic credentials you can use */ abstract validateUser(...credentials: string[]): Observable; abstract getUserProfile(token: string): Observable; } /** * Extend this to make your own injectables * You'll need to define _host, _level, _path and _searchParams in your child class, and you're good to go. * * @example * ```ts * @Injectable() * export class MyBasicAuthUserService extends SmpBasicAuthUserService { * * validateUser(username: string, password: string) { * return this._findUser({username}).pipe(map(u => u.password === SHA512(password)) * } * * protected _findUser(...) { * // ... * } * } * ``` * * then in your module * * ```ts * {provide: SmpBasicAuthUserService, useClass: SmpMyBasicAuthUserService} * ``` */ declare class SmpBasicAuthUserService extends SmpAbstractUserService { getUserProfile(_token_: string): Observable; validateUser(_username_: string, _password_: string): Observable; } /** * A generic implementation of a basic auth guard. * Just configure in your ConfigService (you can use the env file architecture) the value "app.credentials" * and fill it with a comma-separated list of credentials (e.g. app.credentials=foo:bar,goo:car) * For more control you can use an implementation of SmpBasicAuthUserService * * --- * * @example * ```ts * class SomeController { * * @UseGuards(SmpBasicAuthGuard) * someEndpoint() { * // foo * } * } * ``` * * or in your module * * ```ts * {provide: SmpBasicAuthUserService, useClass: SmpMyBasicAuthUserService} * ``` */ declare class SmpBasicAuthGuard extends SmpAbstractAuthGuard { protected readonly _basicAuthUserSrv: SmpBasicAuthUserService; protected readonly _configSrv: ConfigService; protected _basicRealm: string; constructor(_basicAuthUserSrv: SmpBasicAuthUserService, _configSrv: ConfigService, loggerSrv: SmpWinstonLoggerService, reflector: Reflector); protected _canActivate(context: ExecutionContext): Observable; protected _check(username: string, password: string): Observable; protected _fallbackCheck(username: string, password: string): Observable; } /** * Extend this to make your own injectables * You can customise the getUserProfile method based on your needs * * @example * ```ts * @Injectable() * export class MyBasicAuthUserService extends SmpJwtUserService { * * validateUser(username: string, password: string) { * return this._findUser({username}).pipe(map(u => u.password === SHA512(password)) * } * * protected _findUser(...) { * // ... * } * } * ``` */ declare class SmpJwtUserService extends SmpAbstractUserService { protected readonly _configSrv: ConfigService; protected readonly _loggerSrv: SmpWinstonLoggerService; protected _jwt: { verify: typeof verify; decode: typeof decode; }; constructor(_configSrv: ConfigService, _loggerSrv: SmpWinstonLoggerService); decodeToken(token: string): Observable; getUserProfile(token: string): Observable; validateUser(token: string): Observable; protected _loadJwt(): void; } /** * Simple Jwt auth guard. * Verify the token using jsonwebtoken. * You'll have to put your secret in "jwt.accessSecret" * You can bypass the auth using the SmpPublic decorator */ declare class SmpJwtAuthGuard extends SmpAbstractAuthGuard { protected readonly _jwtUserSrv: SmpJwtUserService; protected _basicRealm: string; constructor(_jwtUserSrv: SmpJwtUserService, loggerSrv: SmpWinstonLoggerService, reflector: Reflector); protected _canActivate(context: ExecutionContext): Observable; } interface SmpOidcUserClaims { appName: string; email: string; displayName: string; exp: number; familyName: string; givenName: string; groups?: string[]; roles?: string[]; } declare abstract class SmpAbstractOidcAuthService { abstract acquireTokenByCode(opts: { code: string; redirectUri: string; scopes?: string[]; }): Observable; abstract acquireTokenClientCredentials(): Observable; abstract validateToken(token: string): Observable; } declare class SmpMicrosoftAuthService extends SmpAbstractOidcAuthService { protected readonly _configSrv: ConfigService; protected readonly _loggerSrv: SmpWinstonLoggerService; protected _jwksUri: string; protected _msalApp: ConfidentialClientApplication; constructor(_configSrv: ConfigService, _loggerSrv: SmpWinstonLoggerService); /** * Exchange Authorization Code → Access Token */ acquireTokenByCode({ code, redirectUri, scopes }: { code: string; redirectUri: string; scopes?: string[]; }): Observable; /** * Exchange Client Credentials → Access Token */ acquireTokenClientCredentials(): Observable; validateToken(token: string): Observable; } declare class SmpOidcAuthGuard extends SmpAbstractAuthGuard { private readonly _authSrv; protected _basicRealm: string; constructor(_authSrv: SmpMicrosoftAuthService, loggerSrv: SmpWinstonLoggerService, reflector: Reflector); protected _canActivate(context: ExecutionContext): Observable; } declare const SmpRequiredHeadersGuard: (...requiredHeaders: string[]) => _nestjs_common.Type<{ canActivate(ctx: ExecutionContext): boolean; }>; declare class SmpCacheInterceptor implements NestInterceptor { protected readonly _reflector: Reflector; protected readonly _loggerSrv: SmpWinstonLoggerService; protected readonly _providedCache: SmpCacheInterceptorStrategy; protected _cache: SmpAbstractRxjsTtlCacheStrategy; constructor(_reflector: Reflector, _loggerSrv: SmpWinstonLoggerService, _providedCache: SmpCacheInterceptorStrategy); intercept(context: ExecutionContext, next: CallHandler): Observable; protected _generateKey(request: Request): string; } declare class SmpClassSerializerInterceptor extends ClassSerializerInterceptor { protected _reflector: Reflector; protected _loggerSrv: SmpWinstonLoggerService; constructor(_reflector: Reflector, defaultOptions: ClassSerializerInterceptorOptions | undefined, _loggerSrv: SmpWinstonLoggerService); intercept(context: ExecutionContext, next: CallHandler): Observable; serialize(response: PlainLiteralObject | PlainLiteralObject[], options: ClassTransformOptions): PlainLiteralObject | PlainLiteralObject[]; } type SmpHttpExceptionParams = Partial, "status">>; /** * Use this to build a dynamic exception without ifs or switch cases */ declare class SmpHttpException extends HttpException { constructor(status?: HttpStatus, { messages, errorCode, ...rest }?: SmpHttpExceptionParams); } declare class SmpGlobalErrorLoggerInterceptor implements NestInterceptor { private readonly _reflector; private readonly _loggerSrv; protected _errorMappingStrategies: ({ test: (e: unknown) => e is SmpHttpException; map: (e: SmpHttpException) => string | object; } | { test: (e: unknown) => e is SmpErrorResponse; map: (e: SmpErrorResponse) => _tonysamperi_ts_mapi_core.SmpGenericResponseBase & Pick, "status" | "errorCode" | "timestamp">; })[]; constructor(_reflector: Reflector, _loggerSrv: SmpWinstonLoggerService); intercept(context: ExecutionContext, next: CallHandler): rxjs.Observable; protected _mapError(exception: unknown): unknown; } declare class SmpRestLoggerInterceptor implements NestInterceptor { protected _reflector: Reflector; protected _loggerSrv: SmpWinstonLoggerService; constructor(_reflector: Reflector, _loggerSrv: SmpWinstonLoggerService); intercept(context: ExecutionContext, next: CallHandler): Observable; } declare abstract class SmpAbstractEncryptionStrategy { abstract decrypt(key: string, value: string): string; abstract encrypt(value: string): string; abstract isEncrypted(value: string): boolean; } /** * SmpEnvProperties * ---------------- * This is an internal utility class used by `SmpConfigModule` to centrally manage * loading environment configuration files (`environment-*.properties`). * * Typically, you do NOT need to interact with this class directly, * since initialisation and config loading are fully automated by `SmpConfigModule`. * * --- * * Configuration via `SmpConfigModule.forRoot`: * * - `envsConfig.envsDir`: the directory containing the `.properties` config files. * - `envsConfig.defaultEnv`: optional array specifying the environments to load, in order. * If omitted, the default behavior is to load: * 1. The "COMMON" environment (file `environment-common.properties`) * 2. The environment set in `process.env.ENVIRONMENT` (e.g. `local`, `prod`, etc) * * --- * * @example * ```ts * SmpConfigModule.forRoot({ * envsConfig: { * envsDir: join(__dirname, "..", "..", "config"), * defaultEnv: ["COMMON", "QUA"], * }, * loggerClass: SmpCustomWinstonLoggerService, * }); * ``` * * --- * * Note: * For local development, it is recommended to create a `.env` file * setting the `ENVIRONMENT` variable, so the correct environment file * will be automatically loaded. * * --- * * For advanced use or customisation, * you can instantiate `SmpEnvProperties` directly, * but this is intended only for developers familiar with the internal code. */ declare class SmpEnvProperties { static get INSTANCE(): SmpEnvProperties; protected static _instance?: SmpEnvProperties; protected _envConfig: SmpEnvConfig; private constructor(); /** * @param envConfig */ static create(envConfig?: Partial): SmpEnvProperties; /** * Encrypts selected keys: each item in the list can either be a string (supporting wildcards) or a RegExp * NOTE: DON'T USE THIS IN RUNNING APPLICATIONS! * @param filePath * @param items * @param encryptionStrategy */ static encryptPropertiesFile(filePath: string, items: (string | RegExp)[], encryptionStrategy?: SmpEnvConfig["encryptionStrategy"]): Record; private static _encryptProperty; /** * @deprecated use getConfigAndCast instead! */ getConfig(): Promise>; getConfigAndCast(): Promise | Record>; interpolate(input: Record): Record; interpolate(input: z.infer): z.infer; private _decryptEncryptedConfigValues; /** * This is async because you might want to extend this class and retrieve configs remotely * @private */ private _getConfig; private _getConfigPath; } interface SmpEnvConfig { defaultEnv: string | string[]; encryptionStrategy: SmpAbstractEncryptionStrategy; environmentVariablesSchema: z.ZodObject; envs: Record; envsDir: string; envsFactory: typeof SmpEnvProperties; } declare const smpDefaultEnvConfig: Omit; interface SmpAesEncryptionStrategyOpts { bytesFactory?: (size: number) => Buffer; encryptionKey?: string; } /** * AES encryption strategy for environment properties using v1 encryption protocol. * Encrypts and decrypts property values with the format `ENC_AES(v1:salt:initVector:cipherText)`. * Uses random salt and initialisation vector for each encryption to enhance security. * Supports custom bytes factory and encryption key configuration. */ declare class SmpEnvironmentVariablesAesEncryptionStrategy extends SmpAbstractEncryptionStrategy { protected static readonly _ENCRYPTED_VARIABLE_PATTERN: RegExp; protected static readonly _INIT_VECTOR_SIZE: number; protected static readonly _SALT_SIZE: number; protected _bytesFactory: (size: number) => Buffer; protected _encryptionKey?: string; constructor(opts?: SmpAesEncryptionStrategyOpts); decrypt(key: string, value: string): string; encrypt(value: string): string; isEncrypted(value: string): boolean; protected _getEncryptionKey(key?: string): string; } /** * These are the same you can find as Dockerfiles */ declare const smpEnvironments: { COMMON: string; QUA: string; RELEASE: string; STAGING: string; PROD: string; }; interface SmpConfigModuleOpts { envsConfig: Partial; disableEnvVarsCache: boolean; loggerClass: Type; } declare class SmpConfigModule { private static _initialized; constructor(); static forRoot(config?: Partial): DynamicModule; static forRootAsync(factory: () => Promise>): Promise; } interface SmpCronJobMetadata { schedule: string; deadline?: `${number}m` | `${number}s`; maxAttempts?: number; authType?: "basic" | "token"; headers?: Record; } declare const SMP_CRON_JOB_META_KEY = "smp:cronjob"; declare const SmpCronJob: (opts: SmpCronJobMetadata) => MethodDecorator; declare namespace SmpScheduler { enum RestVerbs { OPTIONS = "OPTIONS", HEAD = "HEAD", GET = "GET", POST = "POST", PUT = "PUT", PATCH = "PATCH", DELETE = "DELETE" } enum AuthType { basic = "basic", token = "token" } interface Context { readonly PROJECT_ID: string; readonly REGION: string; readonly ENVIRONMENT: string; readonly SERVICE_NAME: string; readonly SCHEDULER_SA: string; readonly TIME_ZONE?: string; readonly SCHEDULER_BASE_URL?: string; } interface Defaults { readonly method?: RestVerbs; readonly headers?: Readonly>; } interface DiscoveredCronRoute { readonly jobId: string; readonly schedule: string; readonly scheduleToHuman: string; readonly deadline?: `${number}m` | `${number}s`; readonly maxAttempts?: number; readonly method: RestVerbs; readonly path: `/${string}` | "/"; readonly authType?: AuthType; readonly headers?: Readonly>; } interface Job extends DiscoveredCronRoute { readonly service: string; readonly body?: string; } interface Config { readonly version: 1; readonly project: string; readonly region: string; readonly timeZone: string; readonly schedulerServiceAccount: string; readonly schedulerBaseUrl: string; readonly defaults?: Defaults; readonly jobs: readonly Job[]; } } interface SmpSchedulerDiscoveryResult { module: string; globalPrefix: string; discoveredAt: string; jobs: readonly SmpScheduler.DiscoveredCronRoute[]; } declare class SmpCronSchedulerDiscoveryService { private readonly _modulesContainer; private readonly _configService?; constructor(_modulesContainer: ModulesContainer, _configService?: ConfigService | undefined); discoverCronRoutes(): readonly SmpScheduler.DiscoveredCronRoute[]; getDiscoveryResult(): SmpSchedulerDiscoveryResult; protected _cronToHuman(exp: string): string; } type CommonMethodNames = Extract; type MappableRequestMethod = (typeof RequestMethod)[CommonMethodNames]; type RequestMethodToRestVerbMap = Record; declare class SmpSchedulerUtils { static get REQUEST_METHOD_TO_REST_VERB_MAP(): RequestMethodToRestVerbMap; private static readonly _REQUEST_METHOD_TO_REST_VERB_MAP; static normalizePath(...parts: (string | undefined)[]): `/${string}` | "/"; static requestMethodToVerb(requestMethod: unknown): SmpScheduler.RestVerbs | undefined; static requireEnv(name: keyof SmpScheduler.Context, ctx: Partial): string; static toPathSegments(v: unknown): string[]; static toSchedulerJobId(pkgName: string, path: string): string; } declare class SmpSchedulerConfig { private readonly _ctx; private readonly _discoveredCronRoutes; constructor(_ctx: SmpScheduler.Context, _discoveredCronRoutes: readonly SmpScheduler.DiscoveredCronRoute[]); static fromEnv(): SmpScheduler.Context; static loadFromEnvAndBuild(): SmpScheduler.Config; buildConfig(): SmpScheduler.Config; private _buildDefaults; private _buildJobs; } declare class SmpCronModule { } /** * Use this to override the default strategy used by SmpCacheInterceptor. * You can either provide a custom implementation of SmpCacheInterceptorStrategy, * or you can use the Firestore strategy by simply importing the SmpFirestoreModule and enabling the related feature. * For more advanced use cases (e.g. useFactory), you can manage the provisioning yourself. */ declare function smpProvideCacheInterceptorStrategy(cacheStrategy: T): { provide: typeof SmpCacheInterceptorStrategy; useValue: T; }; declare class SmpDatadogWinstonLoggerService extends SmpWinstonLoggerService { protected readonly _configSrv: ConfigService; protected get _searchParams(): url.URLSearchParams; constructor(_configSrv: ConfigService); protected _init(): void; } /** * Dynamically generates the @nextLink for DTOs derived from smpQueryFilterSchema. * * @param basePath The endpoint path, e.g. "/api/rules" * @param query The DTO derived from smpQueryFilterSchema * @param total The total number of available items */ declare function smpBuildPaginationNextLink>(basePath: string, query: T, total: number): string | undefined; declare const SMP_CACHE_HEADER = "x-cache"; declare const SMP_CORRELATION_ID_HEADER = "x-correlation-id"; /** * This can be put before the global exception interceptor, to automagically map other errors into HttpException (and derivatives) * @example * ```ts * providers: [ * {provide: APP_FILTER, useClass: SmpErrorMappingFilter}, // IMPORTANT! LAST IS EXECUTED FIRST! * {provide: APP_FILTER, useClass: SmpHttpExceptionFilter}, * ] * ``` */ declare class SmpErrorMappingFilter implements ExceptionFilter { catch(exception: unknown): void; } declare const smpHopByHopHeaders: Set; declare class SmpHttpBadRequestException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpConflictException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpExceptionFilter implements ExceptionFilter { private readonly _loggerSrv; constructor(_loggerSrv: SmpWinstonLoggerService); catch(exception: HttpException, host: ArgumentsHost): void; } declare class SmpHttpForbiddenException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpMethodNotAllowedException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpNotFoundException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpServerException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpUnauthorizedException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare class SmpHttpTooManyRequestsException extends SmpHttpException { constructor({ messages, ...rest }?: SmpHttpExceptionParams); } declare enum SmpMapiHeaders { X_MAPI_CACHE = "X-MAPI-Cache" } type ProxyPredicate = (req: Request) => boolean; type GetTargetUrlFunction = (req: Request) => string; declare const smpProxyMiddlewareFactory: (predicate: ProxyPredicate, getTargetUrl: GetTargetUrlFunction, logger?: SmpLoggerMethods) => (req: Request, res: Response, next: NextFunction) => Promise; declare enum SmpDbQueryOps { AND = "AND", OR = "OR", EQUALS = "=", NOT_EQUALS = "!=", GT = ">", GTE = ">=", LT = "<", LTE = "<=", LIKE = "LIKE", NOT_LIKE = "NOT LIKE", IN = "IN", IS = "IS", NOT_IN = "NOT IN", STAR = "*", PERCENT = "%" } interface SmpDbQueryFieldCondition { field: string; op: Exclude; value: any; } interface SmpQueryNestedCondition { op: SmpDbQueryOps.AND | SmpDbQueryOps.OR; value: SmpDbQueryCondition[]; } type SmpDbQueryCondition = SmpDbQueryFieldCondition | SmpQueryNestedCondition; type SmpDbQueryWhere = string | object | SmpDbQueryCondition[]; interface SmpDbBaseActionConfig { tableName: string; transformColumnNames?: boolean; where: SmpDbQueryWhere; } type SmpQueryConfigParam = SmpPrimitive | null; interface SmpDbQueryConfig extends Pick { distinct?: boolean; limit?: number; offset?: number; query: string; params?: Record | SmpQueryConfigParam[]; } declare class SmpDbCon { protected readonly _logger: SmpLoggerMethods; protected _con?: T; protected _queryTimeout: number; constructor(_logger?: SmpLoggerMethods); static mapValsForQuery(vals: (string | number | boolean)[]): (string | number)[]; doDelete(tableName: string, condition: string): Observable; doInsert(tableName: string, cols: string[], vals: (string | number)[]): Observable; /** * Universal method to do queries. It supports both sequential or key substitutions, * but managing everything in the _doQuery is up to you, * depending on the capabilities of the DB lib you're using */ doQuery(rawConfig: string): Observable; doQuery(rawConfig: SmpDbQueryConfig): Observable; multiQuery(queries: string[]): Observable; multiSelectAll(configs: { tableName: string; condition: string; }[]): Observable; selectAllFromTable(tableName: string, condition?: string): Observable; selectColsFromTable(tableName: string, cols: string[], condition?: string, distinct?: boolean, camelCaseAlias?: boolean): Observable; update(tableName: string, cols: string[], vals: (string | number)[], condition: string): Observable; protected _colsPlaceholder(cols: string[]): string; /** * This method should be implemented on derived classes to perform queries! * @param _config_ * @protected */ protected _doQuery(_config_: SmpDbQueryConfig): Observable; /** * Implement this on derived classes to create this._con; * @protected */ protected _init(): Observable; } type SmpDbDeleteConfig = SmpDbBaseActionConfig; interface SmpDbInsertConfig extends Pick { toInsert: T[]; } interface SmpDbSelectConfig extends Omit { cols: string[]; tableName: string; where?: SmpDbQueryWhere; } type SmpDbSelectCountConfig = Omit; interface SmpDbUpdateConfig extends SmpDbBaseActionConfig { updates: object; } interface SmpKnexDbConConfig { client: Knex.Config["client"]; configPrefix: string; } type DbErrorMap = Record) => SmpHttpException>>; /** * Map of errors grouped by dialect (that is extracted via knex using `this._con.client.dialect`) */ declare const smpDbErrors: DbErrorMap; /** * Base class to build database connections using Knex.js. * You can either: * - inject directly this class if you know you have a unique instance of it * - extend this class if you need more functionalities * - dynamically build a db connection provider using smpKnexDbConProvider */ declare class SmpKnexDbConService implements OnApplicationShutdown { protected readonly _configSrv: ConfigService; protected readonly _logger: SmpWinstonLoggerService; protected readonly _dbErrors: typeof smpDbErrors; protected static _config: SmpKnexDbConConfig; get dialect(): string; protected get _staticSelf(): typeof SmpKnexDbConService & { _config: SmpKnexDbConConfig; }; protected _con?: Knex; protected _dialect: string; protected _knexConfig: Knex.Config; constructor(_configSrv: ConfigService, _logger: SmpWinstonLoggerService, _dbErrors?: typeof smpDbErrors); delete(config: SmpDbDeleteConfig): Observable; doQuery(config: SmpDbQueryConfig): Observable; getQueryBuilder(): Observable; insert(config: SmpDbInsertConfig): Observable<{ id: string; }[]>; /** * Parallelize multiple queries * @param configs * @param[configs.query] the actual query * @param[configs.params] the params to bind * @param[configs.key] the key to find your query result in your returned observable. Optional, will use [configs.query] if not provided. */ multiQuery>(configs: { [K in keyof TMap]: SmpDbQueryConfig; }): Observable<{ [K in keyof TMap]: TMap[K][]; }>; /** * Multiple parallel select all queries (in a mapped format) */ multiSelectAll>(configs: { [K in keyof TMap]: SmpDbSelectConfig; }): Observable<{ [K in keyof TMap]: TMap[K][]; }>; onApplicationShutdown(signal?: string): void; selectAllFromTable(config: Omit): Observable; selectColsFromTable(config: SmpDbSelectConfig): Observable; selectCountAllFromTable({ where, ...rest }: SmpDbSelectCountConfig): Observable<{ total: number; }>; update(config: SmpDbUpdateConfig): Observable; protected _applyFilter(config: { query: Knex.QueryBuilder; where: SmpDbQueryCondition[]; transformColumnNames?: boolean; isOr?: boolean; }): Knex.QueryBuilder; protected _getConfig(key: string): Exclude ? _nestjs_config.PathValue : never : never : never : never : never : never, undefined> | Exclude; protected _init(): Observable; protected _initConfig(): void; protected _selectFromTable({ where, ...rest }: Omit & Partial>): Observable; protected _withCon(fn: (con: Knex) => Promise): Observable; } /** * Mostly intended to be used through the smpKnexDbConfigProvider to generate dynamic providers and tokens * @param client supports mysql2, sqlite3, better-sqlite3, pg, mssql, tedious you can either pass a string, or the client itself via require * @param configPrefix */ declare function smpKnexDbConFactory(client: SmpKnexDbConConfig["client"], configPrefix?: SmpKnexDbConConfig["configPrefix"]): typeof SmpKnexDbConService; /** * Use this to generate multiple unique providers for different database connections * @param name a unique name that will be used to build the injection token * @param client supports mysql2, sqlite3, better-sqlite3, pg, mssql, tedious you can either pass a string, or the client itself via require * @param configPrefix the prefix of the config keys in your properties file (e.g. db, having db.host, db.port, etc...) see also SmpEnvironmentVariables */ declare function smpKnexDbConProvider(name: string, client: SmpKnexDbConConfig["client"], configPrefix?: string): ClassProvider; type SmpSshConfig = Pick & { onKeyboardInteractive?: (...args: any[]) => void; }; interface SmpSshForwardConfig { dstPort: number; dstIP: string; srcIP: string; srcPort: number; } /** * Represents a database connection over an SSH tunnel. Extends the base functionality of the `SmpDbCon` class * and adds support for creating and managing SSH tunnels using the `Client` from the 'ssh2' module. * To use this class, you should define your configuration and pass it to _createTunnel to create a tunneled connection (to put into this._con). * Then use this._con to run your queries * * @template T * * @extends SmpDbCon * * @remarks * This class provides functionality to establish an SSH tunnel and forward the database connection through it. * Uses observables to handle asynchronous operations related to SSH tunnel creation. */ declare class SmpDbConSsh extends SmpDbCon { protected _tunnel?: Client; constructor(logger?: SmpLoggerMethods); protected _createTunnel(sshConfig: SmpSshConfig, forwardConfig: SmpSshForwardConfig): Observable; } type TransportAuthType = "bearer" | "apikey" | "basic" | "custom" | "none"; type TransportMethod = "POST" | "PUT"; /** * Options for Axios Transport. * @param {string} url - The url to send the logs to. * @param {string} path - The path to send the logs to. The destination url will resolve to url + path. * @param {string} auth - The authentication token to send with the logs. Will override any auth headers provided in {@link headers}. * @param {TransportAuthType} authType - The type of authentication to use. * @param {TransportMethod} method - The method to use when sending the logs. * @param {AxiosRequestHeaders} headers - The headers to send with the logs. */ interface SmpWinstonAxiosTransportOptions extends TransportStream.TransportStreamOptions { url?: string; path?: string; auth?: { username: string; password: string; }; authType?: TransportAuthType; method?: TransportMethod; headers?: AxiosRequestHeaders; bodyAddons?: object; replacer?: (key: string, value: any) => any; timeout?: number; } /** * Transport for Winston that sends log messages to a remote server using Axios. * @param {SmpWinstonAxiosTransportOptions} options - The options for the transport. * @see {@link SmpWinstonAxiosTransportOptions} * @example * const logger = createLogger({ * transports: [ * new AxiosTransport({ * url: 'http://localhost:3000', * path: '/logs' * }), * ], * }); * logger.log({ level: 'info', message: 'Hello World' }); */ declare class SmpWinstonAxiosTransport extends TransportStream { protected _axiosInstance: AxiosInstance; protected _bodyAddons?: SmpWinstonAxiosTransportOptions["bodyAddons"]; protected _cancelTokenSource: CancelTokenSource; protected _closed: boolean; protected _isAxiosCancel: (err: any) => err is Cancel; protected _url: string; constructor(opts?: SmpWinstonAxiosTransportOptions); close(callback?: () => void): void; log(info: any, callback: () => void): void; } declare const kebabName: string; declare const name: string; declare const version: string; declare const index_kebabName: typeof kebabName; declare const index_name: typeof name; declare const index_version: typeof version; declare namespace index { export { index_kebabName as kebabName, index_name as name, index_version as version }; } declare const VERSION: "2.0.2"; export { SMP_BASIC_AUTH_USERS_FORBID_META_KEY, SMP_BASIC_AUTH_USERS_META_KEY, SMP_CACHEABLE_META_KEY, SMP_CACHE_HEADER, SMP_CORRELATION_ID_HEADER, SMP_CRON_JOB_META_KEY, SMP_GLOBAL_ERROR_LOGGER_META_KEY, SMP_OIDC_GROUPS_META_KEY, SMP_OIDC_ROLES_META_KEY, SMP_PUBLIC_KEY, SMP_SKIP_CLASS_SERIALIZER_KEY, SMP_SKIP_REST_LOGGING_KEY, SmpAbstractAuthGuard, SmpAbstractEncryptionStrategy, SmpAbstractOidcAuthService, SmpAbstractUserService, type SmpAesEncryptionStrategyOpts, SmpBasicAuthForbiddenTo, SmpBasicAuthGuard, SmpBasicAuthRestrictedTo, SmpBasicAuthUserService, SmpBasicAuthUsers, SmpBasicAuthUsersForbid, SmpCacheInterceptor, SmpCacheInterceptorStrategy, type SmpCacheMetadata, SmpCacheable, SmpClassSerializerInterceptor, SmpConfigModule, SmpCronJob, type SmpCronJobMetadata, SmpCronModule, SmpCronSchedulerDiscoveryService, SmpDatadogWinstonLoggerService, type SmpDbBaseActionConfig, SmpDbCon, SmpDbConSsh, type SmpDbDeleteConfig, type SmpDbInsertConfig, type SmpDbQueryCondition, type SmpDbQueryConfig, SmpDbQueryOps, type SmpDbQueryWhere, type SmpDbSelectConfig, type SmpDbSelectCountConfig, type SmpDbUpdateConfig, type SmpEnvConfig, SmpEnvProperties, SmpEnvironmentVariables, SmpEnvironmentVariablesAesEncryptionStrategy, SmpErrorMappingFilter, SmpGlobalErrorLogger, SmpGlobalErrorLoggerInterceptor, SmpHttpBadRequestException, SmpHttpConflictException, SmpHttpException, SmpHttpExceptionFilter, type SmpHttpExceptionParams, SmpHttpForbiddenException, SmpHttpMethodNotAllowedException, SmpHttpNotFoundException, SmpHttpServerException, SmpHttpTooManyRequestsException, SmpHttpUnauthorizedException, SmpJwtAuthGuard, SmpJwtUserService, type SmpKnexDbConConfig, SmpKnexDbConService, SmpMapiHeaders, SmpMicrosoftAuthService, SmpOidcAuthGuard, SmpOidcGroups, SmpOidcRoles, SmpOidcUser, type SmpOidcUserClaims, SmpPublic, type SmpQueryConfigParam, SmpRequiredHeadersGuard, SmpRestLoggerInterceptor, SmpScheduler, SmpSchedulerConfig, type SmpSchedulerDiscoveryResult, SmpSchedulerUtils, SmpSkipClassSerializer, SmpSkipRestLogging, type SmpSshConfig, type SmpSshForwardConfig, SmpWinstonAxiosTransport, SmpWinstonLoggerService, VERSION, index as pkg, smpBuildPaginationNextLink, smpDefaultEnvConfig, smpEnvironments, smpHopByHopHeaders, smpKnexDbConFactory, smpKnexDbConProvider, smpProvideCacheInterceptorStrategy, smpProxyMiddlewareFactory };