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/README.md CHANGED
@@ -1 +1 @@
1
- # elseware-nodejs
1
+ # elseware-nodejs
package/dist/index.cjs CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  var dotenv = require('dotenv');
4
4
  var mongoose = require('mongoose');
5
+ var crypto = require('crypto');
6
+ var async_hooks = require('async_hooks');
5
7
  var storageBlob = require('@azure/storage-blob');
6
8
  var fs3 = require('fs');
7
9
  var cloudinaryModule = require('cloudinary');
@@ -1919,7 +1921,6 @@ var CircularQueue = class {
1919
1921
  }
1920
1922
  this.data = new Array(capacity);
1921
1923
  }
1922
- capacity;
1923
1924
  data;
1924
1925
  head = 0;
1925
1926
  tail = 0;
@@ -4848,8 +4849,6 @@ var DatabaseManager = class {
4848
4849
  this.provider = provider;
4849
4850
  this.options = options;
4850
4851
  }
4851
- provider;
4852
- options;
4853
4852
  async connect() {
4854
4853
  try {
4855
4854
  await this.provider.connect();
@@ -4892,7 +4891,6 @@ var MongoDatabaseProvider = class {
4892
4891
  constructor(config) {
4893
4892
  this.config = config;
4894
4893
  }
4895
- config;
4896
4894
  async connect() {
4897
4895
  mongoose__default.default.set("strictQuery", this.config.strictQuery ?? true);
4898
4896
  await mongoose__default.default.connect(this.config.uri);
@@ -5323,7 +5321,6 @@ var JoiValidator = class {
5323
5321
  constructor(schema) {
5324
5322
  this.schema = schema;
5325
5323
  }
5326
- schema;
5327
5324
  validate(data) {
5328
5325
  const result = this.schema.validate(data, {
5329
5326
  abortEarly: false,
@@ -5352,7 +5349,6 @@ var ZodValidator = class {
5352
5349
  constructor(schema) {
5353
5350
  this.schema = schema;
5354
5351
  }
5355
- schema;
5356
5352
  validate(data) {
5357
5353
  const result = this.schema.safeParse(data);
5358
5354
  if (!result.success) {
@@ -5430,6 +5426,275 @@ function pickFields(obj, fields, options = {}) {
5430
5426
  }
5431
5427
  return result;
5432
5428
  }
5429
+ var CorrelationId = class {
5430
+ static generate() {
5431
+ return crypto.randomUUID();
5432
+ }
5433
+ };
5434
+ var RequestContext = class {
5435
+ static storage = new async_hooks.AsyncLocalStorage();
5436
+ static run(context, callback) {
5437
+ return this.storage.run(context, callback);
5438
+ }
5439
+ static get() {
5440
+ return this.storage.getStore();
5441
+ }
5442
+ static getCorrelationId() {
5443
+ return this.get()?.correlationId;
5444
+ }
5445
+ static getRequestId() {
5446
+ return this.get()?.requestId;
5447
+ }
5448
+ static getUserId() {
5449
+ return this.get()?.userId;
5450
+ }
5451
+ static getTenantId() {
5452
+ return this.get()?.tenantId;
5453
+ }
5454
+ };
5455
+
5456
+ // src/networking/middleware/RequestContextMiddleware.ts
5457
+ function createRequestContextMiddleware(options = {}) {
5458
+ const {
5459
+ correlationHeaderName = "X-Correlation-Id",
5460
+ exposeHeader = true
5461
+ } = options;
5462
+ return (req, res, next) => {
5463
+ const correlationId = req.header(correlationHeaderName) ?? CorrelationId.generate();
5464
+ if (exposeHeader) {
5465
+ res.setHeader(correlationHeaderName, correlationId);
5466
+ }
5467
+ RequestContext.run(
5468
+ {
5469
+ correlationId
5470
+ },
5471
+ () => next()
5472
+ );
5473
+ };
5474
+ }
5475
+
5476
+ // src/networking/observability/TracingHeaders.ts
5477
+ var TracingHeaders = class {
5478
+ static build() {
5479
+ const headers = {};
5480
+ const correlationId = RequestContext.getCorrelationId();
5481
+ const requestId = RequestContext.getRequestId();
5482
+ const userId = RequestContext.getUserId();
5483
+ const tenantId = RequestContext.getTenantId();
5484
+ if (correlationId) {
5485
+ headers["X-Correlation-Id"] = correlationId;
5486
+ }
5487
+ if (requestId) {
5488
+ headers["X-Request-Id"] = requestId;
5489
+ }
5490
+ if (userId) {
5491
+ headers["X-User-Id"] = userId;
5492
+ }
5493
+ if (tenantId) {
5494
+ headers["X-Tenant-Id"] = tenantId;
5495
+ }
5496
+ return headers;
5497
+ }
5498
+ };
5499
+
5500
+ // src/networking/resilience/ExponentialBackoffRetryPolicy.ts
5501
+ var ExponentialBackoffRetryPolicy = class {
5502
+ retries;
5503
+ baseDelay;
5504
+ maxDelay;
5505
+ constructor(options = {}) {
5506
+ this.retries = options.retries ?? 5;
5507
+ this.baseDelay = options.baseDelay ?? 200;
5508
+ this.maxDelay = options.maxDelay ?? 1e4;
5509
+ }
5510
+ shouldRetry(attempt) {
5511
+ return attempt < this.retries;
5512
+ }
5513
+ getDelay(attempt) {
5514
+ const delay = this.baseDelay * Math.pow(2, attempt);
5515
+ return Math.min(delay, this.maxDelay);
5516
+ }
5517
+ };
5518
+
5519
+ // src/networking/resilience/FixedRetryPolicy.ts
5520
+ var FixedRetryPolicy = class {
5521
+ retries;
5522
+ delay;
5523
+ constructor(options = {}) {
5524
+ this.retries = options.retries ?? 2;
5525
+ this.delay = options.delay ?? 500;
5526
+ }
5527
+ shouldRetry(attempt) {
5528
+ return attempt < this.retries;
5529
+ }
5530
+ getDelay(_attempt, _error) {
5531
+ return this.delay;
5532
+ }
5533
+ };
5534
+
5535
+ // src/networking/security/BearerTokenStrategy.ts
5536
+ var BearerTokenStrategy = class {
5537
+ constructor(tokenProvider) {
5538
+ this.tokenProvider = tokenProvider;
5539
+ }
5540
+ async getHeaders() {
5541
+ const token = await this.tokenProvider.getToken();
5542
+ return {
5543
+ Authorization: `Bearer ${token}`
5544
+ };
5545
+ }
5546
+ };
5547
+
5548
+ // src/networking/security/StaticTokenProvider.ts
5549
+ var StaticTokenProvider = class {
5550
+ constructor(token) {
5551
+ this.token = token;
5552
+ }
5553
+ getToken() {
5554
+ return this.token;
5555
+ }
5556
+ };
5557
+
5558
+ // src/networking/transport/HttpClient.ts
5559
+ var HttpClient = class {
5560
+ baseUrl;
5561
+ timeout;
5562
+ headers;
5563
+ serviceName;
5564
+ authStrategy;
5565
+ retryPolicy;
5566
+ constructor(baseUrl, options = {}) {
5567
+ this.baseUrl = baseUrl;
5568
+ this.timeout = options.timeout ?? 5e3;
5569
+ this.headers = options.headers ?? {};
5570
+ this.serviceName = options.serviceName ?? "UnknownService";
5571
+ this.authStrategy = options.authStrategy;
5572
+ this.retryPolicy = options.retryPolicy ?? new FixedRetryPolicy({
5573
+ retries: 2,
5574
+ delay: 500
5575
+ });
5576
+ }
5577
+ async get(path2) {
5578
+ return this.request("GET", path2);
5579
+ }
5580
+ async post(path2, body) {
5581
+ return this.request("POST", path2, body);
5582
+ }
5583
+ async put(path2, body) {
5584
+ return this.request("PUT", path2, body);
5585
+ }
5586
+ async patch(path2, body) {
5587
+ return this.request("PATCH", path2, body);
5588
+ }
5589
+ async delete(path2) {
5590
+ return this.request("DELETE", path2);
5591
+ }
5592
+ async request(method, path2, body) {
5593
+ let attempt = 0;
5594
+ let lastError;
5595
+ while (true) {
5596
+ try {
5597
+ const controller = new AbortController();
5598
+ const timeout = setTimeout(() => controller.abort(), this.timeout);
5599
+ const authHeaders = await this.authStrategy?.getHeaders();
5600
+ const response = await fetch(`${this.baseUrl}${path2}`, {
5601
+ method,
5602
+ signal: controller.signal,
5603
+ headers: {
5604
+ "Content-Type": "application/json",
5605
+ ...TracingHeaders.build(),
5606
+ ...this.headers,
5607
+ ...authHeaders
5608
+ },
5609
+ body: body !== void 0 ? JSON.stringify(body) : void 0
5610
+ });
5611
+ clearTimeout(timeout);
5612
+ const json = await response.json();
5613
+ if (!response.ok) {
5614
+ throw new AppError(
5615
+ json?.message ?? "HTTP request failed",
5616
+ response.status,
5617
+ {
5618
+ code: json?.code ?? "HTTP_REQUEST_FAILED",
5619
+ details: {
5620
+ service: this.serviceName,
5621
+ method,
5622
+ path: path2
5623
+ }
5624
+ }
5625
+ );
5626
+ }
5627
+ const correlationId2 = RequestContext.getCorrelationId();
5628
+ logger.info(
5629
+ `[${this.serviceName}]` + (correlationId2 ? ` [${correlationId2}]` : "") + ` ${method} ${path2}`
5630
+ );
5631
+ return json;
5632
+ } catch (error) {
5633
+ lastError = error;
5634
+ if (this.retryPolicy.shouldRetry(attempt, error)) {
5635
+ const delay = this.retryPolicy.getDelay(attempt, error);
5636
+ logger.warning(
5637
+ `[${this.serviceName}] retry ${attempt + 1} after ${delay}ms`
5638
+ );
5639
+ await this.sleep(delay);
5640
+ attempt++;
5641
+ continue;
5642
+ }
5643
+ break;
5644
+ }
5645
+ }
5646
+ const correlationId = RequestContext.getCorrelationId();
5647
+ logger.danger(
5648
+ `[${this.serviceName}]` + (correlationId ? ` [${correlationId}]` : "") + ` request failed`,
5649
+ lastError
5650
+ );
5651
+ throw lastError;
5652
+ }
5653
+ sleep(ms) {
5654
+ return new Promise((resolve) => setTimeout(resolve, ms));
5655
+ }
5656
+ };
5657
+
5658
+ // src/networking/services/ServiceClient.ts
5659
+ var ServiceClient = class extends HttpClient {
5660
+ async getData(path2) {
5661
+ const response = await super.get(path2);
5662
+ return response.data;
5663
+ }
5664
+ async postData(path2, body) {
5665
+ const response = await super.post(path2, body);
5666
+ return response.data;
5667
+ }
5668
+ async putData(path2, body) {
5669
+ const response = await super.put(path2, body);
5670
+ return response.data;
5671
+ }
5672
+ async patchData(path2, body) {
5673
+ const response = await super.patch(path2, body);
5674
+ return response.data;
5675
+ }
5676
+ async deleteData(path2) {
5677
+ const response = await super.delete(path2);
5678
+ return response.data;
5679
+ }
5680
+ };
5681
+
5682
+ // src/networking/services/InternalServiceClient.ts
5683
+ var InternalServiceClient = class extends ServiceClient {
5684
+ constructor(baseUrl, serviceToken, serviceName) {
5685
+ super(baseUrl, {
5686
+ serviceName,
5687
+ authStrategy: new BearerTokenStrategy(
5688
+ new StaticTokenProvider(serviceToken)
5689
+ ),
5690
+ timeout: 5e3,
5691
+ retryPolicy: new ExponentialBackoffRetryPolicy({
5692
+ retries: 3,
5693
+ baseDelay: 200
5694
+ })
5695
+ });
5696
+ }
5697
+ };
5433
5698
 
5434
5699
  // src/repositories/providers/MongoRepository.ts
5435
5700
  var MongoRepository = class {
@@ -6028,6 +6293,7 @@ exports.AsyncHandler = AsyncHandler;
6028
6293
  exports.AzureBlobStorageService = AzureBlobStorageService;
6029
6294
  exports.BPlusTree = BPlusTree;
6030
6295
  exports.BTree = BTree;
6296
+ exports.BearerTokenStrategy = BearerTokenStrategy;
6031
6297
  exports.BinaryHeap = BinaryHeap;
6032
6298
  exports.BinarySearchTree = BinarySearchTree;
6033
6299
  exports.BinaryTree = BinaryTree;
@@ -6037,6 +6303,7 @@ exports.CircularLinkedList = CircularLinkedList;
6037
6303
  exports.CircularQueue = CircularQueue;
6038
6304
  exports.CloudinaryService = CloudinaryService;
6039
6305
  exports.ConsistentHash = ConsistentHash;
6306
+ exports.CorrelationId = CorrelationId;
6040
6307
  exports.CountMinSketch = CountMinSketch;
6041
6308
  exports.CrudControllerFactory = CrudControllerFactory;
6042
6309
  exports.DEFAULT_LIMIT = DEFAULT_LIMIT;
@@ -6050,13 +6317,17 @@ exports.DoublyLinkedList = DoublyLinkedList;
6050
6317
  exports.DynamicArray = DynamicArray;
6051
6318
  exports.EmailService = EmailService;
6052
6319
  exports.ErrorMiddleware = ErrorMiddleware;
6320
+ exports.ExponentialBackoffRetryPolicy = ExponentialBackoffRetryPolicy;
6053
6321
  exports.FenwickTree = FenwickTree;
6054
6322
  exports.FibNode = FibNode;
6055
6323
  exports.FibonacciHeap = FibonacciHeap;
6324
+ exports.FixedRetryPolicy = FixedRetryPolicy;
6056
6325
  exports.Graph = Graph;
6057
6326
  exports.HashMap = HashMap;
6058
6327
  exports.HashSet = HashSet;
6328
+ exports.HttpClient = HttpClient;
6059
6329
  exports.HyperLogLog = HyperLogLog;
6330
+ exports.InternalServiceClient = InternalServiceClient;
6060
6331
  exports.IntervalTree = IntervalTree;
6061
6332
  exports.JWTService = JWTService;
6062
6333
  exports.JoiValidator = JoiValidator;
@@ -6081,25 +6352,30 @@ exports.QuadTree = QuadTree;
6081
6352
  exports.Queue = Queue;
6082
6353
  exports.RadixTree = RadixTree;
6083
6354
  exports.RedBlackTree = RedBlackTree;
6355
+ exports.RequestContext = RequestContext;
6084
6356
  exports.SMTPProvider = SMTPProvider;
6085
6357
  exports.SUPPORTED_OPERATORS = SUPPORTED_OPERATORS;
6086
6358
  exports.SegmentTree = SegmentTree;
6359
+ exports.ServiceClient = ServiceClient;
6087
6360
  exports.Set = Set2;
6088
6361
  exports.SinglyLinkedList = SinglyLinkedList;
6089
6362
  exports.SparseTable = SparseTable;
6090
6363
  exports.SplayTree = SplayTree;
6091
6364
  exports.Stack = Stack;
6092
6365
  exports.StaticArray = StaticArray;
6366
+ exports.StaticTokenProvider = StaticTokenProvider;
6093
6367
  exports.SuffixArray = SuffixArray;
6094
6368
  exports.SuffixTree = SuffixTree;
6095
6369
  exports.TemplateEngine = TemplateEngine;
6096
6370
  exports.TernarySearchTree = TernarySearchTree;
6371
+ exports.TracingHeaders = TracingHeaders;
6097
6372
  exports.TreeNode = TreeNode;
6098
6373
  exports.Trie = Trie;
6099
6374
  exports.ZodValidator = ZodValidator;
6100
6375
  exports.authMiddleware = authMiddleware;
6101
6376
  exports.createAllowedOrigins = createAllowedOrigins;
6102
6377
  exports.createCorsOptions = createCorsOptions;
6378
+ exports.createRequestContextMiddleware = createRequestContextMiddleware;
6103
6379
  exports.days = days;
6104
6380
  exports.errorToString = errorToString;
6105
6381
  exports.hours = hours;