@xeno-js/core 2.0.1 → 3.0.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.js CHANGED
@@ -63,37 +63,8 @@ var init_containers = __esm({
63
63
  }
64
64
  });
65
65
 
66
- // src/application/cqrs/base-handler.ts
67
- import {
68
- AppError
69
- } from "@xeno-js/shared";
70
- var BaseHandler;
71
- var init_base_handler = __esm({
72
- "src/application/cqrs/base-handler.ts"() {
73
- "use strict";
74
- BaseHandler = class {
75
- constructor(_identityFactory) {
76
- this._identityFactory = _identityFactory;
77
- }
78
- _identityFactory;
79
- async handle(request, signal) {
80
- AppError.throwIfAborted(signal, this.constructor.name);
81
- return await this.executeAsync(request, signal);
82
- }
83
- /**
84
- * Gets the current context.
85
- * @returns {UserContext} The current context.
86
- * {@link UserContext}
87
- */
88
- _getCurrentContext() {
89
- return this._identityFactory.create();
90
- }
91
- };
92
- }
93
- });
94
-
95
66
  // src/application/cqrs/mediator.ts
96
- import { AppError as AppError2, Result } from "@xeno-js/shared";
67
+ import { AppError, Result } from "@xeno-js/shared";
97
68
  import { ERROR_CODE_MESSAGES, ERROR_CODES, Guards as Guards2, STATUS_CODES, TOKENS as TOKENS2 } from "@xeno-js/shared";
98
69
  var Mediator;
99
70
  var init_mediator = __esm({
@@ -151,11 +122,11 @@ var init_mediator = __esm({
151
122
  */
152
123
  async process(request, pipelineToken, signal) {
153
124
  if (Guards2.isDefined(signal) && signal.aborted)
154
- return Result.fail(AppError2.aborted(request.intent));
125
+ return Result.fail(AppError.aborted(request.intent));
155
126
  const scope = this._factoryScope.getScope();
156
127
  if (!Guards2.isDefined(scope))
157
128
  return Result.fail(
158
- AppError2.create({
129
+ AppError.create({
159
130
  code: ERROR_CODES.SCOPE_NOT_AVAILABLE,
160
131
  status: STATUS_CODES.INTERNAL_SERVER_ERROR,
161
132
  name: request.intent,
@@ -166,7 +137,7 @@ var init_mediator = __esm({
166
137
  const pipelines = scope.resolve(pipelineToken);
167
138
  if (!Guards2.isDefined(pipelines) || !Guards2.hasMethod(pipelines, "handle")) {
168
139
  return Result.fail(
169
- AppError2.create({
140
+ AppError.create({
170
141
  code: ERROR_CODES.PIPELINE_NOT_AVAILABLE,
171
142
  status: STATUS_CODES.INTERNAL_SERVER_ERROR,
172
143
  name: request.intent,
@@ -178,7 +149,7 @@ var init_mediator = __esm({
178
149
  const next = () => {
179
150
  const handler = scope.resolve(request.intent);
180
151
  if (!Guards2.isDefined(handler) || !Guards2.hasMethod(handler, "handle")) {
181
- AppError2.throw({
152
+ AppError.throw({
182
153
  code: ERROR_CODES.HANDLER_NOT_FOUND,
183
154
  status: STATUS_CODES.INTERNAL_SERVER_ERROR,
184
155
  name: request.intent,
@@ -260,7 +231,7 @@ var init_composite_pipeline = __esm({
260
231
  });
261
232
 
262
233
  // src/application/cqrs/pipelines/concurrency-retry.pipeline.ts
263
- import { AppError as AppError3, Result as Result3 } from "@xeno-js/shared";
234
+ import { AppError as AppError2, Result as Result3 } from "@xeno-js/shared";
264
235
  import {
265
236
  DEFAULT_CONCURRENCY,
266
237
  ERROR_CODES as ERROR_CODES2,
@@ -341,7 +312,7 @@ var init_concurrency_retry_pipeline = __esm({
341
312
  if (result.isOk() || !this.isConcurrencyError(result.getErrorOrThrow())) return result;
342
313
  if (attempts >= this._maxRetries)
343
314
  return Result3.fail(
344
- AppError3.conflict(
315
+ AppError2.conflict(
345
316
  request.intent,
346
317
  `Maximum retry attempts (${this._maxRetries}) exceeded due to concurrency conflicts.`
347
318
  )
@@ -368,7 +339,7 @@ var init_concurrency_retry_pipeline = __esm({
368
339
  });
369
340
 
370
341
  // src/application/cqrs/pipelines/exception.pipeline.ts
371
- import { AppError as AppError4, Result as Result4 } from "@xeno-js/shared";
342
+ import { AppError as AppError3, Result as Result4 } from "@xeno-js/shared";
372
343
  import { ERROR_CODE_MESSAGES as ERROR_CODE_MESSAGES2, ERROR_CODES as ERROR_CODES3, STATUS_CODES as STATUS_CODES3 } from "@xeno-js/shared";
373
344
  var ExceptionPipeline;
374
345
  var init_exception_pipeline = __esm({
@@ -379,8 +350,8 @@ var init_exception_pipeline = __esm({
379
350
  try {
380
351
  return await next();
381
352
  } catch (error) {
382
- if (error instanceof AppError4) return Result4.fail(error);
383
- const appError = AppError4.create({
353
+ if (error instanceof AppError3) return Result4.fail(error);
354
+ const appError = AppError3.create({
384
355
  code: ERROR_CODES3.SYSTEM_ERROR,
385
356
  message: ERROR_CODE_MESSAGES2[ERROR_CODES3.SYSTEM_ERROR],
386
357
  status: STATUS_CODES3.INTERNAL_SERVER_ERROR,
@@ -395,7 +366,7 @@ var init_exception_pipeline = __esm({
395
366
  });
396
367
 
397
368
  // src/application/cqrs/pipelines/idempotency.pipeline.ts
398
- import { AppError as AppError5, Result as Result5 } from "@xeno-js/shared";
369
+ import { AppError as AppError4, Result as Result5 } from "@xeno-js/shared";
399
370
  import { Guards as Guards4, IDEMPOTENCY_CONSTANTS } from "@xeno-js/shared";
400
371
  var IdempotencyPipeline;
401
372
  var init_idempotency_pipeline = __esm({
@@ -455,7 +426,7 @@ var init_idempotency_pipeline = __esm({
455
426
  const network = this._requestContextFactory.getNetworkContext();
456
427
  if (!Guards4.isDefined(network))
457
428
  return Result5.fail(
458
- AppError5.conflict(
429
+ AppError4.conflict(
459
430
  request.intent,
460
431
  `Network context is not defined for request ${request.intent}`
461
432
  )
@@ -468,7 +439,7 @@ var init_idempotency_pipeline = __esm({
468
439
  return Result5.ok(payload);
469
440
  } else {
470
441
  return Result5.fail(
471
- AppError5.conflict(
442
+ AppError4.conflict(
472
443
  request.intent,
473
444
  `Idempotency store indicates request has been processed but no payload found for request ID ${network.requestId}`
474
445
  )
@@ -481,7 +452,7 @@ var init_idempotency_pipeline = __esm({
481
452
  );
482
453
  if (!lockAcquired) {
483
454
  return Result5.fail(
484
- AppError5.conflict(
455
+ AppError4.conflict(
485
456
  request.intent,
486
457
  `Failed to acquire lock for request ID ${network.requestId}`
487
458
  )
@@ -618,7 +589,7 @@ var init_performance_pipeline = __esm({
618
589
  });
619
590
 
620
591
  // src/application/cqrs/pipelines/pipeline_strategies/auth/base-authorization.strategy.ts
621
- import { AppError as AppError6, Result as Result6 } from "@xeno-js/shared";
592
+ import { AppError as AppError5, Result as Result6 } from "@xeno-js/shared";
622
593
  import { Guards as Guards6 } from "@xeno-js/shared";
623
594
  var BaseAuthorizationStrategy;
624
595
  var init_base_authorization_strategy = __esm({
@@ -641,7 +612,7 @@ var init_base_authorization_strategy = __esm({
641
612
  async execute(request) {
642
613
  const context = this._requestContext.getContext();
643
614
  if (!Guards6.isDefined(context)) {
644
- return Result6.fail(AppError6.unauthorized(request.intent, "User is not authenticated."));
615
+ return Result6.fail(AppError5.unauthorized(request.intent, "User is not authenticated."));
645
616
  }
646
617
  return await this.performAuthorizationCheck(request, context.identity);
647
618
  }
@@ -650,7 +621,7 @@ var init_base_authorization_strategy = __esm({
650
621
  });
651
622
 
652
623
  // src/application/cqrs/pipelines/pipeline_strategies/auth/permission-authorization.strategy.ts
653
- import { AppError as AppError7, Result as Result7 } from "@xeno-js/shared";
624
+ import { AppError as AppError6, Result as Result7 } from "@xeno-js/shared";
654
625
  import { Guards as Guards7 } from "@xeno-js/shared";
655
626
  var PermissionAuthorizationStrategy;
656
627
  var init_permission_authorization_strategy = __esm({
@@ -681,7 +652,7 @@ var init_permission_authorization_strategy = __esm({
681
652
  );
682
653
  if (!hasRequiredPermission)
683
654
  return Result7.fail(
684
- AppError7.forbidden(command.intent, "User does not have the required permissions.")
655
+ AppError6.forbidden(command.intent, "User does not have the required permissions.")
685
656
  );
686
657
  }
687
658
  return Result7.ok();
@@ -691,7 +662,7 @@ var init_permission_authorization_strategy = __esm({
691
662
  });
692
663
 
693
664
  // src/application/cqrs/pipelines/pipeline_strategies/auth/role-authorization.strategy.ts
694
- import { AppError as AppError8, Result as Result8 } from "@xeno-js/shared";
665
+ import { AppError as AppError7, Result as Result8 } from "@xeno-js/shared";
695
666
  import { Guards as Guards8 } from "@xeno-js/shared";
696
667
  var RoleAuthorizationStrategy;
697
668
  var init_role_authorization_strategy = __esm({
@@ -719,7 +690,7 @@ var init_role_authorization_strategy = __esm({
719
690
  const hasRequiredRole = policy.roles?.some((role) => roles.includes(role));
720
691
  if (!hasRequiredRole)
721
692
  return Result8.fail(
722
- AppError8.forbidden(command.intent, "User does not have the required roles.")
693
+ AppError7.forbidden(command.intent, "User does not have the required roles.")
723
694
  );
724
695
  }
725
696
  return Result8.ok();
@@ -729,7 +700,7 @@ var init_role_authorization_strategy = __esm({
729
700
  });
730
701
 
731
702
  // src/application/cqrs/pipelines/pipeline_strategies/auth/tenant-authorization.strategy.ts
732
- import { AppError as AppError9, Result as Result9 } from "@xeno-js/shared";
703
+ import { AppError as AppError8, Result as Result9 } from "@xeno-js/shared";
733
704
  import { Guards as Guards9, GuidHelper } from "@xeno-js/shared";
734
705
  var TenantAuthorizationStrategy;
735
706
  var init_tenant_authorization_strategy = __esm({
@@ -754,7 +725,7 @@ var init_tenant_authorization_strategy = __esm({
754
725
  const policy = this._policy.getPolicy(command.intent);
755
726
  if (Guards9.isDefined(policy?.tenantId)) {
756
727
  if (Guards9.isNullOrEmpty(auth.tenantId) || !GuidHelper.isValidGuid(auth.tenantId))
757
- return Result9.fail(AppError9.unauthorized(command.intent, "Tenant is not authenticated."));
728
+ return Result9.fail(AppError8.unauthorized(command.intent, "Tenant is not authenticated."));
758
729
  }
759
730
  return Result9.ok();
760
731
  }
@@ -763,7 +734,7 @@ var init_tenant_authorization_strategy = __esm({
763
734
  });
764
735
 
765
736
  // src/application/cqrs/pipelines/pipeline_strategies/auth/user-authorization.strategy.ts
766
- import { AppError as AppError10, Result as Result10 } from "@xeno-js/shared";
737
+ import { AppError as AppError9, Result as Result10 } from "@xeno-js/shared";
767
738
  import { Guards as Guards10, GuidHelper as GuidHelper2 } from "@xeno-js/shared";
768
739
  var UserAuthorizationStrategy;
769
740
  var init_user_authorization_strategy = __esm({
@@ -788,7 +759,7 @@ var init_user_authorization_strategy = __esm({
788
759
  const policy = this._policy.getPolicy(command.intent);
789
760
  if (Guards10.isDefined(policy?.userId)) {
790
761
  if (Guards10.isNullOrEmpty(auth.userId) || !GuidHelper2.isValidGuid(auth.userId))
791
- return Result10.fail(AppError10.unauthorized(command.intent, "User is not authenticated."));
762
+ return Result10.fail(AppError9.unauthorized(command.intent, "User is not authenticated."));
792
763
  }
793
764
  return Result10.ok();
794
765
  }
@@ -809,7 +780,7 @@ var init_auth = __esm({
809
780
  });
810
781
 
811
782
  // src/application/cqrs/pipelines/pipeline_strategies/validation/schema-validation.strategy.ts
812
- import { AppError as AppError11, Result as Result11 } from "@xeno-js/shared";
783
+ import { AppError as AppError10, Result as Result11 } from "@xeno-js/shared";
813
784
  var SchemaValidationStrategy;
814
785
  var init_schema_validation_strategy = __esm({
815
786
  "src/application/cqrs/pipelines/pipeline_strategies/validation/schema-validation.strategy.ts"() {
@@ -833,7 +804,7 @@ var init_schema_validation_strategy = __esm({
833
804
  const parseResult = await this._validator.validate(key, request);
834
805
  if (!parseResult.isOk())
835
806
  return Result11.fail(
836
- AppError11.validationError(
807
+ AppError10.validationError(
837
808
  request.intent,
838
809
  `Validation failed: ${parseResult.getErrorOrThrow().message}`
839
810
  )
@@ -979,7 +950,6 @@ var init_pipelines = __esm({
979
950
  var init_cqrs = __esm({
980
951
  "src/application/cqrs/index.ts"() {
981
952
  "use strict";
982
- init_base_handler();
983
953
  init_mediator();
984
954
  init_pipelines();
985
955
  }
@@ -1220,7 +1190,6 @@ var application_exports = {};
1220
1190
  __export(application_exports, {
1221
1191
  AuthorizationPipeline: () => AuthorizationPipeline,
1222
1192
  BaseAuthorizationStrategy: () => BaseAuthorizationStrategy,
1223
- BaseHandler: () => BaseHandler,
1224
1193
  ClaimsIdentityMapper: () => ClaimsIdentityMapper,
1225
1194
  CompositePipeline: () => CompositePipeline,
1226
1195
  ConcurrencyRetryPipeline: () => ConcurrencyRetryPipeline,
@@ -1254,595 +1223,572 @@ var init_application = __esm({
1254
1223
  }
1255
1224
  });
1256
1225
 
1257
- // src/infrastructure/factories/service-scope.factory.ts
1258
- var service_scope_factory_exports = {};
1259
- __export(service_scope_factory_exports, {
1260
- ServiceScopeFactory: () => ServiceScopeFactory
1261
- });
1262
- var ServiceScopeFactory;
1263
- var init_service_scope_factory = __esm({
1264
- "src/infrastructure/factories/service-scope.factory.ts"() {
1265
- "use strict";
1266
- ServiceScopeFactory = class {
1267
- constructor(_container) {
1268
- this._container = _container;
1269
- }
1270
- _container;
1271
- create() {
1272
- return this._container.createScope();
1273
- }
1274
- };
1275
- }
1276
- });
1277
-
1278
- // src/infrastructure/context/request-context.ts
1279
- import { Guards as Guards15 } from "@xeno-js/shared";
1280
- var NodeRequestContext;
1281
- var init_request_context = __esm({
1282
- "src/infrastructure/context/request-context.ts"() {
1226
+ // src/infrastructure/http/base.http-adapter.ts
1227
+ import { Guards as Guards15, StringHelper } from "@xeno-js/shared";
1228
+ var BaseHttpAdapter;
1229
+ var init_base_http_adapter = __esm({
1230
+ "src/infrastructure/http/base.http-adapter.ts"() {
1283
1231
  "use strict";
1284
- NodeRequestContext = class {
1232
+ BaseHttpAdapter = class {
1285
1233
  /**
1286
- * @description Constructs a new instance of the NodeRequestContext class, which requires an instance of AsyncLocalStorage to manage the request context. The AsyncLocalStorage instance is used to create and access the context for each request, allowing for the storage of identity information and other relevant data that needs to be accessible across asynchronous operations. This constructor initializes the NodeRequestContext with the provided AsyncLocalStorage, enabling it to implement the methods defined in the IRequestContext interface for managing request-specific context data.
1287
- * @param _storage An instance of AsyncLocalStorage that is used to manage the request context, allowing for the storage and retrieval of identity information and other relevant data across asynchronous operations.
1288
- * @param _factoryScope An instance of IFactory that is used to create a new IServiceScope for managing service dependencies during the execution of the request. This allows for proper scoping and disposal of services after the request is processed, ensuring that resources are managed efficiently and preventing memory leaks.
1289
- *
1290
- * @author Xeno
1291
- * @version 1.0.0
1292
- * @since 2025-09-30
1293
- * @link https://github.com/xeno-js/xeno-js
1234
+ * @description Parse the URL from the request.
1235
+ * @param rawUrl The raw URL.
1236
+ * @param headers The headers.
1237
+ * @param queryParams The query parameters.
1238
+ * @returns The parsed URL.
1294
1239
  */
1295
- constructor(_storage, _factoryScope) {
1296
- this._storage = _storage;
1297
- this._factoryScope = _factoryScope;
1298
- }
1299
- _storage;
1300
- _factoryScope;
1301
- async runAsync(context, fn) {
1302
- const scope = this._factoryScope.create();
1303
- try {
1304
- return await this._storage.run({ context, scope }, fn);
1305
- } finally {
1306
- await scope.dispose();
1240
+ parseUrl(rawUrl = "/", headers, queryParams) {
1241
+ const protocol = StringHelper.getSingleValue(headers["x-forwarded-proto"]) ?? "https";
1242
+ const host = StringHelper.safeStringify(headers["host"]) ?? "localhost";
1243
+ const cleanHost = host.replace(/['"]/g, "");
1244
+ const url = new URL(rawUrl, `${protocol}://${cleanHost}`);
1245
+ if (!Guards15.isNullOrEmpty(queryParams)) {
1246
+ for (const [key, value] of Object.entries(queryParams)) {
1247
+ if (Guards15.isArray(value)) {
1248
+ value.forEach((v) => url.searchParams.append(key, String(v)));
1249
+ } else if (Guards15.isDefined(value)) {
1250
+ url.searchParams.set(key, String(value));
1251
+ }
1252
+ }
1307
1253
  }
1254
+ return url;
1308
1255
  }
1309
- updateIdentity(identity) {
1310
- const store = this._storage.getStore();
1311
- if (Guards15.isDefined(store) && Guards15.isDefined(store.context)) {
1312
- store.context = Object.freeze({
1313
- ...store.context,
1314
- identity: Object.freeze(identity)
1315
- });
1256
+ /**
1257
+ * @description Parses the headers.
1258
+ * @param rawHeaders The raw headers.
1259
+ * @returns The parsed headers.
1260
+ */
1261
+ parseHeaders(rawHeaders) {
1262
+ const headers = new Headers();
1263
+ for (const [key, value] of Object.entries(rawHeaders)) {
1264
+ if (Guards15.isDefined(value)) {
1265
+ if (Guards15.isArray(value)) {
1266
+ value.forEach((v) => headers.append(key, String(v)));
1267
+ } else {
1268
+ headers.set(key, String(value));
1269
+ }
1270
+ }
1316
1271
  }
1272
+ return headers;
1317
1273
  }
1318
- getContext() {
1319
- const store = this._storage.getStore();
1320
- if (!Guards15.isDefined(store)) return void 0;
1321
- const context = store.context;
1322
- return Object.freeze(context);
1323
- }
1324
- getIdentity() {
1325
- const store = this._storage.getStore();
1326
- if (!Guards15.isDefined(store)) return void 0;
1327
- return Object.freeze(store.context?.identity);
1328
- }
1329
- getScope() {
1330
- const store = this._storage.getStore();
1331
- if (!Guards15.isDefined(store)) return void 0;
1332
- return store.scope;
1274
+ /**
1275
+ * @description Parses the body.
1276
+ * @param method The method.
1277
+ * @param rawBody The raw body.
1278
+ * @returns The parsed body.
1279
+ */
1280
+ parseBody(method, rawBody) {
1281
+ if (!Guards15.isDefined(method) || !["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) || !Guards15.isDefined(rawBody))
1282
+ return void 0;
1283
+ if (Guards15.isObject(rawBody)) return JSON.stringify(rawBody);
1284
+ if (Guards15.isString(rawBody) || rawBody instanceof Blob || rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody) || rawBody instanceof URLSearchParams || rawBody instanceof FormData)
1285
+ return rawBody;
1286
+ return String(rawBody);
1333
1287
  }
1334
- getNetworkContext() {
1335
- const store = this._storage.getStore();
1336
- if (!Guards15.isDefined(store)) return void 0;
1337
- return Object.freeze(store.context?.network);
1288
+ /**
1289
+ * @description Creates the XenoWebTransport.
1290
+ * @param url The url.
1291
+ * @param method The method.
1292
+ * @param headers The headers.
1293
+ * @param body The body.
1294
+ * @returns The XenoWebTransport.
1295
+ */
1296
+ createXenoWebTransport(url, method = "GET", headers, body = void 0, res = void 0) {
1297
+ const init2 = {
1298
+ method: method.toUpperCase(),
1299
+ headers
1300
+ };
1301
+ const parsedBody = this.parseBody(method, body);
1302
+ if (Guards15.isDefined(parsedBody)) {
1303
+ init2.body = parsedBody;
1304
+ init2.duplex = "half";
1305
+ }
1306
+ const extendedRequest = new Request(url, init2);
1307
+ extendedRequest.path = url.pathname;
1308
+ const webResponse = new Response();
1309
+ if (Guards15.isDefined(res)) {
1310
+ const originalAppend = webResponse.headers.append.bind(webResponse.headers);
1311
+ const originalSet = webResponse.headers.set.bind(webResponse.headers);
1312
+ const originalDelete = webResponse.headers.delete.bind(webResponse.headers);
1313
+ webResponse.headers.append = (name, value) => {
1314
+ originalAppend(name, value);
1315
+ this.handleHeaderChange(res, name, value, "append");
1316
+ };
1317
+ webResponse.headers.set = (name, value) => {
1318
+ originalSet(name, value);
1319
+ this.handleHeaderChange(res, name, value, "set");
1320
+ };
1321
+ webResponse.headers.delete = (name) => {
1322
+ originalDelete(name);
1323
+ this.handleHeaderChange(res, name, "", "delete");
1324
+ };
1325
+ }
1326
+ return {
1327
+ request: extendedRequest,
1328
+ response: webResponse
1329
+ };
1338
1330
  }
1339
1331
  };
1340
1332
  }
1341
1333
  });
1342
1334
 
1343
- // src/infrastructure/factories/request-context.factory.ts
1344
- var request_context_factory_exports = {};
1345
- __export(request_context_factory_exports, {
1346
- NodeRequestContextFactory: () => NodeRequestContextFactory
1335
+ // src/infrastructure/http/vercel.http-adapter.ts
1336
+ var vercel_http_adapter_exports = {};
1337
+ __export(vercel_http_adapter_exports, {
1338
+ VercelHttpAdapter: () => VercelHttpAdapter
1347
1339
  });
1348
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1349
- var NodeRequestContextFactory;
1350
- var init_request_context_factory = __esm({
1351
- "src/infrastructure/factories/request-context.factory.ts"() {
1340
+ import { Guards as Guards16 } from "@xeno-js/shared";
1341
+ var VercelHttpAdapter;
1342
+ var init_vercel_http_adapter = __esm({
1343
+ "src/infrastructure/http/vercel.http-adapter.ts"() {
1352
1344
  "use strict";
1353
- init_request_context();
1354
- NodeRequestContextFactory = class {
1355
- constructor(_factoryScope) {
1356
- this._factoryScope = _factoryScope;
1345
+ init_base_http_adapter();
1346
+ VercelHttpAdapter = class extends BaseHttpAdapter {
1347
+ adapt(req, res) {
1348
+ const headers = this.parseHeaders(req.headers);
1349
+ const url = this.parseUrl(req.url, req.headers, req.query);
1350
+ return this.createXenoWebTransport(url, req.method, headers, req.body, res);
1357
1351
  }
1358
- _factoryScope;
1359
- _store = new AsyncLocalStorage2();
1360
- create() {
1361
- return new NodeRequestContext(this._store, this._factoryScope);
1352
+ handleHeaderChange(res, name, value, action) {
1353
+ if (action === "delete") {
1354
+ res.removeHeader(name);
1355
+ return;
1356
+ }
1357
+ if (name.toLowerCase() === "set-cookie") {
1358
+ const existing = res.getHeader("Set-Cookie");
1359
+ let cookies = [];
1360
+ if (Guards16.isArray(existing)) {
1361
+ cookies = existing;
1362
+ } else if (Guards16.isString(existing)) {
1363
+ cookies = [existing];
1364
+ }
1365
+ if (action === "append") {
1366
+ cookies.push(value);
1367
+ } else {
1368
+ cookies = [value];
1369
+ }
1370
+ res.setHeader("Set-Cookie", cookies);
1371
+ } else {
1372
+ res.setHeader(name, value);
1373
+ }
1362
1374
  }
1363
1375
  };
1364
1376
  }
1365
1377
  });
1366
1378
 
1367
- // src/infrastructure/factories/user-context.factory.ts
1368
- var user_context_factory_exports = {};
1369
- __export(user_context_factory_exports, {
1370
- UserContextFactory: () => UserContextFactory
1379
+ // src/infrastructure/http/fastify.http-adapter.ts
1380
+ var fastify_http_adapter_exports = {};
1381
+ __export(fastify_http_adapter_exports, {
1382
+ FastifyHttpAdapter: () => FastifyHttpAdapter
1371
1383
  });
1372
- import { Guards as Guards16 } from "@xeno-js/shared";
1373
- var UserContextFactory;
1374
- var init_user_context_factory = __esm({
1375
- "src/infrastructure/factories/user-context.factory.ts"() {
1384
+ import { Guards as Guards17 } from "@xeno-js/shared";
1385
+ var FastifyHttpAdapter;
1386
+ var init_fastify_http_adapter = __esm({
1387
+ "src/infrastructure/http/fastify.http-adapter.ts"() {
1376
1388
  "use strict";
1377
- UserContextFactory = class {
1378
- /**
1379
- * @description Constructs an instance of UserContextFactory.
1380
- * @param _identityFactory - An instance of IIdentityAccessor that provides access to the current identity. This factory is used to retrieve the identity details when creating a UserContext instance.
1381
- *
1382
- * @author Xeno
1383
- * @version 1.0.0
1384
- * @since 2025-09-30
1385
- * @link https://github.com/xeno-js/xeno-js
1386
- */
1387
- constructor(_identityFactory) {
1388
- this._identityFactory = _identityFactory;
1389
+ init_base_http_adapter();
1390
+ FastifyHttpAdapter = class extends BaseHttpAdapter {
1391
+ adapt(req, res) {
1392
+ const headers = this.parseHeaders(req.headers);
1393
+ const url = this.parseUrl(req.url, req.headers, req.query);
1394
+ const body = req.body;
1395
+ return this.createXenoWebTransport(url, req.method, headers, body, res);
1389
1396
  }
1390
- _identityFactory;
1391
- create() {
1392
- const output = {
1393
- userId: void 0,
1394
- tenantId: void 0
1395
- };
1396
- const identity = this._identityFactory.getIdentity();
1397
- if (Guards16.isDefined(identity)) {
1398
- output.userId = identity.userId;
1399
- output.tenantId = identity.tenantId;
1397
+ handleHeaderChange(res, name, value, action) {
1398
+ if (action === "delete") {
1399
+ res.removeHeader(name);
1400
+ return;
1401
+ }
1402
+ if (name.toLowerCase() === "set-cookie") {
1403
+ const existing = res.getHeader("set-cookie");
1404
+ let cookies = [];
1405
+ if (Guards17.isArray(existing)) {
1406
+ cookies = existing;
1407
+ } else if (Guards17.isString(existing)) {
1408
+ cookies = [existing];
1409
+ }
1410
+ if (action === "append") {
1411
+ cookies.push(value);
1412
+ } else {
1413
+ cookies = [value];
1414
+ }
1415
+ res.header("set-cookie", cookies);
1416
+ } else {
1417
+ res.header(name, value);
1400
1418
  }
1401
- return output;
1402
1419
  }
1403
1420
  };
1404
1421
  }
1405
1422
  });
1406
1423
 
1407
- // src/infrastructure/modules/context.module.ts
1408
- var context_module_exports = {};
1409
- __export(context_module_exports, {
1410
- ContextModule: () => ContextModule
1424
+ // src/infrastructure/http/native.http-adapter.ts
1425
+ var native_http_adapter_exports = {};
1426
+ __export(native_http_adapter_exports, {
1427
+ NativeHttpAdapter: () => NativeHttpAdapter
1411
1428
  });
1412
- var ContextModule;
1413
- var init_context_module = __esm({
1414
- "src/infrastructure/modules/context.module.ts"() {
1429
+ var NativeHttpAdapter;
1430
+ var init_native_http_adapter = __esm({
1431
+ "src/infrastructure/http/native.http-adapter.ts"() {
1415
1432
  "use strict";
1416
- ContextModule = class {
1417
- async configure(container) {
1418
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1419
- const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
1420
- const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
1421
- const requestContext = new NodeRequestContextFactory2(
1422
- new ServiceScopeFactory2(container)
1423
- ).create();
1424
- container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
1425
- container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
1426
- container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
1427
- container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
1428
- container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
1429
- const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
1430
- container.addSingleton("USER_CONTEXT_FACTORY", () => {
1431
- return new UserContextFactory2(requestContext);
1432
- });
1433
+ init_base_http_adapter();
1434
+ NativeHttpAdapter = class extends BaseHttpAdapter {
1435
+ adapt(req, res) {
1436
+ const extendedRequest = req;
1437
+ extendedRequest.path = new URL(req.url).pathname;
1438
+ return {
1439
+ request: extendedRequest,
1440
+ response: res
1441
+ };
1442
+ }
1443
+ handleHeaderChange(_res, _name, _value, _action) {
1444
+ return;
1433
1445
  }
1434
1446
  };
1435
1447
  }
1436
1448
  });
1437
1449
 
1438
- // src/infrastructure/services/allow_methods/allow-method.service.ts
1439
- import { Guards as Guards17 } from "@xeno-js/shared";
1440
- var AllowMethodRegistry;
1441
- var init_allow_method_service = __esm({
1442
- "src/infrastructure/services/allow_methods/allow-method.service.ts"() {
1450
+ // src/infrastructure/modules/http-adapter.module.ts
1451
+ var http_adapter_module_exports = {};
1452
+ __export(http_adapter_module_exports, {
1453
+ HttpAdapterModule: () => HttpAdapterModule
1454
+ });
1455
+ import { Guards as Guards18 } from "@xeno-js/shared";
1456
+ var HttpAdapterModule;
1457
+ var init_http_adapter_module = __esm({
1458
+ "src/infrastructure/modules/http-adapter.module.ts"() {
1443
1459
  "use strict";
1444
- AllowMethodRegistry = class {
1445
- _staticRoutes = /* @__PURE__ */ new Map();
1446
- _dynamicRoutes = [];
1447
- add(path, methods) {
1448
- const normalizedPath = this.normalizePath(path);
1449
- if (this.isDynamicPath(normalizedPath)) {
1450
- const pattern = this.createRoutePattern(normalizedPath);
1451
- this._dynamicRoutes.push({ pattern, methods });
1452
- } else {
1453
- this._staticRoutes.set(normalizedPath, methods);
1454
- }
1460
+ HttpAdapterModule = class {
1461
+ async configure(container, opts) {
1462
+ const adapter = await this._getAdapter(opts);
1463
+ container.addSingleton("HTTP_ADAPTER", () => adapter);
1455
1464
  }
1456
- check(path, method) {
1457
- const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1458
- const staticMethods = this._staticRoutes.get(cleanPath);
1459
- if (Guards17.isDefined(staticMethods)) return staticMethods.includes(method);
1460
- for (const route of this._dynamicRoutes) {
1461
- if (route.pattern.test(cleanPath)) return route.methods.includes(method);
1465
+ async _getAdapter(opts) {
1466
+ if (opts.vercel) {
1467
+ const { VercelHttpAdapter: VercelHttpAdapter2 } = await Promise.resolve().then(() => (init_vercel_http_adapter(), vercel_http_adapter_exports));
1468
+ return new VercelHttpAdapter2();
1469
+ } else if (opts.fastify) {
1470
+ const { FastifyHttpAdapter: FastifyHttpAdapter2 } = await Promise.resolve().then(() => (init_fastify_http_adapter(), fastify_http_adapter_exports));
1471
+ return new FastifyHttpAdapter2();
1472
+ } else if (Guards18.isDefined(opts.custom)) {
1473
+ return opts.custom();
1474
+ } else {
1475
+ const { NativeHttpAdapter: NativeHttpAdapter2 } = await Promise.resolve().then(() => (init_native_http_adapter(), native_http_adapter_exports));
1476
+ return new NativeHttpAdapter2();
1462
1477
  }
1463
- return false;
1464
- }
1465
- getMethods(path) {
1466
- const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1467
- const methods = this.findMethods(cleanPath);
1468
- return Guards17.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
1469
- }
1470
- findMethods(cleanPath) {
1471
- const staticMethods = this._staticRoutes.get(cleanPath);
1472
- if (Guards17.isDefined(staticMethods)) return staticMethods;
1473
- for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods;
1474
- return void 0;
1475
- }
1476
- isDynamicPath(path) {
1477
- return path.includes(":") || path.includes("{") && path.includes("}");
1478
- }
1479
- normalizePath(path) {
1480
- const trimmed = path.trim();
1481
- const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
1482
- if (withLeadingSlash === "/") return "/";
1483
- return withLeadingSlash.replace(/\/+$/, "");
1484
- }
1485
- createRoutePattern(path) {
1486
- const segments = path.split("/").filter(Boolean);
1487
- const regexSegments = segments.map((segment) => {
1488
- if (segment.startsWith(":") || segment.startsWith("{") && segment.endsWith("}"))
1489
- return "([^/]+)";
1490
- return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1491
- });
1492
- return new RegExp(`^\\/${regexSegments.join("\\/")}\\/?$`);
1493
1478
  }
1494
1479
  };
1495
1480
  }
1496
1481
  });
1497
1482
 
1498
- // src/infrastructure/services/allow_methods/index.ts
1499
- var init_allow_methods = __esm({
1500
- "src/infrastructure/services/allow_methods/index.ts"() {
1501
- "use strict";
1502
- init_allow_method_service();
1503
- }
1483
+ // src/infrastructure/loggers/console.logger.ts
1484
+ var console_logger_exports = {};
1485
+ __export(console_logger_exports, {
1486
+ ConsoleLogger: () => ConsoleLogger
1504
1487
  });
1505
-
1506
- // src/infrastructure/services/allow_origins/allow-origin.http.ts
1507
- import { Guards as Guards18 } from "@xeno-js/shared";
1508
- var AllowOrigin;
1509
- var init_allow_origin_http = __esm({
1510
- "src/infrastructure/services/allow_origins/allow-origin.http.ts"() {
1488
+ import { Guards as Guards19, LOG_LEVEL } from "@xeno-js/shared";
1489
+ var ConsoleLogger;
1490
+ var init_console_logger = __esm({
1491
+ "src/infrastructure/loggers/console.logger.ts"() {
1511
1492
  "use strict";
1512
- AllowOrigin = class {
1513
- constructor(_list) {
1514
- this._list = _list;
1493
+ ConsoleLogger = class {
1494
+ /**
1495
+ * Constructs a new instance of the ConsoleLogger class, which takes an optional minimum log level. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
1496
+ * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
1497
+
1498
+ *
1499
+ * @author Xeno
1500
+ * @version 1.0.0
1501
+ * @since 2025-09-30
1502
+ * @link https://github.com/xeno-js/xeno-js
1503
+ */
1504
+ constructor(_minLevel = LOG_LEVEL.DEBUG) {
1505
+ this._minLevel = _minLevel;
1515
1506
  }
1516
- _list;
1517
- isAllowed(origin) {
1518
- if (Guards18.isNullOrEmpty(origin)) return true;
1519
- const cleanOrigin = origin.trim().toLowerCase();
1520
- for (const pattern of this._list) {
1521
- const cleanPattern = pattern.trim().toLowerCase();
1522
- if (cleanPattern === "*") return true;
1523
- if (cleanPattern === cleanOrigin) return true;
1524
- if (cleanPattern.startsWith("*.")) {
1525
- const domainSuffix = cleanPattern.substring(1);
1526
- if (cleanOrigin.endsWith(domainSuffix)) {
1527
- const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length);
1528
- if (!Guards18.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
1529
- }
1530
- }
1507
+ _minLevel;
1508
+ track(level, message, context, error = void 0) {
1509
+ if (level < this._minLevel) return;
1510
+ const logMessage = `[${level}] ${message}`;
1511
+ const payload = Guards19.isDefined(error) ? { ...context, error } : context;
1512
+ switch (level) {
1513
+ case LOG_LEVEL.ERROR:
1514
+ console.error(logMessage, payload ?? {});
1515
+ break;
1516
+ case LOG_LEVEL.WARN:
1517
+ console.warn(logMessage, payload ?? {});
1518
+ break;
1519
+ case LOG_LEVEL.DEBUG:
1520
+ console.debug(logMessage, payload ?? {});
1521
+ break;
1522
+ default:
1523
+ console.info(logMessage, payload ?? {});
1524
+ break;
1531
1525
  }
1532
- return false;
1533
1526
  }
1534
1527
  };
1535
1528
  }
1536
1529
  });
1537
1530
 
1538
- // src/infrastructure/services/allow_origins/index.ts
1539
- var init_allow_origins = __esm({
1540
- "src/infrastructure/services/allow_origins/index.ts"() {
1541
- "use strict";
1542
- init_allow_origin_http();
1543
- }
1544
- });
1545
-
1546
- // src/infrastructure/services/concurrency/p-limit.service.ts
1547
- var PLimitConcurrencyService;
1548
- var init_p_limit_service = __esm({
1549
- "src/infrastructure/services/concurrency/p-limit.service.ts"() {
1531
+ // src/infrastructure/loggers/sentry.logger.ts
1532
+ import { Guards as Guards20, LOG_LEVEL as LOG_LEVEL2 } from "@xeno-js/shared";
1533
+ var SentryLogger;
1534
+ var init_sentry_logger = __esm({
1535
+ "src/infrastructure/loggers/sentry.logger.ts"() {
1550
1536
  "use strict";
1551
- PLimitConcurrencyService = class {
1552
- async executeInParallel(tasks, concurrencyLimit) {
1553
- const { default: pLimit } = await import("p-limit");
1554
- const limit = pLimit(concurrencyLimit);
1555
- const promises = tasks.map((task) => limit(task));
1556
- return Promise.all(promises);
1537
+ SentryLogger = class {
1538
+ constructor(_client, _minLevel) {
1539
+ this._client = _client;
1540
+ this._minLevel = _minLevel;
1541
+ }
1542
+ _client;
1543
+ _minLevel;
1544
+ track(level, message, context = void 0, error = void 0) {
1545
+ if (level < this._minLevel) return;
1546
+ if (level === LOG_LEVEL2.ERROR || level === LOG_LEVEL2.WARN) {
1547
+ this._client.withScope((scope) => {
1548
+ if (Guards20.isDefined(context)) scope.setExtras(context);
1549
+ if (Guards20.isDefined(error)) {
1550
+ this._client.captureException(error);
1551
+ } else {
1552
+ this._client.captureMessage(message, "warning");
1553
+ }
1554
+ });
1555
+ }
1557
1556
  }
1558
1557
  };
1559
1558
  }
1560
1559
  });
1561
1560
 
1562
- // src/infrastructure/services/concurrency/index.ts
1563
- var concurrency_exports = {};
1564
- __export(concurrency_exports, {
1565
- PLimitConcurrencyService: () => PLimitConcurrencyService
1561
+ // src/infrastructure/factories/sentry-logger.factory.ts
1562
+ var sentry_logger_factory_exports = {};
1563
+ __export(sentry_logger_factory_exports, {
1564
+ SentryLoggerFactory: () => SentryLoggerFactory
1566
1565
  });
1567
- var init_concurrency = __esm({
1568
- "src/infrastructure/services/concurrency/index.ts"() {
1566
+ import * as Sentry from "@sentry/node";
1567
+ import { Guards as Guards21, LOG_LEVEL as LOG_LEVEL3 } from "@xeno-js/shared";
1568
+ var SentryLoggerFactory;
1569
+ var init_sentry_logger_factory = __esm({
1570
+ "src/infrastructure/factories/sentry-logger.factory.ts"() {
1569
1571
  "use strict";
1570
- init_p_limit_service();
1572
+ init_sentry_logger();
1573
+ SentryLoggerFactory = class {
1574
+ create(config) {
1575
+ const level = config.level ?? LOG_LEVEL3.WARN;
1576
+ const sentryConfig = config.sentry?.config;
1577
+ const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
1578
+ if (!Guards21.isDefined(sentryConfig))
1579
+ throw new Error("Sentry configuration is required when Sentry logging is enabled.");
1580
+ if (!Guards21.isDefined(sentryConfig.dsn))
1581
+ throw new Error("Sentry DSN is required when Sentry logging is enabled.");
1582
+ Sentry.init({
1583
+ dsn: sentryConfig.dsn,
1584
+ environment: env,
1585
+ tracesSampleRate: env === "production" ? 0.1 : 1,
1586
+ integrations: [Sentry.httpIntegration()],
1587
+ beforeSend(event, hint) {
1588
+ const error = hint.originalException;
1589
+ if (error instanceof Error && error.name === "ZodError") {
1590
+ return null;
1591
+ }
1592
+ return event;
1593
+ }
1594
+ });
1595
+ return new SentryLogger(Sentry, level);
1596
+ }
1597
+ };
1571
1598
  }
1572
1599
  });
1573
1600
 
1574
- // src/infrastructure/services/cookies/cookies.service.ts
1575
- import { Guards as Guards19 } from "@xeno-js/shared";
1576
- var CookieHandler;
1577
- var init_cookies_service = __esm({
1578
- "src/infrastructure/services/cookies/cookies.service.ts"() {
1601
+ // src/infrastructure/loggers/pino.logger.ts
1602
+ import { Guards as Guards22, LOG_LEVEL as LOG_LEVEL4 } from "@xeno-js/shared";
1603
+ var PinoLogger;
1604
+ var init_pino_logger = __esm({
1605
+ "src/infrastructure/loggers/pino.logger.ts"() {
1579
1606
  "use strict";
1580
- CookieHandler = class {
1581
- constructor(contextAccessor, _config, _cookieOpts) {
1582
- this.contextAccessor = contextAccessor;
1583
- this._config = _config;
1584
- this._cookieOpts = _cookieOpts;
1585
- }
1586
- contextAccessor;
1587
- _config;
1588
- _cookieOpts;
1589
- getAll() {
1590
- const network = this.contextAccessor.getNetworkContext();
1591
- const req = network?.transport?.req;
1592
- if (!Guards19.isDefined(req) || Guards19.isNullOrEmpty(req.headers.get("cookie"))) return [];
1593
- return req.headers.get("cookie")?.split(";").map((cookie) => {
1594
- const [name, ...rest] = cookie.split("=");
1595
- return { name: name.trim(), value: rest.join("=") };
1596
- }) ?? [];
1607
+ PinoLogger = class {
1608
+ /**
1609
+ * Constructs a new instance of the PinoTransport class, which takes an optional minimum log level and an optional instance of the Pino logger. If no logger instance is provided, it initializes a new Pino logger with default settings. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
1610
+ * @param _logger The Pino logger instance used for logging messages.
1611
+ * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
1612
+
1613
+ *
1614
+ * @author Xeno
1615
+ * @version 1.0.0
1616
+ * @since 2025-09-30
1617
+ * @link https://github.com/xeno-js/xeno-js
1618
+ */
1619
+ constructor(_logger, _minLevel = LOG_LEVEL4.DEBUG) {
1620
+ this._logger = _logger;
1621
+ this._minLevel = _minLevel;
1597
1622
  }
1598
- setAll(cookies) {
1599
- const network = this.contextAccessor.getNetworkContext();
1600
- const res = network?.transport?.res;
1601
- if (!Guards19.isDefined(res)) return;
1602
- const serializedCookies = cookies.map((c) => this.serialize(c));
1603
- const existingSetCookie = res.headers.getSetCookie();
1604
- res.headers.delete("Set-Cookie");
1605
- for (const cookie of [...existingSetCookie, ...serializedCookies]) {
1606
- res.headers.append("Set-Cookie", cookie);
1623
+ _logger;
1624
+ _minLevel;
1625
+ track(level, message, context, error = void 0) {
1626
+ if (level < this._minLevel) return;
1627
+ const payload = Guards22.isDefined(error) ? { ...context, error } : context;
1628
+ switch (level) {
1629
+ case LOG_LEVEL4.ERROR:
1630
+ this._logger.error(payload ?? {}, message);
1631
+ break;
1632
+ case LOG_LEVEL4.WARN:
1633
+ this._logger.warn(payload ?? {}, message);
1634
+ break;
1635
+ case LOG_LEVEL4.DEBUG:
1636
+ this._logger.debug(payload ?? {}, message);
1637
+ break;
1638
+ default:
1639
+ this._logger.info(payload ?? {}, message);
1640
+ break;
1607
1641
  }
1608
1642
  }
1609
- serialize(cookie) {
1610
- const safeName = encodeURIComponent(cookie.name);
1611
- const safeValue = encodeURIComponent(cookie.value);
1612
- let str = `${safeName}=${safeValue}`;
1613
- const isProd = this._config.get("NODE_ENV") === "production";
1614
- const defaultOptions = {
1615
- path: this._cookieOpts.path,
1616
- httpOnly: this._cookieOpts.httpOnly,
1617
- secure: this._cookieOpts.secure ?? isProd,
1618
- sameSite: this._cookieOpts.sameSite ?? "Lax"
1619
- };
1620
- const opts = { ...defaultOptions, ...cookie.options ?? {} };
1621
- str += `; Path=${opts.path}`;
1622
- if (Guards19.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
1623
- if (Guards19.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
1624
- if (Guards19.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
1625
- if (opts.secure) str += `; Secure`;
1626
- if (opts.httpOnly) str += `; HttpOnly`;
1627
- return str;
1628
- }
1629
1643
  };
1630
1644
  }
1631
1645
  });
1632
1646
 
1633
- // src/infrastructure/services/cookies/index.ts
1634
- var init_cookies = __esm({
1635
- "src/infrastructure/services/cookies/index.ts"() {
1636
- "use strict";
1637
- init_cookies_service();
1638
- }
1647
+ // src/infrastructure/factories/pino-logger.factory.ts
1648
+ var pino_logger_factory_exports = {};
1649
+ __export(pino_logger_factory_exports, {
1650
+ PinoLoggerFactory: () => PinoLoggerFactory
1639
1651
  });
1640
-
1641
- // src/infrastructure/services/crypto/crypto.service.ts
1642
- var EdgeCryptoService;
1643
- var init_crypto_service = __esm({
1644
- "src/infrastructure/services/crypto/crypto.service.ts"() {
1652
+ import { LOG_LEVEL as LOG_LEVEL5 } from "@xeno-js/shared";
1653
+ import pino from "pino";
1654
+ var PinoLoggerFactory;
1655
+ var init_pino_logger_factory = __esm({
1656
+ "src/infrastructure/factories/pino-logger.factory.ts"() {
1645
1657
  "use strict";
1646
- EdgeCryptoService = class {
1647
- randomBytes(size) {
1648
- const buffer = new Uint8Array(size);
1649
- crypto.getRandomValues(buffer);
1650
- return buffer;
1651
- }
1652
- async hmacSha256(secret, data) {
1653
- const encoder = new TextEncoder();
1654
- const keyData = encoder.encode(secret);
1655
- const messageData = encoder.encode(data);
1656
- const cryptoKey = await crypto.subtle.importKey(
1657
- "raw",
1658
- keyData,
1659
- { name: "HMAC", hash: "SHA-256" },
1660
- false,
1661
- ["sign"]
1662
- );
1663
- const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
1664
- return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1665
- }
1666
- timingSafeEqual(a, b) {
1667
- if (a.length !== b.length) {
1668
- return false;
1658
+ init_pino_logger();
1659
+ PinoLoggerFactory = class {
1660
+ create(config) {
1661
+ const level = config.level ?? LOG_LEVEL5.DEBUG;
1662
+ const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
1663
+ const destinationType = config.pino.config?.destination ?? "stdout";
1664
+ const filePath = config.pino.config?.filePath ?? "logs/app.log";
1665
+ const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
1666
+ const options = {
1667
+ level: "trace",
1668
+ serializers: {
1669
+ err: pino.stdSerializers.err
1670
+ },
1671
+ timestamp: pino.stdTimeFunctions.isoTime,
1672
+ redact: {
1673
+ paths: ["password", "token", "secret", "authorization", "headers.authorization"],
1674
+ censor: "***"
1675
+ }
1676
+ };
1677
+ if (prettyPrint) {
1678
+ return new PinoLogger(
1679
+ pino({
1680
+ ...options,
1681
+ transport: {
1682
+ target: "pino-pretty",
1683
+ options: {
1684
+ colorize: true,
1685
+ ignore: "pid,hostname",
1686
+ translateTime: "SYS:standard"
1687
+ }
1688
+ }
1689
+ }),
1690
+ level
1691
+ );
1669
1692
  }
1670
- let mismatch = 0;
1671
- for (let i = 0; i < a.length; i++) {
1672
- mismatch |= a[i] ^ b[i];
1693
+ if (destinationType === "file") {
1694
+ const destination = pino.destination({ dest: filePath, sync: false });
1695
+ return new PinoLogger(pino(options, destination), level);
1696
+ } else {
1697
+ const stream = pino.destination({ dest: 1, sync: false });
1698
+ return new PinoLogger(pino(options, stream), level);
1673
1699
  }
1674
- return mismatch === 0;
1675
1700
  }
1676
1701
  };
1677
1702
  }
1678
1703
  });
1679
1704
 
1680
- // src/infrastructure/services/crypto/index.ts
1681
- var init_crypto = __esm({
1682
- "src/infrastructure/services/crypto/index.ts"() {
1705
+ // src/infrastructure/modules/utils/logger.utils.ts
1706
+ var logger_utils_exports = {};
1707
+ __export(logger_utils_exports, {
1708
+ LoggerUtils: () => LoggerUtils
1709
+ });
1710
+ var LoggerUtils;
1711
+ var init_logger_utils = __esm({
1712
+ "src/infrastructure/modules/utils/logger.utils.ts"() {
1683
1713
  "use strict";
1684
- init_crypto_service();
1714
+ LoggerUtils = Object.freeze({
1715
+ /**
1716
+ * @description Configures and registers the logging services in the dependency injection container based on the provided LoggerConfig options. It dynamically imports the necessary logger implementations (e.g., ConsoleLogger, SentryLogger, PinoLogger) and registers them with the container, allowing for flexible and modular logging configuration in the application.
1717
+ *
1718
+ * @param container - The service container to register logging services with.
1719
+ * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
1720
+
1721
+ *
1722
+ * @author Xeno
1723
+ * @version 1.0.0
1724
+ * @since 2025-09-30
1725
+ * @link https://github.com/xeno-js/xeno-js
1726
+ */
1727
+ async addLogger(container, opts) {
1728
+ const loggerDependencies = [];
1729
+ const { Guards: Guards51, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1730
+ if (!Guards51.isDefined(opts) || opts.console) {
1731
+ const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
1732
+ loggerDependencies.push(new ConsoleLogger2(opts?.level));
1733
+ }
1734
+ if (Guards51.isDefined(opts)) {
1735
+ if (Guards51.isDefined(opts.sentry.config)) {
1736
+ const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
1737
+ loggerDependencies.push(new SentryLoggerFactory2().create(opts));
1738
+ }
1739
+ if (Guards51.isDefined(opts.pino.config)) {
1740
+ const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
1741
+ loggerDependencies.push(new PinoLoggerFactory2().create(opts));
1742
+ }
1743
+ if (!Guards51.isNullOrEmpty(opts.customLoggers)) {
1744
+ const customLoggers = opts.customLoggers;
1745
+ customLoggers.forEach((fn) => {
1746
+ if (Guards51.isDefined(fn)) loggerDependencies.push(fn(container));
1747
+ });
1748
+ }
1749
+ }
1750
+ const { BaseLogger } = await import("@xeno-js/shared");
1751
+ container.addSingleton(TOKENS5.LOGGER, (c) => {
1752
+ const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
1753
+ return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
1754
+ });
1755
+ }
1756
+ });
1685
1757
  }
1686
1758
  });
1687
1759
 
1688
- // src/infrastructure/services/csrf/csrf-token.service.ts
1689
- import { Guards as Guards20 } from "@xeno-js/shared";
1690
- var CsrfTokenService;
1691
- var init_csrf_token_service = __esm({
1692
- "src/infrastructure/services/csrf/csrf-token.service.ts"() {
1693
- "use strict";
1694
- CsrfTokenService = class {
1695
- constructor(_secret, _cryptoService) {
1696
- this._secret = _secret;
1697
- this._cryptoService = _cryptoService;
1698
- }
1699
- _secret;
1700
- _cryptoService;
1701
- async generate(subject) {
1702
- const randomBuffer = this._cryptoService.randomBytes(32);
1703
- const nonce = btoa(String.fromCharCode(...randomBuffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1704
- const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1705
- return `${nonce}.${signature}`;
1706
- }
1707
- async validate(token, subject) {
1708
- const separatorIndex = token.indexOf(".");
1709
- if (separatorIndex <= 0) return false;
1710
- const nonce = token.slice(0, separatorIndex);
1711
- const signature = token.slice(separatorIndex + 1);
1712
- if (Guards20.isNullOrEmpty(nonce) || Guards20.isNullOrEmpty(signature)) return false;
1713
- const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1714
- const encoder = new TextEncoder();
1715
- const actualBuffer = encoder.encode(signature);
1716
- const expectedBuffer = encoder.encode(expected);
1717
- if (actualBuffer.length !== expectedBuffer.length) return false;
1718
- return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer);
1719
- }
1720
- };
1721
- }
1722
- });
1723
-
1724
- // src/infrastructure/services/csrf/index.ts
1725
- var init_csrf = __esm({
1726
- "src/infrastructure/services/csrf/index.ts"() {
1727
- "use strict";
1728
- init_csrf_token_service();
1729
- }
1730
- });
1731
-
1732
- // src/infrastructure/services/extractors/extract-bearer.extractor.ts
1733
- import { Guards as Guards21 } from "@xeno-js/shared";
1734
- var BearerTokenExtractor;
1735
- var init_extract_bearer_extractor = __esm({
1736
- "src/infrastructure/services/extractors/extract-bearer.extractor.ts"() {
1737
- "use strict";
1738
- BearerTokenExtractor = class {
1739
- constructor(_cookiePrefix) {
1740
- this._cookiePrefix = _cookiePrefix;
1741
- }
1742
- _cookiePrefix;
1743
- extract(headers) {
1744
- const authHeader = headers.get("Authorization");
1745
- if (Guards21.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1746
- return authHeader.substring(7);
1747
- }
1748
- const cookieHeader = headers.get("cookie");
1749
- if (Guards21.isDefined(cookieHeader)) {
1750
- const regex = new RegExp(`${this._cookiePrefix}=([^;]+)`);
1751
- const match = regex.exec(cookieHeader);
1752
- if (!Guards21.isNullOrEmpty(match) && Guards21.isDefined(match[1])) {
1753
- return match[1].trim();
1754
- }
1755
- }
1756
- return void 0;
1757
- }
1758
- };
1759
- }
1760
- });
1761
-
1762
- // src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts
1763
- import { Guards as Guards22, StringHelper } from "@xeno-js/shared";
1764
- var SupabaseSsrTokenExtractor;
1765
- var init_extract_ssr_bearer_extractor = __esm({
1766
- "src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts"() {
1767
- "use strict";
1768
- SupabaseSsrTokenExtractor = class {
1769
- extract(headers) {
1770
- const authHeader = headers.get("authorization");
1771
- if (Guards22.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1772
- return authHeader.substring(7);
1773
- }
1774
- const cookieHeader = headers.get("cookie");
1775
- if (Guards22.isNullOrEmpty(cookieHeader)) return void 0;
1776
- const cookies = cookieHeader.split(";").map((c) => c.trim());
1777
- const tokenChunks = {};
1778
- let unchunkedToken;
1779
- for (const cookie of cookies) {
1780
- const [name, ...rest] = cookie.split("=");
1781
- if (!Guards22.isDefined(name) || Guards22.isNullOrEmpty(rest)) continue;
1782
- const value = decodeURIComponent(rest.join("="));
1783
- if (Guards22.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
1784
- unchunkedToken = value;
1785
- } else {
1786
- const match = /^sb-[a-z0-9]+-auth-token\.(\d+)$/.exec(name);
1787
- if (Guards22.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
1788
- }
1789
- }
1790
- let fullTokenString = unchunkedToken;
1791
- if (!Guards22.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
1792
- const indices = Object.keys(tokenChunks).map(Number).sort((a, b) => a - b);
1793
- fullTokenString = indices.map((i) => tokenChunks[i]).join("");
1794
- }
1795
- if (Guards22.isNullOrEmpty(fullTokenString)) return void 0;
1796
- try {
1797
- const parsed = StringHelper.safeParse(fullTokenString);
1798
- if (Guards22.isDefined(parsed) && Guards22.isObject(parsed) && "access_token" in parsed) {
1799
- const accessToken = parsed["access_token"];
1800
- if (Guards22.isString(accessToken)) return accessToken;
1801
- }
1802
- } catch {
1803
- return void 0;
1804
- }
1805
- }
1806
- };
1807
- }
1760
+ // src/infrastructure/cache/inmemory.cache.ts
1761
+ var inmemory_cache_exports = {};
1762
+ __export(inmemory_cache_exports, {
1763
+ InMemoryCacheExtended: () => InMemoryCacheExtended
1808
1764
  });
1809
-
1810
- // src/infrastructure/services/extractors/http-cookie.extractor.ts
1811
- import { Guards as Guards23 } from "@xeno-js/shared";
1812
- var HttpCookieExtractor;
1813
- var init_http_cookie_extractor = __esm({
1814
- "src/infrastructure/services/extractors/http-cookie.extractor.ts"() {
1765
+ import { Guards as Guards23, InMemoryCache } from "@xeno-js/shared";
1766
+ var InMemoryCacheExtended;
1767
+ var init_inmemory_cache = __esm({
1768
+ "src/infrastructure/cache/inmemory.cache.ts"() {
1815
1769
  "use strict";
1816
- HttpCookieExtractor = class {
1817
- extract(cookie) {
1818
- if (!Guards23.isDefined(cookie.header)) return void 0;
1819
- for (const rawCookie of cookie.header.split(";")) {
1820
- const separatorIndex = rawCookie.indexOf("=");
1821
- if (separatorIndex <= 0) continue;
1822
- const name = rawCookie.slice(0, separatorIndex).trim();
1823
- if (name !== cookie.name) continue;
1824
- const value = rawCookie.slice(separatorIndex + 1).trim();
1825
- try {
1826
- return decodeURIComponent(value);
1827
- } catch {
1828
- return void 0;
1829
- }
1830
- }
1831
- return void 0;
1770
+ InMemoryCacheExtended = class extends InMemoryCache {
1771
+ async increment(key, ttlSeconds) {
1772
+ const current = await this.get(key) ?? 0;
1773
+ const next = Number(current) + 1;
1774
+ const ttl = Guards23.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
1775
+ await this.set(key, next, ttl);
1776
+ return next;
1832
1777
  }
1833
1778
  };
1834
1779
  }
1835
1780
  });
1836
1781
 
1837
- // src/infrastructure/services/extractors/http-header.extractor.ts
1838
- import { Guards as Guards24, GuidHelper as GuidHelper4, HttpHelper, MathHelper } from "@xeno-js/shared";
1839
- var HttpHeaderExtractor;
1840
- var init_http_header_extractor = __esm({
1841
- "src/infrastructure/services/extractors/http-header.extractor.ts"() {
1782
+ // src/infrastructure/cache/redis.cache.ts
1783
+ import { Guards as Guards24, StringHelper as StringHelper2 } from "@xeno-js/shared";
1784
+ var RedisCache;
1785
+ var init_redis_cache = __esm({
1786
+ "src/infrastructure/cache/redis.cache.ts"() {
1842
1787
  "use strict";
1843
- HttpHeaderExtractor = class {
1788
+ RedisCache = class {
1844
1789
  /**
1845
- * @description Constructor for HttpHeaderExtractor. It takes an instance of IServiceExtractor for extracting Bearer tokens, allowing for separation of concerns and adherence to the Single Responsibility Principle (SRP). This design enables the HttpHeaderExtractor to focus on general header extraction while delegating the specific logic of Bearer token extraction to a dedicated extractor, promoting code reusability and maintainability.
1790
+ * @description Constructs a new instance of the RedisCache class, which takes an instance of the Redis client as a parameter. This client is used to perform caching operations such as setting, getting, and removing values from the Redis database. The constructor initializes the RedisCache with the provided Redis client, allowing it to interact with the Redis server for all caching operations defined in the ICache interface.
1791
+ * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
1846
1792
 
1847
1793
  *
1848
1794
  * @author Xeno
@@ -1850,361 +1796,141 @@ var init_http_header_extractor = __esm({
1850
1796
  * @since 2025-09-30
1851
1797
  * @link https://github.com/xeno-js/xeno-js
1852
1798
  */
1853
- constructor(_bearerExtractor, _cookieExtractor, _trustedIp, _cookieName) {
1854
- this._bearerExtractor = _bearerExtractor;
1855
- this._cookieExtractor = _cookieExtractor;
1856
- this._trustedIp = _trustedIp;
1857
- this._cookieName = _cookieName;
1858
- }
1859
- _bearerExtractor;
1860
- _cookieExtractor;
1861
- _trustedIp;
1862
- _cookieName;
1863
- extract(headers) {
1864
- const correlationId = GuidHelper4.parse(headers.get("x-correlation-id") ?? void 0);
1865
- const requestId = GuidHelper4.parse(headers.get("x-request-id") ?? void 0);
1866
- const token = this._bearerExtractor.extract(headers);
1867
- const clientIp = headers.get(this._trustedIp?.toLowerCase() ?? "x-forwarded-for") ?? headers.get("x-real-ip") ?? void 0;
1868
- const spanId = GuidHelper4.parse(headers.get("x-span-id") ?? void 0);
1869
- const parentSpanId = headers.get("x-parent-span-id") ?? void 0;
1870
- const acceptHeader = headers.get("accept");
1871
- const contentTypeHeader = headers.get("content-type");
1872
- const userAgent = headers.get("user-agent") ?? void 0;
1873
- const returnAddress = headers.get("x-return-address") ?? void 0;
1874
- const sequenceId = headers.get("x-sequence-id") ?? void 0;
1875
- const position = headers.get("x-sequence-position");
1876
- const size = headers.get("x-sequence-size");
1877
- const expiration = headers.get("x-expiration");
1878
- const csrf = headers.get("x-csrf-token") ?? void 0;
1879
- const cookieHeader = headers.get("cookie") ?? void 0;
1880
- const csrfCookie = this._cookieExtractor.extract({
1881
- header: cookieHeader,
1882
- name: this._cookieName
1883
- });
1884
- const origin = headers.get("origin") ?? void 0;
1885
- const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin);
1886
- const referer = headers.get("referer") ?? void 0;
1887
- const cleanReferer = HttpHelper.sanitizeOriginUrl(referer);
1888
- const accept = acceptHeader === "*/*" ? void 0 : acceptHeader;
1889
- const formatIndicator = accept ?? contentTypeHeader ?? "application/json";
1890
- const metadata = {
1891
- correlationId,
1892
- requestId,
1893
- token,
1894
- clientIp,
1895
- spanId,
1896
- parentSpanId,
1897
- formatIndicator,
1898
- userAgent,
1899
- returnAddress,
1900
- csrf,
1901
- csrfCookie,
1902
- origin: cleanOrigin,
1903
- referer: cleanReferer,
1904
- sequence: {
1905
- sequenceId,
1906
- position: Guards24.isDefined(position) ? MathHelper.toNumber(position) : void 0,
1907
- size: Guards24.isDefined(size) ? MathHelper.toNumber(size) : void 0
1908
- },
1909
- expiration: Guards24.isDefined(expiration) ? MathHelper.toNumber(expiration) : void 0
1910
- };
1911
- return metadata;
1912
- }
1913
- };
1914
- }
1915
- });
1916
-
1917
- // src/infrastructure/services/extractors/index.ts
1918
- var init_extractors = __esm({
1919
- "src/infrastructure/services/extractors/index.ts"() {
1920
- "use strict";
1921
- init_extract_bearer_extractor();
1922
- init_extract_ssr_bearer_extractor();
1923
- init_http_cookie_extractor();
1924
- init_http_header_extractor();
1925
- }
1926
- });
1927
-
1928
- // src/infrastructure/services/resiliences/resilience.service.ts
1929
- import { AppError as AppError12 } from "@xeno-js/shared";
1930
- var ServiceResilience;
1931
- var init_resilience_service = __esm({
1932
- "src/infrastructure/services/resiliences/resilience.service.ts"() {
1933
- "use strict";
1934
- ServiceResilience = class {
1935
- constructor(policy) {
1936
- this.policy = policy;
1799
+ constructor(_redisClient) {
1800
+ this._redisClient = _redisClient;
1937
1801
  }
1938
- policy;
1939
- async execute(operation, signal) {
1940
- AppError12.throwIfAborted(signal, "ServiceResilience.execute");
1941
- return this.policy.execute(() => operation(), signal);
1802
+ _redisClient;
1803
+ async increment(key, ttlSeconds) {
1804
+ const multi = this._redisClient.multi();
1805
+ multi.incr(key);
1806
+ multi.expire(key, ttlSeconds ?? 60);
1807
+ const results = await multi.exec();
1808
+ return results?.[0]?.[1] ?? 1;
1942
1809
  }
1943
- };
1944
- }
1945
- });
1946
-
1947
- // src/infrastructure/services/resiliences/index.ts
1948
- var init_resiliences = __esm({
1949
- "src/infrastructure/services/resiliences/index.ts"() {
1950
- "use strict";
1951
- init_resilience_service();
1952
- }
1953
- });
1954
-
1955
- // src/infrastructure/services/resolver/utils/socket.utils.ts
1956
- import { Guards as Guards25 } from "@xeno-js/shared";
1957
- var SocketIpExtractor;
1958
- var init_socket_utils = __esm({
1959
- "src/infrastructure/services/resolver/utils/socket.utils.ts"() {
1960
- "use strict";
1961
- SocketIpExtractor = Object.freeze({
1962
- /**
1963
- * @description Extracts the IP address of the remote socket from an incoming request.
1964
- * @param req The incoming request object.
1965
- * @returns The IP address of the remote socket, or undefined if not available.
1966
- */
1967
- extract(req) {
1968
- if (Guards25.isDefined(req) && Guards25.isObject(req)) {
1969
- const candidate = req;
1970
- return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
1810
+ async get(key) {
1811
+ const value = await this._redisClient.get(key);
1812
+ if (!Guards24.isDefined(value)) {
1813
+ return void 0;
1971
1814
  }
1972
- return void 0;
1815
+ return JSON.parse(value);
1973
1816
  }
1974
- });
1975
- }
1976
- });
1977
-
1978
- // src/infrastructure/services/resolver/utils/index.ts
1979
- var init_utils = __esm({
1980
- "src/infrastructure/services/resolver/utils/index.ts"() {
1981
- "use strict";
1982
- init_socket_utils();
1983
- }
1984
- });
1985
-
1986
- // src/infrastructure/services/resolver/client-ip.resolver.ts
1987
- import { Guards as Guards26 } from "@xeno-js/shared";
1988
- var ClientIpResolver;
1989
- var init_client_ip_resolver = __esm({
1990
- "src/infrastructure/services/resolver/client-ip.resolver.ts"() {
1991
- "use strict";
1992
- init_utils();
1993
- ClientIpResolver = class {
1994
- constructor(_trustedProxies = []) {
1995
- this._trustedProxies = _trustedProxies;
1817
+ async set(key, value, ttl) {
1818
+ const stringValue = StringHelper2.safeStringify(value);
1819
+ const ttlOption = Guards24.isDefined(ttl) ? ttl : 86400;
1820
+ await this._redisClient.set(key, stringValue, "EX", ttlOption);
1996
1821
  }
1997
- _trustedProxies;
1998
- resolve(req, clientIp) {
1999
- const socketIp = SocketIpExtractor.extract(req);
2000
- if (!Guards26.isDefined(socketIp))
2001
- return !Guards26.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
2002
- const isTrustedProxy = this._trustedProxies.includes(socketIp);
2003
- if (!isTrustedProxy) return socketIp;
2004
- if (Guards26.isDefined(clientIp)) return clientIp.split(",")[0].trim();
2005
- return socketIp;
1822
+ async setIfAbsent(key, value, ttl) {
1823
+ const stringValue = StringHelper2.safeStringify(value);
1824
+ const ttlOption = Guards24.isDefined(ttl) ? ttl : 300;
1825
+ const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
1826
+ return result === "OK";
2006
1827
  }
2007
- };
2008
- }
2009
- });
2010
-
2011
- // src/infrastructure/services/resolver/index.ts
2012
- var init_resolver = __esm({
2013
- "src/infrastructure/services/resolver/index.ts"() {
2014
- "use strict";
2015
- init_client_ip_resolver();
2016
- }
2017
- });
2018
-
2019
- // src/infrastructure/services/index.ts
2020
- var services_exports = {};
2021
- __export(services_exports, {
2022
- AllowMethodRegistry: () => AllowMethodRegistry,
2023
- AllowOrigin: () => AllowOrigin,
2024
- BearerTokenExtractor: () => BearerTokenExtractor,
2025
- ClientIpResolver: () => ClientIpResolver,
2026
- CookieHandler: () => CookieHandler,
2027
- CsrfTokenService: () => CsrfTokenService,
2028
- EdgeCryptoService: () => EdgeCryptoService,
2029
- HttpCookieExtractor: () => HttpCookieExtractor,
2030
- HttpHeaderExtractor: () => HttpHeaderExtractor,
2031
- PLimitConcurrencyService: () => PLimitConcurrencyService,
2032
- ServiceResilience: () => ServiceResilience,
2033
- SupabaseSsrTokenExtractor: () => SupabaseSsrTokenExtractor
2034
- });
2035
- var init_services = __esm({
2036
- "src/infrastructure/services/index.ts"() {
2037
- "use strict";
2038
- init_allow_methods();
2039
- init_allow_origins();
2040
- init_concurrency();
2041
- init_cookies();
2042
- init_crypto();
2043
- init_csrf();
2044
- init_extractors();
2045
- init_resiliences();
2046
- init_resolver();
2047
- }
2048
- });
2049
-
2050
- // src/infrastructure/factories/supabase.factory.ts
2051
- var supabase_factory_exports = {};
2052
- __export(supabase_factory_exports, {
2053
- SupabaseServerAuthFactory: () => SupabaseServerAuthFactory
2054
- });
2055
- import { createServerClient } from "@supabase/ssr";
2056
- import { Guards as Guards27, TOKENS as TOKENS3 } from "@xeno-js/shared";
2057
- import {
2058
- SupabaseAuthService,
2059
- SupabaseClaimsMapper,
2060
- SupabaseSessionMapper
2061
- } from "@xeno-js/shared/supabase";
2062
- var SupabaseServerAuthFactory;
2063
- var init_supabase_factory = __esm({
2064
- "src/infrastructure/factories/supabase.factory.ts"() {
2065
- "use strict";
2066
- init_services();
2067
- SupabaseServerAuthFactory = class {
2068
- create({
2069
- config,
2070
- container
2071
- }) {
2072
- const cookieService = this._getCookieSsr(config.ssrOpts, container, config.cookieOpts);
2073
- const client = createServerClient(config.url, config.key, {
2074
- ...config.opts,
2075
- cookies: {
2076
- getAll() {
2077
- return cookieService.getAll();
2078
- },
2079
- setAll(cookiesToSet) {
2080
- cookieService.setAll(cookiesToSet);
2081
- }
2082
- }
2083
- });
2084
- const mapper = new SupabaseClaimsMapper();
2085
- const sessionMapper = new SupabaseSessionMapper(mapper);
2086
- return new SupabaseAuthService(client, mapper, sessionMapper, config);
1828
+ async remove(key) {
1829
+ await this._redisClient.del(key);
1830
+ }
1831
+ async has(key) {
1832
+ const exists = await this._redisClient.exists(key);
1833
+ return exists === 1;
2087
1834
  }
2088
- _getCookieSsr(ssrOpts, container, config) {
2089
- if (Guards27.isDefined(ssrOpts)) {
2090
- return ssrOpts(container);
2091
- } else {
2092
- return new CookieHandler(
2093
- container.resolve(TOKENS3.NETWORK_CONTEXT_ACCESSOR),
2094
- container.resolve(TOKENS3.CONFIGURATION_SERVICE),
2095
- config
2096
- );
2097
- }
1835
+ async clear() {
1836
+ await this._redisClient.flushdb();
2098
1837
  }
2099
1838
  };
2100
1839
  }
2101
1840
  });
2102
1841
 
2103
- // src/infrastructure/modules/utils/auth.utils.ts
2104
- var auth_utils_exports = {};
2105
- __export(auth_utils_exports, {
2106
- AuthUtils: () => AuthUtils
1842
+ // src/infrastructure/factories/redis-cache.factory.ts
1843
+ var redis_cache_factory_exports = {};
1844
+ __export(redis_cache_factory_exports, {
1845
+ RedisCacheFactory: () => RedisCacheFactory
2107
1846
  });
2108
- var AuthUtils;
2109
- var init_auth_utils = __esm({
2110
- "src/infrastructure/modules/utils/auth.utils.ts"() {
1847
+ import { Guards as Guards25 } from "@xeno-js/shared";
1848
+ import { Redis } from "ioredis";
1849
+ var RedisCacheFactory;
1850
+ var init_redis_cache_factory = __esm({
1851
+ "src/infrastructure/factories/redis-cache.factory.ts"() {
2111
1852
  "use strict";
2112
- AuthUtils = Object.freeze({
2113
- /**
2114
- * @description Checks if the provided authorization configuration requires any authorization strategies.
2115
- * @param authorizationConfig The authorization configuration to check.
2116
- * @returns True if any authorization strategies are required, false otherwise.
2117
-
2118
- *
2119
- * @author Xeno
2120
- * @version 1.0.0
2121
- * @since 2025-09-30
2122
- * @link https://github.com/xeno-js/xeno-js
2123
- */
2124
- async addAuthZ(container, opts) {
2125
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2126
- const strategies = [];
2127
- const { Guards: Guards51 } = await import("@xeno-js/shared");
2128
- if (Guards51.isDefined(opts.policies)) {
2129
- const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2130
- const policyRegistry = opts.policies;
2131
- const registryInstance = new PolicyRegistry2();
2132
- const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2133
- const Policies = /* @__PURE__ */ new Set();
2134
- for (const [intent, policy] of Object.entries(policyRegistry)) {
2135
- const intentLower = intent.toLowerCase();
2136
- registryInstance.addPolicy(intentLower, policy);
2137
- if (!Guards51.isNullOrEmpty(policy.roles)) {
2138
- Policies.add("roles");
2139
- }
2140
- if (!Guards51.isNullOrEmpty(policy.permissions)) {
2141
- Policies.add("permissions");
2142
- }
2143
- if (!Guards51.isNullOrEmpty(policy.userId)) {
2144
- Policies.add("userId");
2145
- }
2146
- if (!Guards51.isNullOrEmpty(policy.tenantId)) {
2147
- Policies.add("tenantId");
2148
- }
2149
- }
2150
- if (Policies.has("roles")) {
2151
- const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2152
- strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2153
- }
2154
- if (Policies.has("permissions")) {
2155
- const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2156
- strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2157
- }
2158
- if (Policies.has("userId")) {
2159
- const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2160
- strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2161
- }
2162
- if (Policies.has("tenantId")) {
2163
- const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2164
- strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
1853
+ init_redis_cache();
1854
+ RedisCacheFactory = class {
1855
+ create(config) {
1856
+ const host = config?.host ?? "localhost";
1857
+ const port = config?.port ?? 6379;
1858
+ const password = config?.password;
1859
+ const username = config?.username;
1860
+ const useTls = config?.tls ?? false;
1861
+ const maxRetries = config?.maxRetriesPerRequest ?? 3;
1862
+ const redisOptions = {
1863
+ host,
1864
+ port,
1865
+ maxRetriesPerRequest: maxRetries,
1866
+ // Strategia di riconnessione esponenziale per garantire resilienza
1867
+ retryStrategy(times) {
1868
+ const delay = Math.min(times * 50, 2e3);
1869
+ return delay;
2165
1870
  }
1871
+ };
1872
+ if (Guards25.isDefined(password)) {
1873
+ redisOptions.password = password;
2166
1874
  }
2167
- if (!Guards51.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2168
- const customStrategies = opts.customAuthorizationStrategy;
2169
- customStrategies.forEach((strategyToken) => {
2170
- if (Guards51.isDefined(strategyToken)) {
2171
- strategies.push(strategyToken(container));
2172
- }
2173
- });
1875
+ if (Guards25.isDefined(username)) {
1876
+ redisOptions.username = username;
2174
1877
  }
2175
- const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2176
- return new AuthorizationPipeline2(strategies);
2177
- },
1878
+ if (useTls) {
1879
+ redisOptions.tls = {};
1880
+ }
1881
+ const nativeRedisInstance = new Redis(redisOptions);
1882
+ nativeRedisInstance.on("error", (err) => {
1883
+ console.error("\u274C [Redis Error]:", err.message);
1884
+ });
1885
+ return new RedisCache(nativeRedisInstance);
1886
+ }
1887
+ };
1888
+ }
1889
+ });
1890
+
1891
+ // src/infrastructure/modules/utils/cache.utils.ts
1892
+ var cache_utils_exports = {};
1893
+ __export(cache_utils_exports, {
1894
+ CacheUtils: () => CacheUtils
1895
+ });
1896
+ var CacheUtils;
1897
+ var init_cache_utils = __esm({
1898
+ "src/infrastructure/modules/utils/cache.utils.ts"() {
1899
+ "use strict";
1900
+ CacheUtils = Object.freeze({
2178
1901
  /**
2179
- * @description Configures the authentication service and gatekeeper in the service container.
2180
- * @param container The service container to configure.
2181
- * @param opts The authentication configuration options.
2182
-
2183
- *
1902
+ * @description Checks if the provided cache configuration requires any cache strategies.
1903
+ * @param container The service container to which the cache strategies will be added.
1904
+ * @param opts The cache configuration options.
1905
+ * @returns True if any cache strategies are required, false otherwise.
1906
+ *
2184
1907
  * @author Xeno
2185
1908
  * @version 1.0.0
2186
1909
  * @since 2025-09-30
2187
- * @link https://github.com/xeno-js/xeno-js
1910
+ * @link https://github.com/xeno-js/xeno-js
2188
1911
  */
2189
- async addAuthN(container, opts) {
1912
+ async addCache(container, opts) {
2190
1913
  const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2191
- if (Guards51.isDefined(opts.customAuth)) {
2192
- const authService = opts.customAuth.authExtendedService();
2193
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2194
- return authService;
2195
- });
2196
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2197
- return authService;
2198
- });
2199
- } else {
2200
- const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_supabase_factory(), supabase_factory_exports));
2201
- const factory = new SupabaseServerAuthFactory2();
2202
- const supabase = factory.create({ config: opts, container });
2203
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2204
- return supabase;
2205
- });
2206
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2207
- return supabase;
1914
+ if (!opts.inMemory && !Guards51.isDefined(opts.redis)) {
1915
+ throw new Error(
1916
+ "No cache strategies are configured. Please provide at least one cache strategy."
1917
+ );
1918
+ }
1919
+ const { CacheKeyBuilder } = await import("@xeno-js/shared");
1920
+ container.addSingleton(
1921
+ TOKENS5.CACHE_KEY_BUILDER,
1922
+ (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
1923
+ );
1924
+ if (opts.inMemory || !Guards51.isDefined(opts.redis)) {
1925
+ const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
1926
+ container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
1927
+ return;
1928
+ }
1929
+ if (Guards51.isDefined(opts.redis)) {
1930
+ const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
1931
+ container.addSingleton(TOKENS5.CACHE, () => {
1932
+ const config = opts.redis;
1933
+ return new RedisCacheFactory2().create(config);
2208
1934
  });
2209
1935
  }
2210
1936
  }
@@ -2212,750 +1938,780 @@ var init_auth_utils = __esm({
2212
1938
  }
2213
1939
  });
2214
1940
 
2215
- // src/infrastructure/factories/zod-validator.factory.ts
2216
- var zod_validator_factory_exports = {};
2217
- __export(zod_validator_factory_exports, {
2218
- ZodValidatorFactory: () => ZodValidatorFactory
1941
+ // src/infrastructure/services/allow_methods/allow-method.service.ts
1942
+ import { Guards as Guards26 } from "@xeno-js/shared";
1943
+ var AllowMethodRegistry;
1944
+ var init_allow_method_service = __esm({
1945
+ "src/infrastructure/services/allow_methods/allow-method.service.ts"() {
1946
+ "use strict";
1947
+ AllowMethodRegistry = class {
1948
+ _staticRoutes = /* @__PURE__ */ new Map();
1949
+ _dynamicRoutes = [];
1950
+ add(path, methods) {
1951
+ const normalizedPath = this.normalizePath(path);
1952
+ if (this.isDynamicPath(normalizedPath)) {
1953
+ const pattern = this.createRoutePattern(normalizedPath);
1954
+ this._dynamicRoutes.push({ pattern, methods });
1955
+ } else {
1956
+ this._staticRoutes.set(normalizedPath, methods);
1957
+ }
1958
+ }
1959
+ check(path, method) {
1960
+ const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1961
+ const staticMethods = this._staticRoutes.get(cleanPath);
1962
+ if (Guards26.isDefined(staticMethods)) return staticMethods.includes(method);
1963
+ for (const route of this._dynamicRoutes) {
1964
+ if (route.pattern.test(cleanPath)) return route.methods.includes(method);
1965
+ }
1966
+ return false;
1967
+ }
1968
+ getMethods(path) {
1969
+ const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1970
+ const methods = this.findMethods(cleanPath);
1971
+ return Guards26.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
1972
+ }
1973
+ findMethods(cleanPath) {
1974
+ const staticMethods = this._staticRoutes.get(cleanPath);
1975
+ if (Guards26.isDefined(staticMethods)) return staticMethods;
1976
+ for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods;
1977
+ return void 0;
1978
+ }
1979
+ isDynamicPath(path) {
1980
+ return path.includes(":") || path.includes("{") && path.includes("}");
1981
+ }
1982
+ normalizePath(path) {
1983
+ const trimmed = path.trim();
1984
+ const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
1985
+ if (withLeadingSlash === "/") return "/";
1986
+ return withLeadingSlash.replace(/\/+$/, "");
1987
+ }
1988
+ createRoutePattern(path) {
1989
+ const segments = path.split("/").filter(Boolean);
1990
+ const regexSegments = segments.map((segment) => {
1991
+ if (segment.startsWith(":") || segment.startsWith("{") && segment.endsWith("}"))
1992
+ return "([^/]+)";
1993
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1994
+ });
1995
+ return new RegExp(`^\\/${regexSegments.join("\\/")}\\/?$`);
1996
+ }
1997
+ };
1998
+ }
2219
1999
  });
2220
- import { ZodValidatorService } from "@xeno-js/shared/zod";
2221
- var ZodValidatorFactory;
2222
- var init_zod_validator_factory = __esm({
2223
- "src/infrastructure/factories/zod-validator.factory.ts"() {
2000
+
2001
+ // src/infrastructure/services/allow_methods/index.ts
2002
+ var init_allow_methods = __esm({
2003
+ "src/infrastructure/services/allow_methods/index.ts"() {
2004
+ "use strict";
2005
+ init_allow_method_service();
2006
+ }
2007
+ });
2008
+
2009
+ // src/infrastructure/services/allow_origins/allow-origin.http.ts
2010
+ import { Guards as Guards27 } from "@xeno-js/shared";
2011
+ var AllowOrigin;
2012
+ var init_allow_origin_http = __esm({
2013
+ "src/infrastructure/services/allow_origins/allow-origin.http.ts"() {
2224
2014
  "use strict";
2225
- ZodValidatorFactory = class {
2226
- create(opts) {
2227
- const validatorService = new ZodValidatorService(/* @__PURE__ */ new Map(), opts.logger);
2228
- for (const [intentKey, schema] of Object.entries(opts.schemas)) {
2229
- validatorService.addSchema(intentKey, schema);
2015
+ AllowOrigin = class {
2016
+ constructor(_list) {
2017
+ this._list = _list;
2018
+ }
2019
+ _list;
2020
+ isAllowed(origin) {
2021
+ if (Guards27.isNullOrEmpty(origin)) return true;
2022
+ const cleanOrigin = origin.trim().toLowerCase();
2023
+ for (const pattern of this._list) {
2024
+ const cleanPattern = pattern.trim().toLowerCase();
2025
+ if (cleanPattern === "*") return true;
2026
+ if (cleanPattern === cleanOrigin) return true;
2027
+ if (cleanPattern.startsWith("*.")) {
2028
+ const domainSuffix = cleanPattern.substring(1);
2029
+ if (cleanOrigin.endsWith(domainSuffix)) {
2030
+ const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length);
2031
+ if (!Guards27.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
2032
+ }
2033
+ }
2230
2034
  }
2231
- return validatorService;
2035
+ return false;
2232
2036
  }
2233
2037
  };
2234
2038
  }
2235
2039
  });
2236
2040
 
2237
- // src/infrastructure/modules/utils/validation.utils.ts
2238
- var validation_utils_exports = {};
2239
- __export(validation_utils_exports, {
2240
- ValidationUtils: () => ValidationUtils
2241
- });
2242
- var ValidationUtils;
2243
- var init_validation_utils = __esm({
2244
- "src/infrastructure/modules/utils/validation.utils.ts"() {
2041
+ // src/infrastructure/services/allow_origins/index.ts
2042
+ var init_allow_origins = __esm({
2043
+ "src/infrastructure/services/allow_origins/index.ts"() {
2245
2044
  "use strict";
2246
- ValidationUtils = Object.freeze({
2247
- /**
2248
- * @description Checks if the provided validation configuration requires any validation strategies.
2249
- * @param validationConfig The validation configuration to check.
2250
- * @returns True if any validation strategies are required, false otherwise.
2251
- *
2252
- * @author Xeno
2253
- * @version 1.0.0
2254
- * @since 2025-09-30
2255
- * @link https://github.com/xeno-js/xeno-js
2256
- */
2257
- async addValidation(container, opts, logger) {
2258
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2259
- if (!Guards51.isDefined(opts.zod) && Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
2260
- return;
2261
- }
2262
- const validationStrategies = [];
2263
- if (Guards51.isDefined(opts.zod)) {
2264
- const config = opts.zod;
2265
- const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_zod_validator_factory(), zod_validator_factory_exports));
2266
- const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2267
- const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
2268
- container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
2269
- validationStrategies.push(new SchemaValidationStrategy2(validatorService));
2270
- }
2271
- if (!Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
2272
- for (const strategyToken of opts.customValidationStrategy) {
2273
- if (Guards51.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
2274
- }
2275
- }
2276
- const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2277
- return new ValidationPipeline2(validationStrategies);
2278
- }
2279
- });
2045
+ init_allow_origin_http();
2280
2046
  }
2281
2047
  });
2282
2048
 
2283
- // src/infrastructure/idempotency/idempotency-store.ts
2284
- import { IDEMPOTENCY_CONSTANTS as IDEMPOTENCY_CONSTANTS2 } from "@xeno-js/shared";
2285
- var IdempotencyStore;
2286
- var init_idempotency_store = __esm({
2287
- "src/infrastructure/idempotency/idempotency-store.ts"() {
2049
+ // src/infrastructure/services/concurrency/p-limit.service.ts
2050
+ var PLimitConcurrencyService;
2051
+ var init_p_limit_service = __esm({
2052
+ "src/infrastructure/services/concurrency/p-limit.service.ts"() {
2288
2053
  "use strict";
2289
- IdempotencyStore = class {
2290
- /**
2291
- * @description Constructs a new instance of IdempotencyStore, accepting an instance of ICache for accessing the caching system and an instance of IIdentityAccessor for obtaining the user's identity context. The IdempotencyStore uses the caching system to manage locks and results of idempotent commands, ensuring that commands with the same ID are processed only once. The identity context is used to build contextual keys, allowing for more granular management of idempotent commands in multi-tenant scenarios.
2292
- * @param _cache An instance of ICache that provides methods to interact with the underlying caching system, used to store locks and results of idempotent commands.
2293
- * @param _identityAccessor An instance of IIdentityAccessor that allows access to the user's identity context, used to build contextual keys for idempotent commands, supporting multi-tenant scenarios.
2294
-
2295
- *
2296
- * @author Xeno
2297
- * @version 1.0.0
2298
- * @since 2025-09-30
2299
- * @link https://github.com/xeno-js/xeno-js
2300
- */
2301
- constructor(_cache, _cacheKeyBuilder) {
2302
- this._cache = _cache;
2303
- this._cacheKeyBuilder = _cacheKeyBuilder;
2304
- }
2305
- _cache;
2306
- _cacheKeyBuilder;
2307
- async acquireLock(requestId, ttlSeconds) {
2308
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
2309
- return await this._cache.setIfAbsent(
2310
- `${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`,
2311
- IDEMPOTENCY_CONSTANTS2.LOCKED_VALUE,
2312
- ttlSeconds
2313
- );
2314
- }
2315
- async hasBeenProcessed(commandId) {
2316
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2317
- return await this._cache.has(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
2318
- }
2319
- async markAsProcessed(commandId, payload, ttlSeconds) {
2320
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2321
- await this._cache.set(
2322
- `${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`,
2323
- payload,
2324
- ttlSeconds
2325
- );
2326
- }
2327
- async getPayload(commandId) {
2328
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2329
- const payload = await this._cache.get(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
2330
- return payload;
2331
- }
2332
- async releaseLock(commandId) {
2333
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2334
- await this._cache.remove(`${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`);
2054
+ PLimitConcurrencyService = class {
2055
+ async executeInParallel(tasks, concurrencyLimit) {
2056
+ const { default: pLimit } = await import("p-limit");
2057
+ const limit = pLimit(concurrencyLimit);
2058
+ const promises = tasks.map((task) => limit(task));
2059
+ return Promise.all(promises);
2335
2060
  }
2336
2061
  };
2337
2062
  }
2338
2063
  });
2339
2064
 
2340
- // src/infrastructure/idempotency/index.ts
2341
- var idempotency_exports = {};
2342
- __export(idempotency_exports, {
2343
- IdempotencyStore: () => IdempotencyStore
2065
+ // src/infrastructure/services/concurrency/index.ts
2066
+ var concurrency_exports = {};
2067
+ __export(concurrency_exports, {
2068
+ PLimitConcurrencyService: () => PLimitConcurrencyService
2344
2069
  });
2345
- var init_idempotency = __esm({
2346
- "src/infrastructure/idempotency/index.ts"() {
2070
+ var init_concurrency = __esm({
2071
+ "src/infrastructure/services/concurrency/index.ts"() {
2347
2072
  "use strict";
2348
- init_idempotency_store();
2073
+ init_p_limit_service();
2349
2074
  }
2350
2075
  });
2351
2076
 
2352
- // src/infrastructure/modules/utils/pipeline.utils.ts
2353
- var pipeline_utils_exports = {};
2354
- __export(pipeline_utils_exports, {
2355
- PipelineUtils: () => PipelineUtils
2356
- });
2357
- var PipelineUtils;
2358
- var init_pipeline_utils = __esm({
2359
- "src/infrastructure/modules/utils/pipeline.utils.ts"() {
2077
+ // src/infrastructure/services/cookies/cookies.service.ts
2078
+ import { Guards as Guards28 } from "@xeno-js/shared";
2079
+ var CookieHandler;
2080
+ var init_cookies_service = __esm({
2081
+ "src/infrastructure/services/cookies/cookies.service.ts"() {
2360
2082
  "use strict";
2361
- PipelineUtils = Object.freeze({
2362
- /**
2363
- * @description Checks if the provided command configuration requires any command strategies.
2364
- * @param commandConfig The command configuration to check.
2365
- * @returns True if any command strategies are required, false otherwise.
2366
- *
2367
- * @author Xeno
2368
- * @version 1.0.0
2369
- * @since 2025-09-30
2370
- * @link https://github.com/xeno-js/xeno-js
2371
- */
2372
- async addCommand(container, opts) {
2373
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2374
- const pipelines = [];
2375
- if (Guards51.isDefined(opts.idempotency)) {
2376
- const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
2377
- const imdStore = new IdempotencyStore2(
2378
- container.resolve(TOKENS5.CACHE),
2379
- container.resolve(TOKENS5.CACHE_KEY_BUILDER)
2380
- );
2381
- const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2382
- const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
2383
- const config = opts.idempotency;
2384
- pipelines.push(
2385
- new IdempotencyPipeline2(
2386
- requestContext,
2387
- imdStore,
2388
- config?.lockTtlSeconds,
2389
- config?.processedTtlSeconds
2390
- )
2391
- );
2392
- }
2393
- if (Guards51.isDefined(opts.concurrency)) {
2394
- const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2395
- const config = opts.concurrency;
2396
- pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
2083
+ CookieHandler = class {
2084
+ constructor(contextAccessor, _config, _cookieOpts) {
2085
+ this.contextAccessor = contextAccessor;
2086
+ this._config = _config;
2087
+ this._cookieOpts = _cookieOpts;
2088
+ }
2089
+ contextAccessor;
2090
+ _config;
2091
+ _cookieOpts;
2092
+ getAll() {
2093
+ const network = this.contextAccessor.getNetworkContext();
2094
+ const req = network?.transport?.req;
2095
+ if (!Guards28.isDefined(req) || Guards28.isNullOrEmpty(req.headers.get("cookie"))) return [];
2096
+ return req.headers.get("cookie")?.split(";").map((cookie) => {
2097
+ const [name, ...rest] = cookie.split("=");
2098
+ return { name: name.trim(), value: rest.join("=") };
2099
+ }) ?? [];
2100
+ }
2101
+ setAll(cookies) {
2102
+ const network = this.contextAccessor.getNetworkContext();
2103
+ const res = network?.transport?.res;
2104
+ if (!Guards28.isDefined(res)) return;
2105
+ const serializedCookies = cookies.map((c) => this.serialize(c));
2106
+ const existingSetCookie = res.headers.getSetCookie();
2107
+ res.headers.delete("Set-Cookie");
2108
+ for (const cookie of [...existingSetCookie, ...serializedCookies]) {
2109
+ res.headers.append("Set-Cookie", cookie);
2397
2110
  }
2398
- return pipelines;
2399
- },
2400
- /**
2401
- * @description Checks if the provided query configuration requires any query strategies.
2402
- * @param queryConfig The query configuration to check.
2403
- * @returns True if any query strategies are required, false otherwise.
2404
- *
2405
- * @author Xeno
2406
- * @version 1.0.0
2407
- * @since 2025-09-30
2408
- * @link https://github.com/xeno-js/xeno-js
2409
- */
2410
- async addQuery(container) {
2411
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2412
- const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2413
- return new QueryCachingPipeline2(
2414
- container.resolve(TOKENS5.CACHE),
2415
- container.resolve(TOKENS5.CACHE_KEY_BUILDER),
2416
- container.resolve(TOKENS5.LOGGER)
2417
- );
2418
2111
  }
2419
- });
2112
+ serialize(cookie) {
2113
+ const safeName = encodeURIComponent(cookie.name);
2114
+ const safeValue = encodeURIComponent(cookie.value);
2115
+ let str = `${safeName}=${safeValue}`;
2116
+ const isProd = this._config.get("NODE_ENV") === "production";
2117
+ const defaultOptions = {
2118
+ path: this._cookieOpts.path,
2119
+ httpOnly: this._cookieOpts.httpOnly,
2120
+ secure: this._cookieOpts.secure ?? isProd,
2121
+ sameSite: this._cookieOpts.sameSite ?? "Lax"
2122
+ };
2123
+ const opts = { ...defaultOptions, ...cookie.options ?? {} };
2124
+ str += `; Path=${opts.path}`;
2125
+ if (Guards28.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
2126
+ if (Guards28.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
2127
+ if (Guards28.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
2128
+ if (opts.secure) str += `; Secure`;
2129
+ if (opts.httpOnly) str += `; HttpOnly`;
2130
+ return str;
2131
+ }
2132
+ };
2420
2133
  }
2421
2134
  });
2422
2135
 
2423
- // src/infrastructure/modules/cqrs.module.ts
2424
- var cqrs_module_exports = {};
2425
- __export(cqrs_module_exports, {
2426
- CqrsModule: () => CqrsModule
2136
+ // src/infrastructure/services/cookies/index.ts
2137
+ var init_cookies = __esm({
2138
+ "src/infrastructure/services/cookies/index.ts"() {
2139
+ "use strict";
2140
+ init_cookies_service();
2141
+ }
2427
2142
  });
2428
- var CqrsModule;
2429
- var init_cqrs_module = __esm({
2430
- "src/infrastructure/modules/cqrs.module.ts"() {
2143
+
2144
+ // src/infrastructure/services/crypto/crypto.service.ts
2145
+ var EdgeCryptoService;
2146
+ var init_crypto_service = __esm({
2147
+ "src/infrastructure/services/crypto/crypto.service.ts"() {
2431
2148
  "use strict";
2432
- CqrsModule = class {
2433
- async configure(container, opts) {
2434
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2435
- const logger = container.resolve(TOKENS5.LOGGER);
2436
- const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2437
- container.addSingleton(TOKENS5.MEDIATOR, (c) => {
2438
- const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
2439
- return new Mediator2(serviceScopeAccessor);
2440
- });
2441
- const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2442
- const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2443
- const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2444
- const thresholdMs = opts.performance?.thresholdMs;
2445
- const pipelines = [
2446
- new ExceptionPipeline2(),
2447
- new LoggingPipeline2(logger),
2448
- new PerformancePipeline2(logger, opts.performance.intentThresholdMs, thresholdMs)
2449
- ];
2450
- if (Guards51.isDefined(opts.authorization.policies) || Guards51.isDefined(opts.authorization.customAuthorizationStrategy)) {
2451
- const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
2452
- const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
2453
- pipelines.push(authPipelines);
2454
- }
2455
- if (Guards51.isDefined(opts.validation.zod) || Guards51.isDefined(opts.validation.customValidationStrategy)) {
2456
- const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
2457
- const validationPipelines = await ValidationUtils2.addValidation(
2458
- container,
2459
- opts.validation,
2460
- logger
2461
- );
2462
- if (Guards51.isDefined(validationPipelines)) pipelines.push(validationPipelines);
2463
- }
2464
- const commandPipelines = [...pipelines];
2465
- const queryPipelines = [...pipelines];
2466
- if (Guards51.isDefined(opts.commandBus.idempotency) || Guards51.isDefined(opts.commandBus.concurrency)) {
2467
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
2468
- const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
2469
- commandPipelines.push(...newCommandPipelines);
2149
+ EdgeCryptoService = class {
2150
+ randomBytes(size) {
2151
+ const buffer = new Uint8Array(size);
2152
+ crypto.getRandomValues(buffer);
2153
+ return buffer;
2154
+ }
2155
+ async hmacSha256(secret, data) {
2156
+ const encoder = new TextEncoder();
2157
+ const keyData = encoder.encode(secret);
2158
+ const messageData = encoder.encode(data);
2159
+ const cryptoKey = await crypto.subtle.importKey(
2160
+ "raw",
2161
+ keyData,
2162
+ { name: "HMAC", hash: "SHA-256" },
2163
+ false,
2164
+ ["sign"]
2165
+ );
2166
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
2167
+ return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
2168
+ }
2169
+ timingSafeEqual(a, b) {
2170
+ if (a.length !== b.length) {
2171
+ return false;
2470
2172
  }
2471
- if (opts.queryBus.isEnabled) {
2472
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
2473
- const newQueryPipelines = await PipelineUtils2.addQuery(container);
2474
- queryPipelines.push(newQueryPipelines);
2173
+ let mismatch = 0;
2174
+ for (let i = 0; i < a.length; i++) {
2175
+ mismatch |= a[i] ^ b[i];
2475
2176
  }
2476
- const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2477
- container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
2478
- return new CompositePipeline2(commandPipelines);
2479
- });
2480
- container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
2481
- return new CompositePipeline2(queryPipelines);
2482
- });
2177
+ return mismatch === 0;
2483
2178
  }
2484
2179
  };
2485
2180
  }
2486
2181
  });
2487
2182
 
2488
- // src/infrastructure/factories/sql-light-db-client.factory.ts
2489
- var sql_light_db_client_factory_exports = {};
2490
- __export(sql_light_db_client_factory_exports, {
2491
- DbSqlLiteClientFactory: () => DbSqlLiteClientFactory
2492
- });
2493
- import { createClient } from "@libsql/client";
2494
- import { drizzle } from "drizzle-orm/libsql";
2495
- var DbSqlLiteClientFactory;
2496
- var init_sql_light_db_client_factory = __esm({
2497
- "src/infrastructure/factories/sql-light-db-client.factory.ts"() {
2183
+ // src/infrastructure/services/crypto/index.ts
2184
+ var init_crypto = __esm({
2185
+ "src/infrastructure/services/crypto/index.ts"() {
2498
2186
  "use strict";
2499
- DbSqlLiteClientFactory = class {
2500
- create(opts) {
2501
- const client = createClient({ url: opts.connectionString });
2502
- return drizzle({ client });
2187
+ init_crypto_service();
2188
+ }
2189
+ });
2190
+
2191
+ // src/infrastructure/services/csrf/csrf-token.service.ts
2192
+ import { Guards as Guards29 } from "@xeno-js/shared";
2193
+ var CsrfTokenService;
2194
+ var init_csrf_token_service = __esm({
2195
+ "src/infrastructure/services/csrf/csrf-token.service.ts"() {
2196
+ "use strict";
2197
+ CsrfTokenService = class {
2198
+ constructor(_secret, _cryptoService) {
2199
+ this._secret = _secret;
2200
+ this._cryptoService = _cryptoService;
2201
+ }
2202
+ _secret;
2203
+ _cryptoService;
2204
+ async generate(subject) {
2205
+ const randomBuffer = this._cryptoService.randomBytes(32);
2206
+ const nonce = btoa(String.fromCharCode(...randomBuffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
2207
+ const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
2208
+ return `${nonce}.${signature}`;
2209
+ }
2210
+ async validate(token, subject) {
2211
+ const separatorIndex = token.indexOf(".");
2212
+ if (separatorIndex <= 0) return false;
2213
+ const nonce = token.slice(0, separatorIndex);
2214
+ const signature = token.slice(separatorIndex + 1);
2215
+ if (Guards29.isNullOrEmpty(nonce) || Guards29.isNullOrEmpty(signature)) return false;
2216
+ const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
2217
+ const encoder = new TextEncoder();
2218
+ const actualBuffer = encoder.encode(signature);
2219
+ const expectedBuffer = encoder.encode(expected);
2220
+ if (actualBuffer.length !== expectedBuffer.length) return false;
2221
+ return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer);
2503
2222
  }
2504
2223
  };
2505
2224
  }
2506
2225
  });
2507
2226
 
2508
- // src/infrastructure/factories/db-client.factory.ts
2509
- var db_client_factory_exports = {};
2510
- __export(db_client_factory_exports, {
2511
- DbClientFactory: () => DbClientFactory
2512
- });
2513
- import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
2514
- import { Pool } from "pg";
2515
- var DbClientFactory;
2516
- var init_db_client_factory = __esm({
2517
- "src/infrastructure/factories/db-client.factory.ts"() {
2227
+ // src/infrastructure/services/csrf/index.ts
2228
+ var init_csrf = __esm({
2229
+ "src/infrastructure/services/csrf/index.ts"() {
2518
2230
  "use strict";
2519
- DbClientFactory = class {
2520
- create(opts) {
2521
- const pool = new Pool({
2522
- connectionString: opts.connectionString
2523
- });
2524
- return drizzle2({ client: pool });
2231
+ init_csrf_token_service();
2232
+ }
2233
+ });
2234
+
2235
+ // src/infrastructure/services/extractors/extract-bearer.extractor.ts
2236
+ import { Guards as Guards30 } from "@xeno-js/shared";
2237
+ var BearerTokenExtractor;
2238
+ var init_extract_bearer_extractor = __esm({
2239
+ "src/infrastructure/services/extractors/extract-bearer.extractor.ts"() {
2240
+ "use strict";
2241
+ BearerTokenExtractor = class {
2242
+ constructor(_cookiePrefix) {
2243
+ this._cookiePrefix = _cookiePrefix;
2244
+ }
2245
+ _cookiePrefix;
2246
+ extract(headers) {
2247
+ const authHeader = headers.get("Authorization");
2248
+ if (Guards30.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
2249
+ return authHeader.substring(7);
2250
+ }
2251
+ const cookieHeader = headers.get("cookie");
2252
+ if (Guards30.isDefined(cookieHeader)) {
2253
+ const regex = new RegExp(`${this._cookiePrefix}=([^;]+)`);
2254
+ const match = regex.exec(cookieHeader);
2255
+ if (!Guards30.isNullOrEmpty(match) && Guards30.isDefined(match[1])) {
2256
+ return match[1].trim();
2257
+ }
2258
+ }
2259
+ return void 0;
2525
2260
  }
2526
2261
  };
2527
2262
  }
2528
2263
  });
2529
2264
 
2530
- // src/infrastructure/modules/utils/db.utils.ts
2531
- var db_utils_exports = {};
2532
- __export(db_utils_exports, {
2533
- DbUtils: () => DbUtils
2534
- });
2535
- var DbUtils;
2536
- var init_db_utils = __esm({
2537
- "src/infrastructure/modules/utils/db.utils.ts"() {
2265
+ // src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts
2266
+ import { Guards as Guards31, StringHelper as StringHelper3 } from "@xeno-js/shared";
2267
+ var SupabaseSsrTokenExtractor;
2268
+ var init_extract_ssr_bearer_extractor = __esm({
2269
+ "src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts"() {
2538
2270
  "use strict";
2539
- DbUtils = Object.freeze({
2540
- /**
2541
- * @description Creates a new instance of a database client configured for SQLite using the provided database configuration options. This utility function encapsulates the logic for initializing a SQLite database client, allowing for easy integration with the application's dependency injection system. It ensures that the necessary connection string and other configuration parameters are correctly applied to create a functional database client instance.
2542
- *
2543
- * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the SQLite database.
2544
- * @returns A new instance of a database client configured for SQLite, ready for use in the application.
2545
- *
2546
- * @author Xeno
2547
- * @version 1.0.0
2548
- * @since 2025-09-30
2549
- * @link https://github.com/xeno-js/xeno-js
2550
- */
2551
- async addSqlLite(opts) {
2552
- const { DbSqlLiteClientFactory: DbSqlLiteClientFactory2 } = await Promise.resolve().then(() => (init_sql_light_db_client_factory(), sql_light_db_client_factory_exports));
2553
- return new DbSqlLiteClientFactory2().create(opts);
2554
- },
2555
- /**
2556
- * @description Creates a new instance of a database client based on the provided database configuration options. This utility function encapsulates the logic for initializing a database client, allowing for easy integration with the application's dependency injection system. It ensures that the necessary connection string and other configuration parameters are correctly applied to create a functional database client instance.
2557
- * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the database.
2558
- * @returns A new instance of a database client, ready for use in the application.
2559
- * @author Xeno
2560
- * @version 1.0.0
2561
- * @since 2025-09-30
2562
- * @link https://github.com/xeno-js/xeno-js
2563
- */
2564
- async addDbClient(opts) {
2565
- const { DbClientFactory: DbClientFactory2 } = await Promise.resolve().then(() => (init_db_client_factory(), db_client_factory_exports));
2566
- return new DbClientFactory2().create(opts);
2271
+ SupabaseSsrTokenExtractor = class {
2272
+ extract(headers) {
2273
+ const authHeader = headers.get("authorization");
2274
+ if (Guards31.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
2275
+ return authHeader.substring(7);
2276
+ }
2277
+ const cookieHeader = headers.get("cookie");
2278
+ if (Guards31.isNullOrEmpty(cookieHeader)) return void 0;
2279
+ const cookies = cookieHeader.split(";").map((c) => c.trim());
2280
+ const tokenChunks = {};
2281
+ let unchunkedToken;
2282
+ for (const cookie of cookies) {
2283
+ const [name, ...rest] = cookie.split("=");
2284
+ if (!Guards31.isDefined(name) || Guards31.isNullOrEmpty(rest)) continue;
2285
+ const value = decodeURIComponent(rest.join("="));
2286
+ if (Guards31.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
2287
+ unchunkedToken = value;
2288
+ } else {
2289
+ const match = /^sb-[a-z0-9]+-auth-token\.(\d+)$/.exec(name);
2290
+ if (Guards31.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
2291
+ }
2292
+ }
2293
+ let fullTokenString = unchunkedToken;
2294
+ if (!Guards31.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
2295
+ const indices = Object.keys(tokenChunks).map(Number).sort((a, b) => a - b);
2296
+ fullTokenString = indices.map((i) => tokenChunks[i]).join("");
2297
+ }
2298
+ if (Guards31.isNullOrEmpty(fullTokenString)) return void 0;
2299
+ try {
2300
+ const parsed = StringHelper3.safeParse(fullTokenString);
2301
+ if (Guards31.isDefined(parsed) && Guards31.isObject(parsed) && "access_token" in parsed) {
2302
+ const accessToken = parsed["access_token"];
2303
+ if (Guards31.isString(accessToken)) return accessToken;
2304
+ }
2305
+ } catch {
2306
+ return void 0;
2307
+ }
2567
2308
  }
2568
- });
2309
+ };
2569
2310
  }
2570
2311
  });
2571
2312
 
2572
- // src/infrastructure/transaction/transaction-state.ts
2573
- var transaction_state_exports = {};
2574
- __export(transaction_state_exports, {
2575
- TransactionState: () => TransactionState
2576
- });
2577
- var TransactionState;
2578
- var init_transaction_state = __esm({
2579
- "src/infrastructure/transaction/transaction-state.ts"() {
2313
+ // src/infrastructure/services/extractors/http-cookie.extractor.ts
2314
+ import { Guards as Guards32 } from "@xeno-js/shared";
2315
+ var HttpCookieExtractor;
2316
+ var init_http_cookie_extractor = __esm({
2317
+ "src/infrastructure/services/extractors/http-cookie.extractor.ts"() {
2580
2318
  "use strict";
2581
- TransactionState = class {
2582
- /**
2583
- * The current state of the transaction, which can be either a specific transaction type or null.
2584
- * @author Xeno
2585
- * @version 1.0.0
2586
- * @since 2025-09-30
2587
- * @link https://github.com/xeno-js/xeno-js
2588
- */
2589
- _state = null;
2590
- /**
2591
- * Creates an instance of TransactionState.
2592
- * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.
2593
- * @author Xeno
2594
- * @version 1.0.0
2595
- * @since 2025-09-30
2596
- * @link https://github.com/xeno-js/xeno-js
2597
- */
2598
- constructor(initialState = null) {
2599
- this._state = initialState;
2600
- }
2601
- get state() {
2602
- return this._state;
2603
- }
2604
- set state(value) {
2605
- this._state = value;
2319
+ HttpCookieExtractor = class {
2320
+ extract(cookie) {
2321
+ if (!Guards32.isDefined(cookie.header)) return void 0;
2322
+ for (const rawCookie of cookie.header.split(";")) {
2323
+ const separatorIndex = rawCookie.indexOf("=");
2324
+ if (separatorIndex <= 0) continue;
2325
+ const name = rawCookie.slice(0, separatorIndex).trim();
2326
+ if (name !== cookie.name) continue;
2327
+ const value = rawCookie.slice(separatorIndex + 1).trim();
2328
+ try {
2329
+ return decodeURIComponent(value);
2330
+ } catch {
2331
+ return void 0;
2332
+ }
2333
+ }
2334
+ return void 0;
2606
2335
  }
2607
2336
  };
2608
2337
  }
2609
2338
  });
2610
2339
 
2611
- // src/infrastructure/transaction/unit-of-work.ts
2612
- var unit_of_work_exports = {};
2613
- __export(unit_of_work_exports, {
2614
- UnitOfWork: () => UnitOfWork
2615
- });
2616
- import { AppError as AppError13 } from "@xeno-js/shared";
2617
- import { Guards as Guards28 } from "@xeno-js/shared";
2618
- var UnitOfWork;
2619
- var init_unit_of_work = __esm({
2620
- "src/infrastructure/transaction/unit-of-work.ts"() {
2340
+ // src/infrastructure/services/extractors/http-header.extractor.ts
2341
+ import { Guards as Guards33, GuidHelper as GuidHelper4, HttpHelper, MathHelper } from "@xeno-js/shared";
2342
+ var HttpHeaderExtractor;
2343
+ var init_http_header_extractor = __esm({
2344
+ "src/infrastructure/services/extractors/http-header.extractor.ts"() {
2621
2345
  "use strict";
2622
- UnitOfWork = class {
2346
+ HttpHeaderExtractor = class {
2623
2347
  /**
2624
- * Creates an instance of UnitOfWork.
2625
- * @param _dbContext - The database context used for managing transactions.
2626
- * @param _ttx - The transaction state, which can be either a specific transaction type or null.
2627
- *
2348
+ * @description Constructor for HttpHeaderExtractor. It takes an instance of IServiceExtractor for extracting Bearer tokens, allowing for separation of concerns and adherence to the Single Responsibility Principle (SRP). This design enables the HttpHeaderExtractor to focus on general header extraction while delegating the specific logic of Bearer token extraction to a dedicated extractor, promoting code reusability and maintainability.
2349
+
2350
+ *
2628
2351
  * @author Xeno
2629
2352
  * @version 1.0.0
2630
2353
  * @since 2025-09-30
2631
- * @link https://github.com/xeno-js/xeno-js
2354
+ * @link https://github.com/xeno-js/xeno-js
2632
2355
  */
2633
- constructor(_dbContext, _ttx) {
2634
- this._dbContext = _dbContext;
2635
- this._ttx = _ttx;
2356
+ constructor(_bearerExtractor, _cookieExtractor, _trustedIp, _cookieName) {
2357
+ this._bearerExtractor = _bearerExtractor;
2358
+ this._cookieExtractor = _cookieExtractor;
2359
+ this._trustedIp = _trustedIp;
2360
+ this._cookieName = _cookieName;
2636
2361
  }
2637
- _dbContext;
2638
- _ttx;
2639
- async runInTransaction(callback, signal) {
2640
- AppError13.throwIfAborted(signal, "UnitOfWork.runInTransaction");
2641
- return this._dbContext.transaction(async (tx) => {
2642
- this._ttx.state = tx;
2643
- try {
2644
- const result = await callback();
2645
- return result;
2646
- } finally {
2647
- this._ttx.state = null;
2648
- }
2362
+ _bearerExtractor;
2363
+ _cookieExtractor;
2364
+ _trustedIp;
2365
+ _cookieName;
2366
+ extract(headers) {
2367
+ const correlationId = GuidHelper4.parse(headers.get("x-correlation-id") ?? void 0);
2368
+ const requestId = GuidHelper4.parse(headers.get("x-request-id") ?? void 0);
2369
+ const token = this._bearerExtractor.extract(headers);
2370
+ const clientIp = headers.get(this._trustedIp?.toLowerCase() ?? "x-forwarded-for") ?? headers.get("x-real-ip") ?? void 0;
2371
+ const spanId = GuidHelper4.parse(headers.get("x-span-id") ?? void 0);
2372
+ const parentSpanId = headers.get("x-parent-span-id") ?? void 0;
2373
+ const acceptHeader = headers.get("accept");
2374
+ const contentTypeHeader = headers.get("content-type");
2375
+ const userAgent = headers.get("user-agent") ?? void 0;
2376
+ const returnAddress = headers.get("x-return-address") ?? void 0;
2377
+ const sequenceId = headers.get("x-sequence-id") ?? void 0;
2378
+ const position = headers.get("x-sequence-position");
2379
+ const size = headers.get("x-sequence-size");
2380
+ const expiration = headers.get("x-expiration");
2381
+ const csrf = headers.get("x-csrf-token") ?? void 0;
2382
+ const cookieHeader = headers.get("cookie") ?? void 0;
2383
+ const csrfCookie = this._cookieExtractor.extract({
2384
+ header: cookieHeader,
2385
+ name: this._cookieName
2649
2386
  });
2650
- }
2651
- async dispose() {
2652
- if (Guards28.isDefined(this._ttx.state)) {
2653
- try {
2654
- if (Guards28.hasMethod(this._ttx.state, "rollback")) {
2655
- await this._ttx.state.rollback();
2656
- }
2657
- } finally {
2658
- this._ttx.state = null;
2659
- }
2660
- }
2387
+ const origin = headers.get("origin") ?? void 0;
2388
+ const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin);
2389
+ const referer = headers.get("referer") ?? void 0;
2390
+ const cleanReferer = HttpHelper.sanitizeOriginUrl(referer);
2391
+ const accept = acceptHeader === "*/*" ? void 0 : acceptHeader;
2392
+ const formatIndicator = accept ?? contentTypeHeader ?? "application/json";
2393
+ const metadata = {
2394
+ correlationId,
2395
+ requestId,
2396
+ token,
2397
+ clientIp,
2398
+ spanId,
2399
+ parentSpanId,
2400
+ formatIndicator,
2401
+ userAgent,
2402
+ returnAddress,
2403
+ csrf,
2404
+ csrfCookie,
2405
+ origin: cleanOrigin,
2406
+ referer: cleanReferer,
2407
+ sequence: {
2408
+ sequenceId,
2409
+ position: Guards33.isDefined(position) ? MathHelper.toNumber(position) : void 0,
2410
+ size: Guards33.isDefined(size) ? MathHelper.toNumber(size) : void 0
2411
+ },
2412
+ expiration: Guards33.isDefined(expiration) ? MathHelper.toNumber(expiration) : void 0
2413
+ };
2414
+ return metadata;
2661
2415
  }
2662
2416
  };
2663
2417
  }
2664
2418
  });
2665
2419
 
2666
- // src/infrastructure/modules/db.module.ts
2667
- var db_module_exports = {};
2668
- __export(db_module_exports, {
2669
- DbModule: () => DbModule
2420
+ // src/infrastructure/services/extractors/index.ts
2421
+ var init_extractors = __esm({
2422
+ "src/infrastructure/services/extractors/index.ts"() {
2423
+ "use strict";
2424
+ init_extract_bearer_extractor();
2425
+ init_extract_ssr_bearer_extractor();
2426
+ init_http_cookie_extractor();
2427
+ init_http_header_extractor();
2428
+ }
2670
2429
  });
2671
- var DbModule;
2672
- var init_db_module = __esm({
2673
- "src/infrastructure/modules/db.module.ts"() {
2430
+
2431
+ // src/infrastructure/services/resiliences/resilience.service.ts
2432
+ import { AppError as AppError11 } from "@xeno-js/shared";
2433
+ var ServiceResilience;
2434
+ var init_resilience_service = __esm({
2435
+ "src/infrastructure/services/resiliences/resilience.service.ts"() {
2674
2436
  "use strict";
2675
- DbModule = class {
2676
- async configure(container, opts) {
2677
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2678
- const { DbUtils: DbUtils2 } = await Promise.resolve().then(() => (init_db_utils(), db_utils_exports));
2679
- const db = opts.enableSqlLite ? await DbUtils2.addSqlLite(opts) : await DbUtils2.addDbClient(opts);
2680
- const { TransactionState: TransactionState2 } = await Promise.resolve().then(() => (init_transaction_state(), transaction_state_exports));
2681
- container.addScoped("TRANSACTION_STATE", () => {
2682
- return new TransactionState2();
2683
- });
2684
- const { UnitOfWork: UnitOfWork2 } = await Promise.resolve().then(() => (init_unit_of_work(), unit_of_work_exports));
2685
- container.addScoped(TOKENS5.UNIT_OF_WORK, (c) => {
2686
- const ttx = c.resolve("TRANSACTION_STATE");
2687
- return new UnitOfWork2(db, ttx);
2688
- });
2689
- container.addScoped(TOKENS5.DB_CONTEXT, (c) => {
2690
- const ttx = c.resolve("TRANSACTION_STATE");
2691
- return new Proxy(db, {
2692
- get(_target, prop, receiver) {
2693
- const activeState = ttx.state;
2694
- if (Guards51.isDefined(activeState)) {
2695
- if (prop === "transaction") {
2696
- return activeState.transaction.bind(activeState);
2697
- }
2698
- return Reflect.get(activeState, prop, receiver);
2699
- }
2700
- return Reflect.get(db, prop, receiver);
2701
- }
2702
- });
2703
- });
2437
+ ServiceResilience = class {
2438
+ constructor(policy) {
2439
+ this.policy = policy;
2440
+ }
2441
+ policy;
2442
+ async execute(operation, signal) {
2443
+ AppError11.throwIfAborted(signal, "ServiceResilience.execute");
2444
+ return this.policy.execute(() => operation(), signal);
2704
2445
  }
2705
2446
  };
2706
2447
  }
2707
2448
  });
2708
2449
 
2709
- // src/infrastructure/http/base.http-adapter.ts
2710
- import { Guards as Guards29, StringHelper as StringHelper2 } from "@xeno-js/shared";
2711
- var BaseHttpAdapter;
2712
- var init_base_http_adapter = __esm({
2713
- "src/infrastructure/http/base.http-adapter.ts"() {
2450
+ // src/infrastructure/services/resiliences/index.ts
2451
+ var init_resiliences = __esm({
2452
+ "src/infrastructure/services/resiliences/index.ts"() {
2714
2453
  "use strict";
2715
- BaseHttpAdapter = class {
2716
- /**
2717
- * @description Parse the URL from the request.
2718
- * @param rawUrl The raw URL.
2719
- * @param headers The headers.
2720
- * @param queryParams The query parameters.
2721
- * @returns The parsed URL.
2722
- */
2723
- parseUrl(rawUrl = "/", headers, queryParams) {
2724
- const protocol = StringHelper2.getSingleValue(headers["x-forwarded-proto"]) ?? "https";
2725
- const host = StringHelper2.safeStringify(headers["host"]) ?? "localhost";
2726
- const cleanHost = host.replace(/['"]/g, "");
2727
- const url = new URL(rawUrl, `${protocol}://${cleanHost}`);
2728
- if (!Guards29.isNullOrEmpty(queryParams)) {
2729
- for (const [key, value] of Object.entries(queryParams)) {
2730
- if (Guards29.isArray(value)) {
2731
- value.forEach((v) => url.searchParams.append(key, String(v)));
2732
- } else if (Guards29.isDefined(value)) {
2733
- url.searchParams.set(key, String(value));
2734
- }
2735
- }
2736
- }
2737
- return url;
2738
- }
2739
- /**
2740
- * @description Parses the headers.
2741
- * @param rawHeaders The raw headers.
2742
- * @returns The parsed headers.
2743
- */
2744
- parseHeaders(rawHeaders) {
2745
- const headers = new Headers();
2746
- for (const [key, value] of Object.entries(rawHeaders)) {
2747
- if (Guards29.isDefined(value)) {
2748
- if (Guards29.isArray(value)) {
2749
- value.forEach((v) => headers.append(key, String(v)));
2750
- } else {
2751
- headers.set(key, String(value));
2752
- }
2753
- }
2754
- }
2755
- return headers;
2756
- }
2757
- /**
2758
- * @description Parses the body.
2759
- * @param method The method.
2760
- * @param rawBody The raw body.
2761
- * @returns The parsed body.
2762
- */
2763
- parseBody(method, rawBody) {
2764
- if (!Guards29.isDefined(method) || !["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) || !Guards29.isDefined(rawBody))
2765
- return void 0;
2766
- if (Guards29.isObject(rawBody)) return JSON.stringify(rawBody);
2767
- if (Guards29.isString(rawBody) || rawBody instanceof Blob || rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody) || rawBody instanceof URLSearchParams || rawBody instanceof FormData)
2768
- return rawBody;
2769
- return String(rawBody);
2770
- }
2454
+ init_resilience_service();
2455
+ }
2456
+ });
2457
+
2458
+ // src/infrastructure/services/resolver/utils/socket.utils.ts
2459
+ import { Guards as Guards34 } from "@xeno-js/shared";
2460
+ var SocketIpExtractor;
2461
+ var init_socket_utils = __esm({
2462
+ "src/infrastructure/services/resolver/utils/socket.utils.ts"() {
2463
+ "use strict";
2464
+ SocketIpExtractor = Object.freeze({
2771
2465
  /**
2772
- * @description Creates the XenoWebTransport.
2773
- * @param url The url.
2774
- * @param method The method.
2775
- * @param headers The headers.
2776
- * @param body The body.
2777
- * @returns The XenoWebTransport.
2466
+ * @description Extracts the IP address of the remote socket from an incoming request.
2467
+ * @param req The incoming request object.
2468
+ * @returns The IP address of the remote socket, or undefined if not available.
2778
2469
  */
2779
- createXenoWebTransport(url, method = "GET", headers, body = void 0, res = void 0) {
2780
- const init2 = {
2781
- method: method.toUpperCase(),
2782
- headers
2783
- };
2784
- const parsedBody = this.parseBody(method, body);
2785
- if (Guards29.isDefined(parsedBody)) {
2786
- init2.body = parsedBody;
2787
- init2.duplex = "half";
2788
- }
2789
- const extendedRequest = new Request(url, init2);
2790
- extendedRequest.path = url.pathname;
2791
- const webResponse = new Response();
2792
- if (Guards29.isDefined(res)) {
2793
- const originalAppend = webResponse.headers.append.bind(webResponse.headers);
2794
- const originalSet = webResponse.headers.set.bind(webResponse.headers);
2795
- const originalDelete = webResponse.headers.delete.bind(webResponse.headers);
2796
- webResponse.headers.append = (name, value) => {
2797
- originalAppend(name, value);
2798
- this.handleHeaderChange(res, name, value, "append");
2799
- };
2800
- webResponse.headers.set = (name, value) => {
2801
- originalSet(name, value);
2802
- this.handleHeaderChange(res, name, value, "set");
2803
- };
2804
- webResponse.headers.delete = (name) => {
2805
- originalDelete(name);
2806
- this.handleHeaderChange(res, name, "", "delete");
2807
- };
2470
+ extract(req) {
2471
+ if (Guards34.isDefined(req) && Guards34.isObject(req)) {
2472
+ const candidate = req;
2473
+ return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
2808
2474
  }
2809
- return {
2810
- request: extendedRequest,
2811
- response: webResponse
2812
- };
2475
+ return void 0;
2813
2476
  }
2814
- };
2477
+ });
2815
2478
  }
2816
2479
  });
2817
2480
 
2818
- // src/infrastructure/http/vercel.http-adapter.ts
2819
- var vercel_http_adapter_exports = {};
2820
- __export(vercel_http_adapter_exports, {
2821
- VercelHttpAdapter: () => VercelHttpAdapter
2481
+ // src/infrastructure/services/resolver/utils/index.ts
2482
+ var init_utils = __esm({
2483
+ "src/infrastructure/services/resolver/utils/index.ts"() {
2484
+ "use strict";
2485
+ init_socket_utils();
2486
+ }
2822
2487
  });
2823
- import { Guards as Guards30 } from "@xeno-js/shared";
2824
- var VercelHttpAdapter;
2825
- var init_vercel_http_adapter = __esm({
2826
- "src/infrastructure/http/vercel.http-adapter.ts"() {
2488
+
2489
+ // src/infrastructure/services/resolver/client-ip.resolver.ts
2490
+ import { Guards as Guards35 } from "@xeno-js/shared";
2491
+ var ClientIpResolver;
2492
+ var init_client_ip_resolver = __esm({
2493
+ "src/infrastructure/services/resolver/client-ip.resolver.ts"() {
2827
2494
  "use strict";
2828
- init_base_http_adapter();
2829
- VercelHttpAdapter = class extends BaseHttpAdapter {
2830
- adapt(req, res) {
2831
- const headers = this.parseHeaders(req.headers);
2832
- const url = this.parseUrl(req.url, req.headers, req.query);
2833
- return this.createXenoWebTransport(url, req.method, headers, req.body, res);
2495
+ init_utils();
2496
+ ClientIpResolver = class {
2497
+ constructor(_trustedProxies = []) {
2498
+ this._trustedProxies = _trustedProxies;
2834
2499
  }
2835
- handleHeaderChange(res, name, value, action) {
2836
- if (action === "delete") {
2837
- res.removeHeader(name);
2838
- return;
2839
- }
2840
- if (name.toLowerCase() === "set-cookie") {
2841
- const existing = res.getHeader("Set-Cookie");
2842
- let cookies = [];
2843
- if (Guards30.isArray(existing)) {
2844
- cookies = existing;
2845
- } else if (Guards30.isString(existing)) {
2846
- cookies = [existing];
2847
- }
2848
- if (action === "append") {
2849
- cookies.push(value);
2850
- } else {
2851
- cookies = [value];
2852
- }
2853
- res.setHeader("Set-Cookie", cookies);
2854
- } else {
2855
- res.setHeader(name, value);
2856
- }
2500
+ _trustedProxies;
2501
+ resolve(req, clientIp) {
2502
+ const socketIp = SocketIpExtractor.extract(req);
2503
+ if (!Guards35.isDefined(socketIp))
2504
+ return !Guards35.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
2505
+ const isTrustedProxy = this._trustedProxies.includes(socketIp);
2506
+ if (!isTrustedProxy) return socketIp;
2507
+ if (Guards35.isDefined(clientIp)) return clientIp.split(",")[0].trim();
2508
+ return socketIp;
2857
2509
  }
2858
2510
  };
2859
2511
  }
2860
2512
  });
2861
2513
 
2862
- // src/infrastructure/http/fastify.http-adapter.ts
2863
- var fastify_http_adapter_exports = {};
2864
- __export(fastify_http_adapter_exports, {
2865
- FastifyHttpAdapter: () => FastifyHttpAdapter
2514
+ // src/infrastructure/services/resolver/index.ts
2515
+ var init_resolver = __esm({
2516
+ "src/infrastructure/services/resolver/index.ts"() {
2517
+ "use strict";
2518
+ init_client_ip_resolver();
2519
+ }
2866
2520
  });
2867
- import { Guards as Guards31 } from "@xeno-js/shared";
2868
- var FastifyHttpAdapter;
2869
- var init_fastify_http_adapter = __esm({
2870
- "src/infrastructure/http/fastify.http-adapter.ts"() {
2521
+
2522
+ // src/infrastructure/services/index.ts
2523
+ var services_exports = {};
2524
+ __export(services_exports, {
2525
+ AllowMethodRegistry: () => AllowMethodRegistry,
2526
+ AllowOrigin: () => AllowOrigin,
2527
+ BearerTokenExtractor: () => BearerTokenExtractor,
2528
+ ClientIpResolver: () => ClientIpResolver,
2529
+ CookieHandler: () => CookieHandler,
2530
+ CsrfTokenService: () => CsrfTokenService,
2531
+ EdgeCryptoService: () => EdgeCryptoService,
2532
+ HttpCookieExtractor: () => HttpCookieExtractor,
2533
+ HttpHeaderExtractor: () => HttpHeaderExtractor,
2534
+ PLimitConcurrencyService: () => PLimitConcurrencyService,
2535
+ ServiceResilience: () => ServiceResilience,
2536
+ SupabaseSsrTokenExtractor: () => SupabaseSsrTokenExtractor
2537
+ });
2538
+ var init_services = __esm({
2539
+ "src/infrastructure/services/index.ts"() {
2871
2540
  "use strict";
2872
- init_base_http_adapter();
2873
- FastifyHttpAdapter = class extends BaseHttpAdapter {
2874
- adapt(req, res) {
2875
- const headers = this.parseHeaders(req.headers);
2876
- const url = this.parseUrl(req.url, req.headers, req.query);
2877
- const body = req.body;
2878
- return this.createXenoWebTransport(url, req.method, headers, body, res);
2879
- }
2880
- handleHeaderChange(res, name, value, action) {
2881
- if (action === "delete") {
2882
- res.removeHeader(name);
2883
- return;
2884
- }
2885
- if (name.toLowerCase() === "set-cookie") {
2886
- const existing = res.getHeader("set-cookie");
2887
- let cookies = [];
2888
- if (Guards31.isArray(existing)) {
2889
- cookies = existing;
2890
- } else if (Guards31.isString(existing)) {
2891
- cookies = [existing];
2892
- }
2893
- if (action === "append") {
2894
- cookies.push(value);
2895
- } else {
2896
- cookies = [value];
2897
- }
2898
- res.header("set-cookie", cookies);
2899
- } else {
2900
- res.header(name, value);
2901
- }
2902
- }
2903
- };
2541
+ init_allow_methods();
2542
+ init_allow_origins();
2543
+ init_concurrency();
2544
+ init_cookies();
2545
+ init_crypto();
2546
+ init_csrf();
2547
+ init_extractors();
2548
+ init_resiliences();
2549
+ init_resolver();
2904
2550
  }
2905
2551
  });
2906
2552
 
2907
- // src/infrastructure/http/native.http-adapter.ts
2908
- var native_http_adapter_exports = {};
2909
- __export(native_http_adapter_exports, {
2910
- NativeHttpAdapter: () => NativeHttpAdapter
2553
+ // src/infrastructure/factories/supabase.factory.ts
2554
+ var supabase_factory_exports = {};
2555
+ __export(supabase_factory_exports, {
2556
+ SupabaseServerAuthFactory: () => SupabaseServerAuthFactory
2911
2557
  });
2912
- var NativeHttpAdapter;
2913
- var init_native_http_adapter = __esm({
2914
- "src/infrastructure/http/native.http-adapter.ts"() {
2558
+ import { createServerClient } from "@supabase/ssr";
2559
+ import { Guards as Guards36, TOKENS as TOKENS3 } from "@xeno-js/shared";
2560
+ import {
2561
+ SupabaseAuthService,
2562
+ SupabaseClaimsMapper,
2563
+ SupabaseSessionMapper
2564
+ } from "@xeno-js/shared/supabase";
2565
+ var SupabaseServerAuthFactory;
2566
+ var init_supabase_factory = __esm({
2567
+ "src/infrastructure/factories/supabase.factory.ts"() {
2915
2568
  "use strict";
2916
- init_base_http_adapter();
2917
- NativeHttpAdapter = class extends BaseHttpAdapter {
2918
- adapt(req, res) {
2919
- const extendedRequest = req;
2920
- extendedRequest.path = new URL(req.url).pathname;
2921
- return {
2922
- request: extendedRequest,
2923
- response: res
2924
- };
2569
+ init_services();
2570
+ SupabaseServerAuthFactory = class {
2571
+ create({
2572
+ config,
2573
+ container
2574
+ }) {
2575
+ const cookieService = this._getCookieSsr(config.ssrOpts, container, config.cookieOpts);
2576
+ const client = createServerClient(config.url, config.key, {
2577
+ ...config.opts,
2578
+ cookies: {
2579
+ getAll() {
2580
+ return cookieService.getAll();
2581
+ },
2582
+ setAll(cookiesToSet) {
2583
+ cookieService.setAll(cookiesToSet);
2584
+ }
2585
+ }
2586
+ });
2587
+ const mapper = new SupabaseClaimsMapper();
2588
+ const sessionMapper = new SupabaseSessionMapper(mapper);
2589
+ return new SupabaseAuthService(client, mapper, sessionMapper, config);
2925
2590
  }
2926
- handleHeaderChange(_res, _name, _value, _action) {
2927
- return;
2591
+ _getCookieSsr(ssrOpts, container, config) {
2592
+ if (Guards36.isDefined(ssrOpts)) {
2593
+ return ssrOpts(container);
2594
+ } else {
2595
+ return new CookieHandler(
2596
+ container.resolve(TOKENS3.NETWORK_CONTEXT_ACCESSOR),
2597
+ container.resolve(TOKENS3.CONFIGURATION_SERVICE),
2598
+ config
2599
+ );
2600
+ }
2928
2601
  }
2929
2602
  };
2930
2603
  }
2931
2604
  });
2932
2605
 
2933
- // src/infrastructure/modules/http-adapter.module.ts
2934
- import { Guards as Guards32 } from "@xeno-js/shared";
2935
- var HttpAdapterModule;
2936
- var init_http_adapter_module = __esm({
2937
- "src/infrastructure/modules/http-adapter.module.ts"() {
2606
+ // src/infrastructure/modules/utils/auth.utils.ts
2607
+ var auth_utils_exports = {};
2608
+ __export(auth_utils_exports, {
2609
+ AuthUtils: () => AuthUtils
2610
+ });
2611
+ var AuthUtils;
2612
+ var init_auth_utils = __esm({
2613
+ "src/infrastructure/modules/utils/auth.utils.ts"() {
2938
2614
  "use strict";
2939
- HttpAdapterModule = class {
2940
- async configure(container, opts) {
2941
- const adapter = await this._getAdapter(opts);
2942
- container.addSingleton("HTTP_ADAPTER", () => adapter);
2943
- }
2944
- async _getAdapter(opts) {
2945
- if (opts.vercel) {
2946
- const { VercelHttpAdapter: VercelHttpAdapter2 } = await Promise.resolve().then(() => (init_vercel_http_adapter(), vercel_http_adapter_exports));
2947
- return new VercelHttpAdapter2();
2948
- } else if (opts.fastify) {
2949
- const { FastifyHttpAdapter: FastifyHttpAdapter2 } = await Promise.resolve().then(() => (init_fastify_http_adapter(), fastify_http_adapter_exports));
2950
- return new FastifyHttpAdapter2();
2951
- } else if (Guards32.isDefined(opts.custom)) {
2952
- return opts.custom();
2615
+ AuthUtils = Object.freeze({
2616
+ /**
2617
+ * @description Checks if the provided authorization configuration requires any authorization strategies.
2618
+ * @param authorizationConfig The authorization configuration to check.
2619
+ * @returns True if any authorization strategies are required, false otherwise.
2620
+
2621
+ *
2622
+ * @author Xeno
2623
+ * @version 1.0.0
2624
+ * @since 2025-09-30
2625
+ * @link https://github.com/xeno-js/xeno-js
2626
+ */
2627
+ async addAuthZ(container, opts) {
2628
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2629
+ const strategies = [];
2630
+ const { Guards: Guards51 } = await import("@xeno-js/shared");
2631
+ if (Guards51.isDefined(opts.policies)) {
2632
+ const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2633
+ const policyRegistry = opts.policies;
2634
+ const registryInstance = new PolicyRegistry2();
2635
+ const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2636
+ const Policies = /* @__PURE__ */ new Set();
2637
+ for (const [intent, policy] of Object.entries(policyRegistry)) {
2638
+ const intentLower = intent.toLowerCase();
2639
+ registryInstance.addPolicy(intentLower, policy);
2640
+ if (!Guards51.isNullOrEmpty(policy.roles)) {
2641
+ Policies.add("roles");
2642
+ }
2643
+ if (!Guards51.isNullOrEmpty(policy.permissions)) {
2644
+ Policies.add("permissions");
2645
+ }
2646
+ if (!Guards51.isNullOrEmpty(policy.userId)) {
2647
+ Policies.add("userId");
2648
+ }
2649
+ if (!Guards51.isNullOrEmpty(policy.tenantId)) {
2650
+ Policies.add("tenantId");
2651
+ }
2652
+ }
2653
+ if (Policies.has("roles")) {
2654
+ const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2655
+ strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2656
+ }
2657
+ if (Policies.has("permissions")) {
2658
+ const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2659
+ strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2660
+ }
2661
+ if (Policies.has("userId")) {
2662
+ const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2663
+ strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2664
+ }
2665
+ if (Policies.has("tenantId")) {
2666
+ const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2667
+ strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2668
+ }
2669
+ }
2670
+ if (!Guards51.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2671
+ const customStrategies = opts.customAuthorizationStrategy;
2672
+ customStrategies.forEach((strategyToken) => {
2673
+ if (Guards51.isDefined(strategyToken)) {
2674
+ strategies.push(strategyToken(container));
2675
+ }
2676
+ });
2677
+ }
2678
+ const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2679
+ return new AuthorizationPipeline2(strategies);
2680
+ },
2681
+ /**
2682
+ * @description Configures the authentication service and gatekeeper in the service container.
2683
+ * @param container The service container to configure.
2684
+ * @param opts The authentication configuration options.
2685
+
2686
+ *
2687
+ * @author Xeno
2688
+ * @version 1.0.0
2689
+ * @since 2025-09-30
2690
+ * @link https://github.com/xeno-js/xeno-js
2691
+ */
2692
+ async addAuthN(container, opts) {
2693
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2694
+ if (Guards51.isDefined(opts.customAuth)) {
2695
+ const authService = opts.customAuth.authExtendedService();
2696
+ container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2697
+ return authService;
2698
+ });
2699
+ container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2700
+ return authService;
2701
+ });
2953
2702
  } else {
2954
- const { NativeHttpAdapter: NativeHttpAdapter2 } = await Promise.resolve().then(() => (init_native_http_adapter(), native_http_adapter_exports));
2955
- return new NativeHttpAdapter2();
2703
+ const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_supabase_factory(), supabase_factory_exports));
2704
+ const factory = new SupabaseServerAuthFactory2();
2705
+ const supabase = factory.create({ config: opts, container });
2706
+ container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2707
+ return supabase;
2708
+ });
2709
+ container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2710
+ return supabase;
2711
+ });
2956
2712
  }
2957
2713
  }
2958
- };
2714
+ });
2959
2715
  }
2960
2716
  });
2961
2717
 
@@ -3008,7 +2764,7 @@ var cockatiel_resilience_factory_exports = {};
3008
2764
  __export(cockatiel_resilience_factory_exports, {
3009
2765
  CockatielResilienceFactory: () => CockatielResilienceFactory
3010
2766
  });
3011
- import { AppError as AppError14, Guards as Guards33, RESILIENCE_DEFAULTS } from "@xeno-js/shared";
2767
+ import { AppError as AppError12, Guards as Guards37, RESILIENCE_DEFAULTS } from "@xeno-js/shared";
3012
2768
  import {
3013
2769
  bulkhead,
3014
2770
  circuitBreaker,
@@ -3085,13 +2841,13 @@ var init_cockatiel_resilience_factory = __esm({
3085
2841
  return new ServiceResilience(wrap(bulkheadPolicy, circuitBreakerPolicy, retryPolicy));
3086
2842
  }
3087
2843
  isTransientError(error) {
3088
- if (!Guards33.isDefined(error) || !Guards33.isObject(error)) return false;
2844
+ if (!Guards37.isDefined(error) || !Guards37.isObject(error)) return false;
3089
2845
  let status;
3090
2846
  let isNetworkError = false;
3091
- if (error instanceof AppError14) {
2847
+ if (error instanceof AppError12) {
3092
2848
  status = error.status;
3093
2849
  const cause = error.cause;
3094
- if (Guards33.isDefined(cause) && Guards33.isString(cause.code)) {
2850
+ if (Guards37.isDefined(cause) && Guards37.isString(cause.code)) {
3095
2851
  isNetworkError = [
3096
2852
  "ECONNABORTED",
3097
2853
  "ECONNRESET",
@@ -3103,7 +2859,7 @@ var init_cockatiel_resilience_factory = __esm({
3103
2859
  } else {
3104
2860
  const err = error;
3105
2861
  status = err.status;
3106
- if (Guards33.isString(err.code)) {
2862
+ if (Guards37.isString(err.code)) {
3107
2863
  isNetworkError = [
3108
2864
  "ECONNABORTED",
3109
2865
  "ECONNRESET",
@@ -3114,111 +2870,384 @@ var init_cockatiel_resilience_factory = __esm({
3114
2870
  }
3115
2871
  }
3116
2872
  if (isNetworkError) return true;
3117
- if (Guards33.isDefined(status)) return status === 408 || status >= 500 && status < 600;
2873
+ if (Guards37.isDefined(status)) return status === 408 || status >= 500 && status < 600;
3118
2874
  return false;
3119
2875
  }
3120
2876
  isTransientAndIdempotent(error) {
3121
2877
  if (!this.isTransientError(error)) return false;
3122
2878
  let method;
3123
- if (error instanceof AppError14) {
2879
+ if (error instanceof AppError12) {
3124
2880
  const cause = error.cause;
3125
- if (Guards33.isDefined(cause) && Guards33.isDefined(cause.config) && Guards33.isString(cause.config.method)) {
2881
+ if (Guards37.isDefined(cause) && Guards37.isDefined(cause.config) && Guards37.isString(cause.config.method)) {
3126
2882
  method = cause.config.method.toUpperCase();
3127
2883
  }
3128
2884
  } else {
3129
2885
  const err = error;
3130
- if (Guards33.isDefined(err.config) && Guards33.isString(err.config.method)) {
2886
+ if (Guards37.isDefined(err.config) && Guards37.isString(err.config.method)) {
3131
2887
  method = err.config.method.toUpperCase();
3132
2888
  }
3133
2889
  }
3134
- if (Guards33.isNullOrEmpty(method)) return false;
2890
+ if (Guards37.isNullOrEmpty(method)) return false;
3135
2891
  const idempotentMethods = ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"];
3136
2892
  return idempotentMethods.includes(method);
3137
2893
  }
3138
- checkConfigValue(value, defaultValue, message) {
3139
- if (Guards33.isDefined(value)) {
3140
- Guards33.throwIfNegative(value, message);
3141
- return value;
3142
- }
3143
- return defaultValue;
2894
+ checkConfigValue(value, defaultValue, message) {
2895
+ if (Guards37.isDefined(value)) {
2896
+ Guards37.throwIfNegative(value, message);
2897
+ return value;
2898
+ }
2899
+ return defaultValue;
2900
+ }
2901
+ };
2902
+ }
2903
+ });
2904
+
2905
+ // src/infrastructure/modules/utils/http.utils.ts
2906
+ var http_utils_exports = {};
2907
+ __export(http_utils_exports, {
2908
+ HttpUtils: () => HttpUtils
2909
+ });
2910
+ var HttpUtils;
2911
+ var init_http_utils = __esm({
2912
+ "src/infrastructure/modules/utils/http.utils.ts"() {
2913
+ "use strict";
2914
+ HttpUtils = Object.freeze({
2915
+ /**
2916
+ * @description Utility function to create a query string from an object of query parameters. It takes an object where the keys are the parameter names and the values are the parameter values, and returns a properly encoded query string that can be appended to a URL for making HTTP requests.
2917
+ * @param params - An object containing the query parameters as key-value pairs. The keys represent the parameter names, and the values represent the parameter values.
2918
+ * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.
2919
+ *
2920
+ * @author Xeno
2921
+ * @version 1.0.0
2922
+ * @since 2025-09-30
2923
+ * @link https://github.com/xeno-js/xeno-js
2924
+ */
2925
+ async addAxios(container, opts) {
2926
+ const { NodeAxiosFactory: NodeAxiosFactory2 } = await Promise.resolve().then(() => (init_axios_factory(), axios_factory_exports));
2927
+ const { Guards: Guards51 } = await import("@xeno-js/shared");
2928
+ if (!Guards51.isDefined(opts.token)) {
2929
+ throw new Error("HttpConfig.token is required and must be defined.");
2930
+ }
2931
+ container.addSingleton(opts.token, () => {
2932
+ const factory = new NodeAxiosFactory2();
2933
+ const instance = factory.create(opts.client);
2934
+ if (!Guards51.hasMethod(instance, "get") || !Guards51.hasMethod(instance, "post") || !Guards51.hasMethod(instance, "put") || !Guards51.hasMethod(instance, "patch") || !Guards51.hasMethod(instance, "delete")) {
2935
+ throw new Error(
2936
+ "The created HTTP client instance does not implement the required methods of IHttpClient."
2937
+ );
2938
+ }
2939
+ return instance;
2940
+ });
2941
+ },
2942
+ /**
2943
+ * @description Utility function to add resilience features to the service container. It takes a ResilienceConfig object that specifies whether resilience features are enabled and provides the necessary settings for implementing resilience strategies such as retries, circuit breakers, and timeouts. If resilience is enabled, it registers a singleton factory in the service container that creates an instance of the resilience client based on the provided configuration.
2944
+ * @param container - The service container to register the resilience client with.
2945
+ * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.
2946
+ *
2947
+ * @author Xeno
2948
+ * @version 1.0.0
2949
+ * @since 2025-09-30
2950
+ * @link https://github.com/xeno-js/xeno-js
2951
+ */
2952
+ async addResilience(container, opts) {
2953
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2954
+ const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_cockatiel_resilience_factory(), cockatiel_resilience_factory_exports));
2955
+ container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
2956
+ const factory = new CockatielResilienceFactory2();
2957
+ return factory.create(opts);
2958
+ });
2959
+ }
2960
+ });
2961
+ }
2962
+ });
2963
+
2964
+ // src/infrastructure/modules/http-core.module.ts
2965
+ var http_core_module_exports = {};
2966
+ __export(http_core_module_exports, {
2967
+ HttpCoreModule: () => HttpCoreModule
2968
+ });
2969
+ var HttpCoreModule;
2970
+ var init_http_core_module = __esm({
2971
+ "src/infrastructure/modules/http-core.module.ts"() {
2972
+ "use strict";
2973
+ HttpCoreModule = class {
2974
+ async configure(container, opts) {
2975
+ const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
2976
+ await HttpUtils2.addAxios(container, opts.http);
2977
+ await HttpUtils2.addResilience(container, opts.resilience);
2978
+ }
2979
+ };
2980
+ }
2981
+ });
2982
+
2983
+ // src/infrastructure/factories/zod-validator.factory.ts
2984
+ var zod_validator_factory_exports = {};
2985
+ __export(zod_validator_factory_exports, {
2986
+ ZodValidatorFactory: () => ZodValidatorFactory
2987
+ });
2988
+ import { ZodValidatorService } from "@xeno-js/shared/zod";
2989
+ var ZodValidatorFactory;
2990
+ var init_zod_validator_factory = __esm({
2991
+ "src/infrastructure/factories/zod-validator.factory.ts"() {
2992
+ "use strict";
2993
+ ZodValidatorFactory = class {
2994
+ create(opts) {
2995
+ const validatorService = new ZodValidatorService(/* @__PURE__ */ new Map(), opts.logger);
2996
+ for (const [intentKey, schema] of Object.entries(opts.schemas)) {
2997
+ validatorService.addSchema(intentKey, schema);
2998
+ }
2999
+ return validatorService;
3000
+ }
3001
+ };
3002
+ }
3003
+ });
3004
+
3005
+ // src/infrastructure/modules/utils/validation.utils.ts
3006
+ var validation_utils_exports = {};
3007
+ __export(validation_utils_exports, {
3008
+ ValidationUtils: () => ValidationUtils
3009
+ });
3010
+ var ValidationUtils;
3011
+ var init_validation_utils = __esm({
3012
+ "src/infrastructure/modules/utils/validation.utils.ts"() {
3013
+ "use strict";
3014
+ ValidationUtils = Object.freeze({
3015
+ /**
3016
+ * @description Checks if the provided validation configuration requires any validation strategies.
3017
+ * @param validationConfig The validation configuration to check.
3018
+ * @returns True if any validation strategies are required, false otherwise.
3019
+ *
3020
+ * @author Xeno
3021
+ * @version 1.0.0
3022
+ * @since 2025-09-30
3023
+ * @link https://github.com/xeno-js/xeno-js
3024
+ */
3025
+ async addValidation(container, opts, logger) {
3026
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3027
+ if (!Guards51.isDefined(opts.zod) && Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
3028
+ return;
3029
+ }
3030
+ const validationStrategies = [];
3031
+ if (Guards51.isDefined(opts.zod)) {
3032
+ const config = opts.zod;
3033
+ const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_zod_validator_factory(), zod_validator_factory_exports));
3034
+ const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3035
+ const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
3036
+ container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
3037
+ validationStrategies.push(new SchemaValidationStrategy2(validatorService));
3038
+ }
3039
+ if (!Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
3040
+ for (const strategyToken of opts.customValidationStrategy) {
3041
+ if (Guards51.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
3042
+ }
3043
+ }
3044
+ const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3045
+ return new ValidationPipeline2(validationStrategies);
3046
+ }
3047
+ });
3048
+ }
3049
+ });
3050
+
3051
+ // src/infrastructure/idempotency/idempotency-store.ts
3052
+ import { IDEMPOTENCY_CONSTANTS as IDEMPOTENCY_CONSTANTS2 } from "@xeno-js/shared";
3053
+ var IdempotencyStore;
3054
+ var init_idempotency_store = __esm({
3055
+ "src/infrastructure/idempotency/idempotency-store.ts"() {
3056
+ "use strict";
3057
+ IdempotencyStore = class {
3058
+ /**
3059
+ * @description Constructs a new instance of IdempotencyStore, accepting an instance of ICache for accessing the caching system and an instance of IIdentityAccessor for obtaining the user's identity context. The IdempotencyStore uses the caching system to manage locks and results of idempotent commands, ensuring that commands with the same ID are processed only once. The identity context is used to build contextual keys, allowing for more granular management of idempotent commands in multi-tenant scenarios.
3060
+ * @param _cache An instance of ICache that provides methods to interact with the underlying caching system, used to store locks and results of idempotent commands.
3061
+ * @param _identityAccessor An instance of IIdentityAccessor that allows access to the user's identity context, used to build contextual keys for idempotent commands, supporting multi-tenant scenarios.
3062
+
3063
+ *
3064
+ * @author Xeno
3065
+ * @version 1.0.0
3066
+ * @since 2025-09-30
3067
+ * @link https://github.com/xeno-js/xeno-js
3068
+ */
3069
+ constructor(_cache, _cacheKeyBuilder) {
3070
+ this._cache = _cache;
3071
+ this._cacheKeyBuilder = _cacheKeyBuilder;
3072
+ }
3073
+ _cache;
3074
+ _cacheKeyBuilder;
3075
+ async acquireLock(requestId, ttlSeconds) {
3076
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
3077
+ return await this._cache.setIfAbsent(
3078
+ `${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`,
3079
+ IDEMPOTENCY_CONSTANTS2.LOCKED_VALUE,
3080
+ ttlSeconds
3081
+ );
3082
+ }
3083
+ async hasBeenProcessed(commandId) {
3084
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3085
+ return await this._cache.has(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
3086
+ }
3087
+ async markAsProcessed(commandId, payload, ttlSeconds) {
3088
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3089
+ await this._cache.set(
3090
+ `${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`,
3091
+ payload,
3092
+ ttlSeconds
3093
+ );
3094
+ }
3095
+ async getPayload(commandId) {
3096
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3097
+ const payload = await this._cache.get(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
3098
+ return payload;
3099
+ }
3100
+ async releaseLock(commandId) {
3101
+ const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
3102
+ await this._cache.remove(`${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`);
3144
3103
  }
3145
3104
  };
3146
3105
  }
3147
3106
  });
3148
3107
 
3149
- // src/infrastructure/modules/utils/http.utils.ts
3150
- var http_utils_exports = {};
3151
- __export(http_utils_exports, {
3152
- HttpUtils: () => HttpUtils
3108
+ // src/infrastructure/idempotency/index.ts
3109
+ var idempotency_exports = {};
3110
+ __export(idempotency_exports, {
3111
+ IdempotencyStore: () => IdempotencyStore
3153
3112
  });
3154
- var HttpUtils;
3155
- var init_http_utils = __esm({
3156
- "src/infrastructure/modules/utils/http.utils.ts"() {
3113
+ var init_idempotency = __esm({
3114
+ "src/infrastructure/idempotency/index.ts"() {
3157
3115
  "use strict";
3158
- HttpUtils = Object.freeze({
3116
+ init_idempotency_store();
3117
+ }
3118
+ });
3119
+
3120
+ // src/infrastructure/modules/utils/pipeline.utils.ts
3121
+ var pipeline_utils_exports = {};
3122
+ __export(pipeline_utils_exports, {
3123
+ PipelineUtils: () => PipelineUtils
3124
+ });
3125
+ var PipelineUtils;
3126
+ var init_pipeline_utils = __esm({
3127
+ "src/infrastructure/modules/utils/pipeline.utils.ts"() {
3128
+ "use strict";
3129
+ PipelineUtils = Object.freeze({
3159
3130
  /**
3160
- * @description Utility function to create a query string from an object of query parameters. It takes an object where the keys are the parameter names and the values are the parameter values, and returns a properly encoded query string that can be appended to a URL for making HTTP requests.
3161
- * @param params - An object containing the query parameters as key-value pairs. The keys represent the parameter names, and the values represent the parameter values.
3162
- * @returns A string representing the encoded query string that can be appended to a URL for making HTTP requests.
3131
+ * @description Checks if the provided command configuration requires any command strategies.
3132
+ * @param commandConfig The command configuration to check.
3133
+ * @returns True if any command strategies are required, false otherwise.
3163
3134
  *
3164
3135
  * @author Xeno
3165
3136
  * @version 1.0.0
3166
3137
  * @since 2025-09-30
3167
3138
  * @link https://github.com/xeno-js/xeno-js
3168
3139
  */
3169
- async addAxios(container, opts) {
3170
- const { NodeAxiosFactory: NodeAxiosFactory2 } = await Promise.resolve().then(() => (init_axios_factory(), axios_factory_exports));
3171
- const { Guards: Guards51 } = await import("@xeno-js/shared");
3172
- if (!Guards51.isDefined(opts.token)) {
3173
- throw new Error("HttpConfig.token is required and must be defined.");
3140
+ async addCommand(container, opts) {
3141
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3142
+ const pipelines = [];
3143
+ if (Guards51.isDefined(opts.idempotency)) {
3144
+ const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
3145
+ const imdStore = new IdempotencyStore2(
3146
+ container.resolve(TOKENS5.CACHE),
3147
+ container.resolve(TOKENS5.CACHE_KEY_BUILDER)
3148
+ );
3149
+ const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3150
+ const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
3151
+ const config = opts.idempotency;
3152
+ pipelines.push(
3153
+ new IdempotencyPipeline2(
3154
+ requestContext,
3155
+ imdStore,
3156
+ config?.lockTtlSeconds,
3157
+ config?.processedTtlSeconds
3158
+ )
3159
+ );
3174
3160
  }
3175
- container.addSingleton(opts.token, () => {
3176
- const factory = new NodeAxiosFactory2();
3177
- const instance = factory.create(opts.client);
3178
- if (!Guards51.hasMethod(instance, "get") || !Guards51.hasMethod(instance, "post") || !Guards51.hasMethod(instance, "put") || !Guards51.hasMethod(instance, "patch") || !Guards51.hasMethod(instance, "delete")) {
3179
- throw new Error(
3180
- "The created HTTP client instance does not implement the required methods of IHttpClient."
3181
- );
3182
- }
3183
- return instance;
3184
- });
3161
+ if (Guards51.isDefined(opts.concurrency)) {
3162
+ const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3163
+ const config = opts.concurrency;
3164
+ pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
3165
+ }
3166
+ return pipelines;
3185
3167
  },
3186
3168
  /**
3187
- * @description Utility function to add resilience features to the service container. It takes a ResilienceConfig object that specifies whether resilience features are enabled and provides the necessary settings for implementing resilience strategies such as retries, circuit breakers, and timeouts. If resilience is enabled, it registers a singleton factory in the service container that creates an instance of the resilience client based on the provided configuration.
3188
- * @param container - The service container to register the resilience client with.
3189
- * @param opts - The ResilienceConfig options that determine whether resilience features are enabled and provide the necessary settings for implementing resilience strategies.
3169
+ * @description Checks if the provided query configuration requires any query strategies.
3170
+ * @param queryConfig The query configuration to check.
3171
+ * @returns True if any query strategies are required, false otherwise.
3190
3172
  *
3191
3173
  * @author Xeno
3192
3174
  * @version 1.0.0
3193
3175
  * @since 2025-09-30
3194
3176
  * @link https://github.com/xeno-js/xeno-js
3195
3177
  */
3196
- async addResilience(container, opts) {
3178
+ async addQuery(container) {
3197
3179
  const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3198
- const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_cockatiel_resilience_factory(), cockatiel_resilience_factory_exports));
3199
- container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
3200
- const factory = new CockatielResilienceFactory2();
3201
- return factory.create(opts);
3202
- });
3180
+ const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3181
+ return new QueryCachingPipeline2(
3182
+ container.resolve(TOKENS5.CACHE),
3183
+ container.resolve(TOKENS5.CACHE_KEY_BUILDER),
3184
+ container.resolve(TOKENS5.LOGGER)
3185
+ );
3203
3186
  }
3204
3187
  });
3205
3188
  }
3206
3189
  });
3207
3190
 
3208
- // src/infrastructure/modules/http-core.module.ts
3209
- var http_core_module_exports = {};
3210
- __export(http_core_module_exports, {
3211
- HttpCoreModule: () => HttpCoreModule
3191
+ // src/infrastructure/modules/cqrs.module.ts
3192
+ var cqrs_module_exports = {};
3193
+ __export(cqrs_module_exports, {
3194
+ CqrsModule: () => CqrsModule
3212
3195
  });
3213
- var HttpCoreModule;
3214
- var init_http_core_module = __esm({
3215
- "src/infrastructure/modules/http-core.module.ts"() {
3196
+ var CqrsModule;
3197
+ var init_cqrs_module = __esm({
3198
+ "src/infrastructure/modules/cqrs.module.ts"() {
3216
3199
  "use strict";
3217
- HttpCoreModule = class {
3200
+ CqrsModule = class {
3218
3201
  async configure(container, opts) {
3219
- const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
3220
- await HttpUtils2.addAxios(container, opts.http);
3221
- await HttpUtils2.addResilience(container, opts.resilience);
3202
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3203
+ const logger = container.resolve(TOKENS5.LOGGER);
3204
+ const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3205
+ container.addSingleton(TOKENS5.MEDIATOR, (c) => {
3206
+ const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
3207
+ return new Mediator2(serviceScopeAccessor);
3208
+ });
3209
+ const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3210
+ const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3211
+ const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3212
+ const thresholdMs = opts.performance?.thresholdMs;
3213
+ const pipelines = [
3214
+ new ExceptionPipeline2(),
3215
+ new LoggingPipeline2(logger),
3216
+ new PerformancePipeline2(logger, opts.performance.intentThresholdMs, thresholdMs)
3217
+ ];
3218
+ if (Guards51.isDefined(opts.authorization.policies) || Guards51.isDefined(opts.authorization.customAuthorizationStrategy)) {
3219
+ const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
3220
+ const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
3221
+ pipelines.push(authPipelines);
3222
+ }
3223
+ if (Guards51.isDefined(opts.validation.zod) || Guards51.isDefined(opts.validation.customValidationStrategy)) {
3224
+ const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
3225
+ const validationPipelines = await ValidationUtils2.addValidation(
3226
+ container,
3227
+ opts.validation,
3228
+ logger
3229
+ );
3230
+ if (Guards51.isDefined(validationPipelines)) pipelines.push(validationPipelines);
3231
+ }
3232
+ const commandPipelines = [...pipelines];
3233
+ const queryPipelines = [...pipelines];
3234
+ if (Guards51.isDefined(opts.commandBus.idempotency) || Guards51.isDefined(opts.commandBus.concurrency)) {
3235
+ const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3236
+ const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
3237
+ commandPipelines.push(...newCommandPipelines);
3238
+ }
3239
+ if (opts.queryBus.isEnabled) {
3240
+ const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
3241
+ const newQueryPipelines = await PipelineUtils2.addQuery(container);
3242
+ queryPipelines.push(newQueryPipelines);
3243
+ }
3244
+ const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
3245
+ container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
3246
+ return new CompositePipeline2(commandPipelines);
3247
+ });
3248
+ container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
3249
+ return new CompositePipeline2(queryPipelines);
3250
+ });
3222
3251
  }
3223
3252
  };
3224
3253
  }
@@ -3517,7 +3546,7 @@ var init_composite_middleware = __esm({
3517
3546
  });
3518
3547
 
3519
3548
  // src/presentation/middlewares/cors.middleware.ts
3520
- import { Guards as Guards34 } from "@xeno-js/shared";
3549
+ import { Guards as Guards38 } from "@xeno-js/shared";
3521
3550
  var CORSMiddleware;
3522
3551
  var init_cors_middleware = __esm({
3523
3552
  "src/presentation/middlewares/cors.middleware.ts"() {
@@ -3533,7 +3562,7 @@ var init_cors_middleware = __esm({
3533
3562
  const { network } = this._requestContext.getContext() ?? {};
3534
3563
  const origin = network?.origin;
3535
3564
  const response = await next();
3536
- if (Guards34.isDefined(origin))
3565
+ if (Guards38.isDefined(origin))
3537
3566
  response.headers = {
3538
3567
  ...response.headers ?? {},
3539
3568
  "Access-Control-Allow-Origin": origin,
@@ -3550,7 +3579,7 @@ var init_cors_middleware = __esm({
3550
3579
  import {
3551
3580
  ERROR_CODE_MESSAGES as ERROR_CODE_MESSAGES5,
3552
3581
  ERROR_CODES as ERROR_CODES6,
3553
- Guards as Guards35,
3582
+ Guards as Guards39,
3554
3583
  GuidHelper as GuidHelper9,
3555
3584
  HttpHelper as HttpHelper6,
3556
3585
  STATUS_CODES as STATUS_CODES7
@@ -3573,7 +3602,7 @@ var init_csrf_middleware = __esm({
3573
3602
  const { network, tracing, identity } = this._requestContext.getContext() ?? {};
3574
3603
  const headerToken = network?.csrf;
3575
3604
  const cookieToken = network?.csrfCookie;
3576
- if (!Guards35.isDefined(headerToken) || !Guards35.isDefined(cookieToken)) {
3605
+ if (!Guards39.isDefined(headerToken) || !Guards39.isDefined(cookieToken)) {
3577
3606
  return HttpHelper6.error(
3578
3607
  {
3579
3608
  success: false,
@@ -3615,7 +3644,7 @@ var init_csrf_middleware = __esm({
3615
3644
  }
3616
3645
  );
3617
3646
  }
3618
- if (!Guards35.isDefined(identity?.userId) || !await this._csrfTokenService.validate(headerToken, identity?.userId)) {
3647
+ if (!Guards39.isDefined(identity?.userId) || !await this._csrfTokenService.validate(headerToken, identity?.userId)) {
3619
3648
  return HttpHelper6.error(
3620
3649
  {
3621
3650
  success: false,
@@ -3644,7 +3673,7 @@ var init_csrf_middleware = __esm({
3644
3673
  });
3645
3674
 
3646
3675
  // src/presentation/middlewares/csrf-cookie.middleware.ts
3647
- import { Guards as Guards36 } from "@xeno-js/shared";
3676
+ import { Guards as Guards40 } from "@xeno-js/shared";
3648
3677
  var CsrfCookieMiddleware;
3649
3678
  var init_csrf_cookie_middleware = __esm({
3650
3679
  "src/presentation/middlewares/csrf-cookie.middleware.ts"() {
@@ -3663,8 +3692,8 @@ var init_csrf_cookie_middleware = __esm({
3663
3692
  const context = this._requestContext.getContext();
3664
3693
  const identity = context?.identity;
3665
3694
  const network = context?.network;
3666
- if (!Guards36.isDefined(identity?.userId)) return response;
3667
- if (Guards36.isDefined(network?.csrfCookie)) return response;
3695
+ if (!Guards40.isDefined(identity?.userId)) return response;
3696
+ if (Guards40.isDefined(network?.csrfCookie)) return response;
3668
3697
  const token = await this._csrfTokenService.generate(identity.userId);
3669
3698
  const cookieName = this._csrf.cookieName ?? "__Host-xeno-csrf";
3670
3699
  const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600;
@@ -3682,7 +3711,7 @@ var init_csrf_cookie_middleware = __esm({
3682
3711
  });
3683
3712
 
3684
3713
  // src/presentation/middlewares/options.middleware.ts
3685
- import { Guards as Guards37, HttpHelper as HttpHelper7, STATUS_CODES as STATUS_CODES8 } from "@xeno-js/shared";
3714
+ import { Guards as Guards41, HttpHelper as HttpHelper7, STATUS_CODES as STATUS_CODES8 } from "@xeno-js/shared";
3686
3715
  var OptionsMiddleware;
3687
3716
  var init_options_middleware = __esm({
3688
3717
  "src/presentation/middlewares/options.middleware.ts"() {
@@ -3703,7 +3732,7 @@ var init_options_middleware = __esm({
3703
3732
  const network = this._requestContext.getNetworkContext();
3704
3733
  const origin = network?.origin;
3705
3734
  const headers = {};
3706
- if (Guards37.isDefined(origin)) {
3735
+ if (Guards41.isDefined(origin)) {
3707
3736
  headers["Access-Control-Allow-Origin"] = origin;
3708
3737
  headers["Access-Control-Allow-Credentials"] = this._withCredentials;
3709
3738
  headers["Vary"] = "Origin";
@@ -3722,7 +3751,7 @@ var init_options_middleware = __esm({
3722
3751
  import {
3723
3752
  ERROR_CODE_MESSAGES as ERROR_CODE_MESSAGES6,
3724
3753
  ERROR_CODES as ERROR_CODES7,
3725
- Guards as Guards38,
3754
+ Guards as Guards42,
3726
3755
  GuidHelper as GuidHelper10,
3727
3756
  HttpHelper as HttpHelper8,
3728
3757
  STATUS_CODES as STATUS_CODES9
@@ -3747,7 +3776,7 @@ var init_rate_limiter_middleware = __esm({
3747
3776
  async execute(req, _res, next) {
3748
3777
  const cacheKey = this._keyBuilder.buildRateLimitKey(req.path);
3749
3778
  const { network, tracing } = this._ctxAccessor.getContext() ?? {};
3750
- if (!Guards38.isDefined(cacheKey))
3779
+ if (!Guards42.isDefined(cacheKey))
3751
3780
  return HttpHelper8.error(
3752
3781
  {
3753
3782
  success: false,
@@ -3799,10 +3828,10 @@ var init_rate_limiter_middleware = __esm({
3799
3828
  });
3800
3829
 
3801
3830
  // src/presentation/mappers/context.mapper.ts
3802
- import { Guards as Guards39 } from "@xeno-js/shared";
3831
+ import { Guards as Guards43 } from "@xeno-js/shared";
3803
3832
  function _buildMessagingContext(meta) {
3804
- const hasSequenceData = Guards39.isDefined(meta.sequence?.sequenceId) || Guards39.isDefined(meta.sequence?.position) || Guards39.isDefined(meta.sequence?.size);
3805
- const hasMessagingData = hasSequenceData || Guards39.isDefined(meta.expiration) || Guards39.isDefined(meta.returnAddress);
3833
+ const hasSequenceData = Guards43.isDefined(meta.sequence?.sequenceId) || Guards43.isDefined(meta.sequence?.position) || Guards43.isDefined(meta.sequence?.size);
3834
+ const hasMessagingData = hasSequenceData || Guards43.isDefined(meta.expiration) || Guards43.isDefined(meta.returnAddress);
3806
3835
  const messaging = hasMessagingData ? {
3807
3836
  returnAddress: meta.returnAddress,
3808
3837
  expiration: meta.expiration,
@@ -3985,30 +4014,8 @@ var init_presentation = __esm({
3985
4014
  }
3986
4015
  });
3987
4016
 
3988
- // src/infrastructure/cache/inmemory.cache.ts
3989
- var inmemory_cache_exports = {};
3990
- __export(inmemory_cache_exports, {
3991
- InMemoryCacheExtended: () => InMemoryCacheExtended
3992
- });
3993
- import { Guards as Guards40, InMemoryCache } from "@xeno-js/shared";
3994
- var InMemoryCacheExtended;
3995
- var init_inmemory_cache = __esm({
3996
- "src/infrastructure/cache/inmemory.cache.ts"() {
3997
- "use strict";
3998
- InMemoryCacheExtended = class extends InMemoryCache {
3999
- async increment(key, ttlSeconds) {
4000
- const current = await this.get(key) ?? 0;
4001
- const next = Number(current) + 1;
4002
- const ttl = Guards40.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
4003
- await this.set(key, next, ttl);
4004
- return next;
4005
- }
4006
- };
4007
- }
4008
- });
4009
-
4010
4017
  // src/infrastructure/cache/rate-limit-key-builder.cache.ts
4011
- import { Guards as Guards41 } from "@xeno-js/shared";
4018
+ import { Guards as Guards44 } from "@xeno-js/shared";
4012
4019
  var RateLimitKeyBuilder;
4013
4020
  var init_rate_limit_key_builder_cache = __esm({
4014
4021
  "src/infrastructure/cache/rate-limit-key-builder.cache.ts"() {
@@ -4021,75 +4028,15 @@ var init_rate_limit_key_builder_cache = __esm({
4021
4028
  buildRateLimitKey(resource) {
4022
4029
  const ctx = this._contextAccessor.getContext();
4023
4030
  const tenantId = ctx?.identity?.tenantId;
4024
- const userId = ctx?.identity?.userId;
4025
- const clientIp = ctx?.network?.clientIp;
4026
- if (!Guards41.isNullOrEmpty(tenantId) && !Guards41.isNullOrEmpty(userId))
4027
- return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`;
4028
- if (!Guards41.isNullOrEmpty(tenantId) && !Guards41.isNullOrEmpty(clientIp))
4029
- return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`;
4030
- if (!Guards41.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4031
- if (!Guards41.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4032
- return void 0;
4033
- }
4034
- };
4035
- }
4036
- });
4037
-
4038
- // src/infrastructure/cache/redis.cache.ts
4039
- import { Guards as Guards42, StringHelper as StringHelper3 } from "@xeno-js/shared";
4040
- var RedisCache;
4041
- var init_redis_cache = __esm({
4042
- "src/infrastructure/cache/redis.cache.ts"() {
4043
- "use strict";
4044
- RedisCache = class {
4045
- /**
4046
- * @description Constructs a new instance of the RedisCache class, which takes an instance of the Redis client as a parameter. This client is used to perform caching operations such as setting, getting, and removing values from the Redis database. The constructor initializes the RedisCache with the provided Redis client, allowing it to interact with the Redis server for all caching operations defined in the ICache interface.
4047
- * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
4048
-
4049
- *
4050
- * @author Xeno
4051
- * @version 1.0.0
4052
- * @since 2025-09-30
4053
- * @link https://github.com/xeno-js/xeno-js
4054
- */
4055
- constructor(_redisClient) {
4056
- this._redisClient = _redisClient;
4057
- }
4058
- _redisClient;
4059
- async increment(key, ttlSeconds) {
4060
- const multi = this._redisClient.multi();
4061
- multi.incr(key);
4062
- multi.expire(key, ttlSeconds ?? 60);
4063
- const results = await multi.exec();
4064
- return results?.[0]?.[1] ?? 1;
4065
- }
4066
- async get(key) {
4067
- const value = await this._redisClient.get(key);
4068
- if (!Guards42.isDefined(value)) {
4069
- return void 0;
4070
- }
4071
- return JSON.parse(value);
4072
- }
4073
- async set(key, value, ttl) {
4074
- const stringValue = StringHelper3.safeStringify(value);
4075
- const ttlOption = Guards42.isDefined(ttl) ? ttl : 86400;
4076
- await this._redisClient.set(key, stringValue, "EX", ttlOption);
4077
- }
4078
- async setIfAbsent(key, value, ttl) {
4079
- const stringValue = StringHelper3.safeStringify(value);
4080
- const ttlOption = Guards42.isDefined(ttl) ? ttl : 300;
4081
- const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
4082
- return result === "OK";
4083
- }
4084
- async remove(key) {
4085
- await this._redisClient.del(key);
4086
- }
4087
- async has(key) {
4088
- const exists = await this._redisClient.exists(key);
4089
- return exists === 1;
4090
- }
4091
- async clear() {
4092
- await this._redisClient.flushdb();
4031
+ const userId = ctx?.identity?.userId;
4032
+ const clientIp = ctx?.network?.clientIp;
4033
+ if (!Guards44.isNullOrEmpty(tenantId) && !Guards44.isNullOrEmpty(userId))
4034
+ return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`;
4035
+ if (!Guards44.isNullOrEmpty(tenantId) && !Guards44.isNullOrEmpty(clientIp))
4036
+ return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`;
4037
+ if (!Guards44.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4038
+ if (!Guards44.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4039
+ return void 0;
4093
4040
  }
4094
4041
  };
4095
4042
  }
@@ -4290,423 +4237,278 @@ var init_middleware_module = __esm({
4290
4237
  }
4291
4238
  });
4292
4239
 
4293
- // src/infrastructure/factories/redis-cache.factory.ts
4294
- var redis_cache_factory_exports = {};
4295
- __export(redis_cache_factory_exports, {
4296
- RedisCacheFactory: () => RedisCacheFactory
4240
+ // src/infrastructure/factories/service-scope.factory.ts
4241
+ var service_scope_factory_exports = {};
4242
+ __export(service_scope_factory_exports, {
4243
+ ServiceScopeFactory: () => ServiceScopeFactory
4297
4244
  });
4298
- import { Guards as Guards43 } from "@xeno-js/shared";
4299
- import { Redis } from "ioredis";
4300
- var RedisCacheFactory;
4301
- var init_redis_cache_factory = __esm({
4302
- "src/infrastructure/factories/redis-cache.factory.ts"() {
4245
+ var ServiceScopeFactory;
4246
+ var init_service_scope_factory = __esm({
4247
+ "src/infrastructure/factories/service-scope.factory.ts"() {
4303
4248
  "use strict";
4304
- init_redis_cache();
4305
- RedisCacheFactory = class {
4306
- create(config) {
4307
- const host = config?.host ?? "localhost";
4308
- const port = config?.port ?? 6379;
4309
- const password = config?.password;
4310
- const username = config?.username;
4311
- const useTls = config?.tls ?? false;
4312
- const maxRetries = config?.maxRetriesPerRequest ?? 3;
4313
- const redisOptions = {
4314
- host,
4315
- port,
4316
- maxRetriesPerRequest: maxRetries,
4317
- // Strategia di riconnessione esponenziale per garantire resilienza
4318
- retryStrategy(times) {
4319
- const delay = Math.min(times * 50, 2e3);
4320
- return delay;
4321
- }
4322
- };
4323
- if (Guards43.isDefined(password)) {
4324
- redisOptions.password = password;
4325
- }
4326
- if (Guards43.isDefined(username)) {
4327
- redisOptions.username = username;
4328
- }
4329
- if (useTls) {
4330
- redisOptions.tls = {};
4331
- }
4332
- const nativeRedisInstance = new Redis(redisOptions);
4333
- nativeRedisInstance.on("error", (err) => {
4334
- console.error("\u274C [Redis Error]:", err.message);
4335
- });
4336
- return new RedisCache(nativeRedisInstance);
4249
+ ServiceScopeFactory = class {
4250
+ constructor(_container) {
4251
+ this._container = _container;
4252
+ }
4253
+ _container;
4254
+ create() {
4255
+ return this._container.createScope();
4337
4256
  }
4338
4257
  };
4339
4258
  }
4340
4259
  });
4341
4260
 
4342
- // src/infrastructure/modules/utils/cache.utils.ts
4343
- var cache_utils_exports = {};
4344
- __export(cache_utils_exports, {
4345
- CacheUtils: () => CacheUtils
4346
- });
4347
- var CacheUtils;
4348
- var init_cache_utils = __esm({
4349
- "src/infrastructure/modules/utils/cache.utils.ts"() {
4261
+ // src/infrastructure/context/request-context.ts
4262
+ import { Guards as Guards45 } from "@xeno-js/shared";
4263
+ var NodeRequestContext;
4264
+ var init_request_context = __esm({
4265
+ "src/infrastructure/context/request-context.ts"() {
4350
4266
  "use strict";
4351
- CacheUtils = Object.freeze({
4267
+ NodeRequestContext = class {
4352
4268
  /**
4353
- * @description Checks if the provided cache configuration requires any cache strategies.
4354
- * @param container The service container to which the cache strategies will be added.
4355
- * @param opts The cache configuration options.
4356
- * @returns True if any cache strategies are required, false otherwise.
4269
+ * @description Constructs a new instance of the NodeRequestContext class, which requires an instance of AsyncLocalStorage to manage the request context. The AsyncLocalStorage instance is used to create and access the context for each request, allowing for the storage of identity information and other relevant data that needs to be accessible across asynchronous operations. This constructor initializes the NodeRequestContext with the provided AsyncLocalStorage, enabling it to implement the methods defined in the IRequestContext interface for managing request-specific context data.
4270
+ * @param _storage An instance of AsyncLocalStorage that is used to manage the request context, allowing for the storage and retrieval of identity information and other relevant data across asynchronous operations.
4271
+ * @param _factoryScope An instance of IFactory that is used to create a new IServiceScope for managing service dependencies during the execution of the request. This allows for proper scoping and disposal of services after the request is processed, ensuring that resources are managed efficiently and preventing memory leaks.
4357
4272
  *
4358
4273
  * @author Xeno
4359
4274
  * @version 1.0.0
4360
4275
  * @since 2025-09-30
4361
4276
  * @link https://github.com/xeno-js/xeno-js
4362
4277
  */
4363
- async addCache(container, opts) {
4364
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4365
- if (!opts.inMemory && !Guards51.isDefined(opts.redis)) {
4366
- throw new Error(
4367
- "No cache strategies are configured. Please provide at least one cache strategy."
4368
- );
4369
- }
4370
- const { CacheKeyBuilder } = await import("@xeno-js/shared");
4371
- container.addSingleton(
4372
- TOKENS5.CACHE_KEY_BUILDER,
4373
- (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
4374
- );
4375
- if (opts.inMemory || !Guards51.isDefined(opts.redis)) {
4376
- const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
4377
- container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
4378
- return;
4278
+ constructor(_storage, _factoryScope) {
4279
+ this._storage = _storage;
4280
+ this._factoryScope = _factoryScope;
4281
+ }
4282
+ _storage;
4283
+ _factoryScope;
4284
+ async runAsync(context, fn) {
4285
+ const scope = this._factoryScope.create();
4286
+ try {
4287
+ return await this._storage.run({ context, scope }, fn);
4288
+ } finally {
4289
+ await scope.dispose();
4379
4290
  }
4380
- if (Guards51.isDefined(opts.redis)) {
4381
- const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
4382
- container.addSingleton(TOKENS5.CACHE, () => {
4383
- const config = opts.redis;
4384
- return new RedisCacheFactory2().create(config);
4291
+ }
4292
+ updateIdentity(identity) {
4293
+ const store = this._storage.getStore();
4294
+ if (Guards45.isDefined(store) && Guards45.isDefined(store.context)) {
4295
+ store.context = Object.freeze({
4296
+ ...store.context,
4297
+ identity: Object.freeze(identity)
4385
4298
  });
4386
4299
  }
4387
4300
  }
4388
- });
4301
+ getContext() {
4302
+ const store = this._storage.getStore();
4303
+ if (!Guards45.isDefined(store)) return void 0;
4304
+ const context = store.context;
4305
+ return Object.freeze(context);
4306
+ }
4307
+ getIdentity() {
4308
+ const store = this._storage.getStore();
4309
+ if (!Guards45.isDefined(store)) return void 0;
4310
+ return Object.freeze(store.context?.identity);
4311
+ }
4312
+ getScope() {
4313
+ const store = this._storage.getStore();
4314
+ if (!Guards45.isDefined(store)) return void 0;
4315
+ return store.scope;
4316
+ }
4317
+ getNetworkContext() {
4318
+ const store = this._storage.getStore();
4319
+ if (!Guards45.isDefined(store)) return void 0;
4320
+ return Object.freeze(store.context?.network);
4321
+ }
4322
+ };
4389
4323
  }
4390
4324
  });
4391
4325
 
4392
- // src/infrastructure/loggers/console.logger.ts
4393
- var console_logger_exports = {};
4394
- __export(console_logger_exports, {
4395
- ConsoleLogger: () => ConsoleLogger
4326
+ // src/infrastructure/factories/request-context.factory.ts
4327
+ var request_context_factory_exports = {};
4328
+ __export(request_context_factory_exports, {
4329
+ NodeRequestContextFactory: () => NodeRequestContextFactory
4396
4330
  });
4397
- import { Guards as Guards44, LOG_LEVEL } from "@xeno-js/shared";
4398
- var ConsoleLogger;
4399
- var init_console_logger = __esm({
4400
- "src/infrastructure/loggers/console.logger.ts"() {
4331
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4332
+ var NodeRequestContextFactory;
4333
+ var init_request_context_factory = __esm({
4334
+ "src/infrastructure/factories/request-context.factory.ts"() {
4401
4335
  "use strict";
4402
- ConsoleLogger = class {
4403
- /**
4404
- * Constructs a new instance of the ConsoleLogger class, which takes an optional minimum log level. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
4405
- * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
4406
-
4407
- *
4408
- * @author Xeno
4409
- * @version 1.0.0
4410
- * @since 2025-09-30
4411
- * @link https://github.com/xeno-js/xeno-js
4412
- */
4413
- constructor(_minLevel = LOG_LEVEL.DEBUG) {
4414
- this._minLevel = _minLevel;
4336
+ init_request_context();
4337
+ NodeRequestContextFactory = class {
4338
+ constructor(_factoryScope) {
4339
+ this._factoryScope = _factoryScope;
4415
4340
  }
4416
- _minLevel;
4417
- track(level, message, context, error = void 0) {
4418
- if (level < this._minLevel) return;
4419
- const logMessage = `[${level}] ${message}`;
4420
- const payload = Guards44.isDefined(error) ? { ...context, error } : context;
4421
- switch (level) {
4422
- case LOG_LEVEL.ERROR:
4423
- console.error(logMessage, payload ?? {});
4424
- break;
4425
- case LOG_LEVEL.WARN:
4426
- console.warn(logMessage, payload ?? {});
4427
- break;
4428
- case LOG_LEVEL.DEBUG:
4429
- console.debug(logMessage, payload ?? {});
4430
- break;
4431
- default:
4432
- console.info(logMessage, payload ?? {});
4433
- break;
4434
- }
4341
+ _factoryScope;
4342
+ _store = new AsyncLocalStorage2();
4343
+ create() {
4344
+ return new NodeRequestContext(this._store, this._factoryScope);
4435
4345
  }
4436
4346
  };
4437
4347
  }
4438
4348
  });
4439
4349
 
4440
- // src/infrastructure/loggers/sentry.logger.ts
4441
- import { Guards as Guards45, LOG_LEVEL as LOG_LEVEL2 } from "@xeno-js/shared";
4442
- var SentryLogger;
4443
- var init_sentry_logger = __esm({
4444
- "src/infrastructure/loggers/sentry.logger.ts"() {
4350
+ // src/infrastructure/factories/user-context.factory.ts
4351
+ var user_context_factory_exports = {};
4352
+ __export(user_context_factory_exports, {
4353
+ UserContextFactory: () => UserContextFactory
4354
+ });
4355
+ import { Guards as Guards46 } from "@xeno-js/shared";
4356
+ var UserContextFactory;
4357
+ var init_user_context_factory = __esm({
4358
+ "src/infrastructure/factories/user-context.factory.ts"() {
4445
4359
  "use strict";
4446
- SentryLogger = class {
4447
- constructor(_client, _minLevel) {
4448
- this._client = _client;
4449
- this._minLevel = _minLevel;
4360
+ UserContextFactory = class {
4361
+ /**
4362
+ * @description Constructs an instance of UserContextFactory.
4363
+ * @param _identityFactory - An instance of IIdentityAccessor that provides access to the current identity. This factory is used to retrieve the identity details when creating a UserContext instance.
4364
+ *
4365
+ * @author Xeno
4366
+ * @version 1.0.0
4367
+ * @since 2025-09-30
4368
+ * @link https://github.com/xeno-js/xeno-js
4369
+ */
4370
+ constructor(_identityFactory) {
4371
+ this._identityFactory = _identityFactory;
4450
4372
  }
4451
- _client;
4452
- _minLevel;
4453
- track(level, message, context = void 0, error = void 0) {
4454
- if (level < this._minLevel) return;
4455
- if (level === LOG_LEVEL2.ERROR || level === LOG_LEVEL2.WARN) {
4456
- this._client.withScope((scope) => {
4457
- if (Guards45.isDefined(context)) scope.setExtras(context);
4458
- if (Guards45.isDefined(error)) {
4459
- this._client.captureException(error);
4460
- } else {
4461
- this._client.captureMessage(message, "warning");
4462
- }
4463
- });
4373
+ _identityFactory;
4374
+ create() {
4375
+ const output = {
4376
+ userId: void 0,
4377
+ tenantId: void 0
4378
+ };
4379
+ const identity = this._identityFactory.getIdentity();
4380
+ if (Guards46.isDefined(identity)) {
4381
+ output.userId = identity.userId;
4382
+ output.tenantId = identity.tenantId;
4464
4383
  }
4384
+ return output;
4465
4385
  }
4466
4386
  };
4467
4387
  }
4468
4388
  });
4469
4389
 
4470
- // src/infrastructure/factories/sentry-logger.factory.ts
4471
- var sentry_logger_factory_exports = {};
4472
- __export(sentry_logger_factory_exports, {
4473
- SentryLoggerFactory: () => SentryLoggerFactory
4390
+ // src/infrastructure/modules/context.module.ts
4391
+ var context_module_exports = {};
4392
+ __export(context_module_exports, {
4393
+ ContextModule: () => ContextModule
4474
4394
  });
4475
- import * as Sentry from "@sentry/node";
4476
- import { Guards as Guards46, LOG_LEVEL as LOG_LEVEL3 } from "@xeno-js/shared";
4477
- var SentryLoggerFactory;
4478
- var init_sentry_logger_factory = __esm({
4479
- "src/infrastructure/factories/sentry-logger.factory.ts"() {
4395
+ var ContextModule;
4396
+ var init_context_module = __esm({
4397
+ "src/infrastructure/modules/context.module.ts"() {
4480
4398
  "use strict";
4481
- init_sentry_logger();
4482
- SentryLoggerFactory = class {
4483
- create(config) {
4484
- const level = config.level ?? LOG_LEVEL3.WARN;
4485
- const sentryConfig = config.sentry?.config;
4486
- const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
4487
- if (!Guards46.isDefined(sentryConfig))
4488
- throw new Error("Sentry configuration is required when Sentry logging is enabled.");
4489
- if (!Guards46.isDefined(sentryConfig.dsn))
4490
- throw new Error("Sentry DSN is required when Sentry logging is enabled.");
4491
- Sentry.init({
4492
- dsn: sentryConfig.dsn,
4493
- environment: env,
4494
- tracesSampleRate: env === "production" ? 0.1 : 1,
4495
- integrations: [Sentry.httpIntegration()],
4496
- beforeSend(event, hint) {
4497
- const error = hint.originalException;
4498
- if (error instanceof Error && error.name === "ZodError") {
4499
- return null;
4500
- }
4501
- return event;
4502
- }
4399
+ ContextModule = class {
4400
+ async configure(container) {
4401
+ const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4402
+ const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
4403
+ const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
4404
+ const requestContext = new NodeRequestContextFactory2(
4405
+ new ServiceScopeFactory2(container)
4406
+ ).create();
4407
+ container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
4408
+ container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
4409
+ container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
4410
+ container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
4411
+ container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
4412
+ const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
4413
+ container.addSingleton("USER_CONTEXT_FACTORY", () => {
4414
+ return new UserContextFactory2(requestContext);
4503
4415
  });
4504
- return new SentryLogger(Sentry, level);
4505
4416
  }
4506
4417
  };
4507
4418
  }
4508
4419
  });
4509
4420
 
4510
- // src/infrastructure/loggers/pino.logger.ts
4511
- import { Guards as Guards47, LOG_LEVEL as LOG_LEVEL4 } from "@xeno-js/shared";
4512
- var PinoLogger;
4513
- var init_pino_logger = __esm({
4514
- "src/infrastructure/loggers/pino.logger.ts"() {
4421
+ // src/infrastructure/transaction/transaction-state.ts
4422
+ var transaction_state_exports = {};
4423
+ __export(transaction_state_exports, {
4424
+ TransactionState: () => TransactionState
4425
+ });
4426
+ var TransactionState;
4427
+ var init_transaction_state = __esm({
4428
+ "src/infrastructure/transaction/transaction-state.ts"() {
4515
4429
  "use strict";
4516
- PinoLogger = class {
4430
+ TransactionState = class {
4517
4431
  /**
4518
- * Constructs a new instance of the PinoTransport class, which takes an optional minimum log level and an optional instance of the Pino logger. If no logger instance is provided, it initializes a new Pino logger with default settings. The minimum log level determines the threshold for logging messages, where messages with a log level below the specified minimum will be ignored.
4519
- * @param _logger The Pino logger instance used for logging messages.
4520
- * @param _minLevel The minimum log level for logging messages. Messages with a log level below this threshold will not be logged. Default is LOG_LEVEL.DEBUG.
4521
-
4522
- *
4432
+ * The current state of the transaction, which can be either a specific transaction type or null.
4523
4433
  * @author Xeno
4524
4434
  * @version 1.0.0
4525
4435
  * @since 2025-09-30
4526
- * @link https://github.com/xeno-js/xeno-js
4436
+ * @link https://github.com/xeno-js/xeno-js
4527
4437
  */
4528
- constructor(_logger, _minLevel = LOG_LEVEL4.DEBUG) {
4529
- this._logger = _logger;
4530
- this._minLevel = _minLevel;
4438
+ _state = null;
4439
+ /**
4440
+ * Creates an instance of TransactionState.
4441
+ * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.
4442
+ * @author Xeno
4443
+ * @version 1.0.0
4444
+ * @since 2025-09-30
4445
+ * @link https://github.com/xeno-js/xeno-js
4446
+ */
4447
+ constructor(initialState = null) {
4448
+ this._state = initialState;
4531
4449
  }
4532
- _logger;
4533
- _minLevel;
4534
- track(level, message, context, error = void 0) {
4535
- if (level < this._minLevel) return;
4536
- const payload = Guards47.isDefined(error) ? { ...context, error } : context;
4537
- switch (level) {
4538
- case LOG_LEVEL4.ERROR:
4539
- this._logger.error(payload ?? {}, message);
4540
- break;
4541
- case LOG_LEVEL4.WARN:
4542
- this._logger.warn(payload ?? {}, message);
4543
- break;
4544
- case LOG_LEVEL4.DEBUG:
4545
- this._logger.debug(payload ?? {}, message);
4546
- break;
4547
- default:
4548
- this._logger.info(payload ?? {}, message);
4549
- break;
4550
- }
4450
+ get state() {
4451
+ return this._state;
4551
4452
  }
4552
- };
4553
- }
4554
- });
4555
-
4556
- // src/infrastructure/factories/pino-logger.factory.ts
4557
- var pino_logger_factory_exports = {};
4558
- __export(pino_logger_factory_exports, {
4559
- PinoLoggerFactory: () => PinoLoggerFactory
4560
- });
4561
- import { LOG_LEVEL as LOG_LEVEL5 } from "@xeno-js/shared";
4562
- import pino from "pino";
4563
- var PinoLoggerFactory;
4564
- var init_pino_logger_factory = __esm({
4565
- "src/infrastructure/factories/pino-logger.factory.ts"() {
4566
- "use strict";
4567
- init_pino_logger();
4568
- PinoLoggerFactory = class {
4569
- create(config) {
4570
- const level = config.level ?? LOG_LEVEL5.DEBUG;
4571
- const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
4572
- const destinationType = config.pino.config?.destination ?? "stdout";
4573
- const filePath = config.pino.config?.filePath ?? "logs/app.log";
4574
- const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
4575
- const options = {
4576
- level: "trace",
4577
- serializers: {
4578
- err: pino.stdSerializers.err
4579
- },
4580
- timestamp: pino.stdTimeFunctions.isoTime,
4581
- redact: {
4582
- paths: ["password", "token", "secret", "authorization", "headers.authorization"],
4583
- censor: "***"
4584
- }
4585
- };
4586
- if (prettyPrint) {
4587
- return new PinoLogger(
4588
- pino({
4589
- ...options,
4590
- transport: {
4591
- target: "pino-pretty",
4592
- options: {
4593
- colorize: true,
4594
- ignore: "pid,hostname",
4595
- translateTime: "SYS:standard"
4596
- }
4597
- }
4598
- }),
4599
- level
4600
- );
4601
- }
4602
- if (destinationType === "file") {
4603
- const destination = pino.destination({ dest: filePath, sync: false });
4604
- return new PinoLogger(pino(options, destination), level);
4605
- } else {
4606
- const stream = pino.destination({ dest: 1, sync: false });
4607
- return new PinoLogger(pino(options, stream), level);
4608
- }
4453
+ set state(value) {
4454
+ this._state = value;
4609
4455
  }
4610
4456
  };
4611
4457
  }
4612
4458
  });
4613
4459
 
4614
- // src/infrastructure/modules/utils/logger.utils.ts
4615
- var logger_utils_exports = {};
4616
- __export(logger_utils_exports, {
4617
- LoggerUtils: () => LoggerUtils
4460
+ // src/infrastructure/transaction/unit-of-work.ts
4461
+ var unit_of_work_exports = {};
4462
+ __export(unit_of_work_exports, {
4463
+ UnitOfWork: () => UnitOfWork
4618
4464
  });
4619
- var LoggerUtils;
4620
- var init_logger_utils = __esm({
4621
- "src/infrastructure/modules/utils/logger.utils.ts"() {
4465
+ import { AppError as AppError13 } from "@xeno-js/shared";
4466
+ import { Guards as Guards48 } from "@xeno-js/shared";
4467
+ var UnitOfWork;
4468
+ var init_unit_of_work = __esm({
4469
+ "src/infrastructure/transaction/unit-of-work.ts"() {
4622
4470
  "use strict";
4623
- LoggerUtils = Object.freeze({
4471
+ UnitOfWork = class {
4624
4472
  /**
4625
- * @description Configures and registers the logging services in the dependency injection container based on the provided LoggerConfig options. It dynamically imports the necessary logger implementations (e.g., ConsoleLogger, SentryLogger, PinoLogger) and registers them with the container, allowing for flexible and modular logging configuration in the application.
4473
+ * Creates an instance of UnitOfWork.
4474
+ * @param _dbContext - The database context used for managing transactions.
4475
+ * @param _ttx - The transaction state, which can be either a specific transaction type or null.
4626
4476
  *
4627
- * @param container - The service container to register logging services with.
4628
- * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
4629
-
4630
- *
4631
4477
  * @author Xeno
4632
4478
  * @version 1.0.0
4633
4479
  * @since 2025-09-30
4634
- * @link https://github.com/xeno-js/xeno-js
4480
+ * @link https://github.com/xeno-js/xeno-js
4635
4481
  */
4636
- async addLogger(container, opts) {
4637
- const loggerDependencies = [];
4638
- const { Guards: Guards51, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4639
- if (!Guards51.isDefined(opts) || opts.console) {
4640
- const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
4641
- loggerDependencies.push(new ConsoleLogger2(opts?.level));
4642
- }
4643
- if (Guards51.isDefined(opts)) {
4644
- if (Guards51.isDefined(opts.sentry.config)) {
4645
- const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
4646
- loggerDependencies.push(new SentryLoggerFactory2().create(opts));
4647
- }
4648
- if (Guards51.isDefined(opts.pino.config)) {
4649
- const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
4650
- loggerDependencies.push(new PinoLoggerFactory2().create(opts));
4482
+ constructor(_dbContext, _ttx) {
4483
+ this._dbContext = _dbContext;
4484
+ this._ttx = _ttx;
4485
+ }
4486
+ _dbContext;
4487
+ _ttx;
4488
+ async runInTransaction(callback, signal) {
4489
+ AppError13.throwIfAborted(signal, "UnitOfWork.runInTransaction");
4490
+ return this._dbContext.transaction(async (tx) => {
4491
+ this._ttx.state = tx;
4492
+ try {
4493
+ const result = await callback();
4494
+ return result;
4495
+ } finally {
4496
+ this._ttx.state = null;
4651
4497
  }
4652
- if (!Guards51.isNullOrEmpty(opts.customLoggers)) {
4653
- const customLoggers = opts.customLoggers;
4654
- customLoggers.forEach((fn) => {
4655
- if (Guards51.isDefined(fn)) loggerDependencies.push(fn(container));
4656
- });
4498
+ });
4499
+ }
4500
+ async dispose() {
4501
+ if (Guards48.isDefined(this._ttx.state)) {
4502
+ try {
4503
+ if (Guards48.hasMethod(this._ttx.state, "rollback")) {
4504
+ await this._ttx.state.rollback();
4505
+ }
4506
+ } finally {
4507
+ this._ttx.state = null;
4657
4508
  }
4658
4509
  }
4659
- const { BaseLogger } = await import("@xeno-js/shared");
4660
- container.addSingleton(TOKENS5.LOGGER, (c) => {
4661
- const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
4662
- return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
4663
- });
4664
4510
  }
4665
- });
4666
- }
4667
- });
4668
-
4669
- // src/infrastructure/modules/utils/index.ts
4670
- var init_utils2 = __esm({
4671
- "src/infrastructure/modules/utils/index.ts"() {
4672
- "use strict";
4673
- init_auth_utils();
4674
- init_cache_utils();
4675
- init_db_utils();
4676
- init_http_utils();
4677
- init_logger_utils();
4678
- init_pipeline_utils();
4679
- init_validation_utils();
4680
- }
4681
- });
4682
-
4683
- // src/infrastructure/modules/index.ts
4684
- var modules_exports = {};
4685
- __export(modules_exports, {
4686
- AuthUtils: () => AuthUtils,
4687
- CacheUtils: () => CacheUtils,
4688
- ContextModule: () => ContextModule,
4689
- CqrsModule: () => CqrsModule,
4690
- DbModule: () => DbModule,
4691
- DbUtils: () => DbUtils,
4692
- HttpAdapterModule: () => HttpAdapterModule,
4693
- HttpCoreModule: () => HttpCoreModule,
4694
- HttpUtils: () => HttpUtils,
4695
- LoggerUtils: () => LoggerUtils,
4696
- MiddlewareModule: () => MiddlewareModule,
4697
- PipelineUtils: () => PipelineUtils,
4698
- ValidationUtils: () => ValidationUtils
4699
- });
4700
- var init_modules = __esm({
4701
- "src/infrastructure/modules/index.ts"() {
4702
- "use strict";
4703
- init_context_module();
4704
- init_cqrs_module();
4705
- init_db_module();
4706
- init_http_adapter_module();
4707
- init_http_core_module();
4708
- init_middleware_module();
4709
- init_utils2();
4511
+ };
4710
4512
  }
4711
4513
  });
4712
4514
 
@@ -4714,7 +4516,7 @@ var init_modules = __esm({
4714
4516
  init_application();
4715
4517
 
4716
4518
  // src/infrastructure/builder/app.builder.ts
4717
- import { Guards as Guards48, LOG_LEVEL as LOG_LEVEL6, TOKENS as TOKENS4 } from "@xeno-js/shared";
4519
+ import { Guards as Guards47, LOG_LEVEL as LOG_LEVEL6, TOKENS as TOKENS4 } from "@xeno-js/shared";
4718
4520
 
4719
4521
  // src/infrastructure/configuration/configuration.ts
4720
4522
  import { Guards as Guards13 } from "@xeno-js/shared";
@@ -5100,7 +4902,7 @@ var AppBuilder = class {
5100
4902
  priority: 50,
5101
4903
  name: "AdapterModule",
5102
4904
  action: async () => {
5103
- const { HttpAdapterModule: HttpAdapterModule2 } = await Promise.resolve().then(() => (init_modules(), modules_exports));
4905
+ const { HttpAdapterModule: HttpAdapterModule2 } = await Promise.resolve().then(() => (init_http_adapter_module(), http_adapter_module_exports));
5104
4906
  await new HttpAdapterModule2().configure(this._container, this._adapterConfig);
5105
4907
  }
5106
4908
  });
@@ -5146,7 +4948,7 @@ var AppBuilder = class {
5146
4948
  * @link https://github.com/xeno-js/xeno-js
5147
4949
  */
5148
4950
  addLogger(setupAction) {
5149
- if (Guards48.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
4951
+ if (Guards47.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
5150
4952
  if (this._isLoggerModuleQueued) return this;
5151
4953
  this._isLoggerModuleQueued = true;
5152
4954
  this._modules.push({
@@ -5171,7 +4973,7 @@ var AppBuilder = class {
5171
4973
  * @link https://github.com/xeno-js/xeno-js
5172
4974
  */
5173
4975
  addCache(setupAction) {
5174
- if (Guards48.isDefined(setupAction)) setupAction(this._config, this._configuration);
4976
+ if (Guards47.isDefined(setupAction)) setupAction(this._config, this._configuration);
5175
4977
  if (this._isCacheModuleQueued) return this;
5176
4978
  this._isCacheModuleQueued = true;
5177
4979
  this._modules.push({
@@ -5220,21 +5022,11 @@ var AppBuilder = class {
5220
5022
  * @since 2025-09-30
5221
5023
  * @link https://github.com/xeno-js/xeno-js
5222
5024
  */
5223
- addDb(setupAction) {
5025
+ addDb(plugin) {
5224
5026
  if (this._isDbContextModuleQueued) return this;
5027
+ const result = plugin(this);
5225
5028
  this._isDbContextModuleQueued = true;
5226
- const config = { connectionString: "", enableSqlLite: false };
5227
- setupAction(config, this._configuration);
5228
- this._modules.push({
5229
- priority: 4,
5230
- name: "DbModule",
5231
- action: async () => {
5232
- const { DbModule: DbModule2 } = await Promise.resolve().then(() => (init_db_module(), db_module_exports));
5233
- const dbModule = new DbModule2();
5234
- await dbModule.configure(this._container, config);
5235
- }
5236
- });
5237
- return this;
5029
+ return result;
5238
5030
  }
5239
5031
  /**
5240
5032
  * @description Enables the use of the service for concurrency control in the application. This method allows you to limit the number of concurrent asynchronous tasks being executed, which is useful for managing system resources and preventing event loop blocking during massive batch operations.
@@ -5274,7 +5066,7 @@ var AppBuilder = class {
5274
5066
  * @link https://github.com/xeno-js/xeno-js
5275
5067
  */
5276
5068
  addPipeline(setupAction) {
5277
- if (Guards48.isDefined(setupAction)) {
5069
+ if (Guards47.isDefined(setupAction)) {
5278
5070
  setupAction(this._pipelineConfig, this._configuration);
5279
5071
  }
5280
5072
  this._queuePipelineModule();
@@ -5393,7 +5185,7 @@ var AppBuilder = class {
5393
5185
  console.error(`\u{1F449} Module: **${queued.name}**`);
5394
5186
  console.error(`\u{1F4DD} Reason: ${errorMessage}
5395
5187
  `);
5396
- if (error instanceof Error && Guards48.isDefined(error.stack)) {
5188
+ if (error instanceof Error && Guards47.isDefined(error.stack)) {
5397
5189
  console.error(error.stack);
5398
5190
  }
5399
5191
  throw new Error(`Bootstrap failed at [${queued.name}]: ${errorMessage}`, { cause: error });
@@ -5485,8 +5277,41 @@ var AppBuilder = class {
5485
5277
  // src/infrastructure/http/index.ts
5486
5278
  init_base_http_adapter();
5487
5279
 
5280
+ // src/infrastructure/modules/db.module.ts
5281
+ var DbModule = class {
5282
+ async configure(container, opts) {
5283
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
5284
+ const db = opts.client;
5285
+ const { TransactionState: TransactionState2 } = await Promise.resolve().then(() => (init_transaction_state(), transaction_state_exports));
5286
+ container.addScoped("TRANSACTION_STATE", () => {
5287
+ return new TransactionState2();
5288
+ });
5289
+ const { UnitOfWork: UnitOfWork2 } = await Promise.resolve().then(() => (init_unit_of_work(), unit_of_work_exports));
5290
+ container.addScoped(TOKENS5.UNIT_OF_WORK, (c) => {
5291
+ const ttx = c.resolve("TRANSACTION_STATE");
5292
+ return new UnitOfWork2(db, ttx);
5293
+ });
5294
+ container.addScoped(TOKENS5.DB_CONTEXT, (c) => {
5295
+ const ttx = c.resolve("TRANSACTION_STATE");
5296
+ return new Proxy(db, {
5297
+ get(_target, prop, receiver) {
5298
+ const activeState = ttx.state;
5299
+ if (Guards51.isDefined(activeState)) {
5300
+ const value = Reflect.get(activeState, prop, receiver);
5301
+ if (Guards51.isFunction(value)) {
5302
+ return value.bind(activeState);
5303
+ }
5304
+ return value;
5305
+ }
5306
+ return Reflect.get(db, prop, receiver);
5307
+ }
5308
+ });
5309
+ });
5310
+ }
5311
+ };
5312
+
5488
5313
  // src/infrastructure/repositories/read-dao.ts
5489
- import { AppError as AppError15, Result as Result16 } from "@xeno-js/shared";
5314
+ import { AppError as AppError14, Result as Result16 } from "@xeno-js/shared";
5490
5315
  import { Guards as Guards49 } from "@xeno-js/shared";
5491
5316
  var ReadDao = class {
5492
5317
  /**
@@ -5507,14 +5332,14 @@ var ReadDao = class {
5507
5332
  _dataSource;
5508
5333
  _mapper;
5509
5334
  async findById(id, ctx, signal) {
5510
- AppError15.throwIfAborted(signal, "ReadDao.findById");
5335
+ AppError14.throwIfAborted(signal, "ReadDao.findById");
5511
5336
  const result = await this._dataSource.findById(id, ctx, signal);
5512
5337
  if (Guards49.isNullOrEmpty(result)) return Result16.ok();
5513
5338
  const entity = this._mapper.toEntity(result);
5514
5339
  return Result16.ok(entity);
5515
5340
  }
5516
5341
  async findAll(ctx, signal) {
5517
- AppError15.throwIfAborted(signal, "ReadDao.findAll");
5342
+ AppError14.throwIfAborted(signal, "ReadDao.findAll");
5518
5343
  const results = await this._dataSource.findAll(ctx, signal);
5519
5344
  const entities = results.map((result) => this._mapper.toEntity(result));
5520
5345
  return Result16.ok(entities);
@@ -5522,7 +5347,7 @@ var ReadDao = class {
5522
5347
  };
5523
5348
 
5524
5349
  // src/infrastructure/repositories/repository.ts
5525
- import { AppError as AppError16, Result as Result17 } from "@xeno-js/shared";
5350
+ import { AppError as AppError15, Result as Result17 } from "@xeno-js/shared";
5526
5351
  import { Guards as Guards50 } from "@xeno-js/shared";
5527
5352
  var Repository = class {
5528
5353
  /**
@@ -5543,33 +5368,33 @@ var Repository = class {
5543
5368
  _dataSource;
5544
5369
  _mapper;
5545
5370
  async findById(id, ctx, signal) {
5546
- AppError16.throwIfAborted(signal, "Repository.findById");
5371
+ AppError15.throwIfAborted(signal, "Repository.findById");
5547
5372
  const result = await this._dataSource.findById(id, ctx, signal);
5548
5373
  if (Guards50.isNullOrEmpty(result)) return Result17.ok();
5549
5374
  const entity = this._mapper.toEntity(result);
5550
5375
  return Result17.ok(entity);
5551
5376
  }
5552
5377
  async findAll(ctx, signal) {
5553
- AppError16.throwIfAborted(signal, "Repository.findAll");
5378
+ AppError15.throwIfAborted(signal, "Repository.findAll");
5554
5379
  const results = await this._dataSource.findAll(ctx, signal);
5555
5380
  const entities = results.map((result) => this._mapper.toEntity(result));
5556
5381
  return Result17.ok(entities);
5557
5382
  }
5558
5383
  async save(entity, signal) {
5559
5384
  const dto = this._mapper.toDto(entity);
5560
- AppError16.throwIfAborted(signal, "Repository.save");
5385
+ AppError15.throwIfAborted(signal, "Repository.save");
5561
5386
  await this._dataSource.insert(dto, signal);
5562
5387
  return Result17.ok();
5563
5388
  }
5564
5389
  async delete(entity, ctx, signal) {
5565
5390
  const dto = this._mapper.toDto(entity);
5566
- AppError16.throwIfAborted(signal, "Repository.delete");
5391
+ AppError15.throwIfAborted(signal, "Repository.delete");
5567
5392
  await this._dataSource.delete(dto, ctx, signal);
5568
5393
  return Result17.ok();
5569
5394
  }
5570
5395
  async update(id, entity, ctx, signal) {
5571
5396
  const dto = this._mapper.toPartialDto(entity);
5572
- AppError16.throwIfAborted(signal, "Repository.update");
5397
+ AppError15.throwIfAborted(signal, "Repository.update");
5573
5398
  await this._dataSource.update(id, dto, ctx, signal);
5574
5399
  return Result17.ok();
5575
5400
  }
@@ -5583,9 +5408,9 @@ export {
5583
5408
  AppBuilder,
5584
5409
  BaseAuthorizationStrategy,
5585
5410
  BaseController,
5586
- BaseHandler,
5587
5411
  BaseHttpAdapter,
5588
5412
  ContainerUtils,
5413
+ DbModule,
5589
5414
  Query,
5590
5415
  ReadDao,
5591
5416
  Repository,