wsp-ms-core 1.0.68 → 1.0.70

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.js CHANGED
@@ -194,7 +194,7 @@ var _UUID = class _UUID extends ValueObject {
194
194
  return { value: this.value };
195
195
  }
196
196
  static create(uuid) {
197
- return new _UUID(uuid != null ? uuid : crypto.randomUUID());
197
+ return new _UUID(uuid ?? crypto.randomUUID());
198
198
  }
199
199
  static version(uuid) {
200
200
  const m = /^[0-9a-f]{8}-[0-9a-f]{4}-([1-8])[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.exec(uuid);
@@ -207,9 +207,8 @@ var _UUID = class _UUID extends ValueObject {
207
207
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid);
208
208
  }
209
209
  static isValid(uuid, opts = {}) {
210
- var _a, _b;
211
- const allowed = (_a = opts.allowedVersions) != null ? _a : [1, 2, 3, 4, 5, 6, 7, 8];
212
- const allowNil = (_b = opts.allowNil) != null ? _b : false;
210
+ const allowed = opts.allowedVersions ?? [1, 2, 3, 4, 5, 6, 7, 8];
211
+ const allowNil = opts.allowNil ?? false;
213
212
  if (allowNil && _UUID.isNil(uuid))
214
213
  return true;
215
214
  if (!_UUID.isRFCStyle(uuid))
@@ -318,7 +317,6 @@ var DomainEvent = class _DomainEvent {
318
317
  this._errorMessage = error;
319
318
  }
320
319
  toPrimitives() {
321
- var _a, _b, _c, _d, _e;
322
320
  return {
323
321
  eventUuid: this.eventUuid.value,
324
322
  eventType: this.eventType,
@@ -329,14 +327,13 @@ var DomainEvent = class _DomainEvent {
329
327
  payload: this.payload,
330
328
  status: this.status.value,
331
329
  attempts: this.attempts,
332
- errorMessage: (_a = this.errorMessage) != null ? _a : void 0,
333
- publishedAt: (_c = (_b = this.publishedAt) == null ? void 0 : _b.value) != null ? _c : void 0,
334
- lastAttempt: (_e = (_d = this.lastAttempt) == null ? void 0 : _d.value) != null ? _e : void 0,
330
+ errorMessage: this.errorMessage ?? void 0,
331
+ publishedAt: this.publishedAt?.value ?? void 0,
332
+ lastAttempt: this.lastAttempt?.value ?? void 0,
335
333
  createdAt: this.createdAt.value
336
334
  };
337
335
  }
338
336
  static reconstitute(data) {
339
- var _a;
340
337
  return new _DomainEvent(
341
338
  UUID.create(data.event_uuid),
342
339
  String(data.event_type),
@@ -347,7 +344,7 @@ var DomainEvent = class _DomainEvent {
347
344
  String(data.payload),
348
345
  DomainEventStatus.create(data.status),
349
346
  Number(data.attempts),
350
- (_a = data.error_message) != null ? _a : void 0,
347
+ data.error_message ?? void 0,
351
348
  data.published_at ? DateTime.create(data.published_at) : void 0,
352
349
  data.last_attempt ? DateTime.create(data.last_attempt) : void 0,
353
350
  data.created_at ? DateTime.create(data.created_at) : void 0
@@ -440,6 +437,297 @@ _Currency.ARS = new _Currency("ARS");
440
437
  _Currency.BRL = new _Currency("BRL");
441
438
  var Currency = _Currency;
442
439
 
440
+ // src/utils/StringVars.ts
441
+ var StringVars = class {
442
+ static parse(str, ob) {
443
+ const regex = /{{(.*?)}}/g;
444
+ return str.replace(regex, (match, variable) => {
445
+ if (ob.hasOwnProperty(variable.trim())) {
446
+ return ob[variable.trim()];
447
+ } else {
448
+ return match;
449
+ }
450
+ });
451
+ }
452
+ };
453
+
454
+ // src/infrastructure/errors/ErrorManager.ts
455
+ var _ErrorManager = class _ErrorManager {
456
+ constructor(logger = null) {
457
+ this.logger = logger;
458
+ }
459
+ getDefaultMessage(lang) {
460
+ return _ErrorManager.DEFAULT_MESSAGES[lang.value] || _ErrorManager.DEFAULT_MESSAGES[lang.base()] || "error";
461
+ }
462
+ onFatal(err, lang) {
463
+ this.logger?.fatal(err.type, err.message);
464
+ return { status: "ERROR", message: this.getDefaultMessage(lang) };
465
+ }
466
+ onInternal(err, lang) {
467
+ this.logger?.error(err.type, err.message);
468
+ return { status: "ERROR", message: this.getDefaultMessage(lang) };
469
+ }
470
+ onUsage(err, lang) {
471
+ const tmpl = _ErrorManager.TEMPLATES.get(err.type);
472
+ if (!tmpl) {
473
+ this.logger?.error("TEMPLATE_NOT_FOUND", `${err.type}`);
474
+ return { status: "ERROR", message: this.getDefaultMessage(lang) };
475
+ }
476
+ const code = lang.value;
477
+ const base = lang.base();
478
+ const rawMsg = tmpl.languages[code] ?? tmpl.languages[base] ?? this.getDefaultMessage(lang);
479
+ return {
480
+ status: 400,
481
+ message: StringVars.parse(rawMsg, err.vars)
482
+ };
483
+ }
484
+ onUnknown(err, lang) {
485
+ this.logger?.error("UNKNOWN_ERROR", err.message);
486
+ return { status: "ERROR", message: this.getDefaultMessage(lang) };
487
+ }
488
+ handle(err, lang) {
489
+ if (["local", "dev"].includes(process.env.ENVIRONMENT ?? "")) {
490
+ console.log(err);
491
+ }
492
+ if (err instanceof FatalError) {
493
+ return this.onFatal(err, lang);
494
+ }
495
+ if (err instanceof InternalError) {
496
+ return this.onInternal(err, lang);
497
+ }
498
+ if (err instanceof UsageError) {
499
+ return this.onUsage(err, lang);
500
+ }
501
+ return this.onUnknown(err, lang);
502
+ }
503
+ static addTemplate(template) {
504
+ _ErrorManager.TEMPLATES.set(template.type, template);
505
+ }
506
+ };
507
+ _ErrorManager.DEFAULT_MESSAGES = {
508
+ "es": "Ups, hemos encontrado un error. Nuestro equipo ya est\xE1 trabajando para solucionarlo",
509
+ "en": "Ups, we found an error. Our team is working on it.",
510
+ "pt": "Ops, encontramos um bug. Nossa equipe j\xE1 est\xE1 trabalhando para resolver isso."
511
+ };
512
+ _ErrorManager.APP_ERRORS = {
513
+ UNDEFINED: "UNDEFINED_ERROR",
514
+ PROCESS: "PROCESS_ERROR",
515
+ DATABASE: "DATABASE_ERROR"
516
+ };
517
+ _ErrorManager.TEMPLATES = /* @__PURE__ */ new Map();
518
+ var ErrorManager = _ErrorManager;
519
+
520
+ // src/domain/value-objects/Country.ts
521
+ ErrorManager.addTemplate({
522
+ type: "INVALID_COUNTRY",
523
+ languages: {
524
+ "es": "El pa\xEDs <{{country}}> no es v\xE1lido o no est\xE1 soportado",
525
+ "en": "Country <{{country}}> is not valid or not supported"
526
+ }
527
+ });
528
+ ErrorManager.addTemplate({
529
+ type: "COUNTRY_NOT_FOUND_BY_ALPHA2",
530
+ languages: {
531
+ "es": "No se encontr\xF3 pa\xEDs con c\xF3digo alpha2 <{{alpha2}}>",
532
+ "en": "Country not found with alpha2 code <{{alpha2}}>"
533
+ }
534
+ });
535
+ ErrorManager.addTemplate({
536
+ type: "COUNTRY_NOT_FOUND_BY_UUID",
537
+ languages: {
538
+ "es": "No se encontr\xF3 pa\xEDs con UUID <{{uuid}}>",
539
+ "en": "Country not found with UUID <{{uuid}}>"
540
+ }
541
+ });
542
+ var _Country = class _Country extends ValueObject {
543
+ constructor(country) {
544
+ const normalizedCountry = country.toUpperCase().trim();
545
+ super(normalizedCountry);
546
+ this._name = normalizedCountry;
547
+ this._alpha2 = _Country.COUNTRIES[normalizedCountry].alpha2;
548
+ this._alpha3 = _Country.COUNTRIES[normalizedCountry].alpha3;
549
+ this._numeric = _Country.COUNTRIES[normalizedCountry].numeric;
550
+ this._uuid = _Country.COUNTRIES[normalizedCountry].uuid;
551
+ this._phoneCode = _Country.COUNTRIES[normalizedCountry].phoneCode;
552
+ this._url = _Country.COUNTRIES[normalizedCountry].url;
553
+ }
554
+ validate(country) {
555
+ if (!_Country.NAMES.includes(country)) {
556
+ throw new UsageError("INVALID_COUNTRY", { country });
557
+ }
558
+ }
559
+ name() {
560
+ return this._name;
561
+ }
562
+ alpha2() {
563
+ return this._alpha2;
564
+ }
565
+ alpha3() {
566
+ return this._alpha3;
567
+ }
568
+ numeric() {
569
+ return this._numeric;
570
+ }
571
+ uuid() {
572
+ return this._uuid;
573
+ }
574
+ phoneCode() {
575
+ return this._phoneCode;
576
+ }
577
+ url() {
578
+ return this._url;
579
+ }
580
+ static findCountryByAlpha2(alpha2) {
581
+ for (const [country, codes] of Object.entries(_Country.COUNTRIES)) {
582
+ if (codes.alpha2 === alpha2.toUpperCase()) {
583
+ return new _Country(country);
584
+ }
585
+ }
586
+ throw new UsageError("COUNTRY_NOT_FOUND_BY_ALPHA2", { alpha2 });
587
+ }
588
+ static findCountryByUUID(uuid) {
589
+ for (const [country, codes] of Object.entries(_Country.COUNTRIES)) {
590
+ if (codes.uuid === uuid) {
591
+ return new _Country(country);
592
+ }
593
+ }
594
+ throw new UsageError("COUNTRY_NOT_FOUND_BY_UUID", { uuid });
595
+ }
596
+ static create(country) {
597
+ return new _Country(country);
598
+ }
599
+ static createOrDefault(country) {
600
+ try {
601
+ return new _Country(country);
602
+ } catch (error) {
603
+ return _Country.DEFAULT;
604
+ }
605
+ }
606
+ toPrimitives() {
607
+ return {
608
+ value: this.value,
609
+ name: this._name,
610
+ alpha2: this._alpha2,
611
+ alpha3: this._alpha3,
612
+ numeric: this._numeric,
613
+ uuid: this._uuid,
614
+ phoneCode: this._phoneCode,
615
+ url: this._url
616
+ };
617
+ }
618
+ static isValid(country) {
619
+ try {
620
+ _Country.create(country);
621
+ return true;
622
+ } catch {
623
+ return false;
624
+ }
625
+ }
626
+ };
627
+ _Country.COUNTRIES = {
628
+ URUGUAY: {
629
+ alpha2: "UY",
630
+ alpha3: "URY",
631
+ numeric: "858",
632
+ phoneCode: "+598",
633
+ uuid: "5739ecc0-d12b-4db5-8897-e03a04a95c72",
634
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/uruguay.png"
635
+ },
636
+ ARGENTINA: {
637
+ alpha2: "AR",
638
+ alpha3: "ARG",
639
+ numeric: "032",
640
+ phoneCode: "+54",
641
+ uuid: "66663efe-ab7a-4166-b971-9f36fd0ea6b2",
642
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/argentina.png"
643
+ },
644
+ ECUADOR: {
645
+ alpha2: "EC",
646
+ alpha3: "ECU",
647
+ numeric: "218",
648
+ phoneCode: "+593",
649
+ uuid: "ee109239-0150-4e5f-9ff2-a85f270092b1",
650
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/ecuador.png"
651
+ },
652
+ PERU: {
653
+ alpha2: "PE",
654
+ alpha3: "PER",
655
+ numeric: "604",
656
+ phoneCode: "+51",
657
+ uuid: "e4d61ef5-b92d-4f9c-8ec1-23f4beb50abd",
658
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/peru.png"
659
+ },
660
+ BRASIL: {
661
+ alpha2: "BR",
662
+ alpha3: "BRA",
663
+ numeric: "076",
664
+ phoneCode: "+55",
665
+ uuid: "b7b91d72-deaf-4641-957c-a65003e33104",
666
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/brasil.png"
667
+ },
668
+ CHILE: {
669
+ alpha2: "CL",
670
+ alpha3: "CHL",
671
+ numeric: "152",
672
+ phoneCode: "+56",
673
+ uuid: "f69b35f4-d734-4c76-866c-29a18bf000fb",
674
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/chile.png"
675
+ },
676
+ VENEZUELA: {
677
+ alpha2: "VE",
678
+ alpha3: "VEN",
679
+ numeric: "862",
680
+ phoneCode: "+58",
681
+ uuid: "31b6c591-63f6-43db-8ea9-829bb03746c5",
682
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/venezuela.png"
683
+ },
684
+ COLOMBIA: {
685
+ alpha2: "CO",
686
+ alpha3: "COL",
687
+ numeric: "170",
688
+ phoneCode: "+57",
689
+ uuid: "6fdfe34b-6726-4604-96af-665ea5fc9239",
690
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/colombia.png"
691
+ },
692
+ BOLIVIA: {
693
+ alpha2: "BO",
694
+ alpha3: "BOL",
695
+ numeric: "068",
696
+ phoneCode: "+591",
697
+ uuid: "948886db-c280-4ba7-a777-a76c180b295b",
698
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/bolivia.png"
699
+ },
700
+ PARAGUAY: {
701
+ alpha2: "PY",
702
+ alpha3: "PRY",
703
+ numeric: "600",
704
+ phoneCode: "+595",
705
+ uuid: "d67b3472-e38d-4900-8ae3-02d99cd1d884",
706
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/paraguay.png"
707
+ },
708
+ USA: {
709
+ alpha2: "US",
710
+ alpha3: "USA",
711
+ numeric: "840",
712
+ phoneCode: "+1",
713
+ uuid: "16ac3b9b-8f7b-4c54-91d5-d62c7cd74ad4",
714
+ url: "https://dev-wonasports.s3.us-east-2.amazonaws.com/assets/usa.png"
715
+ }
716
+ };
717
+ _Country.NAMES = Object.keys(_Country.COUNTRIES);
718
+ _Country.DEFAULT = new _Country("URUGUAY");
719
+ _Country.ARGENTINA = new _Country("ARGENTINA");
720
+ _Country.ECUADOR = new _Country("ECUADOR");
721
+ _Country.PERU = new _Country("PERU");
722
+ _Country.BRASIL = new _Country("BRASIL");
723
+ _Country.CHILE = new _Country("CHILE");
724
+ _Country.VENEZUELA = new _Country("VENEZUELA");
725
+ _Country.COLOMBIA = new _Country("COLOMBIA");
726
+ _Country.BOLIVIA = new _Country("BOLIVIA");
727
+ _Country.PARAGUAY = new _Country("PARAGUAY");
728
+ _Country.USA = new _Country("USA");
729
+ var Country = _Country;
730
+
443
731
  // src/domain/value-objects/Email.ts
444
732
  var _Email = class _Email extends ValueObject {
445
733
  constructor(email) {
@@ -563,91 +851,6 @@ _Language.SPANISH_NICARAGUA = new _Language("es-ni");
563
851
  _Language.SPANISH_PUERTO_RICO = new _Language("es-pr");
564
852
  var Language = _Language;
565
853
 
566
- // src/utils/StringVars.ts
567
- var StringVars = class {
568
- static parse(str, ob) {
569
- const regex = /{{(.*?)}}/g;
570
- return str.replace(regex, (match, variable) => {
571
- if (ob.hasOwnProperty(variable.trim())) {
572
- return ob[variable.trim()];
573
- } else {
574
- return match;
575
- }
576
- });
577
- }
578
- };
579
-
580
- // src/infrastructure/errors/ErrorManager.ts
581
- var _ErrorManager = class _ErrorManager {
582
- constructor(logger = null) {
583
- this.logger = logger;
584
- }
585
- getDefaultMessage(lang) {
586
- return _ErrorManager.DEFAULT_MESSAGES[lang.value] || _ErrorManager.DEFAULT_MESSAGES[lang.base()] || "error";
587
- }
588
- onFatal(err, lang) {
589
- var _a;
590
- (_a = this.logger) == null ? void 0 : _a.fatal(err.type, err.message);
591
- return { status: "ERROR", message: this.getDefaultMessage(lang) };
592
- }
593
- onInternal(err, lang) {
594
- var _a;
595
- (_a = this.logger) == null ? void 0 : _a.error(err.type, err.message);
596
- return { status: "ERROR", message: this.getDefaultMessage(lang) };
597
- }
598
- onUsage(err, lang) {
599
- var _a, _b, _c;
600
- const tmpl = _ErrorManager.TEMPLATES.get(err.type);
601
- if (!tmpl) {
602
- (_a = this.logger) == null ? void 0 : _a.error("TEMPLATE_NOT_FOUND", `${err.type}`);
603
- return { status: "ERROR", message: this.getDefaultMessage(lang) };
604
- }
605
- const code = lang.value;
606
- const base = lang.base();
607
- const rawMsg = (_c = (_b = tmpl.languages[code]) != null ? _b : tmpl.languages[base]) != null ? _c : this.getDefaultMessage(lang);
608
- return {
609
- status: 400,
610
- message: StringVars.parse(rawMsg, err.vars)
611
- };
612
- }
613
- onUnknown(err, lang) {
614
- var _a;
615
- (_a = this.logger) == null ? void 0 : _a.error("UNKNOWN_ERROR", err.message);
616
- return { status: "ERROR", message: this.getDefaultMessage(lang) };
617
- }
618
- handle(err, lang) {
619
- var _a;
620
- if (["local", "dev"].includes((_a = process.env.ENVIRONMENT) != null ? _a : "")) {
621
- console.log(err);
622
- }
623
- if (err instanceof FatalError) {
624
- return this.onFatal(err, lang);
625
- }
626
- if (err instanceof InternalError) {
627
- return this.onInternal(err, lang);
628
- }
629
- if (err instanceof UsageError) {
630
- return this.onUsage(err, lang);
631
- }
632
- return this.onUnknown(err, lang);
633
- }
634
- static addTemplate(template) {
635
- _ErrorManager.TEMPLATES.set(template.type, template);
636
- }
637
- };
638
- _ErrorManager.DEFAULT_MESSAGES = {
639
- "es": "Ups, hemos encontrado un error. Nuestro equipo ya est\xE1 trabajando para solucionarlo",
640
- "en": "Ups, we found an error. Our team is working on it.",
641
- "pt": "Ops, encontramos um bug. Nossa equipe j\xE1 est\xE1 trabalhando para resolver isso."
642
- };
643
- _ErrorManager.APP_ERRORS = {
644
- UNDEFINED: "UNDEFINED_ERROR",
645
- PROCESS: "PROCESS_ERROR",
646
- DATABASE: "DATABASE_ERROR"
647
- };
648
- _ErrorManager.TEMPLATES = /* @__PURE__ */ new Map();
649
- var ErrorManager = _ErrorManager;
650
-
651
854
  // src/domain/value-objects/Price.ts
652
855
  ErrorManager.addTemplate({
653
856
  type: "INVALID_PRICE_AMOUNT",
@@ -855,14 +1058,70 @@ var BasicUnitOfWorkFactory = class {
855
1058
  }
856
1059
  };
857
1060
 
1061
+ // src/infrastructure/contracts/EventManager.ts
1062
+ var EventManager = class {
1063
+ constructor(connection) {
1064
+ this._connection = connection;
1065
+ this._topics = [];
1066
+ this._callbackList = {};
1067
+ this._onStart = null;
1068
+ this._onConnected = null;
1069
+ this._onSubscribe = null;
1070
+ this._onMessage = null;
1071
+ this._onError = null;
1072
+ this._onCrash = null;
1073
+ this._onReconnect = null;
1074
+ }
1075
+ async execRoute(topic, message) {
1076
+ if (this._callbackList[topic]) {
1077
+ await this._callbackList[topic](message);
1078
+ }
1079
+ }
1080
+ async execCallback(callback, data) {
1081
+ if (callback) {
1082
+ await callback(data);
1083
+ }
1084
+ }
1085
+ route(topic, callback) {
1086
+ this._topics.push(topic);
1087
+ this._callbackList[topic] = callback;
1088
+ }
1089
+ onStart(callback) {
1090
+ this._onStart = callback;
1091
+ }
1092
+ onConnected(callback) {
1093
+ this._onConnected = callback;
1094
+ }
1095
+ onSubscribe(callback) {
1096
+ this._onSubscribe = callback;
1097
+ }
1098
+ onMessage(callback) {
1099
+ this._onMessage = callback;
1100
+ }
1101
+ onError(callback) {
1102
+ this._onError = callback;
1103
+ }
1104
+ onCrash(callback) {
1105
+ this._onCrash = callback;
1106
+ }
1107
+ onReconnect(callback) {
1108
+ this._onReconnect = callback;
1109
+ }
1110
+ get topics() {
1111
+ return this._topics;
1112
+ }
1113
+ get callbackList() {
1114
+ return this._callbackList;
1115
+ }
1116
+ };
1117
+
858
1118
  // src/infrastructure/mysql/Mysql.ts
859
1119
  import { createPool } from "mysql2/promise";
860
1120
  var _MysqlConnector = class _MysqlConnector {
861
1121
  constructor(pool) {
862
- var _a;
863
- this._pool = pool != null ? pool : createPool({
1122
+ this._pool = pool ?? createPool({
864
1123
  host: process.env.DB_HOST,
865
- port: Number((_a = process.env.DB_PORT) != null ? _a : 3306),
1124
+ port: Number(process.env.DB_PORT ?? 3306),
866
1125
  user: process.env.DB_USER,
867
1126
  password: process.env.DB_PASSWORD,
868
1127
  database: process.env.DB_DATABASE,
@@ -975,7 +1234,6 @@ function toUtcDateTimeString(raw) {
975
1234
  return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`;
976
1235
  }
977
1236
  function coerceScalar(key, v) {
978
- var _a;
979
1237
  if (v == null)
980
1238
  return void 0;
981
1239
  if (typeof v !== "string")
@@ -996,7 +1254,7 @@ function coerceScalar(key, v) {
996
1254
  return n;
997
1255
  }
998
1256
  if (DATE_KEY_RE.test(key)) {
999
- return (_a = toUtcDateTimeString(s)) != null ? _a : s;
1257
+ return toUtcDateTimeString(s) ?? s;
1000
1258
  }
1001
1259
  return s;
1002
1260
  }
@@ -1023,8 +1281,7 @@ function hasHeader(headers, name) {
1023
1281
  }
1024
1282
  function adaptExpressRoute(Controller) {
1025
1283
  return async (req, res, next) => {
1026
- var _a, _b;
1027
- const rawLangHeader = (_b = (_a = req.headers["accept-language"]) != null ? _a : req.headers["Accept-Language"]) != null ? _b : "es";
1284
+ const rawLangHeader = req.headers["accept-language"] ?? req.headers["Accept-Language"] ?? "es";
1028
1285
  const rawLang = Array.isArray(rawLangHeader) ? rawLangHeader[0] : rawLangHeader || "";
1029
1286
  const lang = rawLang.split(",")[0].split(";")[0].trim().toLowerCase();
1030
1287
  const httpRequest = {
@@ -1072,7 +1329,7 @@ function adaptExpressRoute(Controller) {
1072
1329
  res.status(statusCode).send(body);
1073
1330
  return;
1074
1331
  }
1075
- res.status(statusCode).json(body != null ? body : {});
1332
+ res.status(statusCode).json(body ?? {});
1076
1333
  } catch (err) {
1077
1334
  next(err);
1078
1335
  }
@@ -1080,9 +1337,8 @@ function adaptExpressRoute(Controller) {
1080
1337
  }
1081
1338
  function adaptExpressErrorHandler(errorManager) {
1082
1339
  return (err, req, res, next) => {
1083
- var _a, _b;
1084
- const raw = (_b = (_a = req.headers["accept-language"]) != null ? _a : req.headers["Accept-Language"]) != null ? _b : "es";
1085
- const rawLang = Array.isArray(raw) ? raw[0] : raw != null ? raw : "";
1340
+ const raw = req.headers["accept-language"] ?? req.headers["Accept-Language"] ?? "es";
1341
+ const rawLang = Array.isArray(raw) ? raw[0] : raw ?? "";
1086
1342
  const langCode = rawLang.split(",")[0].split(";")[0].trim().toLowerCase();
1087
1343
  const result = errorManager.handle(err, Language.create(langCode));
1088
1344
  const statusCode = typeof result.status === "number" ? result.status : 500;
@@ -1096,7 +1352,6 @@ var EventBusMysqlRepository = class {
1096
1352
  this.connection = connection;
1097
1353
  }
1098
1354
  eventToRowValues(e) {
1099
- var _a, _b;
1100
1355
  return [
1101
1356
  e.eventUuid.value,
1102
1357
  e.eventType,
@@ -1108,8 +1363,8 @@ var EventBusMysqlRepository = class {
1108
1363
  e.status.value,
1109
1364
  e.attempts,
1110
1365
  e.errorMessage,
1111
- (_a = e.publishedAt) == null ? void 0 : _a.value,
1112
- (_b = e.lastAttempt) == null ? void 0 : _b.value,
1366
+ e.publishedAt?.value,
1367
+ e.lastAttempt?.value,
1113
1368
  e.createdAt.value
1114
1369
  ];
1115
1370
  }
@@ -1123,8 +1378,7 @@ var EventBusMysqlRepository = class {
1123
1378
  );
1124
1379
  }
1125
1380
  async update(event) {
1126
- var _a, _b;
1127
- const values = [event.status.value, event.attempts, event.errorMessage, (_a = event.publishedAt) == null ? void 0 : _a.value, (_b = event.lastAttempt) == null ? void 0 : _b.value, event.eventUuid.value];
1381
+ const values = [event.status.value, event.attempts, event.errorMessage, event.publishedAt?.value, event.lastAttempt?.value, event.eventUuid.value];
1128
1382
  await this.connection.query(
1129
1383
  `UPDATE events_outbox
1130
1384
  SET status = ?,
@@ -1145,6 +1399,98 @@ var EventBusMysqlRepository = class {
1145
1399
  }
1146
1400
  };
1147
1401
 
1402
+ // src/infrastructure/kafka/KafkaManager.ts
1403
+ import { Kafka, logLevel } from "kafkajs";
1404
+ var KafkaManager = class extends EventManager {
1405
+ constructor(connection) {
1406
+ super(connection);
1407
+ this.kafka = new Kafka({
1408
+ brokers: this._connection.brokers,
1409
+ ssl: true,
1410
+ sasl: {
1411
+ mechanism: "scram-sha-256",
1412
+ username: this._connection.userName,
1413
+ password: this._connection.password
1414
+ },
1415
+ logLevel: logLevel.ERROR
1416
+ });
1417
+ this.consumer = this.kafka.consumer({ groupId: process.env.KAFKA_GROUP || "default" });
1418
+ this.producer = this.kafka.producer();
1419
+ }
1420
+ async run(autocommit) {
1421
+ const __run = async () => {
1422
+ await this.execCallback(this._onStart, { message: `--- ${this.constructor.name} started ---` });
1423
+ await this.consumer.connect();
1424
+ await this.execCallback(this._onConnected, { message: `--- ${this.constructor.name} connected to ${this._connection.brokers} ---` });
1425
+ for (let topic of this._topics) {
1426
+ try {
1427
+ await this.consumer.subscribe({ topic, fromBeginning: true });
1428
+ await this.execCallback(this._onSubscribe, { message: `--- ${this.constructor.name} subscribed to ${topic} ---` });
1429
+ } catch (error) {
1430
+ await this.execCallback(this._onConnected, { message: `Error on subscribe to kafka topic: ${topic}` });
1431
+ }
1432
+ }
1433
+ await this.consumer.run({
1434
+ autoCommit: autocommit,
1435
+ // @ts-ignore
1436
+ eachMessage: async ({ topic, partition, message, heartbeat }) => {
1437
+ try {
1438
+ await this.execCallback(this._onMessage, `[New message detected for ${topic}]: ${message.value?.toString()}`);
1439
+ const evt = JSON.parse(String(message.value?.toString()));
1440
+ await this.execRoute(topic, evt);
1441
+ const next = (BigInt(message.offset) + 1n).toString();
1442
+ await this.consumer.commitOffsets([{ topic, partition, offset: next }]);
1443
+ await heartbeat();
1444
+ } catch (error) {
1445
+ await this.execCallback(this._onError, error);
1446
+ }
1447
+ }
1448
+ });
1449
+ };
1450
+ try {
1451
+ await __run();
1452
+ } catch (error) {
1453
+ await this.execCallback(this._onError, new InternalError(ErrorManager.APP_ERRORS.PROCESS, error.toString()));
1454
+ }
1455
+ }
1456
+ async send(message) {
1457
+ if (!message.producer) {
1458
+ message.producer = process.env.NAME && process.env.ENVIRONMENT ? `${process.env.NAME}-${process.env.ENVIRONMENT}` : "unknown";
1459
+ }
1460
+ if (!message.date) {
1461
+ message.date = DateTime.now().value;
1462
+ }
1463
+ try {
1464
+ if (!this.producer) {
1465
+ throw new InternalError(ErrorManager.APP_ERRORS.PROCESS, "Producer not initialized");
1466
+ }
1467
+ await this.producer.connect();
1468
+ await this.producer.send({
1469
+ topic: message.topic,
1470
+ messages: [{ value: JSON.stringify({ producer: message.producer, data: message }) }]
1471
+ });
1472
+ await this.producer.disconnect();
1473
+ } catch (error) {
1474
+ await this.execCallback(this._onError, new InternalError(ErrorManager.APP_ERRORS.PROCESS, error.toString()));
1475
+ }
1476
+ }
1477
+ async start(autocommit = false) {
1478
+ this.consumer.on(this.consumer.events.CRASH, async (error) => {
1479
+ await this.execCallback(this._onError, new InternalError(ErrorManager.APP_ERRORS.PROCESS, error.payload.error.stack));
1480
+ });
1481
+ await this.run(autocommit);
1482
+ }
1483
+ async pause() {
1484
+ }
1485
+ async restart() {
1486
+ await this.consumer.stop();
1487
+ await this.start();
1488
+ }
1489
+ async stop() {
1490
+ await this.consumer.stop();
1491
+ }
1492
+ };
1493
+
1148
1494
  // src/utils/ExchangeRates.ts
1149
1495
  var ExchangeRates = class _ExchangeRates extends BaseObject {
1150
1496
  constructor(props) {
@@ -1189,11 +1535,10 @@ var ExchangeRates = class _ExchangeRates extends BaseObject {
1189
1535
  return new _ExchangeRates(props);
1190
1536
  }
1191
1537
  static createFromPrimitives(data) {
1192
- var _a, _b;
1193
1538
  return _ExchangeRates.create({
1194
1539
  base: Currency.create(data.base),
1195
- rates: (_a = data.rates) != null ? _a : [],
1196
- date: DateTime.create((_b = data.date) != null ? _b : "")
1540
+ rates: data.rates ?? [],
1541
+ date: DateTime.create(data.date ?? "")
1197
1542
  });
1198
1543
  }
1199
1544
  };
@@ -1201,6 +1546,7 @@ export {
1201
1546
  BaseObject,
1202
1547
  BasicUnitOfWork,
1203
1548
  BasicUnitOfWorkFactory,
1549
+ Country,
1204
1550
  Currency,
1205
1551
  DateTime,
1206
1552
  DomainEntity,
@@ -1211,11 +1557,13 @@ export {
1211
1557
  ErrorManager,
1212
1558
  EventBus,
1213
1559
  EventBusMysqlRepository,
1560
+ EventManager,
1214
1561
  ExchangeRates,
1215
1562
  FatalError,
1216
1563
  HttpHealthCheckController,
1217
1564
  HttpNotFoundController,
1218
1565
  InternalError,
1566
+ KafkaManager,
1219
1567
  Language,
1220
1568
  MysqlConnection,
1221
1569
  MysqlConnector,