@cosmneo/onion-lasagna 0.1.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.
Files changed (97) hide show
  1. package/dist/backend/core/global.cjs +283 -0
  2. package/dist/backend/core/global.cjs.map +1 -0
  3. package/dist/backend/core/global.d.cts +294 -0
  4. package/dist/backend/core/global.d.ts +294 -0
  5. package/dist/backend/core/global.js +39 -0
  6. package/dist/backend/core/global.js.map +1 -0
  7. package/dist/backend/core/onion-layers.cjs +2302 -0
  8. package/dist/backend/core/onion-layers.cjs.map +1 -0
  9. package/dist/backend/core/onion-layers.d.cts +1675 -0
  10. package/dist/backend/core/onion-layers.d.ts +1675 -0
  11. package/dist/backend/core/onion-layers.js +1158 -0
  12. package/dist/backend/core/onion-layers.js.map +1 -0
  13. package/dist/backend/core/presentation.cjs +573 -0
  14. package/dist/backend/core/presentation.cjs.map +1 -0
  15. package/dist/backend/core/presentation.d.cts +5 -0
  16. package/dist/backend/core/presentation.d.ts +5 -0
  17. package/dist/backend/core/presentation.js +28 -0
  18. package/dist/backend/core/presentation.js.map +1 -0
  19. package/dist/backend/core/validators/arktype.cjs +947 -0
  20. package/dist/backend/core/validators/arktype.cjs.map +1 -0
  21. package/dist/backend/core/validators/arktype.d.cts +188 -0
  22. package/dist/backend/core/validators/arktype.d.ts +188 -0
  23. package/dist/backend/core/validators/arktype.js +287 -0
  24. package/dist/backend/core/validators/arktype.js.map +1 -0
  25. package/dist/backend/core/validators/typebox.cjs +939 -0
  26. package/dist/backend/core/validators/typebox.cjs.map +1 -0
  27. package/dist/backend/core/validators/typebox.d.cts +189 -0
  28. package/dist/backend/core/validators/typebox.d.ts +189 -0
  29. package/dist/backend/core/validators/typebox.js +281 -0
  30. package/dist/backend/core/validators/typebox.js.map +1 -0
  31. package/dist/backend/core/validators/valibot.cjs +942 -0
  32. package/dist/backend/core/validators/valibot.cjs.map +1 -0
  33. package/dist/backend/core/validators/valibot.d.cts +160 -0
  34. package/dist/backend/core/validators/valibot.d.ts +160 -0
  35. package/dist/backend/core/validators/valibot.js +294 -0
  36. package/dist/backend/core/validators/valibot.js.map +1 -0
  37. package/dist/backend/core/validators/zod.cjs +934 -0
  38. package/dist/backend/core/validators/zod.cjs.map +1 -0
  39. package/dist/backend/core/validators/zod.d.cts +188 -0
  40. package/dist/backend/core/validators/zod.d.ts +188 -0
  41. package/dist/backend/core/validators/zod.js +278 -0
  42. package/dist/backend/core/validators/zod.js.map +1 -0
  43. package/dist/backend/frameworks/elysia.cjs +715 -0
  44. package/dist/backend/frameworks/elysia.cjs.map +1 -0
  45. package/dist/backend/frameworks/elysia.d.cts +208 -0
  46. package/dist/backend/frameworks/elysia.d.ts +208 -0
  47. package/dist/backend/frameworks/elysia.js +251 -0
  48. package/dist/backend/frameworks/elysia.js.map +1 -0
  49. package/dist/backend/frameworks/fastify.cjs +677 -0
  50. package/dist/backend/frameworks/fastify.cjs.map +1 -0
  51. package/dist/backend/frameworks/fastify.d.cts +201 -0
  52. package/dist/backend/frameworks/fastify.d.ts +201 -0
  53. package/dist/backend/frameworks/fastify.js +213 -0
  54. package/dist/backend/frameworks/fastify.js.map +1 -0
  55. package/dist/backend/frameworks/hono.cjs +715 -0
  56. package/dist/backend/frameworks/hono.cjs.map +1 -0
  57. package/dist/backend/frameworks/hono.d.cts +163 -0
  58. package/dist/backend/frameworks/hono.d.ts +163 -0
  59. package/dist/backend/frameworks/hono.js +249 -0
  60. package/dist/backend/frameworks/hono.js.map +1 -0
  61. package/dist/backend/frameworks/nestjs.cjs +260 -0
  62. package/dist/backend/frameworks/nestjs.cjs.map +1 -0
  63. package/dist/backend/frameworks/nestjs.d.cts +168 -0
  64. package/dist/backend/frameworks/nestjs.d.ts +168 -0
  65. package/dist/backend/frameworks/nestjs.js +193 -0
  66. package/dist/backend/frameworks/nestjs.js.map +1 -0
  67. package/dist/base-dto.class-D7W9iqoU.d.cts +146 -0
  68. package/dist/base-dto.class-D7W9iqoU.d.ts +146 -0
  69. package/dist/base-uuid-v7.vo-BPGEIWLM.d.ts +799 -0
  70. package/dist/base-uuid-v7.vo-BjqKX44G.d.cts +799 -0
  71. package/dist/chunk-74IKUOSE.js +116 -0
  72. package/dist/chunk-74IKUOSE.js.map +1 -0
  73. package/dist/chunk-BKZOLGQW.js +29 -0
  74. package/dist/chunk-BKZOLGQW.js.map +1 -0
  75. package/dist/chunk-CGZBV6BD.js +54 -0
  76. package/dist/chunk-CGZBV6BD.js.map +1 -0
  77. package/dist/chunk-DDAHJZVK.js +258 -0
  78. package/dist/chunk-DDAHJZVK.js.map +1 -0
  79. package/dist/chunk-MQD5GXMT.js +171 -0
  80. package/dist/chunk-MQD5GXMT.js.map +1 -0
  81. package/dist/chunk-OKFXZHBC.js +43 -0
  82. package/dist/chunk-OKFXZHBC.js.map +1 -0
  83. package/dist/chunk-RLLWYFPI.js +168 -0
  84. package/dist/chunk-RLLWYFPI.js.map +1 -0
  85. package/dist/chunk-VCHFXT5W.js +425 -0
  86. package/dist/chunk-VCHFXT5W.js.map +1 -0
  87. package/dist/chunk-ZWLYNGO3.js +40 -0
  88. package/dist/chunk-ZWLYNGO3.js.map +1 -0
  89. package/dist/http-response-BAhi8lF4.d.cts +124 -0
  90. package/dist/http-response-BAhi8lF4.d.ts +124 -0
  91. package/dist/index-DingXh7B.d.cts +1187 -0
  92. package/dist/index-tOH7XBa3.d.ts +1187 -0
  93. package/dist/routing.type-DB4pt-d9.d.ts +184 -0
  94. package/dist/routing.type-DF2BIL7x.d.cts +184 -0
  95. package/dist/validation-error.type-kD4_qNZ9.d.cts +199 -0
  96. package/dist/validation-error.type-kD4_qNZ9.d.ts +199 -0
  97. package/package.json +191 -0
@@ -0,0 +1,116 @@
1
+ import {
2
+ CodedError,
3
+ ErrorCodes
4
+ } from "./chunk-MQD5GXMT.js";
5
+
6
+ // src/backend/core/onion-layers/presentation/exceptions/controller.error.ts
7
+ var ControllerError = class _ControllerError extends CodedError {
8
+ /**
9
+ * Creates a new ControllerError instance.
10
+ *
11
+ * @param options - Error configuration
12
+ * @param options.message - Human-readable error description
13
+ * @param options.code - Machine-readable error code (default: 'CONTROLLER_ERROR')
14
+ * @param options.cause - Optional underlying error
15
+ */
16
+ constructor({
17
+ message,
18
+ code = ErrorCodes.Presentation.CONTROLLER_ERROR,
19
+ cause
20
+ }) {
21
+ super({ message, code, cause });
22
+ }
23
+ /**
24
+ * Creates a ControllerError from a caught error.
25
+ *
26
+ * @param cause - The original caught error
27
+ * @returns A new ControllerError instance with the cause attached
28
+ */
29
+ static fromError(cause) {
30
+ return new _ControllerError({
31
+ message: cause instanceof Error ? cause.message : "Controller error",
32
+ cause
33
+ });
34
+ }
35
+ };
36
+
37
+ // src/backend/core/onion-layers/presentation/exceptions/invalid-request.error.ts
38
+ var InvalidRequestError = class _InvalidRequestError extends CodedError {
39
+ /**
40
+ * Array of field-level validation errors.
41
+ *
42
+ * Each entry contains:
43
+ * - `field`: Dot-notation path to the invalid field
44
+ * - `message`: Human-readable validation failure message
45
+ */
46
+ validationErrors;
47
+ /**
48
+ * Creates a new InvalidRequestError instance.
49
+ *
50
+ * @param options - Error configuration
51
+ * @param options.message - Summary of the validation failure
52
+ * @param options.code - Machine-readable error code (default: 'INVALID_REQUEST')
53
+ * @param options.cause - Optional underlying error
54
+ * @param options.validationErrors - Array of field-level validation errors
55
+ */
56
+ constructor({
57
+ message,
58
+ code = ErrorCodes.Presentation.INVALID_REQUEST,
59
+ cause,
60
+ validationErrors
61
+ }) {
62
+ super({ message, code, cause });
63
+ this.validationErrors = validationErrors;
64
+ }
65
+ /**
66
+ * Creates an InvalidRequestError from a caught error.
67
+ *
68
+ * @param cause - The original caught error
69
+ * @returns A new InvalidRequestError instance with the cause attached
70
+ */
71
+ static fromError(cause) {
72
+ return new _InvalidRequestError({
73
+ message: cause instanceof Error ? cause.message : "Invalid request",
74
+ cause,
75
+ validationErrors: []
76
+ });
77
+ }
78
+ };
79
+
80
+ // src/backend/core/onion-layers/presentation/exceptions/access-denied.error.ts
81
+ var AccessDeniedError = class _AccessDeniedError extends CodedError {
82
+ /**
83
+ * Creates a new AccessDeniedError instance.
84
+ *
85
+ * @param options - Error configuration
86
+ * @param options.message - Description of why access was denied
87
+ * @param options.code - Machine-readable error code (default: 'ACCESS_DENIED')
88
+ * @param options.cause - Optional underlying error
89
+ */
90
+ constructor({
91
+ message,
92
+ code = ErrorCodes.Presentation.ACCESS_DENIED,
93
+ cause
94
+ }) {
95
+ super({ message, code, cause });
96
+ }
97
+ /**
98
+ * Creates an AccessDeniedError from a caught error.
99
+ *
100
+ * @param cause - The original caught error
101
+ * @returns A new AccessDeniedError instance with the cause attached
102
+ */
103
+ static fromError(cause) {
104
+ return new _AccessDeniedError({
105
+ message: cause instanceof Error ? cause.message : "Access denied",
106
+ cause
107
+ });
108
+ }
109
+ };
110
+
111
+ export {
112
+ ControllerError,
113
+ InvalidRequestError,
114
+ AccessDeniedError
115
+ };
116
+ //# sourceMappingURL=chunk-74IKUOSE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/core/onion-layers/presentation/exceptions/controller.error.ts","../src/backend/core/onion-layers/presentation/exceptions/invalid-request.error.ts","../src/backend/core/onion-layers/presentation/exceptions/access-denied.error.ts"],"sourcesContent":["import { CodedError } from '../../../global/exceptions/coded-error.error';\nimport {\n ErrorCodes,\n type PresentationErrorCode,\n} from '../../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for presentation layer (controller) failures.\n *\n * Controller errors represent failures in request handling,\n * such as access control violations or malformed requests.\n * They are the outermost error layer and typically map to HTTP responses.\n *\n * **When to throw:**\n * - Access control failures (unauthorized/forbidden)\n * - Request validation failures\n * - Unexpected controller execution errors\n *\n * **Child classes:**\n * - {@link AccessDeniedError} - Authorization failures (HTTP 403)\n * - {@link InvalidRequestError} - Request validation failures (HTTP 400)\n *\n * @example\n * ```typescript\n * // Thrown automatically by BaseController for unexpected errors\n * throw new ControllerError({\n * message: 'Controller execution failed',\n * cause: originalError,\n * });\n * ```\n */\nexport class ControllerError extends CodedError {\n /**\n * Creates a new ControllerError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'CONTROLLER_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.CONTROLLER_ERROR,\n cause,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a ControllerError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ControllerError instance with the cause attached\n */\n static override fromError(cause: unknown): ControllerError {\n return new ControllerError({\n message: cause instanceof Error ? cause.message : 'Controller error',\n cause,\n });\n }\n}\n","import { CodedError } from '../../../global/exceptions/coded-error.error';\nimport {\n ErrorCodes,\n type PresentationErrorCode,\n} from '../../../global/exceptions/error-codes.const';\nimport type { ValidationError } from '../../../global/interfaces/types/validation-error.type';\n\n/**\n * Error thrown when request validation fails at the controller level.\n *\n * Contains structured validation errors with field paths and messages,\n * converted from {@link ObjectValidationError} by {@link BaseController}.\n * Provides detailed feedback about which fields failed validation.\n *\n * **When thrown:**\n * - Request DTO validation fails\n * - Malformed request data\n * - Missing required fields\n *\n * @example\n * ```typescript\n * // Automatically thrown by BaseController when DTO validation fails\n * // The validationErrors array contains field-level details:\n * // [\n * // { field: 'email', message: 'Invalid email format' },\n * // { field: 'age', message: 'Must be a positive number' }\n * // ]\n * ```\n *\n * @example Manual usage\n * ```typescript\n * throw new InvalidRequestError({\n * message: 'Request validation failed',\n * validationErrors: [\n * { field: 'username', message: 'Username is required' },\n * ],\n * });\n * ```\n *\n * @extends CodedError\n */\nexport class InvalidRequestError extends CodedError {\n /**\n * Array of field-level validation errors.\n *\n * Each entry contains:\n * - `field`: Dot-notation path to the invalid field\n * - `message`: Human-readable validation failure message\n */\n readonly validationErrors: ValidationError[];\n\n /**\n * Creates a new InvalidRequestError instance.\n *\n * @param options - Error configuration\n * @param options.message - Summary of the validation failure\n * @param options.code - Machine-readable error code (default: 'INVALID_REQUEST')\n * @param options.cause - Optional underlying error\n * @param options.validationErrors - Array of field-level validation errors\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.INVALID_REQUEST,\n cause,\n validationErrors,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n validationErrors: ValidationError[];\n }) {\n super({ message, code, cause });\n this.validationErrors = validationErrors;\n }\n\n /**\n * Creates an InvalidRequestError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new InvalidRequestError instance with the cause attached\n */\n static override fromError(cause: unknown): InvalidRequestError {\n return new InvalidRequestError({\n message: cause instanceof Error ? cause.message : 'Invalid request',\n cause,\n validationErrors: [],\n });\n }\n}\n","import { CodedError } from '../../../global/exceptions/coded-error.error';\nimport {\n ErrorCodes,\n type PresentationErrorCode,\n} from '../../../global/exceptions/error-codes.const';\n\n/**\n * Error thrown when access to a resource is denied.\n *\n * Indicates that the requester does not have permission to perform\n * the requested operation. Thrown by {@link GuardedController} when\n * an access guard returns `isAllowed: false`.\n *\n * **When thrown:**\n * - Access guard denies the request\n * - User lacks required permissions\n * - Resource ownership check fails\n *\n * @example GuardedController usage\n * ```typescript\n * const controller = GuardedController.create({\n * accessGuard: (req) => ({\n * isAllowed: req.user?.role === 'admin',\n * reason: 'Admin access required',\n * }),\n * // ... other config\n * });\n * ```\n *\n * @example Manual usage\n * ```typescript\n * if (!user.canAccess(resource)) {\n * throw new AccessDeniedError({\n * message: 'You do not have access to this resource',\n * code: 'RESOURCE_ACCESS_DENIED',\n * });\n * }\n * ```\n *\n * @extends CodedError\n */\nexport class AccessDeniedError extends CodedError {\n /**\n * Creates a new AccessDeniedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why access was denied\n * @param options.code - Machine-readable error code (default: 'ACCESS_DENIED')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.ACCESS_DENIED,\n cause,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an AccessDeniedError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new AccessDeniedError instance with the cause attached\n */\n static override fromError(cause: unknown): AccessDeniedError {\n return new AccessDeniedError({\n message: cause instanceof Error ? cause.message : 'Access denied',\n cause,\n });\n }\n}\n"],"mappings":";;;;;;AA+BO,IAAM,kBAAN,MAAM,yBAAwB,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS9C,YAAY;AAAA,IACV;AAAA,IACA,OAAO,WAAW,aAAa;AAAA,IAC/B;AAAA,EACF,GAIG;AACD,UAAM,EAAE,SAAS,MAAM,MAAM,CAAC;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAgB,UAAU,OAAiC;AACzD,WAAO,IAAI,iBAAgB;AAAA,MACzB,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MAClD;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACvBO,IAAM,sBAAN,MAAM,6BAA4B,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWT,YAAY;AAAA,IACV;AAAA,IACA,OAAO,WAAW,aAAa;AAAA,IAC/B;AAAA,IACA;AAAA,EACF,GAKG;AACD,UAAM,EAAE,SAAS,MAAM,MAAM,CAAC;AAC9B,SAAK,mBAAmB;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAgB,UAAU,OAAqC;AAC7D,WAAO,IAAI,qBAAoB;AAAA,MAC7B,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MAClD;AAAA,MACA,kBAAkB,CAAC;AAAA,IACrB,CAAC;AAAA,EACH;AACF;;;AC/CO,IAAM,oBAAN,MAAM,2BAA0B,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShD,YAAY;AAAA,IACV;AAAA,IACA,OAAO,WAAW,aAAa;AAAA,IAC/B;AAAA,EACF,GAIG;AACD,UAAM,EAAE,SAAS,MAAM,MAAM,CAAC;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAgB,UAAU,OAAmC;AAC3D,WAAO,IAAI,mBAAkB;AAAA,MAC3B,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MAClD;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,29 @@
1
+ // src/backend/core/global/classes/base-dto.class.ts
2
+ var SKIP_DTO_VALIDATION = "skip dto validation";
3
+ var BaseDto = class {
4
+ _data;
5
+ /**
6
+ * Creates a new DTO instance.
7
+ *
8
+ * @param data - The raw data to validate and wrap
9
+ * @param validator - A bound validator or SKIP_DTO_VALIDATION to bypass
10
+ * @throws {ObjectValidationError} When validation fails
11
+ */
12
+ constructor(data, validator) {
13
+ this._data = validator === SKIP_DTO_VALIDATION ? data : validator.validate(data);
14
+ }
15
+ /**
16
+ * The validated data payload.
17
+ *
18
+ * @returns The validated data of type T
19
+ */
20
+ get data() {
21
+ return this._data;
22
+ }
23
+ };
24
+
25
+ export {
26
+ SKIP_DTO_VALIDATION,
27
+ BaseDto
28
+ };
29
+ //# sourceMappingURL=chunk-BKZOLGQW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/core/global/classes/base-dto.class.ts"],"sourcesContent":["import type { BoundValidator } from '../interfaces/ports/object-validator.port';\n\n/**\n * Sentinel value to skip validation in DTO constructors.\n *\n * Use this when creating a DTO from already-validated data,\n * such as when mapping between layers or in tests.\n *\n * @example\n * ```typescript\n * // Skip validation for already-validated data\n * const dto = new CreateUserInputDto(validatedData, SKIP_DTO_VALIDATION);\n * ```\n */\nexport const SKIP_DTO_VALIDATION = 'skip dto validation' as const;\n\n/**\n * Base class for Data Transfer Objects (DTOs).\n *\n * DTOs are validated data containers used to transfer data between layers.\n * Unlike Value Objects, DTOs are not domain concepts - they are purely\n * for data transfer and validation at system boundaries.\n *\n * Key differences from Value Objects:\n * - **DTOs**: Transfer data between layers (e.g., request/response payloads)\n * - **Value Objects**: Represent domain concepts with behavior (e.g., Email, Money)\n *\n * @typeParam T - The shape of the data being transferred\n *\n * @example\n * ```typescript\n * // Define a DTO with validation\n * class CreateUserInputDto extends BaseDto<{ name: string; email: string }> {\n * private constructor(data: unknown, validator: BoundValidator<{ name: string; email: string }>) {\n * super(data, validator);\n * }\n *\n * static create(data: unknown): CreateUserInputDto {\n * return new CreateUserInputDto(data, createUserValidator);\n * }\n * }\n *\n * // Usage in a controller\n * const dto = CreateUserInputDto.create(request.body);\n * console.log(dto.data.name); // Typed and validated\n * ```\n */\nexport class BaseDto<T> {\n private readonly _data: T;\n\n /**\n * Creates a new DTO instance.\n *\n * @param data - The raw data to validate and wrap\n * @param validator - A bound validator or SKIP_DTO_VALIDATION to bypass\n * @throws {ObjectValidationError} When validation fails\n */\n constructor(data: T, validator: BoundValidator<T> | typeof SKIP_DTO_VALIDATION) {\n this._data = validator === SKIP_DTO_VALIDATION ? data : validator.validate(data);\n }\n\n /**\n * The validated data payload.\n *\n * @returns The validated data of type T\n */\n public get data(): T {\n return this._data;\n }\n}\n"],"mappings":";AAcO,IAAM,sBAAsB;AAiC5B,IAAM,UAAN,MAAiB;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjB,YAAY,MAAS,WAA2D;AAC9E,SAAK,QAAQ,cAAc,sBAAsB,OAAO,UAAU,SAAS,IAAI;AAAA,EACjF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAW,OAAU;AACnB,WAAO,KAAK;AAAA,EACd;AACF;","names":[]}
@@ -0,0 +1,54 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
11
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
12
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
13
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
14
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
15
+ var __runInitializers = (array, flags, self, value) => {
16
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
17
+ return value;
18
+ };
19
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
20
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
21
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
22
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
23
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
24
+ return __privateGet(this, extra);
25
+ }, set [name](x) {
26
+ return __privateSet(this, extra, x);
27
+ } }, name));
28
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
29
+ for (var i = decorators.length - 1; i >= 0; i--) {
30
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
31
+ if (k) {
32
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
33
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
34
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
35
+ }
36
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
37
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
38
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
39
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
40
+ }
41
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
42
+ };
43
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
44
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
45
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
46
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
47
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
48
+
49
+ export {
50
+ __decoratorStart,
51
+ __runInitializers,
52
+ __decorateElement
53
+ };
54
+ //# sourceMappingURL=chunk-CGZBV6BD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,258 @@
1
+ import {
2
+ wrapErrorUnless,
3
+ wrapErrorUnlessAsync
4
+ } from "./chunk-OKFXZHBC.js";
5
+ import {
6
+ AccessDeniedError,
7
+ ControllerError,
8
+ InvalidRequestError
9
+ } from "./chunk-74IKUOSE.js";
10
+ import {
11
+ CodedError,
12
+ ObjectValidationError
13
+ } from "./chunk-MQD5GXMT.js";
14
+
15
+ // src/backend/core/onion-layers/presentation/classes/base-controller.class.ts
16
+ var BaseController = class _BaseController {
17
+ /**
18
+ * Creates a new BaseController instance.
19
+ *
20
+ * @param requestMapper - Function to map request DTO to use case input DTO
21
+ * @param useCase - The use case port to execute
22
+ * @param responseMapper - Function to map use case output DTO to response DTO
23
+ */
24
+ constructor(requestMapper, useCase, responseMapper) {
25
+ this.requestMapper = requestMapper;
26
+ this.useCase = useCase;
27
+ this.responseMapper = responseMapper;
28
+ }
29
+ /**
30
+ * Factory method to create a controller from a configuration object.
31
+ *
32
+ * @param config - Controller configuration
33
+ * @returns A new BaseController instance
34
+ */
35
+ static create(config) {
36
+ return new _BaseController(config.requestMapper, config.useCase, config.responseMapper);
37
+ }
38
+ /**
39
+ * Executes the controller pipeline with error wrapping.
40
+ *
41
+ * This is the public entry point that ensures consistent error handling.
42
+ * All errors are wrapped in {@link ControllerError} unless they extend {@link CodedError}.
43
+ *
44
+ * **Do not override this method.** Override {@link pipeline} instead for custom pipeline logic.
45
+ *
46
+ * @param input - The validated request DTO
47
+ * @returns Promise resolving to the validated response DTO
48
+ * @throws {InvalidRequestError} When request mapping/validation fails
49
+ * @throws {ControllerError} When an unexpected error occurs
50
+ * @throws {CodedError} When use case throws a known error type
51
+ */
52
+ async execute(input) {
53
+ return wrapErrorUnlessAsync(
54
+ () => this.pipeline(input),
55
+ (cause) => new ControllerError({
56
+ message: cause instanceof Error ? cause.message : "Controller execution failed",
57
+ cause
58
+ }),
59
+ [CodedError]
60
+ );
61
+ }
62
+ /**
63
+ * Runs the controller pipeline.
64
+ *
65
+ * Orchestrates: `mapRequest → executeUseCase → mapResponse`
66
+ *
67
+ * Override this method to customize the entire pipeline flow, or override
68
+ * individual protected methods ({@link mapRequest}, {@link executeUseCase},
69
+ * {@link mapResponse}) for more granular control.
70
+ *
71
+ * @param input - The validated request DTO
72
+ * @returns Promise resolving to the validated response DTO
73
+ */
74
+ async pipeline(input) {
75
+ const mappedInput = this.mapRequest(input);
76
+ const result = await this.executeUseCase(mappedInput);
77
+ return this.mapResponse(result);
78
+ }
79
+ /**
80
+ * Maps the request DTO to a use case input DTO.
81
+ *
82
+ * Override to add custom pre-processing, logging, or transformation logic.
83
+ * The default implementation uses the configured `requestMapper` and converts
84
+ * {@link ObjectValidationError} to {@link InvalidRequestError}.
85
+ *
86
+ * @param input - The validated request DTO
87
+ * @returns The use case input DTO
88
+ * @throws {InvalidRequestError} When validation fails
89
+ * @throws {ControllerError} When mapping fails unexpectedly
90
+ */
91
+ mapRequest(input) {
92
+ return wrapErrorUnless(
93
+ () => this.requestMapper(input),
94
+ (cause) => {
95
+ if (cause instanceof ObjectValidationError) {
96
+ return new InvalidRequestError({
97
+ message: cause.message,
98
+ cause,
99
+ validationErrors: cause.validationErrors
100
+ });
101
+ }
102
+ return new ControllerError({
103
+ message: cause instanceof Error ? cause.message : "Request mapping failed",
104
+ cause
105
+ });
106
+ },
107
+ [CodedError]
108
+ );
109
+ }
110
+ /**
111
+ * Executes the use case with the mapped input.
112
+ *
113
+ * Override to add custom logic around use case execution, such as:
114
+ * - Logging/tracing
115
+ * - Caching
116
+ * - Retry logic
117
+ * - Multi-use-case orchestration
118
+ *
119
+ * @param input - The use case input DTO
120
+ * @returns Promise resolving to the use case output DTO
121
+ */
122
+ async executeUseCase(input) {
123
+ return this.useCase.execute(input);
124
+ }
125
+ /**
126
+ * Maps the use case output DTO to a response DTO.
127
+ *
128
+ * Override to add custom post-processing, logging, or transformation logic.
129
+ * The default implementation uses the configured `responseMapper`.
130
+ *
131
+ * @param output - The use case output DTO
132
+ * @returns The response DTO
133
+ * @throws {ControllerError} When mapping or validation fails
134
+ */
135
+ mapResponse(output) {
136
+ return wrapErrorUnless(
137
+ () => this.responseMapper(output),
138
+ (cause) => new ControllerError({
139
+ message: cause instanceof ObjectValidationError ? "Response validation failed" : cause instanceof Error ? cause.message : "Response mapping failed",
140
+ cause
141
+ }),
142
+ [CodedError]
143
+ );
144
+ }
145
+ };
146
+
147
+ // src/backend/core/onion-layers/presentation/classes/guarded-controller.class.ts
148
+ function createAllowAllGuard() {
149
+ return async () => ({
150
+ isAllowed: true
151
+ });
152
+ }
153
+ var GuardedController = class _GuardedController extends BaseController {
154
+ /** The access guard function for this controller. */
155
+ accessGuard;
156
+ /**
157
+ * Creates a new GuardedController instance.
158
+ *
159
+ * @param requestMapper - Function to map request DTO to use case input DTO
160
+ * @param useCase - The use case port to execute
161
+ * @param responseMapper - Function to map use case output DTO to response DTO
162
+ * @param accessGuard - Optional access guard; defaults to allowing all
163
+ */
164
+ constructor(requestMapper, useCase, responseMapper, accessGuard) {
165
+ super(requestMapper, useCase, responseMapper);
166
+ this.accessGuard = accessGuard ?? createAllowAllGuard();
167
+ }
168
+ /**
169
+ * Factory method to create a guarded controller from a configuration object.
170
+ *
171
+ * @param config - Controller configuration including optional access guard
172
+ * @returns A new GuardedController instance
173
+ */
174
+ static create(config) {
175
+ return new _GuardedController(
176
+ config.requestMapper,
177
+ config.useCase,
178
+ config.responseMapper,
179
+ config.accessGuard
180
+ );
181
+ }
182
+ /**
183
+ * Runs the controller pipeline with access control.
184
+ *
185
+ * Checks the access guard before executing the pipeline.
186
+ * If denied, throws {@link AccessDeniedError}.
187
+ *
188
+ * @param input - The validated request DTO
189
+ * @returns Promise resolving to the validated response DTO
190
+ * @throws {AccessDeniedError} When access guard denies the request
191
+ */
192
+ async pipeline(input) {
193
+ await this.checkAccess(input);
194
+ return super.pipeline(input);
195
+ }
196
+ /**
197
+ * Checks access using the configured guard.
198
+ *
199
+ * Override to customize access control logic.
200
+ *
201
+ * @param input - The validated request DTO
202
+ * @throws {AccessDeniedError} When access is denied
203
+ */
204
+ async checkAccess(input) {
205
+ const result = await this.accessGuard(input);
206
+ if (!result.isAllowed) {
207
+ throw new AccessDeniedError({
208
+ message: result.reason ?? "Access denied"
209
+ });
210
+ }
211
+ }
212
+ };
213
+
214
+ // src/backend/core/onion-layers/presentation/interfaces/types/metadata/system-metadata.type.ts
215
+ function defineSystemMetadata(metadata) {
216
+ return metadata;
217
+ }
218
+
219
+ // src/backend/core/onion-layers/presentation/routing/compute-route-path.util.ts
220
+ function trimSlashes(segment) {
221
+ return segment.replace(/^\/+|\/+$/g, "");
222
+ }
223
+ function computeRoutePath(service, resource, endpoint) {
224
+ const segments = [service.basePath, resource.path, endpoint.path].map(trimSlashes).filter((s) => s.length > 0);
225
+ if (segments.length === 0) {
226
+ return "/";
227
+ }
228
+ return "/" + segments.join("/");
229
+ }
230
+
231
+ // src/backend/core/onion-layers/presentation/utils/http-response.util.ts
232
+ function isHttpResponse(value) {
233
+ return typeof value === "object" && value !== null && "statusCode" in value && typeof value.statusCode === "number";
234
+ }
235
+ function assertHttpResponse(value, context = "value") {
236
+ if (!isHttpResponse(value)) {
237
+ const actualType = value === null ? "null" : value === void 0 ? "undefined" : typeof value;
238
+ const hasStatusCode = typeof value === "object" && value !== null && "statusCode" in value;
239
+ let message = `Expected ${context} to be an HttpResponse with a numeric statusCode, `;
240
+ if (hasStatusCode) {
241
+ const statusCodeType = typeof value["statusCode"];
242
+ message += `but statusCode was ${statusCodeType}`;
243
+ } else {
244
+ message += `but got ${actualType}`;
245
+ }
246
+ throw new Error(message);
247
+ }
248
+ }
249
+
250
+ export {
251
+ BaseController,
252
+ GuardedController,
253
+ defineSystemMetadata,
254
+ computeRoutePath,
255
+ isHttpResponse,
256
+ assertHttpResponse
257
+ };
258
+ //# sourceMappingURL=chunk-DDAHJZVK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/core/onion-layers/presentation/classes/base-controller.class.ts","../src/backend/core/onion-layers/presentation/classes/guarded-controller.class.ts","../src/backend/core/onion-layers/presentation/interfaces/types/metadata/system-metadata.type.ts","../src/backend/core/onion-layers/presentation/routing/compute-route-path.util.ts","../src/backend/core/onion-layers/presentation/utils/http-response.util.ts"],"sourcesContent":["import type { BaseInboundPort } from '../../app/interfaces/ports/base-inbound.port';\nimport type { BaseDto } from '../../../global/classes/base-dto.class';\nimport { CodedError } from '../../../global/exceptions/coded-error.error';\nimport { ObjectValidationError } from '../../../global/exceptions/object-validation.error';\nimport { wrapErrorUnless, wrapErrorUnlessAsync } from '../../../global/utils/wrap-error.util';\nimport { ControllerError } from '../exceptions/controller.error';\nimport { InvalidRequestError } from '../exceptions/invalid-request.error';\n\n/**\n * Configuration for creating a BaseController instance.\n *\n * All types must be DTOs (extending BaseDto) to ensure validation at every boundary:\n * - TRequestDto: Validated HTTP request (body, headers, params, query)\n * - TResponseDto: Validated HTTP response structure\n * - TInDto: Validated use case input\n * - TOutDto: Validated use case output\n *\n * @typeParam TRequestDto - Validated request DTO from the framework layer\n * @typeParam TResponseDto - Validated response DTO to return to the framework\n * @typeParam TInDto - Input DTO type for the use case\n * @typeParam TOutDto - Output DTO type from the use case\n */\nexport interface BaseControllerConfig<\n TRequestDto extends BaseDto<unknown>,\n TResponseDto extends BaseDto<unknown>,\n TInDto extends BaseDto<unknown>,\n TOutDto extends BaseDto<unknown>,\n> {\n /** Maps the validated request DTO to a use case input DTO. */\n requestMapper: (request: TRequestDto) => TInDto;\n /** The use case to execute. */\n useCase: BaseInboundPort<TInDto, TOutDto>;\n /** Maps the use case output DTO to a validated response DTO. */\n responseMapper: (output: TOutDto) => TResponseDto;\n}\n\n/**\n * Base controller implementing the request/response pipeline.\n *\n * Orchestrates the flow: `requestDto → mapRequest → executeUseCase → mapResponse → responseDto`\n *\n * All boundaries are validated DTOs:\n * - Input: TRequestDto (validated by framework layer before controller)\n * - Use case input: TInDto (validated by mapRequest)\n * - Use case output: TOutDto (validated by use case)\n * - Output: TResponseDto (validated by mapResponse)\n *\n * Features:\n * - Converts {@link ObjectValidationError} to {@link InvalidRequestError}\n * - Passes through known {@link CodedError} types\n * - Wraps unknown errors in {@link ControllerError}\n *\n * Architecture:\n * - {@link execute} - Public entry point with error wrapping (do not override)\n * - {@link pipeline} - Protected pipeline orchestration (override for custom flow)\n * - {@link mapRequest} - Request-to-input transformation\n * - {@link executeUseCase} - Use case execution\n * - {@link mapResponse} - Output-to-response transformation\n *\n * @typeParam TRequestDto - Validated request DTO from the framework layer\n * @typeParam TResponseDto - Validated response DTO to return to the framework\n * @typeParam TInDto - Input DTO type for the use case\n * @typeParam TOutDto - Output DTO type from the use case\n *\n * @example Basic usage\n * ```typescript\n * const controller = BaseController.create({\n * requestMapper: (req) => CreateUserInputDto.create(req.data),\n * useCase: createUserUseCase,\n * responseMapper: (output) => CreateUserResponseDto.create({ id: output.data.id }),\n * });\n *\n * // Framework layer creates the request DTO\n * const requestDto = CreateUserRequestDto.create(httpRequest);\n * const responseDto = await controller.execute(requestDto);\n * ```\n *\n * @example Custom controller overriding pipeline\n * ```typescript\n * class LoggingController extends BaseController<...> {\n * protected override async pipeline(input: TRequestDto): Promise<TResponseDto> {\n * console.log('Request received:', input);\n * const result = await super.pipeline(input);\n * console.log('Response:', result);\n * return result;\n * }\n * }\n * ```\n *\n * @example Custom controller overriding individual methods\n * ```typescript\n * class CachingController extends BaseController<...> {\n * private cache = new Map();\n *\n * protected override async executeUseCase(input: TInDto): Promise<TOutDto> {\n * const key = JSON.stringify(input.data);\n * if (this.cache.has(key)) return this.cache.get(key);\n * const result = await super.executeUseCase(input);\n * this.cache.set(key, result);\n * return result;\n * }\n * }\n * ```\n */\nexport class BaseController<\n TRequestDto extends BaseDto<unknown>,\n TResponseDto extends BaseDto<unknown>,\n TInDto extends BaseDto<unknown>,\n TOutDto extends BaseDto<unknown>,\n> {\n /**\n * Creates a new BaseController instance.\n *\n * @param requestMapper - Function to map request DTO to use case input DTO\n * @param useCase - The use case port to execute\n * @param responseMapper - Function to map use case output DTO to response DTO\n */\n constructor(\n protected readonly requestMapper: (request: TRequestDto) => TInDto,\n protected readonly useCase: BaseInboundPort<TInDto, TOutDto>,\n protected readonly responseMapper: (output: TOutDto) => TResponseDto,\n ) {}\n\n /**\n * Factory method to create a controller from a configuration object.\n *\n * @param config - Controller configuration\n * @returns A new BaseController instance\n */\n static create<\n TRequestDto extends BaseDto<unknown>,\n TResponseDto extends BaseDto<unknown>,\n TInDto extends BaseDto<unknown>,\n TOutDto extends BaseDto<unknown>,\n >(\n config: BaseControllerConfig<TRequestDto, TResponseDto, TInDto, TOutDto>,\n ): BaseController<TRequestDto, TResponseDto, TInDto, TOutDto> {\n return new BaseController(config.requestMapper, config.useCase, config.responseMapper);\n }\n\n /**\n * Executes the controller pipeline with error wrapping.\n *\n * This is the public entry point that ensures consistent error handling.\n * All errors are wrapped in {@link ControllerError} unless they extend {@link CodedError}.\n *\n * **Do not override this method.** Override {@link pipeline} instead for custom pipeline logic.\n *\n * @param input - The validated request DTO\n * @returns Promise resolving to the validated response DTO\n * @throws {InvalidRequestError} When request mapping/validation fails\n * @throws {ControllerError} When an unexpected error occurs\n * @throws {CodedError} When use case throws a known error type\n */\n async execute(input: TRequestDto): Promise<TResponseDto> {\n return wrapErrorUnlessAsync(\n () => this.pipeline(input),\n (cause) =>\n new ControllerError({\n message: cause instanceof Error ? cause.message : 'Controller execution failed',\n cause,\n }),\n [CodedError],\n );\n }\n\n /**\n * Runs the controller pipeline.\n *\n * Orchestrates: `mapRequest → executeUseCase → mapResponse`\n *\n * Override this method to customize the entire pipeline flow, or override\n * individual protected methods ({@link mapRequest}, {@link executeUseCase},\n * {@link mapResponse}) for more granular control.\n *\n * @param input - The validated request DTO\n * @returns Promise resolving to the validated response DTO\n */\n protected async pipeline(input: TRequestDto): Promise<TResponseDto> {\n const mappedInput = this.mapRequest(input);\n const result = await this.executeUseCase(mappedInput);\n return this.mapResponse(result);\n }\n\n /**\n * Maps the request DTO to a use case input DTO.\n *\n * Override to add custom pre-processing, logging, or transformation logic.\n * The default implementation uses the configured `requestMapper` and converts\n * {@link ObjectValidationError} to {@link InvalidRequestError}.\n *\n * @param input - The validated request DTO\n * @returns The use case input DTO\n * @throws {InvalidRequestError} When validation fails\n * @throws {ControllerError} When mapping fails unexpectedly\n */\n protected mapRequest(input: TRequestDto): TInDto {\n return wrapErrorUnless(\n () => this.requestMapper(input),\n (cause) => {\n if (cause instanceof ObjectValidationError) {\n return new InvalidRequestError({\n message: cause.message,\n cause,\n validationErrors: cause.validationErrors,\n });\n }\n return new ControllerError({\n message: cause instanceof Error ? cause.message : 'Request mapping failed',\n cause,\n });\n },\n [CodedError],\n );\n }\n\n /**\n * Executes the use case with the mapped input.\n *\n * Override to add custom logic around use case execution, such as:\n * - Logging/tracing\n * - Caching\n * - Retry logic\n * - Multi-use-case orchestration\n *\n * @param input - The use case input DTO\n * @returns Promise resolving to the use case output DTO\n */\n protected async executeUseCase(input: TInDto): Promise<TOutDto> {\n return this.useCase.execute(input);\n }\n\n /**\n * Maps the use case output DTO to a response DTO.\n *\n * Override to add custom post-processing, logging, or transformation logic.\n * The default implementation uses the configured `responseMapper`.\n *\n * @param output - The use case output DTO\n * @returns The response DTO\n * @throws {ControllerError} When mapping or validation fails\n */\n protected mapResponse(output: TOutDto): TResponseDto {\n return wrapErrorUnless(\n () => this.responseMapper(output),\n (cause) =>\n new ControllerError({\n message:\n cause instanceof ObjectValidationError\n ? 'Response validation failed'\n : cause instanceof Error\n ? cause.message\n : 'Response mapping failed',\n cause,\n }),\n [CodedError],\n );\n }\n}\n","import type { AccessGuard } from '../interfaces/types/access-guard.type';\nimport type { AccessGuardResult } from '../interfaces/types/access-guard-result.type';\nimport type { BaseInboundPort } from '../../app/interfaces/ports/base-inbound.port';\nimport type { BaseDto } from '../../../global/classes/base-dto.class';\nimport { BaseController } from './base-controller.class';\nimport { AccessDeniedError } from '../exceptions/access-denied.error';\n\n/**\n * Configuration for creating a GuardedController instance.\n *\n * All types must be DTOs (extending BaseDto) to ensure validation at every boundary.\n *\n * @typeParam TRequestDto - Validated request DTO from the framework layer\n * @typeParam TResponseDto - Validated response DTO to return to the framework\n * @typeParam TInDto - Input DTO type for the use case\n * @typeParam TOutDto - Output DTO type from the use case\n */\nexport interface GuardedControllerConfig<\n TRequestDto extends BaseDto<unknown>,\n TResponseDto extends BaseDto<unknown>,\n TInDto extends BaseDto<unknown>,\n TOutDto extends BaseDto<unknown>,\n> {\n /** Maps the validated request DTO to a use case input DTO. */\n requestMapper: (request: TRequestDto) => TInDto;\n /** The use case to execute. */\n useCase: BaseInboundPort<TInDto, TOutDto>;\n /** Maps the use case output DTO to a validated response DTO. */\n responseMapper: (output: TOutDto) => TResponseDto;\n /** Optional access guard; defaults to allowing all requests. */\n accessGuard?: AccessGuard<TRequestDto>;\n}\n\n/**\n * Creates a type-safe default access guard that allows all requests.\n * @internal\n */\nfunction createAllowAllGuard<T>(): AccessGuard<T> {\n return async (): Promise<AccessGuardResult> => ({\n isAllowed: true,\n });\n}\n\n/**\n * Controller with access control.\n *\n * Extends {@link BaseController} with an access guard that runs before\n * the pipeline. If the guard denies access, an {@link AccessDeniedError}\n * is thrown.\n *\n * All types must be DTOs (extending BaseDto) to ensure validation at every boundary.\n *\n * @typeParam TRequestDto - Validated request DTO from the framework layer\n * @typeParam TResponseDto - Validated response DTO to return to the framework\n * @typeParam TInDto - Input DTO type for the use case\n * @typeParam TOutDto - Output DTO type from the use case\n *\n * @example\n * ```typescript\n * const controller = GuardedController.create({\n * requestMapper: (req) => UpdateUserInputDto.create(req.data),\n * useCase: updateUserUseCase,\n * responseMapper: (output) => UpdateUserResponseDto.create(output.data),\n * accessGuard: async (req) => ({\n * isAllowed: req.data.user?.role === 'admin',\n * reason: 'Admin access required',\n * }),\n * });\n * ```\n */\nexport class GuardedController<\n TRequestDto extends BaseDto<unknown>,\n TResponseDto extends BaseDto<unknown>,\n TInDto extends BaseDto<unknown>,\n TOutDto extends BaseDto<unknown>,\n> extends BaseController<TRequestDto, TResponseDto, TInDto, TOutDto> {\n /** The access guard function for this controller. */\n protected readonly accessGuard: AccessGuard<TRequestDto>;\n\n /**\n * Creates a new GuardedController instance.\n *\n * @param requestMapper - Function to map request DTO to use case input DTO\n * @param useCase - The use case port to execute\n * @param responseMapper - Function to map use case output DTO to response DTO\n * @param accessGuard - Optional access guard; defaults to allowing all\n */\n constructor(\n requestMapper: (request: TRequestDto) => TInDto,\n useCase: BaseInboundPort<TInDto, TOutDto>,\n responseMapper: (output: TOutDto) => TResponseDto,\n accessGuard?: AccessGuard<TRequestDto>,\n ) {\n super(requestMapper, useCase, responseMapper);\n this.accessGuard = accessGuard ?? createAllowAllGuard<TRequestDto>();\n }\n\n /**\n * Factory method to create a guarded controller from a configuration object.\n *\n * @param config - Controller configuration including optional access guard\n * @returns A new GuardedController instance\n */\n static override create<\n TRequestDto extends BaseDto<unknown>,\n TResponseDto extends BaseDto<unknown>,\n TInDto extends BaseDto<unknown>,\n TOutDto extends BaseDto<unknown>,\n >(\n config: GuardedControllerConfig<TRequestDto, TResponseDto, TInDto, TOutDto>,\n ): GuardedController<TRequestDto, TResponseDto, TInDto, TOutDto> {\n return new GuardedController(\n config.requestMapper,\n config.useCase,\n config.responseMapper,\n config.accessGuard,\n );\n }\n\n /**\n * Runs the controller pipeline with access control.\n *\n * Checks the access guard before executing the pipeline.\n * If denied, throws {@link AccessDeniedError}.\n *\n * @param input - The validated request DTO\n * @returns Promise resolving to the validated response DTO\n * @throws {AccessDeniedError} When access guard denies the request\n */\n protected override async pipeline(input: TRequestDto): Promise<TResponseDto> {\n await this.checkAccess(input);\n return super.pipeline(input);\n }\n\n /**\n * Checks access using the configured guard.\n *\n * Override to customize access control logic.\n *\n * @param input - The validated request DTO\n * @throws {AccessDeniedError} When access is denied\n */\n protected async checkAccess(input: TRequestDto): Promise<void> {\n const result = await this.accessGuard(input);\n if (!result.isAllowed) {\n throw new AccessDeniedError({\n message: result.reason ?? 'Access denied',\n });\n }\n }\n}\n","/**\n * System metadata.\n *\n * Top-level metadata for the whole API surface (\"the system\"), sitting above\n * individual services/resources/endpoints.\n *\n * This is intentionally stable and serializable so it can be consumed by tools\n * (OpenAPI generation, docs, code generation).\n */\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Auth Scheme Types\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * API Key authentication scheme (header, query, or cookie).\n */\nexport interface ApiKeyAuthScheme {\n type: 'apiKey';\n in: 'header' | 'query' | 'cookie';\n /** Header/query/cookie parameter name, e.g. 'x-api-key' */\n name: string;\n description?: string;\n}\n\n/**\n * HTTP Bearer authentication scheme.\n */\nexport interface HttpBearerAuthScheme {\n type: 'http';\n scheme: 'bearer';\n bearerFormat?: string;\n description?: string;\n}\n\n/**\n * HTTP Basic authentication scheme.\n */\nexport interface HttpBasicAuthScheme {\n type: 'http';\n scheme: 'basic';\n description?: string;\n}\n\n/**\n * Union of all supported authentication schemes.\n */\nexport type AuthScheme = ApiKeyAuthScheme | HttpBearerAuthScheme | HttpBasicAuthScheme;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// System Metadata Type\n// ═══════════════════════════════════════════════════════════════════════════════\n\nexport interface SystemMetadata {\n // ═══════════════════════════════════════════════════════════════════════════\n // IDENTITY (required — routing, logging, code generation)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Stable system identifier.\n *\n * Recommendation: kebab-case.\n * Example: `acmp-connector`\n */\n id: string;\n\n /**\n * Short identifier for compact displays/logging.\n *\n * Example: `acmp`\n */\n shortId: string;\n\n /**\n * Human-readable system name.\n *\n * Example: `ACMP Connector`\n */\n name: string;\n\n /**\n * Human-readable description.\n */\n description?: string;\n\n /**\n * System/API version (SemVer recommended).\n *\n * Example: `1.0.0`\n */\n version: string;\n\n // ═══════════════════════════════════════════════════════════════════════════\n // DOMAIN (system-specific — servers, auth)\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * Default servers for the API.\n * Used by OpenAPI generation and client configuration.\n */\n servers?: {\n url: string;\n description?: string;\n }[];\n\n /**\n * Authentication configuration.\n */\n auth?: {\n /**\n * Whether endpoints should be considered secure by default.\n * @default true\n */\n secureByDefault?: boolean;\n\n /**\n * Available authentication schemes.\n *\n * Keyed by scheme name (must be unique within the system).\n * Example: `{ apiKeyAuth: { type: 'apiKey', in: 'header', name: 'x-api-key' } }`\n */\n schemes: Record<string, AuthScheme>;\n\n /**\n * Default security requirements (applies to all secure endpoints).\n *\n * OpenAPI semantics:\n * - Array is OR (any requirement can satisfy)\n * - Object is AND (all schemes required together)\n *\n * Example: `[{ apiKeyAuth: [] }]`\n */\n defaultSecurity?: Record<string, string[]>[];\n };\n\n // ═══════════════════════════════════════════════════════════════════════════\n // OPENAPI (optional — documentation generation)\n // Override pattern: openApi.xxx overrides base xxx\n // ═══════════════════════════════════════════════════════════════════════════\n\n /**\n * OpenAPI-specific overrides for global spec generation.\n */\n openApi?: {\n /**\n * OpenAPI info.title.\n * Overrides `name` if set.\n */\n title?: string;\n\n /**\n * OpenAPI info.description.\n * Overrides `description` if set.\n */\n description?: string;\n\n /**\n * OpenAPI info.termsOfService URL.\n */\n termsOfService?: string;\n\n /**\n * OpenAPI info.contact.\n */\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n\n /**\n * OpenAPI info.license.\n */\n license?: {\n name: string;\n url?: string;\n };\n };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Utility Types\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Extracts the scheme names (keys) from a SystemMetadata constant.\n *\n * @example\n * const systemMeta = { auth: { schemes: { apiKeyAuth: {...}, bearerAuth: {...} } } } as const;\n * type Names = SchemeNamesOf<typeof systemMeta>; // 'apiKeyAuth' | 'bearerAuth'\n */\nexport type SchemeNamesOf<TSystem> = TSystem extends {\n auth: { schemes: infer S };\n}\n ? keyof S & string\n : never;\n\n/**\n * Creates a typed OpenAPI security requirement array from scheme names.\n *\n * @example\n * type Req = SecurityRequirementOf<'apiKeyAuth' | 'bearerAuth'>;\n * // Array<Partial<Record<'apiKeyAuth' | 'bearerAuth', string[]>>>\n */\nexport type SecurityRequirementOf<TSchemeNames extends string> = Partial<\n Record<TSchemeNames, string[]>\n>[];\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Helper Function\n// ═══════════════════════════════════════════════════════════════════════════════\n\n/**\n * Input type for defineSystemMetadata helper (with generic auth).\n */\ntype SystemMetadataInput<TSchemeNames extends string> = Omit<SystemMetadata, 'auth'> & {\n auth?: {\n secureByDefault?: boolean;\n schemes: Record<TSchemeNames, AuthScheme>;\n defaultSecurity?: Partial<Record<TSchemeNames, string[]>>[];\n };\n};\n\n/**\n * Defines system metadata with fully-typed `defaultSecurity`.\n *\n * Infers scheme names from the `schemes` object and validates that\n * `defaultSecurity` only references existing scheme names.\n *\n * @example\n * export const systemMetadata = defineSystemMetadata({\n * id: 'my-api',\n * shortId: 'api',\n * name: 'My API',\n * version: '1.0.0',\n * auth: {\n * schemes: {\n * apiKeyAuth: { type: 'apiKey', in: 'header', name: 'x-api-key' },\n * },\n * defaultSecurity: [{ apiKeyAuth: [] }], // ✅ Valid\n * // defaultSecurity: [{ typoAuth: [] }], // ❌ TypeScript error!\n * },\n * });\n */\nexport function defineSystemMetadata<const TSchemeNames extends string>(\n metadata: SystemMetadataInput<TSchemeNames>,\n): SystemMetadataInput<TSchemeNames> & SystemMetadata {\n return metadata as SystemMetadataInput<TSchemeNames> & SystemMetadata;\n}\n","import type { HttpEndpointMetadata } from '../interfaces/types/metadata/http-endpoint-metadata.type';\nimport type { ResourceMetadata } from '../interfaces/types/metadata/resource-metadata.type';\nimport type { ServiceMetadata } from '../interfaces/types/metadata/service-metadata.type';\n\n/**\n * Normalizes a path segment by removing leading/trailing slashes.\n */\nfunction trimSlashes(segment: string): string {\n return segment.replace(/^\\/+|\\/+$/g, '');\n}\n\n/**\n * Computes the full route path from service, resource, and endpoint metadata.\n *\n * Handles path normalization:\n * - Ensures leading slash\n * - Joins segments with single slashes\n * - Removes trailing slash (except for root)\n *\n * @example\n * ```typescript\n * computeRoutePath(\n * { basePath: '/user-service' },\n * { path: '/users' },\n * { path: '/{id}' }\n * ); // => '/user-service/users/{id}'\n * ```\n */\nexport function computeRoutePath(\n service: Pick<ServiceMetadata, 'basePath'>,\n resource: Pick<ResourceMetadata, 'path'>,\n endpoint: Pick<HttpEndpointMetadata, 'path'>,\n): string {\n const segments = [service.basePath, resource.path, endpoint.path]\n .map(trimSlashes)\n .filter((s) => s.length > 0);\n\n if (segments.length === 0) {\n return '/';\n }\n\n return '/' + segments.join('/');\n}\n","import type { HttpResponse } from '../interfaces/types/http/http-response';\n\n/**\n * Type guard to validate that a value is a valid HttpResponse.\n *\n * Checks that the value has the required `statusCode` property as a number.\n * This is used to validate controller outputs before passing to response mappers.\n *\n * @param value - The value to check\n * @returns True if the value is a valid HttpResponse\n *\n * @example\n * ```typescript\n * const output = controller.execute(input);\n * if (!isHttpResponse(output)) {\n * throw new Error('Controller must return an HttpResponse');\n * }\n * ```\n */\nexport function isHttpResponse(value: unknown): value is HttpResponse {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'statusCode' in value &&\n typeof (value as { statusCode: unknown }).statusCode === 'number'\n );\n}\n\n/**\n * Asserts that a value is a valid HttpResponse.\n *\n * Throws a descriptive error if the value is not a valid HttpResponse,\n * making it easier to debug controller output issues.\n *\n * @param value - The value to validate\n * @param context - Optional context for the error message (e.g., 'mapOutput')\n * @throws Error if the value is not a valid HttpResponse\n *\n * @example\n * ```typescript\n * const output = controller.execute(input);\n * assertHttpResponse(output, 'controller output');\n * // Now TypeScript knows output is HttpResponse\n * ```\n */\nexport function assertHttpResponse(\n value: unknown,\n context = 'value',\n): asserts value is HttpResponse {\n if (!isHttpResponse(value)) {\n const actualType = value === null ? 'null' : value === undefined ? 'undefined' : typeof value;\n const hasStatusCode = typeof value === 'object' && value !== null && 'statusCode' in value;\n\n let message = `Expected ${context} to be an HttpResponse with a numeric statusCode, `;\n\n if (hasStatusCode) {\n const statusCodeType = typeof (value as { statusCode: unknown })['statusCode'];\n message += `but statusCode was ${statusCodeType}`;\n } else {\n message += `but got ${actualType}`;\n }\n\n throw new Error(message);\n }\n}\n"],"mappings":"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","names":[]}