elseware-nodejs 1.9.1 → 1.11.0

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
@@ -1994,6 +1994,145 @@ declare class ZodValidator implements IValidator {
1994
1994
  validate<T = unknown>(data: unknown): ValidationResult<T>;
1995
1995
  }
1996
1996
 
1997
+ interface RequestContextOptions {
1998
+ /**
1999
+ * Header used for correlation id propagation.
2000
+ *
2001
+ * Default:
2002
+ * X-Correlation-Id
2003
+ */
2004
+ correlationHeaderName?: string;
2005
+ /**
2006
+ * Whether to expose the correlation id
2007
+ * back to the client in response headers.
2008
+ *
2009
+ * Default:
2010
+ * true
2011
+ */
2012
+ exposeHeader?: boolean;
2013
+ }
2014
+
2015
+ declare function createRequestContextMiddleware(options?: RequestContextOptions): RequestHandler;
2016
+
2017
+ declare class CorrelationId {
2018
+ static generate(): string;
2019
+ }
2020
+
2021
+ interface RequestContextData {
2022
+ correlationId: string;
2023
+ requestId?: string;
2024
+ userId?: string;
2025
+ tenantId?: string;
2026
+ }
2027
+ declare class RequestContext {
2028
+ private static readonly storage;
2029
+ static run<T>(context: RequestContextData, callback: () => T): T;
2030
+ static get(): RequestContextData | undefined;
2031
+ static getCorrelationId(): string | undefined;
2032
+ static getRequestId(): string | undefined;
2033
+ static getUserId(): string | undefined;
2034
+ static getTenantId(): string | undefined;
2035
+ }
2036
+
2037
+ declare class TracingHeaders {
2038
+ static build(): Record<string, string>;
2039
+ }
2040
+
2041
+ interface RetryPolicy {
2042
+ shouldRetry(attempt: number, error?: unknown): boolean;
2043
+ getDelay(attempt: number, error?: unknown): number;
2044
+ }
2045
+
2046
+ interface ExponentialBackoffOptions {
2047
+ retries?: number;
2048
+ baseDelay?: number;
2049
+ maxDelay?: number;
2050
+ }
2051
+ declare class ExponentialBackoffRetryPolicy implements RetryPolicy {
2052
+ private readonly retries;
2053
+ private readonly baseDelay;
2054
+ private readonly maxDelay;
2055
+ constructor(options?: ExponentialBackoffOptions);
2056
+ shouldRetry(attempt: number): boolean;
2057
+ getDelay(attempt: number): number;
2058
+ }
2059
+
2060
+ interface FixedRetryPolicyOptions {
2061
+ retries?: number;
2062
+ delay?: number;
2063
+ }
2064
+ declare class FixedRetryPolicy implements RetryPolicy {
2065
+ private readonly retries;
2066
+ private readonly delay;
2067
+ constructor(options?: FixedRetryPolicyOptions);
2068
+ shouldRetry(attempt: number): boolean;
2069
+ getDelay(_attempt: number, _error?: unknown): number;
2070
+ }
2071
+
2072
+ interface AuthStrategy {
2073
+ getHeaders(): Promise<Record<string, string>>;
2074
+ }
2075
+
2076
+ interface TokenProvider {
2077
+ getToken(): Promise<string> | string;
2078
+ }
2079
+
2080
+ declare class BearerTokenStrategy implements AuthStrategy {
2081
+ private readonly tokenProvider;
2082
+ constructor(tokenProvider: TokenProvider);
2083
+ getHeaders(): Promise<Record<string, string>>;
2084
+ }
2085
+
2086
+ declare class StaticTokenProvider implements TokenProvider {
2087
+ private readonly token;
2088
+ constructor(token: string);
2089
+ getToken(): string;
2090
+ }
2091
+
2092
+ interface HttpClientOptions {
2093
+ timeout?: number;
2094
+ headers?: Record<string, string>;
2095
+ serviceName?: string;
2096
+ retryPolicy?: RetryPolicy;
2097
+ }
2098
+
2099
+ declare class HttpClient {
2100
+ protected readonly baseUrl: string;
2101
+ protected readonly timeout: number;
2102
+ protected readonly headers: Record<string, string>;
2103
+ protected readonly serviceName: string;
2104
+ protected readonly authStrategy?: AuthStrategy;
2105
+ protected readonly retryPolicy: RetryPolicy;
2106
+ constructor(baseUrl: string, options?: HttpClientOptions & {
2107
+ authStrategy?: AuthStrategy;
2108
+ });
2109
+ protected get<T>(path: string): Promise<T>;
2110
+ protected post<T>(path: string, body?: unknown): Promise<T>;
2111
+ protected put<T>(path: string, body?: unknown): Promise<T>;
2112
+ protected patch<T>(path: string, body?: unknown): Promise<T>;
2113
+ protected delete<T>(path: string): Promise<T>;
2114
+ private request;
2115
+ private sleep;
2116
+ }
2117
+
2118
+ declare abstract class ServiceClient extends HttpClient {
2119
+ protected getData<T>(path: string): Promise<T>;
2120
+ protected postData<T>(path: string, body?: unknown): Promise<T>;
2121
+ protected putData<T>(path: string, body?: unknown): Promise<T>;
2122
+ protected patchData<T>(path: string, body?: unknown): Promise<T>;
2123
+ protected deleteData<T>(path: string): Promise<T>;
2124
+ }
2125
+
2126
+ declare abstract class InternalServiceClient extends ServiceClient {
2127
+ constructor(baseUrl: string, serviceToken: string, serviceName?: string);
2128
+ }
2129
+
2130
+ interface ServiceResponse<T> {
2131
+ status: string;
2132
+ message?: string;
2133
+ data: T;
2134
+ }
2135
+
1997
2136
  declare class MongoRepository<T> implements Repository<T> {
1998
2137
  protected model: Model<T>;
1999
2138
  constructor(model: Model<T>);
@@ -2176,4 +2315,4 @@ declare function toMinutes(ms: number): number;
2176
2315
  declare function toHours(ms: number): number;
2177
2316
  declare function sleep(ms: number): Promise<void>;
2178
2317
 
2179
- export { AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, ApiFeatures, type ApiMeta, ApiResponse, type ApiResponseOptions, AppError, AsyncHandler, type AsyncRequestHandler, type AuthenticatedUser, type AzureBlobStorageConfig, AzureBlobStorageService, BPlusTree, BTree, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CountMinSketch, CrudControllerFactory, type CrudControllerOptions, DEFAULT_LIMIT, DEFAULT_PAGE, DEFAULT_SORT_DIRECTION, type DatabaseConnectionOptions, DatabaseManager, type DatabaseProvider, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, type EmailProvider, EmailService, type ErrorMeta, ErrorMiddleware, FenwickTree, FibNode, FibonacciHeap, type Filter, Graph, HashMap, HashSet, HyperLogLog, type IValidator, type Interval, IntervalTree, JWTService, type JWTServiceOptions, JoiValidator, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, type MongoDatabaseConfig, MongoDatabaseProvider, MongoRepository, MulterFileHandlerService, MultiSet, Node, OrderedSet, type PaginationMeta, type PaginationQuery, PairingHeap, PairingNode, type ParsedQuery, type PickOptions, type Point, type Point2D, PriorityQueue, type ProgressCallback, QUERY_RESERVED_FIELDS, QuadTree, type QueryFilter, type QueryOperator, type QueryOptions, type QuerySort, Queue, RadixTree, type Rect, RedBlackTree, type Repository, SMTPProvider, SUPPORTED_OPERATORS, SegmentTree, type Select, type SendEmailOptions, Set, SinglyLinkedList, type Sort, SparseTable, SplayTree, Stack, type StandardApiResponse, StaticArray, SuffixArray, SuffixTree, TemplateEngine, TernarySearchTree, TreeNode, Trie, type UpdateQueryOptions, type UploadOptions, type ValidationResult, type ValidationSchema, ZodValidator, authMiddleware, createAllowedOrigins, createCorsOptions, days, errorToString, hours, isJoiSchema, isZodSchema, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
2318
+ export { AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, ApiFeatures, type ApiMeta, ApiResponse, type ApiResponseOptions, AppError, AsyncHandler, type AsyncRequestHandler, type AuthStrategy, type AuthenticatedUser, type AzureBlobStorageConfig, AzureBlobStorageService, BPlusTree, BTree, BearerTokenStrategy, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CorrelationId, CountMinSketch, CrudControllerFactory, type CrudControllerOptions, DEFAULT_LIMIT, DEFAULT_PAGE, DEFAULT_SORT_DIRECTION, type DatabaseConnectionOptions, DatabaseManager, type DatabaseProvider, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, type EmailProvider, EmailService, type ErrorMeta, ErrorMiddleware, type ExponentialBackoffOptions, ExponentialBackoffRetryPolicy, FenwickTree, FibNode, FibonacciHeap, type Filter, FixedRetryPolicy, type FixedRetryPolicyOptions, Graph, HashMap, HashSet, HttpClient, type HttpClientOptions, HyperLogLog, type IValidator, InternalServiceClient, type Interval, IntervalTree, JWTService, type JWTServiceOptions, JoiValidator, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, type MongoDatabaseConfig, MongoDatabaseProvider, MongoRepository, MulterFileHandlerService, MultiSet, Node, OrderedSet, type PaginationMeta, type PaginationQuery, PairingHeap, PairingNode, type ParsedQuery, type PickOptions, type Point, type Point2D, PriorityQueue, type ProgressCallback, QUERY_RESERVED_FIELDS, QuadTree, type QueryFilter, type QueryOperator, type QueryOptions, type QuerySort, Queue, RadixTree, type Rect, RedBlackTree, type Repository, RequestContext, type RequestContextData, type RequestContextOptions, type RetryPolicy, SMTPProvider, SUPPORTED_OPERATORS, SegmentTree, type Select, type SendEmailOptions, ServiceClient, type ServiceResponse, Set, SinglyLinkedList, type Sort, SparseTable, SplayTree, Stack, type StandardApiResponse, StaticArray, StaticTokenProvider, SuffixArray, SuffixTree, TemplateEngine, TernarySearchTree, type TokenProvider, TracingHeaders, TreeNode, Trie, type UpdateQueryOptions, type UploadOptions, type ValidationResult, type ValidationSchema, ZodValidator, authMiddleware, createAllowedOrigins, createCorsOptions, createRequestContextMiddleware, days, errorToString, hours, isJoiSchema, isZodSchema, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
package/dist/index.d.ts CHANGED
@@ -1994,6 +1994,145 @@ declare class ZodValidator implements IValidator {
1994
1994
  validate<T = unknown>(data: unknown): ValidationResult<T>;
1995
1995
  }
1996
1996
 
1997
+ interface RequestContextOptions {
1998
+ /**
1999
+ * Header used for correlation id propagation.
2000
+ *
2001
+ * Default:
2002
+ * X-Correlation-Id
2003
+ */
2004
+ correlationHeaderName?: string;
2005
+ /**
2006
+ * Whether to expose the correlation id
2007
+ * back to the client in response headers.
2008
+ *
2009
+ * Default:
2010
+ * true
2011
+ */
2012
+ exposeHeader?: boolean;
2013
+ }
2014
+
2015
+ declare function createRequestContextMiddleware(options?: RequestContextOptions): RequestHandler;
2016
+
2017
+ declare class CorrelationId {
2018
+ static generate(): string;
2019
+ }
2020
+
2021
+ interface RequestContextData {
2022
+ correlationId: string;
2023
+ requestId?: string;
2024
+ userId?: string;
2025
+ tenantId?: string;
2026
+ }
2027
+ declare class RequestContext {
2028
+ private static readonly storage;
2029
+ static run<T>(context: RequestContextData, callback: () => T): T;
2030
+ static get(): RequestContextData | undefined;
2031
+ static getCorrelationId(): string | undefined;
2032
+ static getRequestId(): string | undefined;
2033
+ static getUserId(): string | undefined;
2034
+ static getTenantId(): string | undefined;
2035
+ }
2036
+
2037
+ declare class TracingHeaders {
2038
+ static build(): Record<string, string>;
2039
+ }
2040
+
2041
+ interface RetryPolicy {
2042
+ shouldRetry(attempt: number, error?: unknown): boolean;
2043
+ getDelay(attempt: number, error?: unknown): number;
2044
+ }
2045
+
2046
+ interface ExponentialBackoffOptions {
2047
+ retries?: number;
2048
+ baseDelay?: number;
2049
+ maxDelay?: number;
2050
+ }
2051
+ declare class ExponentialBackoffRetryPolicy implements RetryPolicy {
2052
+ private readonly retries;
2053
+ private readonly baseDelay;
2054
+ private readonly maxDelay;
2055
+ constructor(options?: ExponentialBackoffOptions);
2056
+ shouldRetry(attempt: number): boolean;
2057
+ getDelay(attempt: number): number;
2058
+ }
2059
+
2060
+ interface FixedRetryPolicyOptions {
2061
+ retries?: number;
2062
+ delay?: number;
2063
+ }
2064
+ declare class FixedRetryPolicy implements RetryPolicy {
2065
+ private readonly retries;
2066
+ private readonly delay;
2067
+ constructor(options?: FixedRetryPolicyOptions);
2068
+ shouldRetry(attempt: number): boolean;
2069
+ getDelay(_attempt: number, _error?: unknown): number;
2070
+ }
2071
+
2072
+ interface AuthStrategy {
2073
+ getHeaders(): Promise<Record<string, string>>;
2074
+ }
2075
+
2076
+ interface TokenProvider {
2077
+ getToken(): Promise<string> | string;
2078
+ }
2079
+
2080
+ declare class BearerTokenStrategy implements AuthStrategy {
2081
+ private readonly tokenProvider;
2082
+ constructor(tokenProvider: TokenProvider);
2083
+ getHeaders(): Promise<Record<string, string>>;
2084
+ }
2085
+
2086
+ declare class StaticTokenProvider implements TokenProvider {
2087
+ private readonly token;
2088
+ constructor(token: string);
2089
+ getToken(): string;
2090
+ }
2091
+
2092
+ interface HttpClientOptions {
2093
+ timeout?: number;
2094
+ headers?: Record<string, string>;
2095
+ serviceName?: string;
2096
+ retryPolicy?: RetryPolicy;
2097
+ }
2098
+
2099
+ declare class HttpClient {
2100
+ protected readonly baseUrl: string;
2101
+ protected readonly timeout: number;
2102
+ protected readonly headers: Record<string, string>;
2103
+ protected readonly serviceName: string;
2104
+ protected readonly authStrategy?: AuthStrategy;
2105
+ protected readonly retryPolicy: RetryPolicy;
2106
+ constructor(baseUrl: string, options?: HttpClientOptions & {
2107
+ authStrategy?: AuthStrategy;
2108
+ });
2109
+ protected get<T>(path: string): Promise<T>;
2110
+ protected post<T>(path: string, body?: unknown): Promise<T>;
2111
+ protected put<T>(path: string, body?: unknown): Promise<T>;
2112
+ protected patch<T>(path: string, body?: unknown): Promise<T>;
2113
+ protected delete<T>(path: string): Promise<T>;
2114
+ private request;
2115
+ private sleep;
2116
+ }
2117
+
2118
+ declare abstract class ServiceClient extends HttpClient {
2119
+ protected getData<T>(path: string): Promise<T>;
2120
+ protected postData<T>(path: string, body?: unknown): Promise<T>;
2121
+ protected putData<T>(path: string, body?: unknown): Promise<T>;
2122
+ protected patchData<T>(path: string, body?: unknown): Promise<T>;
2123
+ protected deleteData<T>(path: string): Promise<T>;
2124
+ }
2125
+
2126
+ declare abstract class InternalServiceClient extends ServiceClient {
2127
+ constructor(baseUrl: string, serviceToken: string, serviceName?: string);
2128
+ }
2129
+
2130
+ interface ServiceResponse<T> {
2131
+ status: string;
2132
+ message?: string;
2133
+ data: T;
2134
+ }
2135
+
1997
2136
  declare class MongoRepository<T> implements Repository<T> {
1998
2137
  protected model: Model<T>;
1999
2138
  constructor(model: Model<T>);
@@ -2176,4 +2315,4 @@ declare function toMinutes(ms: number): number;
2176
2315
  declare function toHours(ms: number): number;
2177
2316
  declare function sleep(ms: number): Promise<void>;
2178
2317
 
2179
- export { AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, ApiFeatures, type ApiMeta, ApiResponse, type ApiResponseOptions, AppError, AsyncHandler, type AsyncRequestHandler, type AuthenticatedUser, type AzureBlobStorageConfig, AzureBlobStorageService, BPlusTree, BTree, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CountMinSketch, CrudControllerFactory, type CrudControllerOptions, DEFAULT_LIMIT, DEFAULT_PAGE, DEFAULT_SORT_DIRECTION, type DatabaseConnectionOptions, DatabaseManager, type DatabaseProvider, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, type EmailProvider, EmailService, type ErrorMeta, ErrorMiddleware, FenwickTree, FibNode, FibonacciHeap, type Filter, Graph, HashMap, HashSet, HyperLogLog, type IValidator, type Interval, IntervalTree, JWTService, type JWTServiceOptions, JoiValidator, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, type MongoDatabaseConfig, MongoDatabaseProvider, MongoRepository, MulterFileHandlerService, MultiSet, Node, OrderedSet, type PaginationMeta, type PaginationQuery, PairingHeap, PairingNode, type ParsedQuery, type PickOptions, type Point, type Point2D, PriorityQueue, type ProgressCallback, QUERY_RESERVED_FIELDS, QuadTree, type QueryFilter, type QueryOperator, type QueryOptions, type QuerySort, Queue, RadixTree, type Rect, RedBlackTree, type Repository, SMTPProvider, SUPPORTED_OPERATORS, SegmentTree, type Select, type SendEmailOptions, Set, SinglyLinkedList, type Sort, SparseTable, SplayTree, Stack, type StandardApiResponse, StaticArray, SuffixArray, SuffixTree, TemplateEngine, TernarySearchTree, TreeNode, Trie, type UpdateQueryOptions, type UploadOptions, type ValidationResult, type ValidationSchema, ZodValidator, authMiddleware, createAllowedOrigins, createCorsOptions, days, errorToString, hours, isJoiSchema, isZodSchema, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
2318
+ export { AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, ApiFeatures, type ApiMeta, ApiResponse, type ApiResponseOptions, AppError, AsyncHandler, type AsyncRequestHandler, type AuthStrategy, type AuthenticatedUser, type AzureBlobStorageConfig, AzureBlobStorageService, BPlusTree, BTree, BearerTokenStrategy, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CorrelationId, CountMinSketch, CrudControllerFactory, type CrudControllerOptions, DEFAULT_LIMIT, DEFAULT_PAGE, DEFAULT_SORT_DIRECTION, type DatabaseConnectionOptions, DatabaseManager, type DatabaseProvider, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, type EmailProvider, EmailService, type ErrorMeta, ErrorMiddleware, type ExponentialBackoffOptions, ExponentialBackoffRetryPolicy, FenwickTree, FibNode, FibonacciHeap, type Filter, FixedRetryPolicy, type FixedRetryPolicyOptions, Graph, HashMap, HashSet, HttpClient, type HttpClientOptions, HyperLogLog, type IValidator, InternalServiceClient, type Interval, IntervalTree, JWTService, type JWTServiceOptions, JoiValidator, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, type MongoDatabaseConfig, MongoDatabaseProvider, MongoRepository, MulterFileHandlerService, MultiSet, Node, OrderedSet, type PaginationMeta, type PaginationQuery, PairingHeap, PairingNode, type ParsedQuery, type PickOptions, type Point, type Point2D, PriorityQueue, type ProgressCallback, QUERY_RESERVED_FIELDS, QuadTree, type QueryFilter, type QueryOperator, type QueryOptions, type QuerySort, Queue, RadixTree, type Rect, RedBlackTree, type Repository, RequestContext, type RequestContextData, type RequestContextOptions, type RetryPolicy, SMTPProvider, SUPPORTED_OPERATORS, SegmentTree, type Select, type SendEmailOptions, ServiceClient, type ServiceResponse, Set, SinglyLinkedList, type Sort, SparseTable, SplayTree, Stack, type StandardApiResponse, StaticArray, StaticTokenProvider, SuffixArray, SuffixTree, TemplateEngine, TernarySearchTree, type TokenProvider, TracingHeaders, TreeNode, Trie, type UpdateQueryOptions, type UploadOptions, type ValidationResult, type ValidationSchema, ZodValidator, authMiddleware, createAllowedOrigins, createCorsOptions, createRequestContextMiddleware, days, errorToString, hours, isJoiSchema, isZodSchema, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import dotenv from 'dotenv';
2
2
  import mongoose from 'mongoose';
3
+ import { randomUUID } from 'crypto';
4
+ import { AsyncLocalStorage } from 'async_hooks';
3
5
  import { BlobServiceClient, StorageSharedKeyCredential, generateBlobSASQueryParameters, BlobSASPermissions } from '@azure/storage-blob';
4
6
  import fs3 from 'fs';
5
7
  import cloudinaryModule from 'cloudinary';
@@ -1904,7 +1906,6 @@ var CircularQueue = class {
1904
1906
  }
1905
1907
  this.data = new Array(capacity);
1906
1908
  }
1907
- capacity;
1908
1909
  data;
1909
1910
  head = 0;
1910
1911
  tail = 0;
@@ -4833,8 +4834,6 @@ var DatabaseManager = class {
4833
4834
  this.provider = provider;
4834
4835
  this.options = options;
4835
4836
  }
4836
- provider;
4837
- options;
4838
4837
  async connect() {
4839
4838
  try {
4840
4839
  await this.provider.connect();
@@ -4877,7 +4876,6 @@ var MongoDatabaseProvider = class {
4877
4876
  constructor(config) {
4878
4877
  this.config = config;
4879
4878
  }
4880
- config;
4881
4879
  async connect() {
4882
4880
  mongoose.set("strictQuery", this.config.strictQuery ?? true);
4883
4881
  await mongoose.connect(this.config.uri);
@@ -5308,7 +5306,6 @@ var JoiValidator = class {
5308
5306
  constructor(schema) {
5309
5307
  this.schema = schema;
5310
5308
  }
5311
- schema;
5312
5309
  validate(data) {
5313
5310
  const result = this.schema.validate(data, {
5314
5311
  abortEarly: false,
@@ -5337,7 +5334,6 @@ var ZodValidator = class {
5337
5334
  constructor(schema) {
5338
5335
  this.schema = schema;
5339
5336
  }
5340
- schema;
5341
5337
  validate(data) {
5342
5338
  const result = this.schema.safeParse(data);
5343
5339
  if (!result.success) {
@@ -5415,6 +5411,275 @@ function pickFields(obj, fields, options = {}) {
5415
5411
  }
5416
5412
  return result;
5417
5413
  }
5414
+ var CorrelationId = class {
5415
+ static generate() {
5416
+ return randomUUID();
5417
+ }
5418
+ };
5419
+ var RequestContext = class {
5420
+ static storage = new AsyncLocalStorage();
5421
+ static run(context, callback) {
5422
+ return this.storage.run(context, callback);
5423
+ }
5424
+ static get() {
5425
+ return this.storage.getStore();
5426
+ }
5427
+ static getCorrelationId() {
5428
+ return this.get()?.correlationId;
5429
+ }
5430
+ static getRequestId() {
5431
+ return this.get()?.requestId;
5432
+ }
5433
+ static getUserId() {
5434
+ return this.get()?.userId;
5435
+ }
5436
+ static getTenantId() {
5437
+ return this.get()?.tenantId;
5438
+ }
5439
+ };
5440
+
5441
+ // src/networking/middleware/RequestContextMiddleware.ts
5442
+ function createRequestContextMiddleware(options = {}) {
5443
+ const {
5444
+ correlationHeaderName = "X-Correlation-Id",
5445
+ exposeHeader = true
5446
+ } = options;
5447
+ return (req, res, next) => {
5448
+ const correlationId = req.header(correlationHeaderName) ?? CorrelationId.generate();
5449
+ if (exposeHeader) {
5450
+ res.setHeader(correlationHeaderName, correlationId);
5451
+ }
5452
+ RequestContext.run(
5453
+ {
5454
+ correlationId
5455
+ },
5456
+ () => next()
5457
+ );
5458
+ };
5459
+ }
5460
+
5461
+ // src/networking/observability/TracingHeaders.ts
5462
+ var TracingHeaders = class {
5463
+ static build() {
5464
+ const headers = {};
5465
+ const correlationId = RequestContext.getCorrelationId();
5466
+ const requestId = RequestContext.getRequestId();
5467
+ const userId = RequestContext.getUserId();
5468
+ const tenantId = RequestContext.getTenantId();
5469
+ if (correlationId) {
5470
+ headers["X-Correlation-Id"] = correlationId;
5471
+ }
5472
+ if (requestId) {
5473
+ headers["X-Request-Id"] = requestId;
5474
+ }
5475
+ if (userId) {
5476
+ headers["X-User-Id"] = userId;
5477
+ }
5478
+ if (tenantId) {
5479
+ headers["X-Tenant-Id"] = tenantId;
5480
+ }
5481
+ return headers;
5482
+ }
5483
+ };
5484
+
5485
+ // src/networking/resilience/ExponentialBackoffRetryPolicy.ts
5486
+ var ExponentialBackoffRetryPolicy = class {
5487
+ retries;
5488
+ baseDelay;
5489
+ maxDelay;
5490
+ constructor(options = {}) {
5491
+ this.retries = options.retries ?? 5;
5492
+ this.baseDelay = options.baseDelay ?? 200;
5493
+ this.maxDelay = options.maxDelay ?? 1e4;
5494
+ }
5495
+ shouldRetry(attempt) {
5496
+ return attempt < this.retries;
5497
+ }
5498
+ getDelay(attempt) {
5499
+ const delay = this.baseDelay * Math.pow(2, attempt);
5500
+ return Math.min(delay, this.maxDelay);
5501
+ }
5502
+ };
5503
+
5504
+ // src/networking/resilience/FixedRetryPolicy.ts
5505
+ var FixedRetryPolicy = class {
5506
+ retries;
5507
+ delay;
5508
+ constructor(options = {}) {
5509
+ this.retries = options.retries ?? 2;
5510
+ this.delay = options.delay ?? 500;
5511
+ }
5512
+ shouldRetry(attempt) {
5513
+ return attempt < this.retries;
5514
+ }
5515
+ getDelay(_attempt, _error) {
5516
+ return this.delay;
5517
+ }
5518
+ };
5519
+
5520
+ // src/networking/security/BearerTokenStrategy.ts
5521
+ var BearerTokenStrategy = class {
5522
+ constructor(tokenProvider) {
5523
+ this.tokenProvider = tokenProvider;
5524
+ }
5525
+ async getHeaders() {
5526
+ const token = await this.tokenProvider.getToken();
5527
+ return {
5528
+ Authorization: `Bearer ${token}`
5529
+ };
5530
+ }
5531
+ };
5532
+
5533
+ // src/networking/security/StaticTokenProvider.ts
5534
+ var StaticTokenProvider = class {
5535
+ constructor(token) {
5536
+ this.token = token;
5537
+ }
5538
+ getToken() {
5539
+ return this.token;
5540
+ }
5541
+ };
5542
+
5543
+ // src/networking/transport/HttpClient.ts
5544
+ var HttpClient = class {
5545
+ baseUrl;
5546
+ timeout;
5547
+ headers;
5548
+ serviceName;
5549
+ authStrategy;
5550
+ retryPolicy;
5551
+ constructor(baseUrl, options = {}) {
5552
+ this.baseUrl = baseUrl;
5553
+ this.timeout = options.timeout ?? 5e3;
5554
+ this.headers = options.headers ?? {};
5555
+ this.serviceName = options.serviceName ?? "UnknownService";
5556
+ this.authStrategy = options.authStrategy;
5557
+ this.retryPolicy = options.retryPolicy ?? new FixedRetryPolicy({
5558
+ retries: 2,
5559
+ delay: 500
5560
+ });
5561
+ }
5562
+ async get(path2) {
5563
+ return this.request("GET", path2);
5564
+ }
5565
+ async post(path2, body) {
5566
+ return this.request("POST", path2, body);
5567
+ }
5568
+ async put(path2, body) {
5569
+ return this.request("PUT", path2, body);
5570
+ }
5571
+ async patch(path2, body) {
5572
+ return this.request("PATCH", path2, body);
5573
+ }
5574
+ async delete(path2) {
5575
+ return this.request("DELETE", path2);
5576
+ }
5577
+ async request(method, path2, body) {
5578
+ let attempt = 0;
5579
+ let lastError;
5580
+ while (true) {
5581
+ try {
5582
+ const controller = new AbortController();
5583
+ const timeout = setTimeout(() => controller.abort(), this.timeout);
5584
+ const authHeaders = await this.authStrategy?.getHeaders();
5585
+ const response = await fetch(`${this.baseUrl}${path2}`, {
5586
+ method,
5587
+ signal: controller.signal,
5588
+ headers: {
5589
+ "Content-Type": "application/json",
5590
+ ...TracingHeaders.build(),
5591
+ ...this.headers,
5592
+ ...authHeaders
5593
+ },
5594
+ body: body !== void 0 ? JSON.stringify(body) : void 0
5595
+ });
5596
+ clearTimeout(timeout);
5597
+ const json = await response.json();
5598
+ if (!response.ok) {
5599
+ throw new AppError(
5600
+ json?.message ?? "HTTP request failed",
5601
+ response.status,
5602
+ {
5603
+ code: json?.code ?? "HTTP_REQUEST_FAILED",
5604
+ details: {
5605
+ service: this.serviceName,
5606
+ method,
5607
+ path: path2
5608
+ }
5609
+ }
5610
+ );
5611
+ }
5612
+ const correlationId2 = RequestContext.getCorrelationId();
5613
+ logger.info(
5614
+ `[${this.serviceName}]` + (correlationId2 ? ` [${correlationId2}]` : "") + ` ${method} ${path2}`
5615
+ );
5616
+ return json;
5617
+ } catch (error) {
5618
+ lastError = error;
5619
+ if (this.retryPolicy.shouldRetry(attempt, error)) {
5620
+ const delay = this.retryPolicy.getDelay(attempt, error);
5621
+ logger.warning(
5622
+ `[${this.serviceName}] retry ${attempt + 1} after ${delay}ms`
5623
+ );
5624
+ await this.sleep(delay);
5625
+ attempt++;
5626
+ continue;
5627
+ }
5628
+ break;
5629
+ }
5630
+ }
5631
+ const correlationId = RequestContext.getCorrelationId();
5632
+ logger.danger(
5633
+ `[${this.serviceName}]` + (correlationId ? ` [${correlationId}]` : "") + ` request failed`,
5634
+ lastError
5635
+ );
5636
+ throw lastError;
5637
+ }
5638
+ sleep(ms) {
5639
+ return new Promise((resolve) => setTimeout(resolve, ms));
5640
+ }
5641
+ };
5642
+
5643
+ // src/networking/services/ServiceClient.ts
5644
+ var ServiceClient = class extends HttpClient {
5645
+ async getData(path2) {
5646
+ const response = await super.get(path2);
5647
+ return response.data;
5648
+ }
5649
+ async postData(path2, body) {
5650
+ const response = await super.post(path2, body);
5651
+ return response.data;
5652
+ }
5653
+ async putData(path2, body) {
5654
+ const response = await super.put(path2, body);
5655
+ return response.data;
5656
+ }
5657
+ async patchData(path2, body) {
5658
+ const response = await super.patch(path2, body);
5659
+ return response.data;
5660
+ }
5661
+ async deleteData(path2) {
5662
+ const response = await super.delete(path2);
5663
+ return response.data;
5664
+ }
5665
+ };
5666
+
5667
+ // src/networking/services/InternalServiceClient.ts
5668
+ var InternalServiceClient = class extends ServiceClient {
5669
+ constructor(baseUrl, serviceToken, serviceName) {
5670
+ super(baseUrl, {
5671
+ serviceName,
5672
+ authStrategy: new BearerTokenStrategy(
5673
+ new StaticTokenProvider(serviceToken)
5674
+ ),
5675
+ timeout: 5e3,
5676
+ retryPolicy: new ExponentialBackoffRetryPolicy({
5677
+ retries: 3,
5678
+ baseDelay: 200
5679
+ })
5680
+ });
5681
+ }
5682
+ };
5418
5683
 
5419
5684
  // src/repositories/providers/MongoRepository.ts
5420
5685
  var MongoRepository = class {
@@ -6003,6 +6268,6 @@ function sleep(ms) {
6003
6268
  return new Promise((resolve) => setTimeout(resolve, ms));
6004
6269
  }
6005
6270
 
6006
- export { AVLTree, AdjacencyList, AdjacencyMatrix, ApiFeatures, ApiResponse, AppError, AsyncHandler, AzureBlobStorageService, BPlusTree, BTree, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, CloudinaryService, ConsistentHash, CountMinSketch, CrudControllerFactory, DEFAULT_LIMIT, DEFAULT_PAGE, DEFAULT_SORT_DIRECTION, DatabaseManager, Deque, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, EmailService, ErrorMiddleware, FenwickTree, FibNode, FibonacciHeap, Graph, HashMap, HashSet, HyperLogLog, IntervalTree, JWTService, JoiValidator, KDTree, LFUCache, LRUCache, MaxHeap, MaxStack, MinHeap, MinStack, MongoDatabaseProvider, MongoRepository, MulterFileHandlerService, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, PriorityQueue, QUERY_RESERVED_FIELDS, QuadTree, Queue, RadixTree, RedBlackTree, SMTPProvider, SUPPORTED_OPERATORS, SegmentTree, Set2 as Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TemplateEngine, TernarySearchTree, TreeNode, Trie, ZodValidator, authMiddleware, createAllowedOrigins, createCorsOptions, days, errorToString, hours, isJoiSchema, isZodSchema, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
6271
+ export { AVLTree, AdjacencyList, AdjacencyMatrix, ApiFeatures, ApiResponse, AppError, AsyncHandler, AzureBlobStorageService, BPlusTree, BTree, BearerTokenStrategy, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, CloudinaryService, ConsistentHash, CorrelationId, CountMinSketch, CrudControllerFactory, DEFAULT_LIMIT, DEFAULT_PAGE, DEFAULT_SORT_DIRECTION, DatabaseManager, Deque, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, EmailService, ErrorMiddleware, ExponentialBackoffRetryPolicy, FenwickTree, FibNode, FibonacciHeap, FixedRetryPolicy, Graph, HashMap, HashSet, HttpClient, HyperLogLog, InternalServiceClient, IntervalTree, JWTService, JoiValidator, KDTree, LFUCache, LRUCache, MaxHeap, MaxStack, MinHeap, MinStack, MongoDatabaseProvider, MongoRepository, MulterFileHandlerService, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, PriorityQueue, QUERY_RESERVED_FIELDS, QuadTree, Queue, RadixTree, RedBlackTree, RequestContext, SMTPProvider, SUPPORTED_OPERATORS, SegmentTree, ServiceClient, Set2 as Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, StaticTokenProvider, SuffixArray, SuffixTree, TemplateEngine, TernarySearchTree, TracingHeaders, TreeNode, Trie, ZodValidator, authMiddleware, createAllowedOrigins, createCorsOptions, createRequestContextMiddleware, days, errorToString, hours, isJoiSchema, isZodSchema, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
6007
6272
  //# sourceMappingURL=index.js.map
6008
6273
  //# sourceMappingURL=index.js.map