@xeno-js/core 2.0.2 → 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
@@ -1223,866 +1223,1129 @@ var init_application = __esm({
1223
1223
  }
1224
1224
  });
1225
1225
 
1226
- // src/infrastructure/factories/service-scope.factory.ts
1227
- var service_scope_factory_exports = {};
1228
- __export(service_scope_factory_exports, {
1229
- ServiceScopeFactory: () => ServiceScopeFactory
1230
- });
1231
- var ServiceScopeFactory;
1232
- var init_service_scope_factory = __esm({
1233
- "src/infrastructure/factories/service-scope.factory.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"() {
1234
1231
  "use strict";
1235
- ServiceScopeFactory = class {
1236
- constructor(_container) {
1237
- this._container = _container;
1232
+ BaseHttpAdapter = class {
1233
+ /**
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.
1239
+ */
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
+ }
1253
+ }
1254
+ return url;
1238
1255
  }
1239
- _container;
1240
- create() {
1241
- return this._container.createScope();
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
+ }
1271
+ }
1272
+ return headers;
1273
+ }
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);
1287
+ }
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
+ };
1242
1330
  }
1243
1331
  };
1244
1332
  }
1245
1333
  });
1246
1334
 
1247
- // src/infrastructure/context/request-context.ts
1248
- import { Guards as Guards15 } from "@xeno-js/shared";
1249
- var NodeRequestContext;
1250
- var init_request_context = __esm({
1251
- "src/infrastructure/context/request-context.ts"() {
1335
+ // src/infrastructure/http/vercel.http-adapter.ts
1336
+ var vercel_http_adapter_exports = {};
1337
+ __export(vercel_http_adapter_exports, {
1338
+ VercelHttpAdapter: () => VercelHttpAdapter
1339
+ });
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"() {
1252
1344
  "use strict";
1253
- NodeRequestContext = class {
1254
- /**
1255
- * @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.
1256
- * @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.
1257
- * @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.
1258
- *
1259
- * @author Xeno
1260
- * @version 1.0.0
1261
- * @since 2025-09-30
1262
- * @link https://github.com/xeno-js/xeno-js
1263
- */
1264
- constructor(_storage, _factoryScope) {
1265
- this._storage = _storage;
1266
- 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);
1267
1351
  }
1268
- _storage;
1269
- _factoryScope;
1270
- async runAsync(context, fn) {
1271
- const scope = this._factoryScope.create();
1272
- try {
1273
- return await this._storage.run({ context, scope }, fn);
1274
- } finally {
1275
- await scope.dispose();
1352
+ handleHeaderChange(res, name, value, action) {
1353
+ if (action === "delete") {
1354
+ res.removeHeader(name);
1355
+ return;
1276
1356
  }
1277
- }
1278
- updateIdentity(identity) {
1279
- const store = this._storage.getStore();
1280
- if (Guards15.isDefined(store) && Guards15.isDefined(store.context)) {
1281
- store.context = Object.freeze({
1282
- ...store.context,
1283
- identity: Object.freeze(identity)
1284
- });
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);
1285
1373
  }
1286
1374
  }
1287
- getContext() {
1288
- const store = this._storage.getStore();
1289
- if (!Guards15.isDefined(store)) return void 0;
1290
- const context = store.context;
1291
- return Object.freeze(context);
1292
- }
1293
- getIdentity() {
1294
- const store = this._storage.getStore();
1295
- if (!Guards15.isDefined(store)) return void 0;
1296
- return Object.freeze(store.context?.identity);
1297
- }
1298
- getScope() {
1299
- const store = this._storage.getStore();
1300
- if (!Guards15.isDefined(store)) return void 0;
1301
- return store.scope;
1302
- }
1303
- getNetworkContext() {
1304
- const store = this._storage.getStore();
1305
- if (!Guards15.isDefined(store)) return void 0;
1306
- return Object.freeze(store.context?.network);
1307
- }
1308
1375
  };
1309
1376
  }
1310
1377
  });
1311
1378
 
1312
- // src/infrastructure/factories/request-context.factory.ts
1313
- var request_context_factory_exports = {};
1314
- __export(request_context_factory_exports, {
1315
- NodeRequestContextFactory: () => NodeRequestContextFactory
1379
+ // src/infrastructure/http/fastify.http-adapter.ts
1380
+ var fastify_http_adapter_exports = {};
1381
+ __export(fastify_http_adapter_exports, {
1382
+ FastifyHttpAdapter: () => FastifyHttpAdapter
1316
1383
  });
1317
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1318
- var NodeRequestContextFactory;
1319
- var init_request_context_factory = __esm({
1320
- "src/infrastructure/factories/request-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"() {
1321
1388
  "use strict";
1322
- init_request_context();
1323
- NodeRequestContextFactory = class {
1324
- constructor(_factoryScope) {
1325
- this._factoryScope = _factoryScope;
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);
1326
1396
  }
1327
- _factoryScope;
1328
- _store = new AsyncLocalStorage2();
1329
- create() {
1330
- return new NodeRequestContext(this._store, this._factoryScope);
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);
1418
+ }
1331
1419
  }
1332
1420
  };
1333
1421
  }
1334
1422
  });
1335
1423
 
1336
- // src/infrastructure/factories/user-context.factory.ts
1337
- var user_context_factory_exports = {};
1338
- __export(user_context_factory_exports, {
1339
- UserContextFactory: () => UserContextFactory
1424
+ // src/infrastructure/http/native.http-adapter.ts
1425
+ var native_http_adapter_exports = {};
1426
+ __export(native_http_adapter_exports, {
1427
+ NativeHttpAdapter: () => NativeHttpAdapter
1340
1428
  });
1341
- import { Guards as Guards16 } from "@xeno-js/shared";
1342
- var UserContextFactory;
1343
- var init_user_context_factory = __esm({
1344
- "src/infrastructure/factories/user-context.factory.ts"() {
1429
+ var NativeHttpAdapter;
1430
+ var init_native_http_adapter = __esm({
1431
+ "src/infrastructure/http/native.http-adapter.ts"() {
1345
1432
  "use strict";
1346
- UserContextFactory = class {
1347
- /**
1348
- * @description Constructs an instance of UserContextFactory.
1349
- * @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.
1350
- *
1351
- * @author Xeno
1352
- * @version 1.0.0
1353
- * @since 2025-09-30
1354
- * @link https://github.com/xeno-js/xeno-js
1355
- */
1356
- constructor(_identityFactory) {
1357
- this._identityFactory = _identityFactory;
1358
- }
1359
- _identityFactory;
1360
- create() {
1361
- const output = {
1362
- userId: void 0,
1363
- tenantId: void 0
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
1364
1441
  };
1365
- const identity = this._identityFactory.getIdentity();
1366
- if (Guards16.isDefined(identity)) {
1367
- output.userId = identity.userId;
1368
- output.tenantId = identity.tenantId;
1369
- }
1370
- return output;
1442
+ }
1443
+ handleHeaderChange(_res, _name, _value, _action) {
1444
+ return;
1371
1445
  }
1372
1446
  };
1373
1447
  }
1374
1448
  });
1375
1449
 
1376
- // src/infrastructure/modules/context.module.ts
1377
- var context_module_exports = {};
1378
- __export(context_module_exports, {
1379
- ContextModule: () => ContextModule
1450
+ // src/infrastructure/modules/http-adapter.module.ts
1451
+ var http_adapter_module_exports = {};
1452
+ __export(http_adapter_module_exports, {
1453
+ HttpAdapterModule: () => HttpAdapterModule
1380
1454
  });
1381
- var ContextModule;
1382
- var init_context_module = __esm({
1383
- "src/infrastructure/modules/context.module.ts"() {
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"() {
1384
1459
  "use strict";
1385
- ContextModule = class {
1386
- async configure(container) {
1387
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
1388
- const { ServiceScopeFactory: ServiceScopeFactory2 } = await Promise.resolve().then(() => (init_service_scope_factory(), service_scope_factory_exports));
1389
- const { NodeRequestContextFactory: NodeRequestContextFactory2 } = await Promise.resolve().then(() => (init_request_context_factory(), request_context_factory_exports));
1390
- const requestContext = new NodeRequestContextFactory2(
1391
- new ServiceScopeFactory2(container)
1392
- ).create();
1393
- container.addSingleton(TOKENS5.REQUEST_CONTEXT, () => requestContext);
1394
- container.addSingleton(TOKENS5.CONTEXT_ACCESSOR, () => requestContext);
1395
- container.addSingleton(TOKENS5.IDENTITY_ACCESSOR, () => requestContext);
1396
- container.addSingleton(TOKENS5.SERVICE_SCOPE_ACCESSOR, () => requestContext);
1397
- container.addSingleton(TOKENS5.NETWORK_CONTEXT_ACCESSOR, () => requestContext);
1398
- const { UserContextFactory: UserContextFactory2 } = await Promise.resolve().then(() => (init_user_context_factory(), user_context_factory_exports));
1399
- container.addSingleton("USER_CONTEXT_FACTORY", () => {
1400
- return new UserContextFactory2(requestContext);
1401
- });
1460
+ HttpAdapterModule = class {
1461
+ async configure(container, opts) {
1462
+ const adapter = await this._getAdapter(opts);
1463
+ container.addSingleton("HTTP_ADAPTER", () => adapter);
1464
+ }
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();
1477
+ }
1402
1478
  }
1403
1479
  };
1404
1480
  }
1405
1481
  });
1406
1482
 
1407
- // src/infrastructure/services/allow_methods/allow-method.service.ts
1408
- import { Guards as Guards17 } from "@xeno-js/shared";
1409
- var AllowMethodRegistry;
1410
- var init_allow_method_service = __esm({
1411
- "src/infrastructure/services/allow_methods/allow-method.service.ts"() {
1483
+ // src/infrastructure/loggers/console.logger.ts
1484
+ var console_logger_exports = {};
1485
+ __export(console_logger_exports, {
1486
+ ConsoleLogger: () => ConsoleLogger
1487
+ });
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"() {
1412
1492
  "use strict";
1413
- AllowMethodRegistry = class {
1414
- _staticRoutes = /* @__PURE__ */ new Map();
1415
- _dynamicRoutes = [];
1416
- add(path, methods) {
1417
- const normalizedPath = this.normalizePath(path);
1418
- if (this.isDynamicPath(normalizedPath)) {
1419
- const pattern = this.createRoutePattern(normalizedPath);
1420
- this._dynamicRoutes.push({ pattern, methods });
1421
- } else {
1422
- this._staticRoutes.set(normalizedPath, methods);
1423
- }
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;
1424
1506
  }
1425
- check(path, method) {
1426
- const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1427
- const staticMethods = this._staticRoutes.get(cleanPath);
1428
- if (Guards17.isDefined(staticMethods)) return staticMethods.includes(method);
1429
- for (const route of this._dynamicRoutes) {
1430
- if (route.pattern.test(cleanPath)) return route.methods.includes(method);
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;
1431
1525
  }
1432
- return false;
1433
- }
1434
- getMethods(path) {
1435
- const cleanPath = this.normalizePath(path.split("?")[0].split("#")[0]);
1436
- const methods = this.findMethods(cleanPath);
1437
- return Guards17.isDefined(methods) ? methods.join(", ").toUpperCase() : "";
1438
- }
1439
- findMethods(cleanPath) {
1440
- const staticMethods = this._staticRoutes.get(cleanPath);
1441
- if (Guards17.isDefined(staticMethods)) return staticMethods;
1442
- for (const route of this._dynamicRoutes) if (route.pattern.test(cleanPath)) return route.methods;
1443
- return void 0;
1444
- }
1445
- isDynamicPath(path) {
1446
- return path.includes(":") || path.includes("{") && path.includes("}");
1447
- }
1448
- normalizePath(path) {
1449
- const trimmed = path.trim();
1450
- const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
1451
- if (withLeadingSlash === "/") return "/";
1452
- return withLeadingSlash.replace(/\/+$/, "");
1453
- }
1454
- createRoutePattern(path) {
1455
- const segments = path.split("/").filter(Boolean);
1456
- const regexSegments = segments.map((segment) => {
1457
- if (segment.startsWith(":") || segment.startsWith("{") && segment.endsWith("}"))
1458
- return "([^/]+)";
1459
- return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1460
- });
1461
- return new RegExp(`^\\/${regexSegments.join("\\/")}\\/?$`);
1462
1526
  }
1463
1527
  };
1464
1528
  }
1465
1529
  });
1466
1530
 
1467
- // src/infrastructure/services/allow_methods/index.ts
1468
- var init_allow_methods = __esm({
1469
- "src/infrastructure/services/allow_methods/index.ts"() {
1470
- "use strict";
1471
- init_allow_method_service();
1472
- }
1473
- });
1474
-
1475
- // src/infrastructure/services/allow_origins/allow-origin.http.ts
1476
- import { Guards as Guards18 } from "@xeno-js/shared";
1477
- var AllowOrigin;
1478
- var init_allow_origin_http = __esm({
1479
- "src/infrastructure/services/allow_origins/allow-origin.http.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"() {
1480
1536
  "use strict";
1481
- AllowOrigin = class {
1482
- constructor(_list) {
1483
- this._list = _list;
1537
+ SentryLogger = class {
1538
+ constructor(_client, _minLevel) {
1539
+ this._client = _client;
1540
+ this._minLevel = _minLevel;
1484
1541
  }
1485
- _list;
1486
- isAllowed(origin) {
1487
- if (Guards18.isNullOrEmpty(origin)) return true;
1488
- const cleanOrigin = origin.trim().toLowerCase();
1489
- for (const pattern of this._list) {
1490
- const cleanPattern = pattern.trim().toLowerCase();
1491
- if (cleanPattern === "*") return true;
1492
- if (cleanPattern === cleanOrigin) return true;
1493
- if (cleanPattern.startsWith("*.")) {
1494
- const domainSuffix = cleanPattern.substring(1);
1495
- if (cleanOrigin.endsWith(domainSuffix)) {
1496
- const prefix = cleanOrigin.slice(0, cleanOrigin.length - domainSuffix.length);
1497
- if (!Guards18.isNullOrEmpty(prefix) && !prefix.includes(".")) return true;
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");
1498
1553
  }
1499
- }
1554
+ });
1500
1555
  }
1501
- return false;
1502
1556
  }
1503
1557
  };
1504
1558
  }
1505
1559
  });
1506
1560
 
1507
- // src/infrastructure/services/allow_origins/index.ts
1508
- var init_allow_origins = __esm({
1509
- "src/infrastructure/services/allow_origins/index.ts"() {
1561
+ // src/infrastructure/factories/sentry-logger.factory.ts
1562
+ var sentry_logger_factory_exports = {};
1563
+ __export(sentry_logger_factory_exports, {
1564
+ SentryLoggerFactory: () => SentryLoggerFactory
1565
+ });
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"() {
1510
1571
  "use strict";
1511
- init_allow_origin_http();
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
+ };
1512
1598
  }
1513
1599
  });
1514
1600
 
1515
- // src/infrastructure/services/concurrency/p-limit.service.ts
1516
- var PLimitConcurrencyService;
1517
- var init_p_limit_service = __esm({
1518
- "src/infrastructure/services/concurrency/p-limit.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"() {
1519
1606
  "use strict";
1520
- PLimitConcurrencyService = class {
1521
- async executeInParallel(tasks, concurrencyLimit) {
1522
- const { default: pLimit } = await import("p-limit");
1523
- const limit = pLimit(concurrencyLimit);
1524
- const promises = tasks.map((task) => limit(task));
1525
- return Promise.all(promises);
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;
1622
+ }
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;
1641
+ }
1526
1642
  }
1527
1643
  };
1528
1644
  }
1529
1645
  });
1530
1646
 
1531
- // src/infrastructure/services/concurrency/index.ts
1532
- var concurrency_exports = {};
1533
- __export(concurrency_exports, {
1534
- PLimitConcurrencyService: () => PLimitConcurrencyService
1535
- });
1536
- var init_concurrency = __esm({
1537
- "src/infrastructure/services/concurrency/index.ts"() {
1538
- "use strict";
1539
- init_p_limit_service();
1540
- }
1647
+ // src/infrastructure/factories/pino-logger.factory.ts
1648
+ var pino_logger_factory_exports = {};
1649
+ __export(pino_logger_factory_exports, {
1650
+ PinoLoggerFactory: () => PinoLoggerFactory
1541
1651
  });
1542
-
1543
- // src/infrastructure/services/cookies/cookies.service.ts
1544
- import { Guards as Guards19 } from "@xeno-js/shared";
1545
- var CookieHandler;
1546
- var init_cookies_service = __esm({
1547
- "src/infrastructure/services/cookies/cookies.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"() {
1548
1657
  "use strict";
1549
- CookieHandler = class {
1550
- constructor(contextAccessor, _config, _cookieOpts) {
1551
- this.contextAccessor = contextAccessor;
1552
- this._config = _config;
1553
- this._cookieOpts = _cookieOpts;
1554
- }
1555
- contextAccessor;
1556
- _config;
1557
- _cookieOpts;
1558
- getAll() {
1559
- const network = this.contextAccessor.getNetworkContext();
1560
- const req = network?.transport?.req;
1561
- if (!Guards19.isDefined(req) || Guards19.isNullOrEmpty(req.headers.get("cookie"))) return [];
1562
- return req.headers.get("cookie")?.split(";").map((cookie) => {
1563
- const [name, ...rest] = cookie.split("=");
1564
- return { name: name.trim(), value: rest.join("=") };
1565
- }) ?? [];
1566
- }
1567
- setAll(cookies) {
1568
- const network = this.contextAccessor.getNetworkContext();
1569
- const res = network?.transport?.res;
1570
- if (!Guards19.isDefined(res)) return;
1571
- const serializedCookies = cookies.map((c) => this.serialize(c));
1572
- const existingSetCookie = res.headers.getSetCookie();
1573
- res.headers.delete("Set-Cookie");
1574
- for (const cookie of [...existingSetCookie, ...serializedCookies]) {
1575
- res.headers.append("Set-Cookie", cookie);
1576
- }
1577
- }
1578
- serialize(cookie) {
1579
- const safeName = encodeURIComponent(cookie.name);
1580
- const safeValue = encodeURIComponent(cookie.value);
1581
- let str = `${safeName}=${safeValue}`;
1582
- const isProd = this._config.get("NODE_ENV") === "production";
1583
- const defaultOptions = {
1584
- path: this._cookieOpts.path,
1585
- httpOnly: this._cookieOpts.httpOnly,
1586
- secure: this._cookieOpts.secure ?? isProd,
1587
- sameSite: this._cookieOpts.sameSite ?? "Lax"
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
+ }
1588
1676
  };
1589
- const opts = { ...defaultOptions, ...cookie.options ?? {} };
1590
- str += `; Path=${opts.path}`;
1591
- if (Guards19.isDefined(opts.maxAge)) str += `; Max-Age=${opts.maxAge}`;
1592
- if (Guards19.isDefined(opts.domain)) str += `; Domain=${opts.domain}`;
1593
- if (Guards19.isDefined(opts.sameSite)) str += `; SameSite=${opts.sameSite}`;
1594
- if (opts.secure) str += `; Secure`;
1595
- if (opts.httpOnly) str += `; HttpOnly`;
1596
- return str;
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
+ );
1692
+ }
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);
1699
+ }
1597
1700
  }
1598
1701
  };
1599
1702
  }
1600
1703
  });
1601
1704
 
1602
- // src/infrastructure/services/cookies/index.ts
1603
- var init_cookies = __esm({
1604
- "src/infrastructure/services/cookies/index.ts"() {
1605
- "use strict";
1606
- init_cookies_service();
1607
- }
1705
+ // src/infrastructure/modules/utils/logger.utils.ts
1706
+ var logger_utils_exports = {};
1707
+ __export(logger_utils_exports, {
1708
+ LoggerUtils: () => LoggerUtils
1608
1709
  });
1609
-
1610
- // src/infrastructure/services/crypto/crypto.service.ts
1611
- var EdgeCryptoService;
1612
- var init_crypto_service = __esm({
1613
- "src/infrastructure/services/crypto/crypto.service.ts"() {
1710
+ var LoggerUtils;
1711
+ var init_logger_utils = __esm({
1712
+ "src/infrastructure/modules/utils/logger.utils.ts"() {
1614
1713
  "use strict";
1615
- EdgeCryptoService = class {
1616
- randomBytes(size) {
1617
- const buffer = new Uint8Array(size);
1618
- crypto.getRandomValues(buffer);
1619
- return buffer;
1620
- }
1621
- async hmacSha256(secret, data) {
1622
- const encoder = new TextEncoder();
1623
- const keyData = encoder.encode(secret);
1624
- const messageData = encoder.encode(data);
1625
- const cryptoKey = await crypto.subtle.importKey(
1626
- "raw",
1627
- keyData,
1628
- { name: "HMAC", hash: "SHA-256" },
1629
- false,
1630
- ["sign"]
1631
- );
1632
- const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
1633
- return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1634
- }
1635
- timingSafeEqual(a, b) {
1636
- if (a.length !== b.length) {
1637
- return false;
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));
1638
1733
  }
1639
- let mismatch = 0;
1640
- for (let i = 0; i < a.length; i++) {
1641
- mismatch |= a[i] ^ b[i];
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
+ }
1642
1749
  }
1643
- return mismatch === 0;
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
+ });
1644
1755
  }
1645
- };
1756
+ });
1646
1757
  }
1647
1758
  });
1648
1759
 
1649
- // src/infrastructure/services/crypto/index.ts
1650
- var init_crypto = __esm({
1651
- "src/infrastructure/services/crypto/index.ts"() {
1760
+ // src/infrastructure/cache/inmemory.cache.ts
1761
+ var inmemory_cache_exports = {};
1762
+ __export(inmemory_cache_exports, {
1763
+ InMemoryCacheExtended: () => InMemoryCacheExtended
1764
+ });
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"() {
1652
1769
  "use strict";
1653
- init_crypto_service();
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;
1777
+ }
1778
+ };
1654
1779
  }
1655
1780
  });
1656
1781
 
1657
- // src/infrastructure/services/csrf/csrf-token.service.ts
1658
- import { Guards as Guards20 } from "@xeno-js/shared";
1659
- var CsrfTokenService;
1660
- var init_csrf_token_service = __esm({
1661
- "src/infrastructure/services/csrf/csrf-token.service.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"() {
1662
1787
  "use strict";
1663
- CsrfTokenService = class {
1664
- constructor(_secret, _cryptoService) {
1665
- this._secret = _secret;
1666
- this._cryptoService = _cryptoService;
1788
+ RedisCache = class {
1789
+ /**
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.
1792
+
1793
+ *
1794
+ * @author Xeno
1795
+ * @version 1.0.0
1796
+ * @since 2025-09-30
1797
+ * @link https://github.com/xeno-js/xeno-js
1798
+ */
1799
+ constructor(_redisClient) {
1800
+ this._redisClient = _redisClient;
1667
1801
  }
1668
- _secret;
1669
- _cryptoService;
1670
- async generate(subject) {
1671
- const randomBuffer = this._cryptoService.randomBytes(32);
1672
- const nonce = btoa(String.fromCharCode(...randomBuffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1673
- const signature = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1674
- return `${nonce}.${signature}`;
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;
1675
1809
  }
1676
- async validate(token, subject) {
1677
- const separatorIndex = token.indexOf(".");
1678
- if (separatorIndex <= 0) return false;
1679
- const nonce = token.slice(0, separatorIndex);
1680
- const signature = token.slice(separatorIndex + 1);
1681
- if (Guards20.isNullOrEmpty(nonce) || Guards20.isNullOrEmpty(signature)) return false;
1682
- const expected = await this._cryptoService.hmacSha256(this._secret, `${subject}.${nonce}`);
1683
- const encoder = new TextEncoder();
1684
- const actualBuffer = encoder.encode(signature);
1685
- const expectedBuffer = encoder.encode(expected);
1686
- if (actualBuffer.length !== expectedBuffer.length) return false;
1687
- return this._cryptoService.timingSafeEqual(actualBuffer, expectedBuffer);
1810
+ async get(key) {
1811
+ const value = await this._redisClient.get(key);
1812
+ if (!Guards24.isDefined(value)) {
1813
+ return void 0;
1814
+ }
1815
+ return JSON.parse(value);
1816
+ }
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);
1821
+ }
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";
1827
+ }
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;
1834
+ }
1835
+ async clear() {
1836
+ await this._redisClient.flushdb();
1688
1837
  }
1689
1838
  };
1690
1839
  }
1691
1840
  });
1692
1841
 
1693
- // src/infrastructure/services/csrf/index.ts
1694
- var init_csrf = __esm({
1695
- "src/infrastructure/services/csrf/index.ts"() {
1696
- "use strict";
1697
- init_csrf_token_service();
1698
- }
1842
+ // src/infrastructure/factories/redis-cache.factory.ts
1843
+ var redis_cache_factory_exports = {};
1844
+ __export(redis_cache_factory_exports, {
1845
+ RedisCacheFactory: () => RedisCacheFactory
1699
1846
  });
1700
-
1701
- // src/infrastructure/services/extractors/extract-bearer.extractor.ts
1702
- import { Guards as Guards21 } from "@xeno-js/shared";
1703
- var BearerTokenExtractor;
1704
- var init_extract_bearer_extractor = __esm({
1705
- "src/infrastructure/services/extractors/extract-bearer.extractor.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"() {
1706
1852
  "use strict";
1707
- BearerTokenExtractor = class {
1708
- constructor(_cookiePrefix) {
1709
- this._cookiePrefix = _cookiePrefix;
1710
- }
1711
- _cookiePrefix;
1712
- extract(headers) {
1713
- const authHeader = headers.get("Authorization");
1714
- if (Guards21.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1715
- return authHeader.substring(7);
1716
- }
1717
- const cookieHeader = headers.get("cookie");
1718
- if (Guards21.isDefined(cookieHeader)) {
1719
- const regex = new RegExp(`${this._cookiePrefix}=([^;]+)`);
1720
- const match = regex.exec(cookieHeader);
1721
- if (!Guards21.isNullOrEmpty(match) && Guards21.isDefined(match[1])) {
1722
- return match[1].trim();
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;
1723
1870
  }
1871
+ };
1872
+ if (Guards25.isDefined(password)) {
1873
+ redisOptions.password = password;
1724
1874
  }
1725
- return void 0;
1875
+ if (Guards25.isDefined(username)) {
1876
+ redisOptions.username = username;
1877
+ }
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);
1726
1886
  }
1727
1887
  };
1728
1888
  }
1729
1889
  });
1730
1890
 
1731
- // src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts
1732
- import { Guards as Guards22, StringHelper } from "@xeno-js/shared";
1733
- var SupabaseSsrTokenExtractor;
1734
- var init_extract_ssr_bearer_extractor = __esm({
1735
- "src/infrastructure/services/extractors/extract-ssr-bearer.extractor.ts"() {
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"() {
1736
1899
  "use strict";
1737
- SupabaseSsrTokenExtractor = class {
1738
- extract(headers) {
1739
- const authHeader = headers.get("authorization");
1740
- if (Guards22.isDefined(authHeader) && authHeader.toLowerCase().startsWith("bearer ")) {
1741
- return authHeader.substring(7);
1742
- }
1743
- const cookieHeader = headers.get("cookie");
1744
- if (Guards22.isNullOrEmpty(cookieHeader)) return void 0;
1745
- const cookies = cookieHeader.split(";").map((c) => c.trim());
1746
- const tokenChunks = {};
1747
- let unchunkedToken;
1748
- for (const cookie of cookies) {
1749
- const [name, ...rest] = cookie.split("=");
1750
- if (!Guards22.isDefined(name) || Guards22.isNullOrEmpty(rest)) continue;
1751
- const value = decodeURIComponent(rest.join("="));
1752
- if (Guards22.isDefined(/^sb-[a-z0-9]+-auth-token$/.exec(name))) {
1753
- unchunkedToken = value;
1754
- } else {
1755
- const match = /^sb-[a-z0-9]+-auth-token\.(\d+)$/.exec(name);
1756
- if (Guards22.isDefined(match)) tokenChunks[parseInt(match[1], 10)] = value;
1757
- }
1900
+ CacheUtils = Object.freeze({
1901
+ /**
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
+ *
1907
+ * @author Xeno
1908
+ * @version 1.0.0
1909
+ * @since 2025-09-30
1910
+ * @link https://github.com/xeno-js/xeno-js
1911
+ */
1912
+ async addCache(container, opts) {
1913
+ const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
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
+ );
1758
1918
  }
1759
- let fullTokenString = unchunkedToken;
1760
- if (!Guards22.isDefined(fullTokenString) && Object.keys(tokenChunks).length > 0) {
1761
- const indices = Object.keys(tokenChunks).map(Number).sort((a, b) => a - b);
1762
- fullTokenString = indices.map((i) => tokenChunks[i]).join("");
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;
1763
1928
  }
1764
- if (Guards22.isNullOrEmpty(fullTokenString)) return void 0;
1765
- try {
1766
- const parsed = StringHelper.safeParse(fullTokenString);
1767
- if (Guards22.isDefined(parsed) && Guards22.isObject(parsed) && "access_token" in parsed) {
1768
- const accessToken = parsed["access_token"];
1769
- if (Guards22.isString(accessToken)) return accessToken;
1770
- }
1771
- } catch {
1772
- return void 0;
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);
1934
+ });
1773
1935
  }
1774
1936
  }
1775
- };
1937
+ });
1776
1938
  }
1777
1939
  });
1778
1940
 
1779
- // src/infrastructure/services/extractors/http-cookie.extractor.ts
1780
- import { Guards as Guards23 } from "@xeno-js/shared";
1781
- var HttpCookieExtractor;
1782
- var init_http_cookie_extractor = __esm({
1783
- "src/infrastructure/services/extractors/http-cookie.extractor.ts"() {
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"() {
1784
1946
  "use strict";
1785
- HttpCookieExtractor = class {
1786
- extract(cookie) {
1787
- if (!Guards23.isDefined(cookie.header)) return void 0;
1788
- for (const rawCookie of cookie.header.split(";")) {
1789
- const separatorIndex = rawCookie.indexOf("=");
1790
- if (separatorIndex <= 0) continue;
1791
- const name = rawCookie.slice(0, separatorIndex).trim();
1792
- if (name !== cookie.name) continue;
1793
- const value = rawCookie.slice(separatorIndex + 1).trim();
1794
- try {
1795
- return decodeURIComponent(value);
1796
- } catch {
1797
- return void 0;
1798
- }
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);
1799
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;
1800
1977
  return void 0;
1801
1978
  }
1802
- };
1803
- }
1804
- });
1805
-
1806
- // src/infrastructure/services/extractors/http-header.extractor.ts
1807
- import { Guards as Guards24, GuidHelper as GuidHelper4, HttpHelper, MathHelper } from "@xeno-js/shared";
1808
- var HttpHeaderExtractor;
1809
- var init_http_header_extractor = __esm({
1810
- "src/infrastructure/services/extractors/http-header.extractor.ts"() {
1811
- "use strict";
1812
- HttpHeaderExtractor = class {
1813
- /**
1814
- * @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.
1815
-
1816
- *
1817
- * @author Xeno
1818
- * @version 1.0.0
1819
- * @since 2025-09-30
1820
- * @link https://github.com/xeno-js/xeno-js
1821
- */
1822
- constructor(_bearerExtractor, _cookieExtractor, _trustedIp, _cookieName) {
1823
- this._bearerExtractor = _bearerExtractor;
1824
- this._cookieExtractor = _cookieExtractor;
1825
- this._trustedIp = _trustedIp;
1826
- this._cookieName = _cookieName;
1979
+ isDynamicPath(path) {
1980
+ return path.includes(":") || path.includes("{") && path.includes("}");
1827
1981
  }
1828
- _bearerExtractor;
1829
- _cookieExtractor;
1830
- _trustedIp;
1831
- _cookieName;
1832
- extract(headers) {
1833
- const correlationId = GuidHelper4.parse(headers.get("x-correlation-id") ?? void 0);
1834
- const requestId = GuidHelper4.parse(headers.get("x-request-id") ?? void 0);
1835
- const token = this._bearerExtractor.extract(headers);
1836
- const clientIp = headers.get(this._trustedIp?.toLowerCase() ?? "x-forwarded-for") ?? headers.get("x-real-ip") ?? void 0;
1837
- const spanId = GuidHelper4.parse(headers.get("x-span-id") ?? void 0);
1838
- const parentSpanId = headers.get("x-parent-span-id") ?? void 0;
1839
- const acceptHeader = headers.get("accept");
1840
- const contentTypeHeader = headers.get("content-type");
1841
- const userAgent = headers.get("user-agent") ?? void 0;
1842
- const returnAddress = headers.get("x-return-address") ?? void 0;
1843
- const sequenceId = headers.get("x-sequence-id") ?? void 0;
1844
- const position = headers.get("x-sequence-position");
1845
- const size = headers.get("x-sequence-size");
1846
- const expiration = headers.get("x-expiration");
1847
- const csrf = headers.get("x-csrf-token") ?? void 0;
1848
- const cookieHeader = headers.get("cookie") ?? void 0;
1849
- const csrfCookie = this._cookieExtractor.extract({
1850
- header: cookieHeader,
1851
- name: this._cookieName
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, "\\$&");
1852
1994
  });
1853
- const origin = headers.get("origin") ?? void 0;
1854
- const cleanOrigin = HttpHelper.sanitizeOriginUrl(origin);
1855
- const referer = headers.get("referer") ?? void 0;
1856
- const cleanReferer = HttpHelper.sanitizeOriginUrl(referer);
1857
- const accept = acceptHeader === "*/*" ? void 0 : acceptHeader;
1858
- const formatIndicator = accept ?? contentTypeHeader ?? "application/json";
1859
- const metadata = {
1860
- correlationId,
1861
- requestId,
1862
- token,
1863
- clientIp,
1864
- spanId,
1865
- parentSpanId,
1866
- formatIndicator,
1867
- userAgent,
1868
- returnAddress,
1869
- csrf,
1870
- csrfCookie,
1871
- origin: cleanOrigin,
1872
- referer: cleanReferer,
1873
- sequence: {
1874
- sequenceId,
1875
- position: Guards24.isDefined(position) ? MathHelper.toNumber(position) : void 0,
1876
- size: Guards24.isDefined(size) ? MathHelper.toNumber(size) : void 0
1877
- },
1878
- expiration: Guards24.isDefined(expiration) ? MathHelper.toNumber(expiration) : void 0
1879
- };
1880
- return metadata;
1995
+ return new RegExp(`^\\/${regexSegments.join("\\/")}\\/?$`);
1881
1996
  }
1882
1997
  };
1883
1998
  }
1884
1999
  });
1885
2000
 
1886
- // src/infrastructure/services/extractors/index.ts
1887
- var init_extractors = __esm({
1888
- "src/infrastructure/services/extractors/index.ts"() {
2001
+ // src/infrastructure/services/allow_methods/index.ts
2002
+ var init_allow_methods = __esm({
2003
+ "src/infrastructure/services/allow_methods/index.ts"() {
1889
2004
  "use strict";
1890
- init_extract_bearer_extractor();
1891
- init_extract_ssr_bearer_extractor();
1892
- init_http_cookie_extractor();
1893
- init_http_header_extractor();
2005
+ init_allow_method_service();
1894
2006
  }
1895
2007
  });
1896
2008
 
1897
- // src/infrastructure/services/resiliences/resilience.service.ts
1898
- import { AppError as AppError11 } from "@xeno-js/shared";
1899
- var ServiceResilience;
1900
- var init_resilience_service = __esm({
1901
- "src/infrastructure/services/resiliences/resilience.service.ts"() {
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"() {
1902
2014
  "use strict";
1903
- ServiceResilience = class {
1904
- constructor(policy) {
1905
- this.policy = policy;
2015
+ AllowOrigin = class {
2016
+ constructor(_list) {
2017
+ this._list = _list;
1906
2018
  }
1907
- policy;
1908
- async execute(operation, signal) {
1909
- AppError11.throwIfAborted(signal, "ServiceResilience.execute");
1910
- return this.policy.execute(() => operation(), signal);
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
+ }
2034
+ }
2035
+ return false;
1911
2036
  }
1912
2037
  };
1913
2038
  }
1914
2039
  });
1915
2040
 
1916
- // src/infrastructure/services/resiliences/index.ts
1917
- var init_resiliences = __esm({
1918
- "src/infrastructure/services/resiliences/index.ts"() {
2041
+ // src/infrastructure/services/allow_origins/index.ts
2042
+ var init_allow_origins = __esm({
2043
+ "src/infrastructure/services/allow_origins/index.ts"() {
1919
2044
  "use strict";
1920
- init_resilience_service();
2045
+ init_allow_origin_http();
1921
2046
  }
1922
2047
  });
1923
2048
 
1924
- // src/infrastructure/services/resolver/utils/socket.utils.ts
1925
- import { Guards as Guards25 } from "@xeno-js/shared";
1926
- var SocketIpExtractor;
1927
- var init_socket_utils = __esm({
1928
- "src/infrastructure/services/resolver/utils/socket.utils.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"() {
1929
2053
  "use strict";
1930
- SocketIpExtractor = Object.freeze({
1931
- /**
1932
- * @description Extracts the IP address of the remote socket from an incoming request.
1933
- * @param req The incoming request object.
1934
- * @returns The IP address of the remote socket, or undefined if not available.
1935
- */
1936
- extract(req) {
1937
- if (Guards25.isDefined(req) && Guards25.isObject(req)) {
1938
- const candidate = req;
1939
- return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
1940
- }
1941
- return void 0;
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);
1942
2060
  }
1943
- });
2061
+ };
1944
2062
  }
1945
2063
  });
1946
2064
 
1947
- // src/infrastructure/services/resolver/utils/index.ts
1948
- var init_utils = __esm({
1949
- "src/infrastructure/services/resolver/utils/index.ts"() {
2065
+ // src/infrastructure/services/concurrency/index.ts
2066
+ var concurrency_exports = {};
2067
+ __export(concurrency_exports, {
2068
+ PLimitConcurrencyService: () => PLimitConcurrencyService
2069
+ });
2070
+ var init_concurrency = __esm({
2071
+ "src/infrastructure/services/concurrency/index.ts"() {
1950
2072
  "use strict";
1951
- init_socket_utils();
2073
+ init_p_limit_service();
1952
2074
  }
1953
2075
  });
1954
2076
 
1955
- // src/infrastructure/services/resolver/client-ip.resolver.ts
1956
- import { Guards as Guards26 } from "@xeno-js/shared";
1957
- var ClientIpResolver;
1958
- var init_client_ip_resolver = __esm({
1959
- "src/infrastructure/services/resolver/client-ip.resolver.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"() {
1960
2082
  "use strict";
1961
- init_utils();
1962
- ClientIpResolver = class {
1963
- constructor(_trustedProxies = []) {
1964
- this._trustedProxies = _trustedProxies;
2083
+ CookieHandler = class {
2084
+ constructor(contextAccessor, _config, _cookieOpts) {
2085
+ this.contextAccessor = contextAccessor;
2086
+ this._config = _config;
2087
+ this._cookieOpts = _cookieOpts;
1965
2088
  }
1966
- _trustedProxies;
1967
- resolve(req, clientIp) {
1968
- const socketIp = SocketIpExtractor.extract(req);
1969
- if (!Guards26.isDefined(socketIp))
1970
- return !Guards26.isNullOrEmpty(clientIp) ? clientIp.split(",")[0].trim() : void 0;
1971
- const isTrustedProxy = this._trustedProxies.includes(socketIp);
1972
- if (!isTrustedProxy) return socketIp;
1973
- if (Guards26.isDefined(clientIp)) return clientIp.split(",")[0].trim();
1974
- return socketIp;
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);
2110
+ }
2111
+ }
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;
1975
2131
  }
1976
2132
  };
1977
2133
  }
1978
2134
  });
1979
2135
 
1980
- // src/infrastructure/services/resolver/index.ts
1981
- var init_resolver = __esm({
1982
- "src/infrastructure/services/resolver/index.ts"() {
2136
+ // src/infrastructure/services/cookies/index.ts
2137
+ var init_cookies = __esm({
2138
+ "src/infrastructure/services/cookies/index.ts"() {
1983
2139
  "use strict";
1984
- init_client_ip_resolver();
2140
+ init_cookies_service();
1985
2141
  }
1986
2142
  });
1987
2143
 
1988
- // src/infrastructure/services/index.ts
1989
- var services_exports = {};
1990
- __export(services_exports, {
1991
- AllowMethodRegistry: () => AllowMethodRegistry,
1992
- AllowOrigin: () => AllowOrigin,
1993
- BearerTokenExtractor: () => BearerTokenExtractor,
1994
- ClientIpResolver: () => ClientIpResolver,
1995
- CookieHandler: () => CookieHandler,
1996
- CsrfTokenService: () => CsrfTokenService,
1997
- EdgeCryptoService: () => EdgeCryptoService,
1998
- HttpCookieExtractor: () => HttpCookieExtractor,
1999
- HttpHeaderExtractor: () => HttpHeaderExtractor,
2000
- PLimitConcurrencyService: () => PLimitConcurrencyService,
2001
- ServiceResilience: () => ServiceResilience,
2002
- SupabaseSsrTokenExtractor: () => SupabaseSsrTokenExtractor
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"() {
2148
+ "use strict";
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;
2172
+ }
2173
+ let mismatch = 0;
2174
+ for (let i = 0; i < a.length; i++) {
2175
+ mismatch |= a[i] ^ b[i];
2176
+ }
2177
+ return mismatch === 0;
2178
+ }
2179
+ };
2180
+ }
2003
2181
  });
2004
- var init_services = __esm({
2005
- "src/infrastructure/services/index.ts"() {
2182
+
2183
+ // src/infrastructure/services/crypto/index.ts
2184
+ var init_crypto = __esm({
2185
+ "src/infrastructure/services/crypto/index.ts"() {
2006
2186
  "use strict";
2007
- init_allow_methods();
2008
- init_allow_origins();
2009
- init_concurrency();
2010
- init_cookies();
2011
- init_crypto();
2012
- init_csrf();
2013
- init_extractors();
2014
- init_resiliences();
2015
- init_resolver();
2187
+ init_crypto_service();
2016
2188
  }
2017
2189
  });
2018
2190
 
2019
- // src/infrastructure/factories/supabase.factory.ts
2020
- var supabase_factory_exports = {};
2021
- __export(supabase_factory_exports, {
2022
- SupabaseServerAuthFactory: () => SupabaseServerAuthFactory
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);
2222
+ }
2223
+ };
2224
+ }
2023
2225
  });
2024
- import { createServerClient } from "@supabase/ssr";
2025
- import { Guards as Guards27, TOKENS as TOKENS3 } from "@xeno-js/shared";
2026
- import {
2027
- SupabaseAuthService,
2028
- SupabaseClaimsMapper,
2029
- SupabaseSessionMapper
2030
- } from "@xeno-js/shared/supabase";
2031
- var SupabaseServerAuthFactory;
2032
- var init_supabase_factory = __esm({
2033
- "src/infrastructure/factories/supabase.factory.ts"() {
2226
+
2227
+ // src/infrastructure/services/csrf/index.ts
2228
+ var init_csrf = __esm({
2229
+ "src/infrastructure/services/csrf/index.ts"() {
2034
2230
  "use strict";
2035
- init_services();
2036
- SupabaseServerAuthFactory = class {
2037
- create({
2038
- config,
2039
- container
2040
- }) {
2041
- const cookieService = this._getCookieSsr(config.ssrOpts, container, config.cookieOpts);
2042
- const client = createServerClient(config.url, config.key, {
2043
- ...config.opts,
2044
- cookies: {
2045
- getAll() {
2046
- return cookieService.getAll();
2047
- },
2048
- setAll(cookiesToSet) {
2049
- cookieService.setAll(cookiesToSet);
2050
- }
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();
2051
2257
  }
2052
- });
2053
- const mapper = new SupabaseClaimsMapper();
2054
- const sessionMapper = new SupabaseSessionMapper(mapper);
2055
- return new SupabaseAuthService(client, mapper, sessionMapper, config);
2258
+ }
2259
+ return void 0;
2056
2260
  }
2057
- _getCookieSsr(ssrOpts, container, config) {
2058
- if (Guards27.isDefined(ssrOpts)) {
2059
- return ssrOpts(container);
2060
- } else {
2061
- return new CookieHandler(
2062
- container.resolve(TOKENS3.NETWORK_CONTEXT_ACCESSOR),
2063
- container.resolve(TOKENS3.CONFIGURATION_SERVICE),
2064
- config
2065
- );
2261
+ };
2262
+ }
2263
+ });
2264
+
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"() {
2270
+ "use strict";
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;
2066
2307
  }
2067
2308
  }
2068
2309
  };
2069
2310
  }
2070
2311
  });
2071
2312
 
2072
- // src/infrastructure/modules/utils/auth.utils.ts
2073
- var auth_utils_exports = {};
2074
- __export(auth_utils_exports, {
2075
- AuthUtils: () => AuthUtils
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"() {
2318
+ "use strict";
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;
2335
+ }
2336
+ };
2337
+ }
2076
2338
  });
2077
- var AuthUtils;
2078
- var init_auth_utils = __esm({
2079
- "src/infrastructure/modules/utils/auth.utils.ts"() {
2339
+
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"() {
2080
2345
  "use strict";
2081
- AuthUtils = Object.freeze({
2346
+ HttpHeaderExtractor = class {
2082
2347
  /**
2083
- * @description Checks if the provided authorization configuration requires any authorization strategies.
2084
- * @param authorizationConfig The authorization configuration to check.
2085
- * @returns True if any authorization strategies are required, false otherwise.
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.
2086
2349
 
2087
2350
  *
2088
2351
  * @author Xeno
@@ -2090,841 +2353,365 @@ var init_auth_utils = __esm({
2090
2353
  * @since 2025-09-30
2091
2354
  * @link https://github.com/xeno-js/xeno-js
2092
2355
  */
2093
- async addAuthZ(container, opts) {
2094
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2095
- const strategies = [];
2096
- const { Guards: Guards51 } = await import("@xeno-js/shared");
2097
- if (Guards51.isDefined(opts.policies)) {
2098
- const { PolicyRegistry: PolicyRegistry2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2099
- const policyRegistry = opts.policies;
2100
- const registryInstance = new PolicyRegistry2();
2101
- const ctxAccessor = container.resolve(TOKENS5.CONTEXT_ACCESSOR);
2102
- const Policies = /* @__PURE__ */ new Set();
2103
- for (const [intent, policy] of Object.entries(policyRegistry)) {
2104
- const intentLower = intent.toLowerCase();
2105
- registryInstance.addPolicy(intentLower, policy);
2106
- if (!Guards51.isNullOrEmpty(policy.roles)) {
2107
- Policies.add("roles");
2108
- }
2109
- if (!Guards51.isNullOrEmpty(policy.permissions)) {
2110
- Policies.add("permissions");
2111
- }
2112
- if (!Guards51.isNullOrEmpty(policy.userId)) {
2113
- Policies.add("userId");
2114
- }
2115
- if (!Guards51.isNullOrEmpty(policy.tenantId)) {
2116
- Policies.add("tenantId");
2117
- }
2118
- }
2119
- if (Policies.has("roles")) {
2120
- const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2121
- strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2122
- }
2123
- if (Policies.has("permissions")) {
2124
- const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2125
- strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2126
- }
2127
- if (Policies.has("userId")) {
2128
- const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2129
- strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2130
- }
2131
- if (Policies.has("tenantId")) {
2132
- const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2133
- strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2134
- }
2135
- }
2136
- if (!Guards51.isNullOrEmpty(opts.customAuthorizationStrategy)) {
2137
- const customStrategies = opts.customAuthorizationStrategy;
2138
- customStrategies.forEach((strategyToken) => {
2139
- if (Guards51.isDefined(strategyToken)) {
2140
- strategies.push(strategyToken(container));
2141
- }
2142
- });
2143
- }
2144
- const { AuthorizationPipeline: AuthorizationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2145
- return new AuthorizationPipeline2(strategies);
2146
- },
2147
- /**
2148
- * @description Configures the authentication service and gatekeeper in the service container.
2149
- * @param container The service container to configure.
2150
- * @param opts The authentication configuration options.
2151
-
2152
- *
2153
- * @author Xeno
2154
- * @version 1.0.0
2155
- * @since 2025-09-30
2156
- * @link https://github.com/xeno-js/xeno-js
2157
- */
2158
- async addAuthN(container, opts) {
2159
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2160
- if (Guards51.isDefined(opts.customAuth)) {
2161
- const authService = opts.customAuth.authExtendedService();
2162
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2163
- return authService;
2164
- });
2165
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2166
- return authService;
2167
- });
2168
- } else {
2169
- const { SupabaseServerAuthFactory: SupabaseServerAuthFactory2 } = await Promise.resolve().then(() => (init_supabase_factory(), supabase_factory_exports));
2170
- const factory = new SupabaseServerAuthFactory2();
2171
- const supabase = factory.create({ config: opts, container });
2172
- container.addScoped(TOKENS5.AUTH_SERVICE, () => {
2173
- return supabase;
2174
- });
2175
- container.addSingleton(TOKENS5.BASE_AUTH_SERVICE, () => {
2176
- return supabase;
2177
- });
2178
- }
2356
+ constructor(_bearerExtractor, _cookieExtractor, _trustedIp, _cookieName) {
2357
+ this._bearerExtractor = _bearerExtractor;
2358
+ this._cookieExtractor = _cookieExtractor;
2359
+ this._trustedIp = _trustedIp;
2360
+ this._cookieName = _cookieName;
2179
2361
  }
2180
- });
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
2386
+ });
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;
2415
+ }
2416
+ };
2181
2417
  }
2182
2418
  });
2183
2419
 
2184
- // src/infrastructure/factories/zod-validator.factory.ts
2185
- var zod_validator_factory_exports = {};
2186
- __export(zod_validator_factory_exports, {
2187
- ZodValidatorFactory: () => ZodValidatorFactory
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
+ }
2188
2429
  });
2189
- import { ZodValidatorService } from "@xeno-js/shared/zod";
2190
- var ZodValidatorFactory;
2191
- var init_zod_validator_factory = __esm({
2192
- "src/infrastructure/factories/zod-validator.factory.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"() {
2193
2436
  "use strict";
2194
- ZodValidatorFactory = class {
2195
- create(opts) {
2196
- const validatorService = new ZodValidatorService(/* @__PURE__ */ new Map(), opts.logger);
2197
- for (const [intentKey, schema] of Object.entries(opts.schemas)) {
2198
- validatorService.addSchema(intentKey, schema);
2199
- }
2200
- return validatorService;
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);
2201
2445
  }
2202
2446
  };
2203
2447
  }
2204
2448
  });
2205
2449
 
2206
- // src/infrastructure/modules/utils/validation.utils.ts
2207
- var validation_utils_exports = {};
2208
- __export(validation_utils_exports, {
2209
- ValidationUtils: () => ValidationUtils
2450
+ // src/infrastructure/services/resiliences/index.ts
2451
+ var init_resiliences = __esm({
2452
+ "src/infrastructure/services/resiliences/index.ts"() {
2453
+ "use strict";
2454
+ init_resilience_service();
2455
+ }
2210
2456
  });
2211
- var ValidationUtils;
2212
- var init_validation_utils = __esm({
2213
- "src/infrastructure/modules/utils/validation.utils.ts"() {
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"() {
2214
2463
  "use strict";
2215
- ValidationUtils = Object.freeze({
2464
+ SocketIpExtractor = Object.freeze({
2216
2465
  /**
2217
- * @description Checks if the provided validation configuration requires any validation strategies.
2218
- * @param validationConfig The validation configuration to check.
2219
- * @returns True if any validation strategies are required, false otherwise.
2220
- *
2221
- * @author Xeno
2222
- * @version 1.0.0
2223
- * @since 2025-09-30
2224
- * @link https://github.com/xeno-js/xeno-js
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.
2225
2469
  */
2226
- async addValidation(container, opts, logger) {
2227
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2228
- if (!Guards51.isDefined(opts.zod) && Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
2229
- return;
2230
- }
2231
- const validationStrategies = [];
2232
- if (Guards51.isDefined(opts.zod)) {
2233
- const config = opts.zod;
2234
- const { ZodValidatorFactory: ZodValidatorFactory2 } = await Promise.resolve().then(() => (init_zod_validator_factory(), zod_validator_factory_exports));
2235
- const { SchemaValidationStrategy: SchemaValidationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2236
- const validatorService = new ZodValidatorFactory2().create({ ...config, logger });
2237
- container.addSingleton(TOKENS5.VALIDATOR_SERVICE, () => validatorService);
2238
- validationStrategies.push(new SchemaValidationStrategy2(validatorService));
2239
- }
2240
- if (!Guards51.isNullOrEmpty(opts.customValidationStrategy)) {
2241
- for (const strategyToken of opts.customValidationStrategy) {
2242
- if (Guards51.isDefined(strategyToken)) validationStrategies.push(strategyToken(container));
2243
- }
2470
+ extract(req) {
2471
+ if (Guards34.isDefined(req) && Guards34.isObject(req)) {
2472
+ const candidate = req;
2473
+ return candidate.socket?.remoteAddress ?? candidate.connection?.remoteAddress;
2244
2474
  }
2245
- const { ValidationPipeline: ValidationPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2246
- return new ValidationPipeline2(validationStrategies);
2475
+ return void 0;
2247
2476
  }
2248
2477
  });
2249
2478
  }
2250
2479
  });
2251
2480
 
2252
- // src/infrastructure/idempotency/idempotency-store.ts
2253
- import { IDEMPOTENCY_CONSTANTS as IDEMPOTENCY_CONSTANTS2 } from "@xeno-js/shared";
2254
- var IdempotencyStore;
2255
- var init_idempotency_store = __esm({
2256
- "src/infrastructure/idempotency/idempotency-store.ts"() {
2481
+ // src/infrastructure/services/resolver/utils/index.ts
2482
+ var init_utils = __esm({
2483
+ "src/infrastructure/services/resolver/utils/index.ts"() {
2257
2484
  "use strict";
2258
- IdempotencyStore = class {
2259
- /**
2260
- * @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.
2261
- * @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.
2262
- * @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.
2263
-
2264
- *
2265
- * @author Xeno
2266
- * @version 1.0.0
2267
- * @since 2025-09-30
2268
- * @link https://github.com/xeno-js/xeno-js
2269
- */
2270
- constructor(_cache, _cacheKeyBuilder) {
2271
- this._cache = _cache;
2272
- this._cacheKeyBuilder = _cacheKeyBuilder;
2485
+ init_socket_utils();
2486
+ }
2487
+ });
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"() {
2494
+ "use strict";
2495
+ init_utils();
2496
+ ClientIpResolver = class {
2497
+ constructor(_trustedProxies = []) {
2498
+ this._trustedProxies = _trustedProxies;
2273
2499
  }
2274
- _cache;
2275
- _cacheKeyBuilder;
2276
- async acquireLock(requestId, ttlSeconds) {
2277
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${requestId}`);
2278
- return await this._cache.setIfAbsent(
2279
- `${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`,
2280
- IDEMPOTENCY_CONSTANTS2.LOCKED_VALUE,
2281
- ttlSeconds
2282
- );
2283
- }
2284
- async hasBeenProcessed(commandId) {
2285
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2286
- return await this._cache.has(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
2287
- }
2288
- async markAsProcessed(commandId, payload, ttlSeconds) {
2289
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2290
- await this._cache.set(
2291
- `${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`,
2292
- payload,
2293
- ttlSeconds
2294
- );
2295
- }
2296
- async getPayload(commandId) {
2297
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2298
- const payload = await this._cache.get(`${IDEMPOTENCY_CONSTANTS2.PROCESSED_KEY_PREFIX}${key}`);
2299
- return payload;
2300
- }
2301
- async releaseLock(commandId) {
2302
- const key = this._cacheKeyBuilder.buildContextualKey(`command:${commandId}`);
2303
- await this._cache.remove(`${IDEMPOTENCY_CONSTANTS2.LOCK_KEY_PREFIX}${key}`);
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;
2304
2509
  }
2305
2510
  };
2306
2511
  }
2307
2512
  });
2308
2513
 
2309
- // src/infrastructure/idempotency/index.ts
2310
- var idempotency_exports = {};
2311
- __export(idempotency_exports, {
2312
- IdempotencyStore: () => IdempotencyStore
2313
- });
2314
- var init_idempotency = __esm({
2315
- "src/infrastructure/idempotency/index.ts"() {
2514
+ // src/infrastructure/services/resolver/index.ts
2515
+ var init_resolver = __esm({
2516
+ "src/infrastructure/services/resolver/index.ts"() {
2316
2517
  "use strict";
2317
- init_idempotency_store();
2518
+ init_client_ip_resolver();
2318
2519
  }
2319
2520
  });
2320
2521
 
2321
- // src/infrastructure/modules/utils/pipeline.utils.ts
2322
- var pipeline_utils_exports = {};
2323
- __export(pipeline_utils_exports, {
2324
- PipelineUtils: () => PipelineUtils
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
2325
2537
  });
2326
- var PipelineUtils;
2327
- var init_pipeline_utils = __esm({
2328
- "src/infrastructure/modules/utils/pipeline.utils.ts"() {
2538
+ var init_services = __esm({
2539
+ "src/infrastructure/services/index.ts"() {
2329
2540
  "use strict";
2330
- PipelineUtils = Object.freeze({
2331
- /**
2332
- * @description Checks if the provided command configuration requires any command strategies.
2333
- * @param commandConfig The command configuration to check.
2334
- * @returns True if any command strategies are required, false otherwise.
2335
- *
2336
- * @author Xeno
2337
- * @version 1.0.0
2338
- * @since 2025-09-30
2339
- * @link https://github.com/xeno-js/xeno-js
2340
- */
2341
- async addCommand(container, opts) {
2342
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2343
- const pipelines = [];
2344
- if (Guards51.isDefined(opts.idempotency)) {
2345
- const { IdempotencyStore: IdempotencyStore2 } = await Promise.resolve().then(() => (init_idempotency(), idempotency_exports));
2346
- const imdStore = new IdempotencyStore2(
2347
- container.resolve(TOKENS5.CACHE),
2348
- container.resolve(TOKENS5.CACHE_KEY_BUILDER)
2349
- );
2350
- const { IdempotencyPipeline: IdempotencyPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2351
- const requestContext = container.resolve(TOKENS5.NETWORK_CONTEXT_ACCESSOR);
2352
- const config = opts.idempotency;
2353
- pipelines.push(
2354
- new IdempotencyPipeline2(
2355
- requestContext,
2356
- imdStore,
2357
- config?.lockTtlSeconds,
2358
- config?.processedTtlSeconds
2359
- )
2360
- );
2361
- }
2362
- if (Guards51.isDefined(opts.concurrency)) {
2363
- const { ConcurrencyRetryPipeline: ConcurrencyRetryPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2364
- const config = opts.concurrency;
2365
- pipelines.push(new ConcurrencyRetryPipeline2(config?.maxRetries, config?.delayConfig));
2366
- }
2367
- return pipelines;
2368
- },
2369
- /**
2370
- * @description Checks if the provided query configuration requires any query strategies.
2371
- * @param queryConfig The query configuration to check.
2372
- * @returns True if any query strategies are required, false otherwise.
2373
- *
2374
- * @author Xeno
2375
- * @version 1.0.0
2376
- * @since 2025-09-30
2377
- * @link https://github.com/xeno-js/xeno-js
2378
- */
2379
- async addQuery(container) {
2380
- const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2381
- const { QueryCachingPipeline: QueryCachingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2382
- return new QueryCachingPipeline2(
2383
- container.resolve(TOKENS5.CACHE),
2384
- container.resolve(TOKENS5.CACHE_KEY_BUILDER),
2385
- container.resolve(TOKENS5.LOGGER)
2386
- );
2387
- }
2388
- });
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();
2389
2550
  }
2390
2551
  });
2391
2552
 
2392
- // src/infrastructure/modules/cqrs.module.ts
2393
- var cqrs_module_exports = {};
2394
- __export(cqrs_module_exports, {
2395
- CqrsModule: () => CqrsModule
2553
+ // src/infrastructure/factories/supabase.factory.ts
2554
+ var supabase_factory_exports = {};
2555
+ __export(supabase_factory_exports, {
2556
+ SupabaseServerAuthFactory: () => SupabaseServerAuthFactory
2396
2557
  });
2397
- var CqrsModule;
2398
- var init_cqrs_module = __esm({
2399
- "src/infrastructure/modules/cqrs.module.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"() {
2400
2568
  "use strict";
2401
- CqrsModule = class {
2402
- async configure(container, opts) {
2403
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2404
- const logger = container.resolve(TOKENS5.LOGGER);
2405
- const { Mediator: Mediator2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2406
- container.addSingleton(TOKENS5.MEDIATOR, (c) => {
2407
- const serviceScopeAccessor = c.resolve(TOKENS5.SERVICE_SCOPE_ACCESSOR);
2408
- return new Mediator2(serviceScopeAccessor);
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
+ }
2409
2586
  });
2410
- const { ExceptionPipeline: ExceptionPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2411
- const { LoggingPipeline: LoggingPipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2412
- const { PerformancePipeline: PerformancePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2413
- const thresholdMs = opts.performance?.thresholdMs;
2414
- const pipelines = [
2415
- new ExceptionPipeline2(),
2416
- new LoggingPipeline2(logger),
2417
- new PerformancePipeline2(logger, opts.performance.intentThresholdMs, thresholdMs)
2418
- ];
2419
- if (Guards51.isDefined(opts.authorization.policies) || Guards51.isDefined(opts.authorization.customAuthorizationStrategy)) {
2420
- const { AuthUtils: AuthUtils2 } = await Promise.resolve().then(() => (init_auth_utils(), auth_utils_exports));
2421
- const authPipelines = await AuthUtils2.addAuthZ(container, opts.authorization);
2422
- pipelines.push(authPipelines);
2423
- }
2424
- if (Guards51.isDefined(opts.validation.zod) || Guards51.isDefined(opts.validation.customValidationStrategy)) {
2425
- const { ValidationUtils: ValidationUtils2 } = await Promise.resolve().then(() => (init_validation_utils(), validation_utils_exports));
2426
- const validationPipelines = await ValidationUtils2.addValidation(
2427
- container,
2428
- opts.validation,
2429
- logger
2587
+ const mapper = new SupabaseClaimsMapper();
2588
+ const sessionMapper = new SupabaseSessionMapper(mapper);
2589
+ return new SupabaseAuthService(client, mapper, sessionMapper, config);
2590
+ }
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
2430
2599
  );
2431
- if (Guards51.isDefined(validationPipelines)) pipelines.push(validationPipelines);
2432
- }
2433
- const commandPipelines = [...pipelines];
2434
- const queryPipelines = [...pipelines];
2435
- if (Guards51.isDefined(opts.commandBus.idempotency) || Guards51.isDefined(opts.commandBus.concurrency)) {
2436
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
2437
- const newCommandPipelines = await PipelineUtils2.addCommand(container, opts.commandBus);
2438
- commandPipelines.push(...newCommandPipelines);
2439
- }
2440
- if (opts.queryBus.isEnabled) {
2441
- const { PipelineUtils: PipelineUtils2 } = await Promise.resolve().then(() => (init_pipeline_utils(), pipeline_utils_exports));
2442
- const newQueryPipelines = await PipelineUtils2.addQuery(container);
2443
- queryPipelines.push(newQueryPipelines);
2444
2600
  }
2445
- const { CompositePipeline: CompositePipeline2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2446
- container.addSingleton(TOKENS5.COMMAND_PIPELINES_BEHAVIOR, () => {
2447
- return new CompositePipeline2(commandPipelines);
2448
- });
2449
- container.addSingleton(TOKENS5.QUERY_PIPELINES_BEHAVIOR, () => {
2450
- return new CompositePipeline2(queryPipelines);
2451
- });
2452
- }
2453
- };
2454
- }
2455
- });
2456
-
2457
- // src/infrastructure/factories/sql-light-db-client.factory.ts
2458
- var sql_light_db_client_factory_exports = {};
2459
- __export(sql_light_db_client_factory_exports, {
2460
- DbSqlLiteClientFactory: () => DbSqlLiteClientFactory
2461
- });
2462
- import { createClient } from "@libsql/client";
2463
- import { drizzle } from "drizzle-orm/libsql";
2464
- var DbSqlLiteClientFactory;
2465
- var init_sql_light_db_client_factory = __esm({
2466
- "src/infrastructure/factories/sql-light-db-client.factory.ts"() {
2467
- "use strict";
2468
- DbSqlLiteClientFactory = class {
2469
- create(opts) {
2470
- const client = createClient({ url: opts.connectionString });
2471
- return drizzle({ client });
2472
2601
  }
2473
2602
  };
2474
2603
  }
2475
2604
  });
2476
2605
 
2477
- // src/infrastructure/factories/db-client.factory.ts
2478
- var db_client_factory_exports = {};
2479
- __export(db_client_factory_exports, {
2480
- DbClientFactory: () => DbClientFactory
2481
- });
2482
- import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
2483
- import { Pool } from "pg";
2484
- var DbClientFactory;
2485
- var init_db_client_factory = __esm({
2486
- "src/infrastructure/factories/db-client.factory.ts"() {
2487
- "use strict";
2488
- DbClientFactory = class {
2489
- create(opts) {
2490
- const pool = new Pool({
2491
- connectionString: opts.connectionString
2492
- });
2493
- return drizzle2({ client: pool });
2494
- }
2495
- };
2496
- }
2606
+ // src/infrastructure/modules/utils/auth.utils.ts
2607
+ var auth_utils_exports = {};
2608
+ __export(auth_utils_exports, {
2609
+ AuthUtils: () => AuthUtils
2497
2610
  });
2498
-
2499
- // src/infrastructure/modules/utils/db.utils.ts
2500
- var db_utils_exports = {};
2501
- __export(db_utils_exports, {
2502
- DbUtils: () => DbUtils
2503
- });
2504
- var DbUtils;
2505
- var init_db_utils = __esm({
2506
- "src/infrastructure/modules/utils/db.utils.ts"() {
2611
+ var AuthUtils;
2612
+ var init_auth_utils = __esm({
2613
+ "src/infrastructure/modules/utils/auth.utils.ts"() {
2507
2614
  "use strict";
2508
- DbUtils = Object.freeze({
2615
+ AuthUtils = Object.freeze({
2509
2616
  /**
2510
- * @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.
2511
- *
2512
- * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the SQLite database.
2513
- * @returns A new instance of a database client configured for SQLite, ready for use in the application.
2514
- *
2515
- * @author Xeno
2516
- * @version 1.0.0
2517
- * @since 2025-09-30
2518
- * @link https://github.com/xeno-js/xeno-js
2519
- */
2520
- async addSqlLite(opts) {
2521
- const { DbSqlLiteClientFactory: DbSqlLiteClientFactory2 } = await Promise.resolve().then(() => (init_sql_light_db_client_factory(), sql_light_db_client_factory_exports));
2522
- return new DbSqlLiteClientFactory2().create(opts);
2523
- },
2524
- /**
2525
- * @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.
2526
- * @param opts - The database configuration options, including the connection string and any other relevant settings required for establishing a connection to the database.
2527
- * @returns A new instance of a database client, ready for use in the application.
2528
- * @author Xeno
2529
- * @version 1.0.0
2530
- * @since 2025-09-30
2531
- * @link https://github.com/xeno-js/xeno-js
2532
- */
2533
- async addDbClient(opts) {
2534
- const { DbClientFactory: DbClientFactory2 } = await Promise.resolve().then(() => (init_db_client_factory(), db_client_factory_exports));
2535
- return new DbClientFactory2().create(opts);
2536
- }
2537
- });
2538
- }
2539
- });
2540
-
2541
- // src/infrastructure/transaction/transaction-state.ts
2542
- var transaction_state_exports = {};
2543
- __export(transaction_state_exports, {
2544
- TransactionState: () => TransactionState
2545
- });
2546
- var TransactionState;
2547
- var init_transaction_state = __esm({
2548
- "src/infrastructure/transaction/transaction-state.ts"() {
2549
- "use strict";
2550
- TransactionState = class {
2551
- /**
2552
- * The current state of the transaction, which can be either a specific transaction type or null.
2553
- * @author Xeno
2554
- * @version 1.0.0
2555
- * @since 2025-09-30
2556
- * @link https://github.com/xeno-js/xeno-js
2557
- */
2558
- _state = null;
2559
- /**
2560
- * Creates an instance of TransactionState.
2561
- * @param initialState - The initial state of the transaction, which can be either a specific transaction type or null.
2562
- * @author Xeno
2563
- * @version 1.0.0
2564
- * @since 2025-09-30
2565
- * @link https://github.com/xeno-js/xeno-js
2566
- */
2567
- constructor(initialState = null) {
2568
- this._state = initialState;
2569
- }
2570
- get state() {
2571
- return this._state;
2572
- }
2573
- set state(value) {
2574
- this._state = value;
2575
- }
2576
- };
2577
- }
2578
- });
2579
-
2580
- // src/infrastructure/transaction/unit-of-work.ts
2581
- var unit_of_work_exports = {};
2582
- __export(unit_of_work_exports, {
2583
- UnitOfWork: () => UnitOfWork
2584
- });
2585
- import { AppError as AppError12 } from "@xeno-js/shared";
2586
- import { Guards as Guards28 } from "@xeno-js/shared";
2587
- var UnitOfWork;
2588
- var init_unit_of_work = __esm({
2589
- "src/infrastructure/transaction/unit-of-work.ts"() {
2590
- "use strict";
2591
- UnitOfWork = class {
2592
- /**
2593
- * Creates an instance of UnitOfWork.
2594
- * @param _dbContext - The database context used for managing transactions.
2595
- * @param _ttx - The transaction state, which can be either a specific transaction type or null.
2596
- *
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
+ *
2597
2622
  * @author Xeno
2598
2623
  * @version 1.0.0
2599
2624
  * @since 2025-09-30
2600
- * @link https://github.com/xeno-js/xeno-js
2625
+ * @link https://github.com/xeno-js/xeno-js
2601
2626
  */
2602
- constructor(_dbContext, _ttx) {
2603
- this._dbContext = _dbContext;
2604
- this._ttx = _ttx;
2605
- }
2606
- _dbContext;
2607
- _ttx;
2608
- async runInTransaction(callback, signal) {
2609
- AppError12.throwIfAborted(signal, "UnitOfWork.runInTransaction");
2610
- return this._dbContext.transaction(async (tx) => {
2611
- this._ttx.state = tx;
2612
- try {
2613
- const result = await callback();
2614
- return result;
2615
- } finally {
2616
- this._ttx.state = null;
2617
- }
2618
- });
2619
- }
2620
- async dispose() {
2621
- if (Guards28.isDefined(this._ttx.state)) {
2622
- try {
2623
- if (Guards28.hasMethod(this._ttx.state, "rollback")) {
2624
- await this._ttx.state.rollback();
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");
2625
2642
  }
2626
- } finally {
2627
- this._ttx.state = null;
2628
- }
2629
- }
2630
- }
2631
- };
2632
- }
2633
- });
2634
-
2635
- // src/infrastructure/modules/db.module.ts
2636
- var db_module_exports = {};
2637
- __export(db_module_exports, {
2638
- DbModule: () => DbModule
2639
- });
2640
- var DbModule;
2641
- var init_db_module = __esm({
2642
- "src/infrastructure/modules/db.module.ts"() {
2643
- "use strict";
2644
- DbModule = class {
2645
- async configure(container, opts) {
2646
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
2647
- const { DbUtils: DbUtils2 } = await Promise.resolve().then(() => (init_db_utils(), db_utils_exports));
2648
- const db = opts.enableSqlLite ? await DbUtils2.addSqlLite(opts) : await DbUtils2.addDbClient(opts);
2649
- const { TransactionState: TransactionState2 } = await Promise.resolve().then(() => (init_transaction_state(), transaction_state_exports));
2650
- container.addScoped("TRANSACTION_STATE", () => {
2651
- return new TransactionState2();
2652
- });
2653
- const { UnitOfWork: UnitOfWork2 } = await Promise.resolve().then(() => (init_unit_of_work(), unit_of_work_exports));
2654
- container.addScoped(TOKENS5.UNIT_OF_WORK, (c) => {
2655
- const ttx = c.resolve("TRANSACTION_STATE");
2656
- return new UnitOfWork2(db, ttx);
2657
- });
2658
- container.addScoped(TOKENS5.DB_CONTEXT, (c) => {
2659
- const ttx = c.resolve("TRANSACTION_STATE");
2660
- return new Proxy(db, {
2661
- get(_target, prop, receiver) {
2662
- const activeState = ttx.state;
2663
- if (Guards51.isDefined(activeState)) {
2664
- if (prop === "transaction") {
2665
- return activeState.transaction.bind(activeState);
2666
- }
2667
- return Reflect.get(activeState, prop, receiver);
2668
- }
2669
- return Reflect.get(db, prop, receiver);
2643
+ if (!Guards51.isNullOrEmpty(policy.permissions)) {
2644
+ Policies.add("permissions");
2670
2645
  }
2671
- });
2672
- });
2673
- }
2674
- };
2675
- }
2676
- });
2677
-
2678
- // src/infrastructure/http/base.http-adapter.ts
2679
- import { Guards as Guards29, StringHelper as StringHelper2 } from "@xeno-js/shared";
2680
- var BaseHttpAdapter;
2681
- var init_base_http_adapter = __esm({
2682
- "src/infrastructure/http/base.http-adapter.ts"() {
2683
- "use strict";
2684
- BaseHttpAdapter = class {
2685
- /**
2686
- * @description Parse the URL from the request.
2687
- * @param rawUrl The raw URL.
2688
- * @param headers The headers.
2689
- * @param queryParams The query parameters.
2690
- * @returns The parsed URL.
2691
- */
2692
- parseUrl(rawUrl = "/", headers, queryParams) {
2693
- const protocol = StringHelper2.getSingleValue(headers["x-forwarded-proto"]) ?? "https";
2694
- const host = StringHelper2.safeStringify(headers["host"]) ?? "localhost";
2695
- const cleanHost = host.replace(/['"]/g, "");
2696
- const url = new URL(rawUrl, `${protocol}://${cleanHost}`);
2697
- if (!Guards29.isNullOrEmpty(queryParams)) {
2698
- for (const [key, value] of Object.entries(queryParams)) {
2699
- if (Guards29.isArray(value)) {
2700
- value.forEach((v) => url.searchParams.append(key, String(v)));
2701
- } else if (Guards29.isDefined(value)) {
2702
- url.searchParams.set(key, String(value));
2646
+ if (!Guards51.isNullOrEmpty(policy.userId)) {
2647
+ Policies.add("userId");
2703
2648
  }
2704
- }
2705
- }
2706
- return url;
2707
- }
2708
- /**
2709
- * @description Parses the headers.
2710
- * @param rawHeaders The raw headers.
2711
- * @returns The parsed headers.
2712
- */
2713
- parseHeaders(rawHeaders) {
2714
- const headers = new Headers();
2715
- for (const [key, value] of Object.entries(rawHeaders)) {
2716
- if (Guards29.isDefined(value)) {
2717
- if (Guards29.isArray(value)) {
2718
- value.forEach((v) => headers.append(key, String(v)));
2719
- } else {
2720
- headers.set(key, String(value));
2649
+ if (!Guards51.isNullOrEmpty(policy.tenantId)) {
2650
+ Policies.add("tenantId");
2721
2651
  }
2722
2652
  }
2723
- }
2724
- return headers;
2725
- }
2726
- /**
2727
- * @description Parses the body.
2728
- * @param method The method.
2729
- * @param rawBody The raw body.
2730
- * @returns The parsed body.
2731
- */
2732
- parseBody(method, rawBody) {
2733
- if (!Guards29.isDefined(method) || !["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase()) || !Guards29.isDefined(rawBody))
2734
- return void 0;
2735
- if (Guards29.isObject(rawBody)) return JSON.stringify(rawBody);
2736
- if (Guards29.isString(rawBody) || rawBody instanceof Blob || rawBody instanceof ArrayBuffer || ArrayBuffer.isView(rawBody) || rawBody instanceof URLSearchParams || rawBody instanceof FormData)
2737
- return rawBody;
2738
- return String(rawBody);
2739
- }
2740
- /**
2741
- * @description Creates the XenoWebTransport.
2742
- * @param url The url.
2743
- * @param method The method.
2744
- * @param headers The headers.
2745
- * @param body The body.
2746
- * @returns The XenoWebTransport.
2747
- */
2748
- createXenoWebTransport(url, method = "GET", headers, body = void 0, res = void 0) {
2749
- const init2 = {
2750
- method: method.toUpperCase(),
2751
- headers
2752
- };
2753
- const parsedBody = this.parseBody(method, body);
2754
- if (Guards29.isDefined(parsedBody)) {
2755
- init2.body = parsedBody;
2756
- init2.duplex = "half";
2757
- }
2758
- const extendedRequest = new Request(url, init2);
2759
- extendedRequest.path = url.pathname;
2760
- const webResponse = new Response();
2761
- if (Guards29.isDefined(res)) {
2762
- const originalAppend = webResponse.headers.append.bind(webResponse.headers);
2763
- const originalSet = webResponse.headers.set.bind(webResponse.headers);
2764
- const originalDelete = webResponse.headers.delete.bind(webResponse.headers);
2765
- webResponse.headers.append = (name, value) => {
2766
- originalAppend(name, value);
2767
- this.handleHeaderChange(res, name, value, "append");
2768
- };
2769
- webResponse.headers.set = (name, value) => {
2770
- originalSet(name, value);
2771
- this.handleHeaderChange(res, name, value, "set");
2772
- };
2773
- webResponse.headers.delete = (name) => {
2774
- originalDelete(name);
2775
- this.handleHeaderChange(res, name, "", "delete");
2776
- };
2777
- }
2778
- return {
2779
- request: extendedRequest,
2780
- response: webResponse
2781
- };
2782
- }
2783
- };
2784
- }
2785
- });
2786
-
2787
- // src/infrastructure/http/vercel.http-adapter.ts
2788
- var vercel_http_adapter_exports = {};
2789
- __export(vercel_http_adapter_exports, {
2790
- VercelHttpAdapter: () => VercelHttpAdapter
2791
- });
2792
- import { Guards as Guards30 } from "@xeno-js/shared";
2793
- var VercelHttpAdapter;
2794
- var init_vercel_http_adapter = __esm({
2795
- "src/infrastructure/http/vercel.http-adapter.ts"() {
2796
- "use strict";
2797
- init_base_http_adapter();
2798
- VercelHttpAdapter = class extends BaseHttpAdapter {
2799
- adapt(req, res) {
2800
- const headers = this.parseHeaders(req.headers);
2801
- const url = this.parseUrl(req.url, req.headers, req.query);
2802
- return this.createXenoWebTransport(url, req.method, headers, req.body, res);
2803
- }
2804
- handleHeaderChange(res, name, value, action) {
2805
- if (action === "delete") {
2806
- res.removeHeader(name);
2807
- return;
2808
- }
2809
- if (name.toLowerCase() === "set-cookie") {
2810
- const existing = res.getHeader("Set-Cookie");
2811
- let cookies = [];
2812
- if (Guards30.isArray(existing)) {
2813
- cookies = existing;
2814
- } else if (Guards30.isString(existing)) {
2815
- cookies = [existing];
2653
+ if (Policies.has("roles")) {
2654
+ const { RoleAuthorizationStrategy: RoleAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2655
+ strategies.push(new RoleAuthorizationStrategy2(registryInstance, ctxAccessor));
2816
2656
  }
2817
- if (action === "append") {
2818
- cookies.push(value);
2819
- } else {
2820
- cookies = [value];
2657
+ if (Policies.has("permissions")) {
2658
+ const { PermissionAuthorizationStrategy: PermissionAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2659
+ strategies.push(new PermissionAuthorizationStrategy2(registryInstance, ctxAccessor));
2821
2660
  }
2822
- res.setHeader("Set-Cookie", cookies);
2823
- } else {
2824
- res.setHeader(name, value);
2825
- }
2826
- }
2827
- };
2828
- }
2829
- });
2830
-
2831
- // src/infrastructure/http/fastify.http-adapter.ts
2832
- var fastify_http_adapter_exports = {};
2833
- __export(fastify_http_adapter_exports, {
2834
- FastifyHttpAdapter: () => FastifyHttpAdapter
2835
- });
2836
- import { Guards as Guards31 } from "@xeno-js/shared";
2837
- var FastifyHttpAdapter;
2838
- var init_fastify_http_adapter = __esm({
2839
- "src/infrastructure/http/fastify.http-adapter.ts"() {
2840
- "use strict";
2841
- init_base_http_adapter();
2842
- FastifyHttpAdapter = class extends BaseHttpAdapter {
2843
- adapt(req, res) {
2844
- const headers = this.parseHeaders(req.headers);
2845
- const url = this.parseUrl(req.url, req.headers, req.query);
2846
- const body = req.body;
2847
- return this.createXenoWebTransport(url, req.method, headers, body, res);
2848
- }
2849
- handleHeaderChange(res, name, value, action) {
2850
- if (action === "delete") {
2851
- res.removeHeader(name);
2852
- return;
2853
- }
2854
- if (name.toLowerCase() === "set-cookie") {
2855
- const existing = res.getHeader("set-cookie");
2856
- let cookies = [];
2857
- if (Guards31.isArray(existing)) {
2858
- cookies = existing;
2859
- } else if (Guards31.isString(existing)) {
2860
- cookies = [existing];
2661
+ if (Policies.has("userId")) {
2662
+ const { UserAuthorizationStrategy: UserAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2663
+ strategies.push(new UserAuthorizationStrategy2(registryInstance, ctxAccessor));
2861
2664
  }
2862
- if (action === "append") {
2863
- cookies.push(value);
2864
- } else {
2865
- cookies = [value];
2665
+ if (Policies.has("tenantId")) {
2666
+ const { TenantAuthorizationStrategy: TenantAuthorizationStrategy2 } = await Promise.resolve().then(() => (init_application(), application_exports));
2667
+ strategies.push(new TenantAuthorizationStrategy2(registryInstance, ctxAccessor));
2866
2668
  }
2867
- res.header("set-cookie", cookies);
2868
- } else {
2869
- res.header(name, value);
2870
2669
  }
2871
- }
2872
- };
2873
- }
2874
- });
2875
-
2876
- // src/infrastructure/http/native.http-adapter.ts
2877
- var native_http_adapter_exports = {};
2878
- __export(native_http_adapter_exports, {
2879
- NativeHttpAdapter: () => NativeHttpAdapter
2880
- });
2881
- var NativeHttpAdapter;
2882
- var init_native_http_adapter = __esm({
2883
- "src/infrastructure/http/native.http-adapter.ts"() {
2884
- "use strict";
2885
- init_base_http_adapter();
2886
- NativeHttpAdapter = class extends BaseHttpAdapter {
2887
- adapt(req, res) {
2888
- const extendedRequest = req;
2889
- extendedRequest.path = new URL(req.url).pathname;
2890
- return {
2891
- request: extendedRequest,
2892
- response: res
2893
- };
2894
- }
2895
- handleHeaderChange(_res, _name, _value, _action) {
2896
- return;
2897
- }
2898
- };
2899
- }
2900
- });
2901
-
2902
- // src/infrastructure/modules/http-adapter.module.ts
2903
- import { Guards as Guards32 } from "@xeno-js/shared";
2904
- var HttpAdapterModule;
2905
- var init_http_adapter_module = __esm({
2906
- "src/infrastructure/modules/http-adapter.module.ts"() {
2907
- "use strict";
2908
- HttpAdapterModule = class {
2909
- async configure(container, opts) {
2910
- const adapter = await this._getAdapter(opts);
2911
- container.addSingleton("HTTP_ADAPTER", () => adapter);
2912
- }
2913
- async _getAdapter(opts) {
2914
- if (opts.vercel) {
2915
- const { VercelHttpAdapter: VercelHttpAdapter2 } = await Promise.resolve().then(() => (init_vercel_http_adapter(), vercel_http_adapter_exports));
2916
- return new VercelHttpAdapter2();
2917
- } else if (opts.fastify) {
2918
- const { FastifyHttpAdapter: FastifyHttpAdapter2 } = await Promise.resolve().then(() => (init_fastify_http_adapter(), fastify_http_adapter_exports));
2919
- return new FastifyHttpAdapter2();
2920
- } else if (Guards32.isDefined(opts.custom)) {
2921
- return opts.custom();
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
+ });
2922
2702
  } else {
2923
- const { NativeHttpAdapter: NativeHttpAdapter2 } = await Promise.resolve().then(() => (init_native_http_adapter(), native_http_adapter_exports));
2924
- 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
+ });
2925
2712
  }
2926
2713
  }
2927
- };
2714
+ });
2928
2715
  }
2929
2716
  });
2930
2717
 
@@ -2977,7 +2764,7 @@ var cockatiel_resilience_factory_exports = {};
2977
2764
  __export(cockatiel_resilience_factory_exports, {
2978
2765
  CockatielResilienceFactory: () => CockatielResilienceFactory
2979
2766
  });
2980
- import { AppError as AppError13, Guards as Guards33, RESILIENCE_DEFAULTS } from "@xeno-js/shared";
2767
+ import { AppError as AppError12, Guards as Guards37, RESILIENCE_DEFAULTS } from "@xeno-js/shared";
2981
2768
  import {
2982
2769
  bulkhead,
2983
2770
  circuitBreaker,
@@ -3054,13 +2841,13 @@ var init_cockatiel_resilience_factory = __esm({
3054
2841
  return new ServiceResilience(wrap(bulkheadPolicy, circuitBreakerPolicy, retryPolicy));
3055
2842
  }
3056
2843
  isTransientError(error) {
3057
- if (!Guards33.isDefined(error) || !Guards33.isObject(error)) return false;
2844
+ if (!Guards37.isDefined(error) || !Guards37.isObject(error)) return false;
3058
2845
  let status;
3059
2846
  let isNetworkError = false;
3060
- if (error instanceof AppError13) {
2847
+ if (error instanceof AppError12) {
3061
2848
  status = error.status;
3062
2849
  const cause = error.cause;
3063
- if (Guards33.isDefined(cause) && Guards33.isString(cause.code)) {
2850
+ if (Guards37.isDefined(cause) && Guards37.isString(cause.code)) {
3064
2851
  isNetworkError = [
3065
2852
  "ECONNABORTED",
3066
2853
  "ECONNRESET",
@@ -3072,7 +2859,7 @@ var init_cockatiel_resilience_factory = __esm({
3072
2859
  } else {
3073
2860
  const err = error;
3074
2861
  status = err.status;
3075
- if (Guards33.isString(err.code)) {
2862
+ if (Guards37.isString(err.code)) {
3076
2863
  isNetworkError = [
3077
2864
  "ECONNABORTED",
3078
2865
  "ECONNRESET",
@@ -3083,30 +2870,30 @@ var init_cockatiel_resilience_factory = __esm({
3083
2870
  }
3084
2871
  }
3085
2872
  if (isNetworkError) return true;
3086
- if (Guards33.isDefined(status)) return status === 408 || status >= 500 && status < 600;
2873
+ if (Guards37.isDefined(status)) return status === 408 || status >= 500 && status < 600;
3087
2874
  return false;
3088
2875
  }
3089
2876
  isTransientAndIdempotent(error) {
3090
2877
  if (!this.isTransientError(error)) return false;
3091
2878
  let method;
3092
- if (error instanceof AppError13) {
2879
+ if (error instanceof AppError12) {
3093
2880
  const cause = error.cause;
3094
- 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)) {
3095
2882
  method = cause.config.method.toUpperCase();
3096
2883
  }
3097
2884
  } else {
3098
2885
  const err = error;
3099
- if (Guards33.isDefined(err.config) && Guards33.isString(err.config.method)) {
2886
+ if (Guards37.isDefined(err.config) && Guards37.isString(err.config.method)) {
3100
2887
  method = err.config.method.toUpperCase();
3101
2888
  }
3102
2889
  }
3103
- if (Guards33.isNullOrEmpty(method)) return false;
2890
+ if (Guards37.isNullOrEmpty(method)) return false;
3104
2891
  const idempotentMethods = ["GET", "PUT", "DELETE", "HEAD", "OPTIONS"];
3105
2892
  return idempotentMethods.includes(method);
3106
2893
  }
3107
2894
  checkConfigValue(value, defaultValue, message) {
3108
- if (Guards33.isDefined(value)) {
3109
- Guards33.throwIfNegative(value, message);
2895
+ if (Guards37.isDefined(value)) {
2896
+ Guards37.throwIfNegative(value, message);
3110
2897
  return value;
3111
2898
  }
3112
2899
  return defaultValue;
@@ -3141,53 +2928,326 @@ var init_http_utils = __esm({
3141
2928
  if (!Guards51.isDefined(opts.token)) {
3142
2929
  throw new Error("HttpConfig.token is required and must be defined.");
3143
2930
  }
3144
- container.addSingleton(opts.token, () => {
3145
- const factory = new NodeAxiosFactory2();
3146
- const instance = factory.create(opts.client);
3147
- if (!Guards51.hasMethod(instance, "get") || !Guards51.hasMethod(instance, "post") || !Guards51.hasMethod(instance, "put") || !Guards51.hasMethod(instance, "patch") || !Guards51.hasMethod(instance, "delete")) {
3148
- throw new Error(
3149
- "The created HTTP client instance does not implement the required methods of IHttpClient."
3150
- );
3151
- }
3152
- return instance;
3153
- });
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}`);
3103
+ }
3104
+ };
3105
+ }
3106
+ });
3107
+
3108
+ // src/infrastructure/idempotency/index.ts
3109
+ var idempotency_exports = {};
3110
+ __export(idempotency_exports, {
3111
+ IdempotencyStore: () => IdempotencyStore
3112
+ });
3113
+ var init_idempotency = __esm({
3114
+ "src/infrastructure/idempotency/index.ts"() {
3115
+ "use strict";
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({
3130
+ /**
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.
3134
+ *
3135
+ * @author Xeno
3136
+ * @version 1.0.0
3137
+ * @since 2025-09-30
3138
+ * @link https://github.com/xeno-js/xeno-js
3139
+ */
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
+ );
3160
+ }
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;
3154
3167
  },
3155
3168
  /**
3156
- * @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.
3157
- * @param container - The service container to register the resilience client with.
3158
- * @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.
3159
3172
  *
3160
3173
  * @author Xeno
3161
3174
  * @version 1.0.0
3162
3175
  * @since 2025-09-30
3163
3176
  * @link https://github.com/xeno-js/xeno-js
3164
3177
  */
3165
- async addResilience(container, opts) {
3178
+ async addQuery(container) {
3166
3179
  const { TOKENS: TOKENS5 } = await import("@xeno-js/shared");
3167
- const { CockatielResilienceFactory: CockatielResilienceFactory2 } = await Promise.resolve().then(() => (init_cockatiel_resilience_factory(), cockatiel_resilience_factory_exports));
3168
- container.addSingleton(TOKENS5.RESILIENCE_CLIENT, () => {
3169
- const factory = new CockatielResilienceFactory2();
3170
- return factory.create(opts);
3171
- });
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
+ );
3172
3186
  }
3173
3187
  });
3174
3188
  }
3175
3189
  });
3176
3190
 
3177
- // src/infrastructure/modules/http-core.module.ts
3178
- var http_core_module_exports = {};
3179
- __export(http_core_module_exports, {
3180
- HttpCoreModule: () => HttpCoreModule
3191
+ // src/infrastructure/modules/cqrs.module.ts
3192
+ var cqrs_module_exports = {};
3193
+ __export(cqrs_module_exports, {
3194
+ CqrsModule: () => CqrsModule
3181
3195
  });
3182
- var HttpCoreModule;
3183
- var init_http_core_module = __esm({
3184
- "src/infrastructure/modules/http-core.module.ts"() {
3196
+ var CqrsModule;
3197
+ var init_cqrs_module = __esm({
3198
+ "src/infrastructure/modules/cqrs.module.ts"() {
3185
3199
  "use strict";
3186
- HttpCoreModule = class {
3200
+ CqrsModule = class {
3187
3201
  async configure(container, opts) {
3188
- const { HttpUtils: HttpUtils2 } = await Promise.resolve().then(() => (init_http_utils(), http_utils_exports));
3189
- await HttpUtils2.addAxios(container, opts.http);
3190
- 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
+ });
3191
3251
  }
3192
3252
  };
3193
3253
  }
@@ -3486,7 +3546,7 @@ var init_composite_middleware = __esm({
3486
3546
  });
3487
3547
 
3488
3548
  // src/presentation/middlewares/cors.middleware.ts
3489
- import { Guards as Guards34 } from "@xeno-js/shared";
3549
+ import { Guards as Guards38 } from "@xeno-js/shared";
3490
3550
  var CORSMiddleware;
3491
3551
  var init_cors_middleware = __esm({
3492
3552
  "src/presentation/middlewares/cors.middleware.ts"() {
@@ -3502,7 +3562,7 @@ var init_cors_middleware = __esm({
3502
3562
  const { network } = this._requestContext.getContext() ?? {};
3503
3563
  const origin = network?.origin;
3504
3564
  const response = await next();
3505
- if (Guards34.isDefined(origin))
3565
+ if (Guards38.isDefined(origin))
3506
3566
  response.headers = {
3507
3567
  ...response.headers ?? {},
3508
3568
  "Access-Control-Allow-Origin": origin,
@@ -3519,7 +3579,7 @@ var init_cors_middleware = __esm({
3519
3579
  import {
3520
3580
  ERROR_CODE_MESSAGES as ERROR_CODE_MESSAGES5,
3521
3581
  ERROR_CODES as ERROR_CODES6,
3522
- Guards as Guards35,
3582
+ Guards as Guards39,
3523
3583
  GuidHelper as GuidHelper9,
3524
3584
  HttpHelper as HttpHelper6,
3525
3585
  STATUS_CODES as STATUS_CODES7
@@ -3542,7 +3602,7 @@ var init_csrf_middleware = __esm({
3542
3602
  const { network, tracing, identity } = this._requestContext.getContext() ?? {};
3543
3603
  const headerToken = network?.csrf;
3544
3604
  const cookieToken = network?.csrfCookie;
3545
- if (!Guards35.isDefined(headerToken) || !Guards35.isDefined(cookieToken)) {
3605
+ if (!Guards39.isDefined(headerToken) || !Guards39.isDefined(cookieToken)) {
3546
3606
  return HttpHelper6.error(
3547
3607
  {
3548
3608
  success: false,
@@ -3584,7 +3644,7 @@ var init_csrf_middleware = __esm({
3584
3644
  }
3585
3645
  );
3586
3646
  }
3587
- 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)) {
3588
3648
  return HttpHelper6.error(
3589
3649
  {
3590
3650
  success: false,
@@ -3613,7 +3673,7 @@ var init_csrf_middleware = __esm({
3613
3673
  });
3614
3674
 
3615
3675
  // src/presentation/middlewares/csrf-cookie.middleware.ts
3616
- import { Guards as Guards36 } from "@xeno-js/shared";
3676
+ import { Guards as Guards40 } from "@xeno-js/shared";
3617
3677
  var CsrfCookieMiddleware;
3618
3678
  var init_csrf_cookie_middleware = __esm({
3619
3679
  "src/presentation/middlewares/csrf-cookie.middleware.ts"() {
@@ -3632,8 +3692,8 @@ var init_csrf_cookie_middleware = __esm({
3632
3692
  const context = this._requestContext.getContext();
3633
3693
  const identity = context?.identity;
3634
3694
  const network = context?.network;
3635
- if (!Guards36.isDefined(identity?.userId)) return response;
3636
- if (Guards36.isDefined(network?.csrfCookie)) return response;
3695
+ if (!Guards40.isDefined(identity?.userId)) return response;
3696
+ if (Guards40.isDefined(network?.csrfCookie)) return response;
3637
3697
  const token = await this._csrfTokenService.generate(identity.userId);
3638
3698
  const cookieName = this._csrf.cookieName ?? "__Host-xeno-csrf";
3639
3699
  const maxAge = this._csrf.cookieMaxAgeSeconds ?? 3600;
@@ -3651,7 +3711,7 @@ var init_csrf_cookie_middleware = __esm({
3651
3711
  });
3652
3712
 
3653
3713
  // src/presentation/middlewares/options.middleware.ts
3654
- 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";
3655
3715
  var OptionsMiddleware;
3656
3716
  var init_options_middleware = __esm({
3657
3717
  "src/presentation/middlewares/options.middleware.ts"() {
@@ -3672,7 +3732,7 @@ var init_options_middleware = __esm({
3672
3732
  const network = this._requestContext.getNetworkContext();
3673
3733
  const origin = network?.origin;
3674
3734
  const headers = {};
3675
- if (Guards37.isDefined(origin)) {
3735
+ if (Guards41.isDefined(origin)) {
3676
3736
  headers["Access-Control-Allow-Origin"] = origin;
3677
3737
  headers["Access-Control-Allow-Credentials"] = this._withCredentials;
3678
3738
  headers["Vary"] = "Origin";
@@ -3691,7 +3751,7 @@ var init_options_middleware = __esm({
3691
3751
  import {
3692
3752
  ERROR_CODE_MESSAGES as ERROR_CODE_MESSAGES6,
3693
3753
  ERROR_CODES as ERROR_CODES7,
3694
- Guards as Guards38,
3754
+ Guards as Guards42,
3695
3755
  GuidHelper as GuidHelper10,
3696
3756
  HttpHelper as HttpHelper8,
3697
3757
  STATUS_CODES as STATUS_CODES9
@@ -3716,7 +3776,7 @@ var init_rate_limiter_middleware = __esm({
3716
3776
  async execute(req, _res, next) {
3717
3777
  const cacheKey = this._keyBuilder.buildRateLimitKey(req.path);
3718
3778
  const { network, tracing } = this._ctxAccessor.getContext() ?? {};
3719
- if (!Guards38.isDefined(cacheKey))
3779
+ if (!Guards42.isDefined(cacheKey))
3720
3780
  return HttpHelper8.error(
3721
3781
  {
3722
3782
  success: false,
@@ -3768,10 +3828,10 @@ var init_rate_limiter_middleware = __esm({
3768
3828
  });
3769
3829
 
3770
3830
  // src/presentation/mappers/context.mapper.ts
3771
- import { Guards as Guards39 } from "@xeno-js/shared";
3831
+ import { Guards as Guards43 } from "@xeno-js/shared";
3772
3832
  function _buildMessagingContext(meta) {
3773
- const hasSequenceData = Guards39.isDefined(meta.sequence?.sequenceId) || Guards39.isDefined(meta.sequence?.position) || Guards39.isDefined(meta.sequence?.size);
3774
- 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);
3775
3835
  const messaging = hasMessagingData ? {
3776
3836
  returnAddress: meta.returnAddress,
3777
3837
  expiration: meta.expiration,
@@ -3954,30 +4014,8 @@ var init_presentation = __esm({
3954
4014
  }
3955
4015
  });
3956
4016
 
3957
- // src/infrastructure/cache/inmemory.cache.ts
3958
- var inmemory_cache_exports = {};
3959
- __export(inmemory_cache_exports, {
3960
- InMemoryCacheExtended: () => InMemoryCacheExtended
3961
- });
3962
- import { Guards as Guards40, InMemoryCache } from "@xeno-js/shared";
3963
- var InMemoryCacheExtended;
3964
- var init_inmemory_cache = __esm({
3965
- "src/infrastructure/cache/inmemory.cache.ts"() {
3966
- "use strict";
3967
- InMemoryCacheExtended = class extends InMemoryCache {
3968
- async increment(key, ttlSeconds) {
3969
- const current = await this.get(key) ?? 0;
3970
- const next = Number(current) + 1;
3971
- const ttl = Guards40.isDefined(ttlSeconds) ? Number(ttlSeconds) : 60;
3972
- await this.set(key, next, ttl);
3973
- return next;
3974
- }
3975
- };
3976
- }
3977
- });
3978
-
3979
4017
  // src/infrastructure/cache/rate-limit-key-builder.cache.ts
3980
- import { Guards as Guards41 } from "@xeno-js/shared";
4018
+ import { Guards as Guards44 } from "@xeno-js/shared";
3981
4019
  var RateLimitKeyBuilder;
3982
4020
  var init_rate_limit_key_builder_cache = __esm({
3983
4021
  "src/infrastructure/cache/rate-limit-key-builder.cache.ts"() {
@@ -3992,78 +4030,18 @@ var init_rate_limit_key_builder_cache = __esm({
3992
4030
  const tenantId = ctx?.identity?.tenantId;
3993
4031
  const userId = ctx?.identity?.userId;
3994
4032
  const clientIp = ctx?.network?.clientIp;
3995
- if (!Guards41.isNullOrEmpty(tenantId) && !Guards41.isNullOrEmpty(userId))
4033
+ if (!Guards44.isNullOrEmpty(tenantId) && !Guards44.isNullOrEmpty(userId))
3996
4034
  return `ratelimit:tenant:${tenantId}:user:${userId}:${resource}`;
3997
- if (!Guards41.isNullOrEmpty(tenantId) && !Guards41.isNullOrEmpty(clientIp))
4035
+ if (!Guards44.isNullOrEmpty(tenantId) && !Guards44.isNullOrEmpty(clientIp))
3998
4036
  return `ratelimit:tenant:${tenantId}:ip:${clientIp}:${resource}`;
3999
- if (!Guards41.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4000
- if (!Guards41.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4037
+ if (!Guards44.isNullOrEmpty(userId)) return `ratelimit:user:${userId}:${resource}`;
4038
+ if (!Guards44.isNullOrEmpty(clientIp)) return `ratelimit:ip:${clientIp}:${resource}`;
4001
4039
  return void 0;
4002
4040
  }
4003
4041
  };
4004
4042
  }
4005
4043
  });
4006
4044
 
4007
- // src/infrastructure/cache/redis.cache.ts
4008
- import { Guards as Guards42, StringHelper as StringHelper3 } from "@xeno-js/shared";
4009
- var RedisCache;
4010
- var init_redis_cache = __esm({
4011
- "src/infrastructure/cache/redis.cache.ts"() {
4012
- "use strict";
4013
- RedisCache = class {
4014
- /**
4015
- * @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.
4016
- * @param _redisClient An instance of the Redis client from the ioredis library, used to perform caching operations in the Redis database.
4017
-
4018
- *
4019
- * @author Xeno
4020
- * @version 1.0.0
4021
- * @since 2025-09-30
4022
- * @link https://github.com/xeno-js/xeno-js
4023
- */
4024
- constructor(_redisClient) {
4025
- this._redisClient = _redisClient;
4026
- }
4027
- _redisClient;
4028
- async increment(key, ttlSeconds) {
4029
- const multi = this._redisClient.multi();
4030
- multi.incr(key);
4031
- multi.expire(key, ttlSeconds ?? 60);
4032
- const results = await multi.exec();
4033
- return results?.[0]?.[1] ?? 1;
4034
- }
4035
- async get(key) {
4036
- const value = await this._redisClient.get(key);
4037
- if (!Guards42.isDefined(value)) {
4038
- return void 0;
4039
- }
4040
- return JSON.parse(value);
4041
- }
4042
- async set(key, value, ttl) {
4043
- const stringValue = StringHelper3.safeStringify(value);
4044
- const ttlOption = Guards42.isDefined(ttl) ? ttl : 86400;
4045
- await this._redisClient.set(key, stringValue, "EX", ttlOption);
4046
- }
4047
- async setIfAbsent(key, value, ttl) {
4048
- const stringValue = StringHelper3.safeStringify(value);
4049
- const ttlOption = Guards42.isDefined(ttl) ? ttl : 300;
4050
- const result = await this._redisClient.set(key, stringValue, "EX", ttlOption, "NX");
4051
- return result === "OK";
4052
- }
4053
- async remove(key) {
4054
- await this._redisClient.del(key);
4055
- }
4056
- async has(key) {
4057
- const exists = await this._redisClient.exists(key);
4058
- return exists === 1;
4059
- }
4060
- async clear() {
4061
- await this._redisClient.flushdb();
4062
- }
4063
- };
4064
- }
4065
- });
4066
-
4067
4045
  // src/infrastructure/cache/index.ts
4068
4046
  var cache_exports = {};
4069
4047
  __export(cache_exports, {
@@ -4220,462 +4198,317 @@ var init_middleware_module = __esm({
4220
4198
  container.addSingleton("CRYPTO_SERVICE", () => new EdgeCryptoService2());
4221
4199
  const { CsrfTokenService: CsrfTokenService2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4222
4200
  container.addSingleton("CSRF_TOKEN_SERVICE", (c) => {
4223
- return new CsrfTokenService2(csrf.secret, c.resolve("CRYPTO_SERVICE"));
4224
- });
4225
- const { CsrfCookieMiddleware: CsrfCookieMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4226
- middlewares.push(
4227
- new CsrfCookieMiddleware2(
4228
- requestContext,
4229
- container.resolve("CSRF_TOKEN_SERVICE"),
4230
- opts.csrf
4231
- )
4232
- );
4233
- const { CsrfMiddleware: CsrfMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4234
- middlewares.push(new CsrfMiddleware2(requestContext, container.resolve("CSRF_TOKEN_SERVICE")));
4235
- }
4236
- const { CompositeMiddleware: CompositeMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4237
- container.addSingleton(TOKENS5.MIDDLEWARE, () => {
4238
- return new CompositeMiddleware2(middlewares);
4239
- });
4240
- }
4241
- async _getTokenExtractor(isSSR, cookieName, customTokenExtractor) {
4242
- const { Guards: Guards51 } = await import("@xeno-js/shared");
4243
- if (Guards51.isDefined(customTokenExtractor)) return customTokenExtractor();
4244
- if (isSSR) {
4245
- const { SupabaseSsrTokenExtractor: SupabaseSsrTokenExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4246
- return new SupabaseSsrTokenExtractor2();
4247
- } else {
4248
- const { BearerTokenExtractor: BearerTokenExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4249
- return new BearerTokenExtractor2(cookieName ?? "sb-access-token");
4250
- }
4251
- }
4252
- async _getAllowMethod(configure, opts) {
4253
- const { Guards: Guards51 } = await import("@xeno-js/shared");
4254
- if (!configure || !Guards51.isDefined(opts)) return void 0;
4255
- const { AllowMethodFactory: AllowMethodFactory2 } = await Promise.resolve().then(() => (init_allow_method_factory(), allow_method_factory_exports));
4256
- return new AllowMethodFactory2().create(opts);
4257
- }
4258
- };
4259
- }
4260
- });
4261
-
4262
- // src/infrastructure/factories/redis-cache.factory.ts
4263
- var redis_cache_factory_exports = {};
4264
- __export(redis_cache_factory_exports, {
4265
- RedisCacheFactory: () => RedisCacheFactory
4266
- });
4267
- import { Guards as Guards43 } from "@xeno-js/shared";
4268
- import { Redis } from "ioredis";
4269
- var RedisCacheFactory;
4270
- var init_redis_cache_factory = __esm({
4271
- "src/infrastructure/factories/redis-cache.factory.ts"() {
4272
- "use strict";
4273
- init_redis_cache();
4274
- RedisCacheFactory = class {
4275
- create(config) {
4276
- const host = config?.host ?? "localhost";
4277
- const port = config?.port ?? 6379;
4278
- const password = config?.password;
4279
- const username = config?.username;
4280
- const useTls = config?.tls ?? false;
4281
- const maxRetries = config?.maxRetriesPerRequest ?? 3;
4282
- const redisOptions = {
4283
- host,
4284
- port,
4285
- maxRetriesPerRequest: maxRetries,
4286
- // Strategia di riconnessione esponenziale per garantire resilienza
4287
- retryStrategy(times) {
4288
- const delay = Math.min(times * 50, 2e3);
4289
- return delay;
4290
- }
4291
- };
4292
- if (Guards43.isDefined(password)) {
4293
- redisOptions.password = password;
4294
- }
4295
- if (Guards43.isDefined(username)) {
4296
- redisOptions.username = username;
4297
- }
4298
- if (useTls) {
4299
- redisOptions.tls = {};
4201
+ return new CsrfTokenService2(csrf.secret, c.resolve("CRYPTO_SERVICE"));
4202
+ });
4203
+ const { CsrfCookieMiddleware: CsrfCookieMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4204
+ middlewares.push(
4205
+ new CsrfCookieMiddleware2(
4206
+ requestContext,
4207
+ container.resolve("CSRF_TOKEN_SERVICE"),
4208
+ opts.csrf
4209
+ )
4210
+ );
4211
+ const { CsrfMiddleware: CsrfMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4212
+ middlewares.push(new CsrfMiddleware2(requestContext, container.resolve("CSRF_TOKEN_SERVICE")));
4300
4213
  }
4301
- const nativeRedisInstance = new Redis(redisOptions);
4302
- nativeRedisInstance.on("error", (err) => {
4303
- console.error("\u274C [Redis Error]:", err.message);
4214
+ const { CompositeMiddleware: CompositeMiddleware2 } = await Promise.resolve().then(() => (init_presentation(), presentation_exports));
4215
+ container.addSingleton(TOKENS5.MIDDLEWARE, () => {
4216
+ return new CompositeMiddleware2(middlewares);
4304
4217
  });
4305
- return new RedisCache(nativeRedisInstance);
4218
+ }
4219
+ async _getTokenExtractor(isSSR, cookieName, customTokenExtractor) {
4220
+ const { Guards: Guards51 } = await import("@xeno-js/shared");
4221
+ if (Guards51.isDefined(customTokenExtractor)) return customTokenExtractor();
4222
+ if (isSSR) {
4223
+ const { SupabaseSsrTokenExtractor: SupabaseSsrTokenExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4224
+ return new SupabaseSsrTokenExtractor2();
4225
+ } else {
4226
+ const { BearerTokenExtractor: BearerTokenExtractor2 } = await Promise.resolve().then(() => (init_services(), services_exports));
4227
+ return new BearerTokenExtractor2(cookieName ?? "sb-access-token");
4228
+ }
4229
+ }
4230
+ async _getAllowMethod(configure, opts) {
4231
+ const { Guards: Guards51 } = await import("@xeno-js/shared");
4232
+ if (!configure || !Guards51.isDefined(opts)) return void 0;
4233
+ const { AllowMethodFactory: AllowMethodFactory2 } = await Promise.resolve().then(() => (init_allow_method_factory(), allow_method_factory_exports));
4234
+ return new AllowMethodFactory2().create(opts);
4306
4235
  }
4307
4236
  };
4308
4237
  }
4309
4238
  });
4310
4239
 
4311
- // src/infrastructure/modules/utils/cache.utils.ts
4312
- var cache_utils_exports = {};
4313
- __export(cache_utils_exports, {
4314
- CacheUtils: () => CacheUtils
4240
+ // src/infrastructure/factories/service-scope.factory.ts
4241
+ var service_scope_factory_exports = {};
4242
+ __export(service_scope_factory_exports, {
4243
+ ServiceScopeFactory: () => ServiceScopeFactory
4315
4244
  });
4316
- var CacheUtils;
4317
- var init_cache_utils = __esm({
4318
- "src/infrastructure/modules/utils/cache.utils.ts"() {
4245
+ var ServiceScopeFactory;
4246
+ var init_service_scope_factory = __esm({
4247
+ "src/infrastructure/factories/service-scope.factory.ts"() {
4319
4248
  "use strict";
4320
- CacheUtils = Object.freeze({
4321
- /**
4322
- * @description Checks if the provided cache configuration requires any cache strategies.
4323
- * @param container The service container to which the cache strategies will be added.
4324
- * @param opts The cache configuration options.
4325
- * @returns True if any cache strategies are required, false otherwise.
4326
- *
4327
- * @author Xeno
4328
- * @version 1.0.0
4329
- * @since 2025-09-30
4330
- * @link https://github.com/xeno-js/xeno-js
4331
- */
4332
- async addCache(container, opts) {
4333
- const { Guards: Guards51, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4334
- if (!opts.inMemory && !Guards51.isDefined(opts.redis)) {
4335
- throw new Error(
4336
- "No cache strategies are configured. Please provide at least one cache strategy."
4337
- );
4338
- }
4339
- const { CacheKeyBuilder } = await import("@xeno-js/shared");
4340
- container.addSingleton(
4341
- TOKENS5.CACHE_KEY_BUILDER,
4342
- (c) => new CacheKeyBuilder(c.resolve(TOKENS5.IDENTITY_ACCESSOR))
4343
- );
4344
- if (opts.inMemory || !Guards51.isDefined(opts.redis)) {
4345
- const { InMemoryCacheExtended: InMemoryCacheExtended2 } = await Promise.resolve().then(() => (init_inmemory_cache(), inmemory_cache_exports));
4346
- container.addSingleton(TOKENS5.CACHE, () => new InMemoryCacheExtended2());
4347
- return;
4348
- }
4349
- if (Guards51.isDefined(opts.redis)) {
4350
- const { RedisCacheFactory: RedisCacheFactory2 } = await Promise.resolve().then(() => (init_redis_cache_factory(), redis_cache_factory_exports));
4351
- container.addSingleton(TOKENS5.CACHE, () => {
4352
- const config = opts.redis;
4353
- return new RedisCacheFactory2().create(config);
4354
- });
4355
- }
4249
+ ServiceScopeFactory = class {
4250
+ constructor(_container) {
4251
+ this._container = _container;
4356
4252
  }
4357
- });
4253
+ _container;
4254
+ create() {
4255
+ return this._container.createScope();
4256
+ }
4257
+ };
4358
4258
  }
4359
4259
  });
4360
4260
 
4361
- // src/infrastructure/loggers/console.logger.ts
4362
- var console_logger_exports = {};
4363
- __export(console_logger_exports, {
4364
- ConsoleLogger: () => ConsoleLogger
4365
- });
4366
- import { Guards as Guards44, LOG_LEVEL } from "@xeno-js/shared";
4367
- var ConsoleLogger;
4368
- var init_console_logger = __esm({
4369
- "src/infrastructure/loggers/console.logger.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"() {
4370
4266
  "use strict";
4371
- ConsoleLogger = class {
4267
+ NodeRequestContext = class {
4372
4268
  /**
4373
- * 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.
4374
- * @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.
4375
-
4376
- *
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.
4272
+ *
4377
4273
  * @author Xeno
4378
4274
  * @version 1.0.0
4379
4275
  * @since 2025-09-30
4380
- * @link https://github.com/xeno-js/xeno-js
4276
+ * @link https://github.com/xeno-js/xeno-js
4381
4277
  */
4382
- constructor(_minLevel = LOG_LEVEL.DEBUG) {
4383
- this._minLevel = _minLevel;
4278
+ constructor(_storage, _factoryScope) {
4279
+ this._storage = _storage;
4280
+ this._factoryScope = _factoryScope;
4384
4281
  }
4385
- _minLevel;
4386
- track(level, message, context, error = void 0) {
4387
- if (level < this._minLevel) return;
4388
- const logMessage = `[${level}] ${message}`;
4389
- const payload = Guards44.isDefined(error) ? { ...context, error } : context;
4390
- switch (level) {
4391
- case LOG_LEVEL.ERROR:
4392
- console.error(logMessage, payload ?? {});
4393
- break;
4394
- case LOG_LEVEL.WARN:
4395
- console.warn(logMessage, payload ?? {});
4396
- break;
4397
- case LOG_LEVEL.DEBUG:
4398
- console.debug(logMessage, payload ?? {});
4399
- break;
4400
- default:
4401
- console.info(logMessage, payload ?? {});
4402
- break;
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();
4403
4290
  }
4404
4291
  }
4405
- };
4406
- }
4407
- });
4408
-
4409
- // src/infrastructure/loggers/sentry.logger.ts
4410
- import { Guards as Guards45, LOG_LEVEL as LOG_LEVEL2 } from "@xeno-js/shared";
4411
- var SentryLogger;
4412
- var init_sentry_logger = __esm({
4413
- "src/infrastructure/loggers/sentry.logger.ts"() {
4414
- "use strict";
4415
- SentryLogger = class {
4416
- constructor(_client, _minLevel) {
4417
- this._client = _client;
4418
- this._minLevel = _minLevel;
4419
- }
4420
- _client;
4421
- _minLevel;
4422
- track(level, message, context = void 0, error = void 0) {
4423
- if (level < this._minLevel) return;
4424
- if (level === LOG_LEVEL2.ERROR || level === LOG_LEVEL2.WARN) {
4425
- this._client.withScope((scope) => {
4426
- if (Guards45.isDefined(context)) scope.setExtras(context);
4427
- if (Guards45.isDefined(error)) {
4428
- this._client.captureException(error);
4429
- } else {
4430
- this._client.captureMessage(message, "warning");
4431
- }
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)
4432
4298
  });
4433
4299
  }
4434
4300
  }
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
+ }
4435
4322
  };
4436
4323
  }
4437
4324
  });
4438
4325
 
4439
- // src/infrastructure/factories/sentry-logger.factory.ts
4440
- var sentry_logger_factory_exports = {};
4441
- __export(sentry_logger_factory_exports, {
4442
- SentryLoggerFactory: () => SentryLoggerFactory
4326
+ // src/infrastructure/factories/request-context.factory.ts
4327
+ var request_context_factory_exports = {};
4328
+ __export(request_context_factory_exports, {
4329
+ NodeRequestContextFactory: () => NodeRequestContextFactory
4443
4330
  });
4444
- import * as Sentry from "@sentry/node";
4445
- import { Guards as Guards46, LOG_LEVEL as LOG_LEVEL3 } from "@xeno-js/shared";
4446
- var SentryLoggerFactory;
4447
- var init_sentry_logger_factory = __esm({
4448
- "src/infrastructure/factories/sentry-logger.factory.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"() {
4449
4335
  "use strict";
4450
- init_sentry_logger();
4451
- SentryLoggerFactory = class {
4452
- create(config) {
4453
- const level = config.level ?? LOG_LEVEL3.WARN;
4454
- const sentryConfig = config.sentry?.config;
4455
- const env = sentryConfig?.environment ?? process.env.NODE_ENV ?? "development";
4456
- if (!Guards46.isDefined(sentryConfig))
4457
- throw new Error("Sentry configuration is required when Sentry logging is enabled.");
4458
- if (!Guards46.isDefined(sentryConfig.dsn))
4459
- throw new Error("Sentry DSN is required when Sentry logging is enabled.");
4460
- Sentry.init({
4461
- dsn: sentryConfig.dsn,
4462
- environment: env,
4463
- tracesSampleRate: env === "production" ? 0.1 : 1,
4464
- integrations: [Sentry.httpIntegration()],
4465
- beforeSend(event, hint) {
4466
- const error = hint.originalException;
4467
- if (error instanceof Error && error.name === "ZodError") {
4468
- return null;
4469
- }
4470
- return event;
4471
- }
4472
- });
4473
- return new SentryLogger(Sentry, level);
4336
+ init_request_context();
4337
+ NodeRequestContextFactory = class {
4338
+ constructor(_factoryScope) {
4339
+ this._factoryScope = _factoryScope;
4340
+ }
4341
+ _factoryScope;
4342
+ _store = new AsyncLocalStorage2();
4343
+ create() {
4344
+ return new NodeRequestContext(this._store, this._factoryScope);
4474
4345
  }
4475
4346
  };
4476
4347
  }
4477
4348
  });
4478
4349
 
4479
- // src/infrastructure/loggers/pino.logger.ts
4480
- import { Guards as Guards47, LOG_LEVEL as LOG_LEVEL4 } from "@xeno-js/shared";
4481
- var PinoLogger;
4482
- var init_pino_logger = __esm({
4483
- "src/infrastructure/loggers/pino.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"() {
4484
4359
  "use strict";
4485
- PinoLogger = class {
4360
+ UserContextFactory = class {
4486
4361
  /**
4487
- * 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.
4488
- * @param _logger The Pino logger instance used for logging messages.
4489
- * @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.
4490
-
4491
- *
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
+ *
4492
4365
  * @author Xeno
4493
4366
  * @version 1.0.0
4494
4367
  * @since 2025-09-30
4495
- * @link https://github.com/xeno-js/xeno-js
4368
+ * @link https://github.com/xeno-js/xeno-js
4496
4369
  */
4497
- constructor(_logger, _minLevel = LOG_LEVEL4.DEBUG) {
4498
- this._logger = _logger;
4499
- this._minLevel = _minLevel;
4370
+ constructor(_identityFactory) {
4371
+ this._identityFactory = _identityFactory;
4500
4372
  }
4501
- _logger;
4502
- _minLevel;
4503
- track(level, message, context, error = void 0) {
4504
- if (level < this._minLevel) return;
4505
- const payload = Guards47.isDefined(error) ? { ...context, error } : context;
4506
- switch (level) {
4507
- case LOG_LEVEL4.ERROR:
4508
- this._logger.error(payload ?? {}, message);
4509
- break;
4510
- case LOG_LEVEL4.WARN:
4511
- this._logger.warn(payload ?? {}, message);
4512
- break;
4513
- case LOG_LEVEL4.DEBUG:
4514
- this._logger.debug(payload ?? {}, message);
4515
- break;
4516
- default:
4517
- this._logger.info(payload ?? {}, message);
4518
- break;
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;
4519
4383
  }
4384
+ return output;
4520
4385
  }
4521
4386
  };
4522
4387
  }
4523
4388
  });
4524
4389
 
4525
- // src/infrastructure/factories/pino-logger.factory.ts
4526
- var pino_logger_factory_exports = {};
4527
- __export(pino_logger_factory_exports, {
4528
- PinoLoggerFactory: () => PinoLoggerFactory
4390
+ // src/infrastructure/modules/context.module.ts
4391
+ var context_module_exports = {};
4392
+ __export(context_module_exports, {
4393
+ ContextModule: () => ContextModule
4529
4394
  });
4530
- import { LOG_LEVEL as LOG_LEVEL5 } from "@xeno-js/shared";
4531
- import pino from "pino";
4532
- var PinoLoggerFactory;
4533
- var init_pino_logger_factory = __esm({
4534
- "src/infrastructure/factories/pino-logger.factory.ts"() {
4395
+ var ContextModule;
4396
+ var init_context_module = __esm({
4397
+ "src/infrastructure/modules/context.module.ts"() {
4535
4398
  "use strict";
4536
- init_pino_logger();
4537
- PinoLoggerFactory = class {
4538
- create(config) {
4539
- const level = config.level ?? LOG_LEVEL5.DEBUG;
4540
- const env = config.pino.config?.env ?? process.env.NODE_ENV ?? "development";
4541
- const destinationType = config.pino.config?.destination ?? "stdout";
4542
- const filePath = config.pino.config?.filePath ?? "logs/app.log";
4543
- const prettyPrint = config.pino.config?.prettyPrint ?? env === "development";
4544
- const options = {
4545
- level: "trace",
4546
- serializers: {
4547
- err: pino.stdSerializers.err
4548
- },
4549
- timestamp: pino.stdTimeFunctions.isoTime,
4550
- redact: {
4551
- paths: ["password", "token", "secret", "authorization", "headers.authorization"],
4552
- censor: "***"
4553
- }
4554
- };
4555
- if (prettyPrint) {
4556
- return new PinoLogger(
4557
- pino({
4558
- ...options,
4559
- transport: {
4560
- target: "pino-pretty",
4561
- options: {
4562
- colorize: true,
4563
- ignore: "pid,hostname",
4564
- translateTime: "SYS:standard"
4565
- }
4566
- }
4567
- }),
4568
- level
4569
- );
4570
- }
4571
- if (destinationType === "file") {
4572
- const destination = pino.destination({ dest: filePath, sync: false });
4573
- return new PinoLogger(pino(options, destination), level);
4574
- } else {
4575
- const stream = pino.destination({ dest: 1, sync: false });
4576
- return new PinoLogger(pino(options, stream), level);
4577
- }
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);
4415
+ });
4578
4416
  }
4579
4417
  };
4580
4418
  }
4581
4419
  });
4582
4420
 
4583
- // src/infrastructure/modules/utils/logger.utils.ts
4584
- var logger_utils_exports = {};
4585
- __export(logger_utils_exports, {
4586
- LoggerUtils: () => LoggerUtils
4421
+ // src/infrastructure/transaction/transaction-state.ts
4422
+ var transaction_state_exports = {};
4423
+ __export(transaction_state_exports, {
4424
+ TransactionState: () => TransactionState
4587
4425
  });
4588
- var LoggerUtils;
4589
- var init_logger_utils = __esm({
4590
- "src/infrastructure/modules/utils/logger.utils.ts"() {
4426
+ var TransactionState;
4427
+ var init_transaction_state = __esm({
4428
+ "src/infrastructure/transaction/transaction-state.ts"() {
4591
4429
  "use strict";
4592
- LoggerUtils = Object.freeze({
4430
+ TransactionState = class {
4593
4431
  /**
4594
- * @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.
4595
- *
4596
- * @param container - The service container to register logging services with.
4597
- * @param opts - The LoggerConfig options to determine which loggers to enable and their configurations.
4598
-
4599
- *
4432
+ * The current state of the transaction, which can be either a specific transaction type or null.
4600
4433
  * @author Xeno
4601
4434
  * @version 1.0.0
4602
4435
  * @since 2025-09-30
4603
- * @link https://github.com/xeno-js/xeno-js
4436
+ * @link https://github.com/xeno-js/xeno-js
4604
4437
  */
4605
- async addLogger(container, opts) {
4606
- const loggerDependencies = [];
4607
- const { Guards: Guards51, LOG_LEVEL: LOG_LEVEL7, TOKENS: TOKENS5 } = await import("@xeno-js/shared");
4608
- if (!Guards51.isDefined(opts) || opts.console) {
4609
- const { ConsoleLogger: ConsoleLogger2 } = await Promise.resolve().then(() => (init_console_logger(), console_logger_exports));
4610
- loggerDependencies.push(new ConsoleLogger2(opts?.level));
4611
- }
4612
- if (Guards51.isDefined(opts)) {
4613
- if (Guards51.isDefined(opts.sentry.config)) {
4614
- const { SentryLoggerFactory: SentryLoggerFactory2 } = await Promise.resolve().then(() => (init_sentry_logger_factory(), sentry_logger_factory_exports));
4615
- loggerDependencies.push(new SentryLoggerFactory2().create(opts));
4616
- }
4617
- if (Guards51.isDefined(opts.pino.config)) {
4618
- const { PinoLoggerFactory: PinoLoggerFactory2 } = await Promise.resolve().then(() => (init_pino_logger_factory(), pino_logger_factory_exports));
4619
- loggerDependencies.push(new PinoLoggerFactory2().create(opts));
4620
- }
4621
- if (!Guards51.isNullOrEmpty(opts.customLoggers)) {
4622
- const customLoggers = opts.customLoggers;
4623
- customLoggers.forEach((fn) => {
4624
- if (Guards51.isDefined(fn)) loggerDependencies.push(fn(container));
4625
- });
4626
- }
4627
- }
4628
- const { BaseLogger } = await import("@xeno-js/shared");
4629
- container.addSingleton(TOKENS5.LOGGER, (c) => {
4630
- const context = c.resolve(TOKENS5.CONTEXT_ACCESSOR);
4631
- return new BaseLogger(context, opts?.level ?? LOG_LEVEL7.DEBUG, loggerDependencies);
4632
- });
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;
4633
4449
  }
4634
- });
4635
- }
4636
- });
4637
-
4638
- // src/infrastructure/modules/utils/index.ts
4639
- var init_utils2 = __esm({
4640
- "src/infrastructure/modules/utils/index.ts"() {
4641
- "use strict";
4642
- init_auth_utils();
4643
- init_cache_utils();
4644
- init_db_utils();
4645
- init_http_utils();
4646
- init_logger_utils();
4647
- init_pipeline_utils();
4648
- init_validation_utils();
4450
+ get state() {
4451
+ return this._state;
4452
+ }
4453
+ set state(value) {
4454
+ this._state = value;
4455
+ }
4456
+ };
4649
4457
  }
4650
4458
  });
4651
4459
 
4652
- // src/infrastructure/modules/index.ts
4653
- var modules_exports = {};
4654
- __export(modules_exports, {
4655
- AuthUtils: () => AuthUtils,
4656
- CacheUtils: () => CacheUtils,
4657
- ContextModule: () => ContextModule,
4658
- CqrsModule: () => CqrsModule,
4659
- DbModule: () => DbModule,
4660
- DbUtils: () => DbUtils,
4661
- HttpAdapterModule: () => HttpAdapterModule,
4662
- HttpCoreModule: () => HttpCoreModule,
4663
- HttpUtils: () => HttpUtils,
4664
- LoggerUtils: () => LoggerUtils,
4665
- MiddlewareModule: () => MiddlewareModule,
4666
- PipelineUtils: () => PipelineUtils,
4667
- ValidationUtils: () => ValidationUtils
4460
+ // src/infrastructure/transaction/unit-of-work.ts
4461
+ var unit_of_work_exports = {};
4462
+ __export(unit_of_work_exports, {
4463
+ UnitOfWork: () => UnitOfWork
4668
4464
  });
4669
- var init_modules = __esm({
4670
- "src/infrastructure/modules/index.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"() {
4671
4470
  "use strict";
4672
- init_context_module();
4673
- init_cqrs_module();
4674
- init_db_module();
4675
- init_http_adapter_module();
4676
- init_http_core_module();
4677
- init_middleware_module();
4678
- init_utils2();
4471
+ UnitOfWork = class {
4472
+ /**
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.
4476
+ *
4477
+ * @author Xeno
4478
+ * @version 1.0.0
4479
+ * @since 2025-09-30
4480
+ * @link https://github.com/xeno-js/xeno-js
4481
+ */
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;
4497
+ }
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;
4508
+ }
4509
+ }
4510
+ }
4511
+ };
4679
4512
  }
4680
4513
  });
4681
4514
 
@@ -4683,7 +4516,7 @@ var init_modules = __esm({
4683
4516
  init_application();
4684
4517
 
4685
4518
  // src/infrastructure/builder/app.builder.ts
4686
- 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";
4687
4520
 
4688
4521
  // src/infrastructure/configuration/configuration.ts
4689
4522
  import { Guards as Guards13 } from "@xeno-js/shared";
@@ -5069,7 +4902,7 @@ var AppBuilder = class {
5069
4902
  priority: 50,
5070
4903
  name: "AdapterModule",
5071
4904
  action: async () => {
5072
- 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));
5073
4906
  await new HttpAdapterModule2().configure(this._container, this._adapterConfig);
5074
4907
  }
5075
4908
  });
@@ -5115,7 +4948,7 @@ var AppBuilder = class {
5115
4948
  * @link https://github.com/xeno-js/xeno-js
5116
4949
  */
5117
4950
  addLogger(setupAction) {
5118
- if (Guards48.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
4951
+ if (Guards47.isDefined(setupAction)) setupAction(this._loggerConfig, this._configuration);
5119
4952
  if (this._isLoggerModuleQueued) return this;
5120
4953
  this._isLoggerModuleQueued = true;
5121
4954
  this._modules.push({
@@ -5140,7 +4973,7 @@ var AppBuilder = class {
5140
4973
  * @link https://github.com/xeno-js/xeno-js
5141
4974
  */
5142
4975
  addCache(setupAction) {
5143
- if (Guards48.isDefined(setupAction)) setupAction(this._config, this._configuration);
4976
+ if (Guards47.isDefined(setupAction)) setupAction(this._config, this._configuration);
5144
4977
  if (this._isCacheModuleQueued) return this;
5145
4978
  this._isCacheModuleQueued = true;
5146
4979
  this._modules.push({
@@ -5189,21 +5022,11 @@ var AppBuilder = class {
5189
5022
  * @since 2025-09-30
5190
5023
  * @link https://github.com/xeno-js/xeno-js
5191
5024
  */
5192
- addDb(setupAction) {
5025
+ addDb(plugin) {
5193
5026
  if (this._isDbContextModuleQueued) return this;
5027
+ const result = plugin(this);
5194
5028
  this._isDbContextModuleQueued = true;
5195
- const config = { connectionString: "", enableSqlLite: false };
5196
- setupAction(config, this._configuration);
5197
- this._modules.push({
5198
- priority: 4,
5199
- name: "DbModule",
5200
- action: async () => {
5201
- const { DbModule: DbModule2 } = await Promise.resolve().then(() => (init_db_module(), db_module_exports));
5202
- const dbModule = new DbModule2();
5203
- await dbModule.configure(this._container, config);
5204
- }
5205
- });
5206
- return this;
5029
+ return result;
5207
5030
  }
5208
5031
  /**
5209
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.
@@ -5243,7 +5066,7 @@ var AppBuilder = class {
5243
5066
  * @link https://github.com/xeno-js/xeno-js
5244
5067
  */
5245
5068
  addPipeline(setupAction) {
5246
- if (Guards48.isDefined(setupAction)) {
5069
+ if (Guards47.isDefined(setupAction)) {
5247
5070
  setupAction(this._pipelineConfig, this._configuration);
5248
5071
  }
5249
5072
  this._queuePipelineModule();
@@ -5362,7 +5185,7 @@ var AppBuilder = class {
5362
5185
  console.error(`\u{1F449} Module: **${queued.name}**`);
5363
5186
  console.error(`\u{1F4DD} Reason: ${errorMessage}
5364
5187
  `);
5365
- if (error instanceof Error && Guards48.isDefined(error.stack)) {
5188
+ if (error instanceof Error && Guards47.isDefined(error.stack)) {
5366
5189
  console.error(error.stack);
5367
5190
  }
5368
5191
  throw new Error(`Bootstrap failed at [${queued.name}]: ${errorMessage}`, { cause: error });
@@ -5454,6 +5277,39 @@ var AppBuilder = class {
5454
5277
  // src/infrastructure/http/index.ts
5455
5278
  init_base_http_adapter();
5456
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
+
5457
5313
  // src/infrastructure/repositories/read-dao.ts
5458
5314
  import { AppError as AppError14, Result as Result16 } from "@xeno-js/shared";
5459
5315
  import { Guards as Guards49 } from "@xeno-js/shared";
@@ -5554,6 +5410,7 @@ export {
5554
5410
  BaseController,
5555
5411
  BaseHttpAdapter,
5556
5412
  ContainerUtils,
5413
+ DbModule,
5557
5414
  Query,
5558
5415
  ReadDao,
5559
5416
  Repository,