@cosmneo/onion-lasagna 0.2.0 → 0.3.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/chunk-36IO4BM7.js +113 -0
- package/dist/chunk-36IO4BM7.js.map +1 -0
- package/dist/chunk-4BVOLXDJ.js +54 -0
- package/dist/chunk-4BVOLXDJ.js.map +1 -0
- package/dist/{chunk-GGSAAZPM.js → chunk-AUMHMWDD.js} +19 -20
- package/dist/chunk-AUMHMWDD.js.map +1 -0
- package/dist/chunk-CBTICRSM.js +34 -0
- package/dist/chunk-CBTICRSM.js.map +1 -0
- package/dist/chunk-H5TNDC5U.js +138 -0
- package/dist/chunk-H5TNDC5U.js.map +1 -0
- package/dist/chunk-KJ4JGZOE.js +96 -0
- package/dist/chunk-KJ4JGZOE.js.map +1 -0
- package/dist/chunk-MF2JDREK.js +168 -0
- package/dist/chunk-MF2JDREK.js.map +1 -0
- package/dist/chunk-RVSBIYY4.js +1 -0
- package/dist/chunk-RVSBIYY4.js.map +1 -0
- package/dist/{chunk-PUVAB3JX.js → chunk-XIRJ73IO.js} +38 -36
- package/dist/chunk-XIRJ73IO.js.map +1 -0
- package/dist/{chunk-DS7TE6KZ.js → chunk-XP6PLTV2.js} +11 -3
- package/dist/chunk-XP6PLTV2.js.map +1 -0
- package/dist/chunk-XWKHOLIP.js +191 -0
- package/dist/chunk-XWKHOLIP.js.map +1 -0
- package/dist/event-router-definition.type-CP9uTlux.d.cts +150 -0
- package/dist/event-router-definition.type-D8CG-kjZ.d.ts +150 -0
- package/dist/events/asyncapi/index.cjs +143 -0
- package/dist/events/asyncapi/index.cjs.map +1 -0
- package/dist/events/asyncapi/index.d.cts +184 -0
- package/dist/events/asyncapi/index.d.ts +184 -0
- package/dist/events/asyncapi/index.js +8 -0
- package/dist/events/asyncapi/index.js.map +1 -0
- package/dist/events/handler/index.cjs +171 -0
- package/dist/events/handler/index.cjs.map +1 -0
- package/dist/events/handler/index.d.cts +153 -0
- package/dist/events/handler/index.d.ts +153 -0
- package/dist/events/handler/index.js +21 -0
- package/dist/events/handler/index.js.map +1 -0
- package/dist/events/index.cjs +497 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +9 -0
- package/dist/events/index.d.ts +9 -0
- package/dist/events/index.js +41 -0
- package/dist/events/index.js.map +1 -0
- package/dist/events/server/index.cjs +291 -0
- package/dist/events/server/index.cjs.map +1 -0
- package/dist/events/server/index.d.cts +281 -0
- package/dist/events/server/index.d.ts +281 -0
- package/dist/events/server/index.js +16 -0
- package/dist/events/server/index.js.map +1 -0
- package/dist/events/shared/index.cjs +85 -0
- package/dist/events/shared/index.cjs.map +1 -0
- package/dist/events/shared/index.d.cts +35 -0
- package/dist/events/shared/index.d.ts +35 -0
- package/dist/events/shared/index.js +13 -0
- package/dist/events/shared/index.js.map +1 -0
- package/dist/global.js +3 -3
- package/dist/http/index.cjs +563 -93
- package/dist/http/index.cjs.map +1 -1
- package/dist/http/index.d.cts +5 -3
- package/dist/http/index.d.ts +5 -3
- package/dist/http/index.js +30 -12
- package/dist/http/openapi/index.cjs +43 -35
- package/dist/http/openapi/index.cjs.map +1 -1
- package/dist/http/openapi/index.d.cts +8 -34
- package/dist/http/openapi/index.d.ts +8 -34
- package/dist/http/openapi/index.js +2 -2
- package/dist/http/route/index.cjs +106 -9
- package/dist/http/route/index.cjs.map +1 -1
- package/dist/http/route/index.d.cts +133 -227
- package/dist/http/route/index.d.ts +133 -227
- package/dist/http/route/index.js +5 -2
- package/dist/http/server/index.cjs +24 -19
- package/dist/http/server/index.cjs.map +1 -1
- package/dist/http/server/index.d.cts +4 -261
- package/dist/http/server/index.d.ts +4 -261
- package/dist/http/server/index.js +2 -2
- package/dist/http/shared/index.cjs.map +1 -1
- package/dist/http/shared/index.d.cts +10 -14
- package/dist/http/shared/index.d.ts +10 -14
- package/dist/http/shared/index.js +11 -127
- package/dist/http/shared/index.js.map +1 -1
- package/dist/index.js +6 -6
- package/dist/{router-definition.type-ynBhT16T.d.cts → router-definition.type-BElX-Pl4.d.cts} +169 -256
- package/dist/{router-definition.type-DORVlLNk.d.ts → router-definition.type-DxG8ncJZ.d.ts} +169 -256
- package/dist/types-B6Q1iCgf.d.ts +262 -0
- package/dist/types-afYpL7Ap.d.cts +262 -0
- package/dist/types-cke61juH.d.cts +42 -0
- package/dist/types-cke61juH.d.ts +42 -0
- package/package.json +35 -2
- package/dist/chunk-BZULBF4N.js +0 -82
- package/dist/chunk-BZULBF4N.js.map +0 -1
- package/dist/chunk-DS7TE6KZ.js.map +0 -1
- package/dist/chunk-GGSAAZPM.js.map +0 -1
- package/dist/chunk-PUVAB3JX.js.map +0 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AccessDeniedError,
|
|
3
|
+
ConflictError,
|
|
4
|
+
DomainError,
|
|
5
|
+
ForbiddenError,
|
|
6
|
+
InfraError,
|
|
7
|
+
NotFoundError,
|
|
8
|
+
UnprocessableError
|
|
9
|
+
} from "./chunk-2BVCU32G.js";
|
|
10
|
+
import {
|
|
11
|
+
ControllerError,
|
|
12
|
+
InvalidRequestError,
|
|
13
|
+
UnauthorizedError,
|
|
14
|
+
UseCaseError
|
|
15
|
+
} from "./chunk-T7S574XQ.js";
|
|
16
|
+
import {
|
|
17
|
+
ObjectValidationError
|
|
18
|
+
} from "./chunk-3BY5RBF2.js";
|
|
19
|
+
import {
|
|
20
|
+
CodedError
|
|
21
|
+
} from "./chunk-A4JUAZK4.js";
|
|
22
|
+
|
|
23
|
+
// src/presentation/http/shared/error-mapping.ts
|
|
24
|
+
var MASKED_ERROR_BODY = {
|
|
25
|
+
message: "An unexpected error occurred",
|
|
26
|
+
errorCode: "INTERNAL_ERROR"
|
|
27
|
+
};
|
|
28
|
+
var INTERNAL_ERROR_TYPES = [
|
|
29
|
+
"DomainError",
|
|
30
|
+
"InfraError",
|
|
31
|
+
"ControllerError",
|
|
32
|
+
"NetworkError",
|
|
33
|
+
"PersistenceError",
|
|
34
|
+
"ExternalServiceError",
|
|
35
|
+
"InvariantViolationError"
|
|
36
|
+
];
|
|
37
|
+
function isErrorType(error, typeName) {
|
|
38
|
+
if (!error || typeof error !== "object") return false;
|
|
39
|
+
const constructor = Object.prototype.hasOwnProperty.call(error, "constructor") ? error.constructor : Object.getPrototypeOf(error)?.constructor;
|
|
40
|
+
if (!constructor) return false;
|
|
41
|
+
const name = constructor.name;
|
|
42
|
+
return name === typeName || name === `_${typeName}`;
|
|
43
|
+
}
|
|
44
|
+
function hasValidationErrors(error) {
|
|
45
|
+
if (!error || typeof error !== "object") return false;
|
|
46
|
+
return "validationErrors" in error && Array.isArray(error.validationErrors);
|
|
47
|
+
}
|
|
48
|
+
function buildValidationErrorBody(message, code, validationErrors) {
|
|
49
|
+
return {
|
|
50
|
+
message,
|
|
51
|
+
errorCode: code,
|
|
52
|
+
errorItems: validationErrors.map((e) => ({
|
|
53
|
+
item: e.field,
|
|
54
|
+
message: e.message
|
|
55
|
+
}))
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function buildSimpleErrorBody(message, code) {
|
|
59
|
+
return {
|
|
60
|
+
message,
|
|
61
|
+
errorCode: code
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function getHttpStatusCode(error) {
|
|
65
|
+
if (error instanceof ObjectValidationError) return 400;
|
|
66
|
+
if (error instanceof InvalidRequestError) return 400;
|
|
67
|
+
if (error instanceof UnauthorizedError) return 401;
|
|
68
|
+
if (error instanceof ForbiddenError) return 403;
|
|
69
|
+
if (error instanceof AccessDeniedError) return 403;
|
|
70
|
+
if (error instanceof NotFoundError) return 404;
|
|
71
|
+
if (error instanceof ConflictError) return 409;
|
|
72
|
+
if (error instanceof UnprocessableError) return 422;
|
|
73
|
+
if (error instanceof UseCaseError) return 400;
|
|
74
|
+
if (isErrorType(error, "ObjectValidationError")) return 400;
|
|
75
|
+
if (isErrorType(error, "InvalidRequestError")) return 400;
|
|
76
|
+
if (isErrorType(error, "UnauthorizedError")) return 401;
|
|
77
|
+
if (isErrorType(error, "ForbiddenError")) return 403;
|
|
78
|
+
if (isErrorType(error, "AccessDeniedError")) return 403;
|
|
79
|
+
if (isErrorType(error, "NotFoundError")) return 404;
|
|
80
|
+
if (isErrorType(error, "ConflictError")) return 409;
|
|
81
|
+
if (isErrorType(error, "UnprocessableError")) return 422;
|
|
82
|
+
if (isErrorType(error, "UseCaseError")) return 400;
|
|
83
|
+
return 500;
|
|
84
|
+
}
|
|
85
|
+
function shouldMaskError(error) {
|
|
86
|
+
if (error instanceof DomainError || error instanceof InfraError || error instanceof ControllerError) {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
for (const errorType of INTERNAL_ERROR_TYPES) {
|
|
90
|
+
if (isErrorType(error, errorType)) {
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
function createErrorResponseBody(error) {
|
|
97
|
+
if (shouldMaskError(error)) {
|
|
98
|
+
return MASKED_ERROR_BODY;
|
|
99
|
+
}
|
|
100
|
+
if (error instanceof ObjectValidationError) {
|
|
101
|
+
return buildValidationErrorBody(error.message, error.code, error.validationErrors);
|
|
102
|
+
}
|
|
103
|
+
if (error instanceof InvalidRequestError) {
|
|
104
|
+
return buildValidationErrorBody(error.message, error.code, error.validationErrors);
|
|
105
|
+
}
|
|
106
|
+
if (isErrorType(error, "ObjectValidationError") && hasValidationErrors(error)) {
|
|
107
|
+
return buildValidationErrorBody(error.message, error.code, error.validationErrors);
|
|
108
|
+
}
|
|
109
|
+
if (isErrorType(error, "InvalidRequestError") && hasValidationErrors(error)) {
|
|
110
|
+
return buildValidationErrorBody(error.message, error.code, error.validationErrors);
|
|
111
|
+
}
|
|
112
|
+
if (error instanceof CodedError) {
|
|
113
|
+
return buildSimpleErrorBody(error.message, error.code);
|
|
114
|
+
}
|
|
115
|
+
if (isErrorType(error, "CodedError")) {
|
|
116
|
+
return buildSimpleErrorBody(error.message, error.code);
|
|
117
|
+
}
|
|
118
|
+
if (error && typeof error === "object" && "message" in error && "code" in error && typeof error.message === "string" && typeof error.code === "string") {
|
|
119
|
+
return buildSimpleErrorBody(error.message, error.code);
|
|
120
|
+
}
|
|
121
|
+
return MASKED_ERROR_BODY;
|
|
122
|
+
}
|
|
123
|
+
function mapErrorToHttpResponse(error) {
|
|
124
|
+
return {
|
|
125
|
+
status: getHttpStatusCode(error),
|
|
126
|
+
body: createErrorResponseBody(error)
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export {
|
|
131
|
+
isErrorType,
|
|
132
|
+
hasValidationErrors,
|
|
133
|
+
getHttpStatusCode,
|
|
134
|
+
shouldMaskError,
|
|
135
|
+
createErrorResponseBody,
|
|
136
|
+
mapErrorToHttpResponse
|
|
137
|
+
};
|
|
138
|
+
//# sourceMappingURL=chunk-H5TNDC5U.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/presentation/http/shared/error-mapping.ts"],"sourcesContent":["/**\n * @fileoverview Centralized error mapping for HTTP frameworks.\n *\n * Provides a single source of truth for mapping onion-lasagna errors\n * to HTTP status codes and response bodies.\n *\n * @module http/shared/error-mapping\n */\n\nimport { CodedError } from '../../../global/exceptions/coded-error.error';\nimport { ObjectValidationError } from '../../../global/exceptions/object-validation.error';\nimport { DomainError } from '../../../domain/exceptions/domain.error';\nimport { UseCaseError } from '../../../app/exceptions/use-case.error';\nimport { NotFoundError } from '../../../app/exceptions/not-found.error';\nimport { ConflictError } from '../../../app/exceptions/conflict.error';\nimport { UnprocessableError } from '../../../app/exceptions/unprocessable.error';\nimport { ForbiddenError } from '../../../app/exceptions/forbidden.error';\nimport { UnauthorizedError } from '../../../app/exceptions/unauthorized.error';\nimport { InfraError } from '../../../infra/exceptions/infra.error';\nimport { ControllerError } from '../../exceptions/controller.error';\nimport { AccessDeniedError } from '../../exceptions/access-denied.error';\nimport { InvalidRequestError } from '../../exceptions/invalid-request.error';\nimport type { ErrorResponseBody, MappedErrorResponse } from './types';\n\n// ============================================================================\n// Constants and Interfaces\n// ============================================================================\n\n/**\n * Default masked error response for internal errors.\n */\nconst MASKED_ERROR_BODY: ErrorResponseBody = {\n message: 'An unexpected error occurred',\n errorCode: 'INTERNAL_ERROR',\n};\n\n/**\n * Known internal error type names that should be masked.\n */\nconst INTERNAL_ERROR_TYPES = [\n 'DomainError',\n 'InfraError',\n 'ControllerError',\n 'NetworkError',\n 'PersistenceError',\n 'ExternalServiceError',\n 'InvariantViolationError',\n];\n\n/**\n * Validation error item structure.\n */\ninterface ValidationErrorInput {\n field: string;\n message: string;\n}\n\n/**\n * Validation error structure for string-based checking.\n */\ninterface ValidationErrorItem {\n field: string;\n message: string;\n}\n\n/**\n * Interface for errors with validation items.\n */\ninterface ErrorWithValidation {\n message: string;\n code: string;\n validationErrors: ValidationErrorItem[];\n}\n\n/**\n * Interface for coded errors.\n */\ninterface CodedErrorLike {\n message: string;\n code: string;\n}\n\n// ============================================================================\n// String-based type checking helpers (for bundled code compatibility)\n// ============================================================================\n\n/**\n * Checks if error matches a specific error type by checking its constructor name.\n * This approach avoids issues with multiple class instances in bundled code.\n * Handles both original names and tsup's mangled names (prefixed with _).\n *\n * @param error - The error to check\n * @param typeName - The error type name to match\n * @returns True if error matches the type name\n */\nexport function isErrorType(error: unknown, typeName: string): error is CodedErrorLike {\n if (!error || typeof error !== 'object') return false;\n // Guard against objects without constructor (e.g., Object.create(null))\n const constructor = Object.prototype.hasOwnProperty.call(error, 'constructor')\n ? (error as { constructor?: { name?: string } }).constructor\n : Object.getPrototypeOf(error)?.constructor;\n if (!constructor) return false;\n const name = constructor.name;\n // Check both the original name and the mangled name (tsup prefixes with _)\n return name === typeName || name === `_${typeName}`;\n}\n\n/**\n * Checks if error has validation errors array.\n *\n * @param error - The error to check\n * @returns True if error has validationErrors property\n */\nexport function hasValidationErrors(error: unknown): error is ErrorWithValidation {\n if (!error || typeof error !== 'object') return false;\n return (\n 'validationErrors' in error && Array.isArray((error as ErrorWithValidation).validationErrors)\n );\n}\n\n// ============================================================================\n// Response body builders\n// ============================================================================\n\n/**\n * Builds a validation error response body from error details.\n *\n * @param message - The error message\n * @param code - The error code\n * @param validationErrors - Array of field validation errors\n * @returns Error response body with errorItems\n */\nfunction buildValidationErrorBody(\n message: string,\n code: string,\n validationErrors: readonly ValidationErrorInput[],\n): ErrorResponseBody {\n return {\n message,\n errorCode: code,\n errorItems: validationErrors.map((e) => ({\n item: e.field,\n message: e.message,\n })),\n };\n}\n\n/**\n * Builds a simple error response body from error details.\n *\n * @param message - The error message\n * @param code - The error code\n * @returns Error response body\n */\nfunction buildSimpleErrorBody(message: string, code: string): ErrorResponseBody {\n return {\n message,\n errorCode: code,\n };\n}\n\n// ============================================================================\n// Primary error mapping functions (with bundled code fallback)\n// ============================================================================\n\n/**\n * Maps an error to the appropriate HTTP status code.\n * Uses instanceof first, then falls back to name-based checking for bundled code.\n *\n * @param error - The error to map\n * @returns HTTP status code\n */\nexport function getHttpStatusCode(error: unknown): number {\n // Try instanceof first (faster)\n if (error instanceof ObjectValidationError) return 400;\n if (error instanceof InvalidRequestError) return 400;\n if (error instanceof UnauthorizedError) return 401;\n if (error instanceof ForbiddenError) return 403;\n if (error instanceof AccessDeniedError) return 403;\n if (error instanceof NotFoundError) return 404;\n if (error instanceof ConflictError) return 409;\n if (error instanceof UnprocessableError) return 422;\n if (error instanceof UseCaseError) return 400;\n\n // Fall back to name-based checking for bundled code (e.g., _NotFoundError)\n if (isErrorType(error, 'ObjectValidationError')) return 400;\n if (isErrorType(error, 'InvalidRequestError')) return 400;\n if (isErrorType(error, 'UnauthorizedError')) return 401;\n if (isErrorType(error, 'ForbiddenError')) return 403;\n if (isErrorType(error, 'AccessDeniedError')) return 403;\n if (isErrorType(error, 'NotFoundError')) return 404;\n if (isErrorType(error, 'ConflictError')) return 409;\n if (isErrorType(error, 'UnprocessableError')) return 422;\n if (isErrorType(error, 'UseCaseError')) return 400;\n\n return 500;\n}\n\n/**\n * Checks if an error should have its details masked in the response.\n *\n * Security-sensitive errors (domain, infrastructure, controller) are masked\n * to prevent leaking implementation details.\n * Uses instanceof first, then falls back to name-based checking for bundled code.\n *\n * @param error - The error to check\n * @returns True if error details should be hidden\n */\nexport function shouldMaskError(error: unknown): boolean {\n // Try instanceof first (faster)\n if (\n error instanceof DomainError ||\n error instanceof InfraError ||\n error instanceof ControllerError\n ) {\n return true;\n }\n\n // Fall back to name-based checking for bundled code\n for (const errorType of INTERNAL_ERROR_TYPES) {\n if (isErrorType(error, errorType)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Creates the response body for an error.\n * Uses instanceof first, then falls back to name-based checking for bundled code.\n *\n * @param error - The error to create body for\n * @returns Error response body\n */\nexport function createErrorResponseBody(error: unknown): ErrorResponseBody {\n // Masked errors - hide internal details\n if (shouldMaskError(error)) {\n return MASKED_ERROR_BODY;\n }\n\n // Validation errors - include field details (try instanceof first)\n if (error instanceof ObjectValidationError) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n if (error instanceof InvalidRequestError) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n\n // Validation errors - fall back to name-based checking for bundled code\n if (isErrorType(error, 'ObjectValidationError') && hasValidationErrors(error)) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n if (isErrorType(error, 'InvalidRequestError') && hasValidationErrors(error)) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n\n // Other coded errors - expose message and code (try instanceof first)\n if (error instanceof CodedError) {\n return buildSimpleErrorBody(error.message, error.code);\n }\n\n // Other coded errors - fall back to name-based checking\n if (isErrorType(error, 'CodedError')) {\n return buildSimpleErrorBody(error.message, error.code);\n }\n\n // Check for any error with message and code properties\n if (\n error &&\n typeof error === 'object' &&\n 'message' in error &&\n 'code' in error &&\n typeof (error as CodedErrorLike).message === 'string' &&\n typeof (error as CodedErrorLike).code === 'string'\n ) {\n return buildSimpleErrorBody((error as CodedErrorLike).message, (error as CodedErrorLike).code);\n }\n\n // Unknown errors - mask\n return MASKED_ERROR_BODY;\n}\n\n/**\n * Maps an error to a complete HTTP response structure.\n *\n * Mapping strategy (checked in order):\n * 1. `ObjectValidationError` / `InvalidRequestError` → 400 Bad Request (with field errors)\n * 2. `UseCaseError` → 400 Bad Request\n * 3. `UnauthorizedError` → 401 Unauthorized\n * 4. `ForbiddenError` / `AccessDeniedError` → 403 Forbidden\n * 5. `NotFoundError` → 404 Not Found\n * 6. `ConflictError` → 409 Conflict\n * 7. `UnprocessableError` → 422 Unprocessable Entity\n * 8. `DomainError` / `InfraError` / `ControllerError` → 500 Internal Server Error (masked)\n * 9. Unknown → 500 Internal Server Error (masked)\n *\n * @param error - The error to map\n * @returns Mapped error response with status and body\n */\nexport function mapErrorToHttpResponse(error: unknown): MappedErrorResponse {\n return {\n status: getHttpStatusCode(error),\n body: createErrorResponseBody(error),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAM,oBAAuC;AAAA,EAC3C,SAAS;AAAA,EACT,WAAW;AACb;AAKA,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAgDO,SAAS,YAAY,OAAgB,UAA2C;AACrF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,cAAc,OAAO,UAAU,eAAe,KAAK,OAAO,aAAa,IACxE,MAA8C,cAC/C,OAAO,eAAe,KAAK,GAAG;AAClC,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,OAAO,YAAY;AAEzB,SAAO,SAAS,YAAY,SAAS,IAAI,QAAQ;AACnD;AAQO,SAAS,oBAAoB,OAA8C;AAChF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,SACE,sBAAsB,SAAS,MAAM,QAAS,MAA8B,gBAAgB;AAEhG;AAcA,SAAS,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// src/presentation/events/asyncapi/generate.ts
|
|
8
|
+
function generateAsyncAPI(router, config) {
|
|
9
|
+
const routerConfig = isEventRouterDefinition(router) ? router.handlers : router;
|
|
10
|
+
const handlers = collectEventHandlers(routerConfig);
|
|
11
|
+
const channels = {};
|
|
12
|
+
const operations = {};
|
|
13
|
+
const allTags = /* @__PURE__ */ new Set();
|
|
14
|
+
for (const { key, handler } of handlers) {
|
|
15
|
+
const handlerId = generateHandlerId(key);
|
|
16
|
+
const channelId = handler.eventType;
|
|
17
|
+
const message = buildMessage(handler.eventType, handler.payload, handler.docs);
|
|
18
|
+
if (!channels[channelId]) {
|
|
19
|
+
channels[channelId] = {
|
|
20
|
+
address: handler.eventType,
|
|
21
|
+
messages: {}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const channelMessages = { ...channels[channelId].messages ?? {} };
|
|
25
|
+
channelMessages[handlerId] = message;
|
|
26
|
+
channels[channelId] = { ...channels[channelId], messages: channelMessages };
|
|
27
|
+
const operation = {
|
|
28
|
+
action: "receive",
|
|
29
|
+
channel: { $ref: `#/channels/${channelId}` },
|
|
30
|
+
messages: [{ $ref: `#/channels/${channelId}/messages/${handlerId}` }]
|
|
31
|
+
};
|
|
32
|
+
if (handler.docs.summary) {
|
|
33
|
+
operation.summary = handler.docs.summary;
|
|
34
|
+
}
|
|
35
|
+
if (handler.docs.description) {
|
|
36
|
+
operation.description = handler.docs.description;
|
|
37
|
+
}
|
|
38
|
+
if (handler.docs.deprecated) {
|
|
39
|
+
operation.deprecated = true;
|
|
40
|
+
}
|
|
41
|
+
if (handler.docs.tags && handler.docs.tags.length > 0) {
|
|
42
|
+
operation.tags = handler.docs.tags.map((t) => ({
|
|
43
|
+
name: t
|
|
44
|
+
}));
|
|
45
|
+
for (const tag of handler.docs.tags) {
|
|
46
|
+
allTags.add(tag);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
operations[handlerId] = operation;
|
|
50
|
+
}
|
|
51
|
+
const tags = config.tags ? [...config.tags] : [];
|
|
52
|
+
for (const tagName of allTags) {
|
|
53
|
+
if (!tags.some((t) => t.name === tagName)) {
|
|
54
|
+
tags.push({ name: tagName });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const info = tags.length > 0 ? { ...config.info, tags } : config.info;
|
|
58
|
+
const spec = {
|
|
59
|
+
asyncapi: config.asyncapi ?? "3.0.0",
|
|
60
|
+
info,
|
|
61
|
+
defaultContentType: config.defaultContentType ?? "application/json",
|
|
62
|
+
channels,
|
|
63
|
+
operations
|
|
64
|
+
};
|
|
65
|
+
if (config.servers && Object.keys(config.servers).length > 0) {
|
|
66
|
+
spec.servers = config.servers;
|
|
67
|
+
}
|
|
68
|
+
if (config.externalDocs) {
|
|
69
|
+
spec.externalDocs = config.externalDocs;
|
|
70
|
+
}
|
|
71
|
+
return spec;
|
|
72
|
+
}
|
|
73
|
+
function buildMessage(eventType, payload, docs) {
|
|
74
|
+
const message = {
|
|
75
|
+
name: eventType
|
|
76
|
+
};
|
|
77
|
+
if (docs.summary) {
|
|
78
|
+
message.summary = docs.summary;
|
|
79
|
+
}
|
|
80
|
+
if (docs.description) {
|
|
81
|
+
message.description = docs.description;
|
|
82
|
+
}
|
|
83
|
+
if (docs.deprecated) {
|
|
84
|
+
message.deprecated = true;
|
|
85
|
+
}
|
|
86
|
+
if (payload) {
|
|
87
|
+
const schema = payload.toJsonSchema();
|
|
88
|
+
message.payload = schema;
|
|
89
|
+
}
|
|
90
|
+
return message;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export {
|
|
94
|
+
generateAsyncAPI
|
|
95
|
+
};
|
|
96
|
+
//# sourceMappingURL=chunk-KJ4JGZOE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/presentation/events/asyncapi/generate.ts"],"sourcesContent":["/**\n * @fileoverview AsyncAPI specification generation from event router definitions.\n *\n * The `generateAsyncAPI` function creates a complete AsyncAPI 3.0 specification\n * from an event router definition. All handler payload schemas are converted to\n * JSON Schema and included in the specification.\n *\n * @module events/asyncapi/generate\n */\n\nimport type { SchemaAdapter } from '../../http/schema/types';\nimport type { EventRouterConfig, EventRouterDefinition } from '../handler/types';\nimport { isEventRouterDefinition, collectEventHandlers } from '../handler/types';\nimport { generateHandlerId } from '../handler/utils';\nimport type {\n AsyncAPIConfig,\n AsyncAPISpec,\n AsyncAPIChannel,\n AsyncAPIOperation,\n AsyncAPIMessage,\n AsyncAPITag,\n} from './types';\n\n/**\n * Generates an AsyncAPI 3.0 specification from an event router definition.\n *\n * This function walks the event router structure, extracts JSON schemas from\n * all handler payload definitions, and builds a complete AsyncAPI 3.0 specification.\n *\n * @param router - Event router definition or raw config\n * @param config - AsyncAPI configuration (info, servers, tags, etc.)\n * @returns Complete AsyncAPI specification\n *\n * @example\n * ```typescript\n * import { generateAsyncAPI } from '@cosmneo/onion-lasagna/events/asyncapi';\n * import { notificationEventRouter } from './events/router';\n *\n * const spec = generateAsyncAPI(notificationEventRouter, {\n * info: {\n * title: 'My Event API',\n * version: '1.0.0',\n * description: 'Domain events for the application',\n * },\n * });\n *\n * app.get('/asyncapi.json', (c) => c.json(spec));\n * ```\n */\nexport function generateAsyncAPI<T extends EventRouterConfig>(\n router: T | EventRouterDefinition<T>,\n config: AsyncAPIConfig,\n): AsyncAPISpec {\n const routerConfig = isEventRouterDefinition(router) ? router.handlers : router;\n const handlers = collectEventHandlers(routerConfig);\n\n const channels: Record<string, AsyncAPIChannel> = {};\n const operations: Record<string, AsyncAPIOperation> = {};\n const allTags = new Set<string>();\n\n for (const { key, handler } of handlers) {\n const handlerId = generateHandlerId(key);\n const channelId = handler.eventType;\n\n // Build message\n const message = buildMessage(handler.eventType, handler.payload, handler.docs);\n\n // Build channel (group by eventType — multiple handlers may share a channel)\n if (!channels[channelId]) {\n channels[channelId] = {\n address: handler.eventType,\n messages: {},\n };\n }\n const channelMessages = { ...(channels[channelId]!.messages ?? {}) };\n channelMessages[handlerId] = message;\n channels[channelId] = { ...channels[channelId]!, messages: channelMessages };\n\n // Build operation (one per handler)\n const operation: AsyncAPIOperation = {\n action: 'receive',\n channel: { $ref: `#/channels/${channelId}` },\n messages: [{ $ref: `#/channels/${channelId}/messages/${handlerId}` }],\n };\n\n if (handler.docs.summary) {\n (operation as { summary: string }).summary = handler.docs.summary;\n }\n if (handler.docs.description) {\n (operation as { description: string }).description = handler.docs.description;\n }\n if (handler.docs.deprecated) {\n (operation as { deprecated: boolean }).deprecated = true;\n }\n if (handler.docs.tags && handler.docs.tags.length > 0) {\n (operation as { tags: readonly AsyncAPITag[] }).tags = handler.docs.tags.map((t) => ({\n name: t,\n }));\n for (const tag of handler.docs.tags) {\n allTags.add(tag);\n }\n }\n\n operations[handlerId] = operation;\n }\n\n // Merge custom tags with collected tags (AsyncAPI 3.0: tags live inside info)\n const tags: AsyncAPITag[] = config.tags ? [...config.tags] : [];\n for (const tagName of allTags) {\n if (!tags.some((t) => t.name === tagName)) {\n tags.push({ name: tagName });\n }\n }\n\n const info = tags.length > 0 ? { ...config.info, tags } : config.info;\n\n // Build the specification\n const spec: AsyncAPISpec = {\n asyncapi: config.asyncapi ?? '3.0.0',\n info,\n defaultContentType: config.defaultContentType ?? 'application/json',\n channels,\n operations,\n };\n\n if (config.servers && Object.keys(config.servers).length > 0) {\n (spec as { servers: typeof config.servers }).servers = config.servers;\n }\n\n if (config.externalDocs) {\n (spec as { externalDocs: typeof config.externalDocs }).externalDocs = config.externalDocs;\n }\n\n return spec;\n}\n\n/**\n * Builds an AsyncAPI message from a handler definition.\n */\nfunction buildMessage(\n eventType: string,\n payload: unknown,\n docs: {\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n },\n): AsyncAPIMessage {\n const message: AsyncAPIMessage = {\n name: eventType,\n };\n\n if (docs.summary) {\n (message as { summary: string }).summary = docs.summary;\n }\n if (docs.description) {\n (message as { description: string }).description = docs.description;\n }\n if (docs.deprecated) {\n (message as { deprecated: boolean }).deprecated = true;\n }\n\n if (payload) {\n const schema = (payload as SchemaAdapter).toJsonSchema();\n (message as { payload: typeof schema }).payload = schema;\n }\n\n return message;\n}\n"],"mappings":";;;;;;;AAiDO,SAAS,iBACd,QACA,QACc;AACd,QAAM,eAAe,wBAAwB,MAAM,IAAI,OAAO,WAAW;AACzE,QAAM,WAAW,qBAAqB,YAAY;AAElD,QAAM,WAA4C,CAAC;AACnD,QAAM,aAAgD,CAAC;AACvD,QAAM,UAAU,oBAAI,IAAY;AAEhC,aAAW,EAAE,KAAK,QAAQ,KAAK,UAAU;AACvC,UAAM,YAAY,kBAAkB,GAAG;AACvC,UAAM,YAAY,QAAQ;AAG1B,UAAM,UAAU,aAAa,QAAQ,WAAW,QAAQ,SAAS,QAAQ,IAAI;AAG7E,QAAI,CAAC,SAAS,SAAS,GAAG;AACxB,eAAS,SAAS,IAAI;AAAA,QACpB,SAAS,QAAQ;AAAA,QACjB,UAAU,CAAC;AAAA,MACb;AAAA,IACF;AACA,UAAM,kBAAkB,EAAE,GAAI,SAAS,SAAS,EAAG,YAAY,CAAC,EAAG;AACnE,oBAAgB,SAAS,IAAI;AAC7B,aAAS,SAAS,IAAI,EAAE,GAAG,SAAS,SAAS,GAAI,UAAU,gBAAgB;AAG3E,UAAM,YAA+B;AAAA,MACnC,QAAQ;AAAA,MACR,SAAS,EAAE,MAAM,cAAc,SAAS,GAAG;AAAA,MAC3C,UAAU,CAAC,EAAE,MAAM,cAAc,SAAS,aAAa,SAAS,GAAG,CAAC;AAAA,IACtE;AAEA,QAAI,QAAQ,KAAK,SAAS;AACxB,MAAC,UAAkC,UAAU,QAAQ,KAAK;AAAA,IAC5D;AACA,QAAI,QAAQ,KAAK,aAAa;AAC5B,MAAC,UAAsC,cAAc,QAAQ,KAAK;AAAA,IACpE;AACA,QAAI,QAAQ,KAAK,YAAY;AAC3B,MAAC,UAAsC,aAAa;AAAA,IACtD;AACA,QAAI,QAAQ,KAAK,QAAQ,QAAQ,KAAK,KAAK,SA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,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isRouteDefinition,
|
|
3
|
+
isRouterDefinition
|
|
4
|
+
} from "./chunk-XP6PLTV2.js";
|
|
5
|
+
import {
|
|
6
|
+
isSchemaAdapter
|
|
7
|
+
} from "./chunk-42JMR62O.js";
|
|
8
|
+
|
|
9
|
+
// src/presentation/http/route/define-route.ts
|
|
10
|
+
function extractSchema(field) {
|
|
11
|
+
if (field == null) return void 0;
|
|
12
|
+
if (isSchemaAdapter(field)) return field;
|
|
13
|
+
return field.schema;
|
|
14
|
+
}
|
|
15
|
+
function extractMeta(field) {
|
|
16
|
+
if (field == null || isSchemaAdapter(field)) return void 0;
|
|
17
|
+
const config = field;
|
|
18
|
+
if (config.description == null && config.contentType == null && config.required == null) {
|
|
19
|
+
return void 0;
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
description: config.description,
|
|
23
|
+
contentType: config.contentType,
|
|
24
|
+
required: config.required
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function normalizeResponses(responses) {
|
|
28
|
+
const result = {};
|
|
29
|
+
for (const [key, value] of Object.entries(responses)) {
|
|
30
|
+
result[String(key)] = value;
|
|
31
|
+
}
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
function defineRoute(input) {
|
|
35
|
+
const req = input.request;
|
|
36
|
+
const bodyMeta = extractMeta(req?.body);
|
|
37
|
+
const queryMeta = extractMeta(req?.query);
|
|
38
|
+
const paramsMeta = extractMeta(req?.params);
|
|
39
|
+
const headersMeta = extractMeta(req?.headers);
|
|
40
|
+
const contextMeta = extractMeta(req?.context);
|
|
41
|
+
const _meta = {
|
|
42
|
+
...bodyMeta ? { body: bodyMeta } : {},
|
|
43
|
+
...queryMeta ? { query: { description: queryMeta.description } } : {},
|
|
44
|
+
...paramsMeta ? { params: { description: paramsMeta.description } } : {},
|
|
45
|
+
...headersMeta ? { headers: { description: headersMeta.description } } : {},
|
|
46
|
+
...contextMeta ? { context: { description: contextMeta.description } } : {}
|
|
47
|
+
};
|
|
48
|
+
const definition = {
|
|
49
|
+
method: input.method,
|
|
50
|
+
path: input.path,
|
|
51
|
+
request: {
|
|
52
|
+
body: extractSchema(req?.body) ?? void 0,
|
|
53
|
+
query: extractSchema(req?.query) ?? void 0,
|
|
54
|
+
params: extractSchema(req?.params) ?? void 0,
|
|
55
|
+
headers: extractSchema(req?.headers) ?? void 0,
|
|
56
|
+
context: extractSchema(req?.context) ?? void 0
|
|
57
|
+
},
|
|
58
|
+
responses: input.responses ? normalizeResponses(input.responses) : void 0,
|
|
59
|
+
docs: {
|
|
60
|
+
summary: input.docs?.summary,
|
|
61
|
+
description: input.docs?.description,
|
|
62
|
+
tags: input.docs?.tags,
|
|
63
|
+
operationId: input.docs?.operationId,
|
|
64
|
+
deprecated: input.docs?.deprecated ?? false,
|
|
65
|
+
security: input.docs?.security,
|
|
66
|
+
externalDocs: input.docs?.externalDocs
|
|
67
|
+
},
|
|
68
|
+
_meta,
|
|
69
|
+
_types: void 0
|
|
70
|
+
};
|
|
71
|
+
return Object.freeze(definition);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/presentation/http/route/define-router.ts
|
|
75
|
+
function defineRouter(routes, options) {
|
|
76
|
+
const defaults = options?.defaults;
|
|
77
|
+
const processedRoutes = defaults?.context || defaults?.tags ? applyRouterDefaults(routes, defaults) : routes;
|
|
78
|
+
const definition = {
|
|
79
|
+
routes: processedRoutes,
|
|
80
|
+
basePath: options?.basePath,
|
|
81
|
+
defaults,
|
|
82
|
+
_isRouter: true
|
|
83
|
+
};
|
|
84
|
+
return deepFreeze(definition);
|
|
85
|
+
}
|
|
86
|
+
function applyRouterDefaults(routes, defaults) {
|
|
87
|
+
const result = {};
|
|
88
|
+
for (const [key, value] of Object.entries(routes)) {
|
|
89
|
+
if (isRouteDefinition(value)) {
|
|
90
|
+
result[key] = applyDefaultsToRoute(value, defaults);
|
|
91
|
+
} else if (isRouterDefinition(value)) {
|
|
92
|
+
result[key] = {
|
|
93
|
+
...value,
|
|
94
|
+
routes: applyRouterDefaults(value.routes, defaults)
|
|
95
|
+
};
|
|
96
|
+
} else if (typeof value === "object" && value !== null) {
|
|
97
|
+
result[key] = applyRouterDefaults(value, defaults);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return result;
|
|
101
|
+
}
|
|
102
|
+
function applyDefaultsToRoute(route, defaults) {
|
|
103
|
+
const needsContext = defaults.context && !route.request.context;
|
|
104
|
+
const needsTags = defaults.tags && defaults.tags.length > 0;
|
|
105
|
+
if (!needsContext && !needsTags) return route;
|
|
106
|
+
return Object.freeze({
|
|
107
|
+
...route,
|
|
108
|
+
request: {
|
|
109
|
+
...route.request,
|
|
110
|
+
context: route.request.context ?? defaults.context ?? void 0
|
|
111
|
+
},
|
|
112
|
+
docs: {
|
|
113
|
+
...route.docs,
|
|
114
|
+
tags: mergeTags(defaults.tags, route.docs.tags)
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function mergeTags(routerTags, routeTags) {
|
|
119
|
+
if (!routerTags || routerTags.length === 0) return routeTags;
|
|
120
|
+
if (!routeTags || routeTags.length === 0) return routerTags;
|
|
121
|
+
const merged = [...routerTags];
|
|
122
|
+
for (const tag of routeTags) {
|
|
123
|
+
if (!merged.includes(tag)) {
|
|
124
|
+
merged.push(tag);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return merged;
|
|
128
|
+
}
|
|
129
|
+
function deepFreeze(obj) {
|
|
130
|
+
const propNames = Object.getOwnPropertyNames(obj);
|
|
131
|
+
for (const name of propNames) {
|
|
132
|
+
const value = obj[name];
|
|
133
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
134
|
+
deepFreeze(value);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return Object.freeze(obj);
|
|
138
|
+
}
|
|
139
|
+
function extractRoutes(input) {
|
|
140
|
+
return isRouterDefinition(input) ? input.routes : input;
|
|
141
|
+
}
|
|
142
|
+
function isSubRouter(value) {
|
|
143
|
+
return typeof value === "object" && value !== null && !isRouteDefinition(value) && !isRouterDefinition(value);
|
|
144
|
+
}
|
|
145
|
+
function deepMergeConfigs(a, b) {
|
|
146
|
+
const result = { ...a };
|
|
147
|
+
for (const key of Object.keys(b)) {
|
|
148
|
+
const aVal = result[key];
|
|
149
|
+
const bVal = b[key];
|
|
150
|
+
if (isSubRouter(aVal) && isSubRouter(bVal)) {
|
|
151
|
+
result[key] = deepMergeConfigs(aVal, bVal);
|
|
152
|
+
} else {
|
|
153
|
+
result[key] = bVal;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
function mergeRouters(...routers) {
|
|
159
|
+
const merged = routers.map(extractRoutes).reduce(deepMergeConfigs);
|
|
160
|
+
return defineRouter(merged);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export {
|
|
164
|
+
defineRoute,
|
|
165
|
+
defineRouter,
|
|
166
|
+
mergeRouters
|
|
167
|
+
};
|
|
168
|
+
//# sourceMappingURL=chunk-MF2JDREK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/presentation/http/route/define-route.ts","../src/presentation/http/route/define-router.ts"],"sourcesContent":["/**\n * @fileoverview Factory function for creating route definitions (v2).\n *\n * The `defineRoute` function is the main entry point for defining routes.\n * Request schemas are grouped under a `request` field, while responses\n * are defined via the `responses` field with per-status-code config.\n *\n * Each schema field accepts either a bare `SchemaAdapter` or an object with\n * metadata: `{ schema, description?, contentType?, required? }`.\n *\n * The success response type is inferred from the first 2xx status with a schema.\n *\n * @module unified/route/define-route\n */\n\nimport type { SchemaAdapter, InferOutput } from '../schema/types';\nimport { isSchemaAdapter } from '../schema/types';\nimport type {\n HttpMethod,\n RouteDefinition,\n PathParams,\n SchemaFieldInput,\n RouteFieldMeta,\n ResponseFieldConfig,\n ResponsesDefinition,\n ExtractSuccessSchema,\n} from './types';\n\n// ============================================================================\n// Input Types\n// ============================================================================\n\n/**\n * Complete input for defineRoute.\n *\n * @example GET with query and response\n * ```typescript\n * defineRoute({\n * method: 'GET',\n * path: '/api/users',\n * request: {\n * query: zodSchema(z.object({ page: z.coerce.number().default(1) })),\n * },\n * responses: {\n * 200: { schema: zodSchema(userListSchema) },\n * },\n * docs: { summary: 'List users', tags: ['Users'] },\n * })\n * ```\n *\n * @example POST with body and multiple statuses\n * ```typescript\n * defineRoute({\n * method: 'POST',\n * path: '/api/users',\n * request: {\n * body: zodSchema(createUserSchema),\n * },\n * responses: {\n * 201: { schema: zodSchema(userSchema), description: 'Created' },\n * 400: { description: 'Validation error' },\n * 409: { description: 'Email already in use' },\n * },\n * })\n * ```\n *\n * @example DELETE with 204\n * ```typescript\n * defineRoute({\n * method: 'DELETE',\n * path: '/api/users/:userId',\n * responses: {\n * 204: { description: 'User deleted' },\n * 404: { description: 'User not found' },\n * },\n * })\n * ```\n */\ninterface DefineRouteInput<\n TMethod extends HttpMethod,\n TPath extends string,\n TBody extends SchemaAdapter | undefined = undefined,\n TQuery extends SchemaAdapter | undefined = undefined,\n TParams extends SchemaAdapter | undefined = undefined,\n THeaders extends SchemaAdapter | undefined = undefined,\n TContext extends SchemaAdapter | undefined = undefined,\n TResponses extends ResponsesDefinition | undefined = undefined,\n> {\n /** HTTP method for this route. */\n readonly method: TMethod;\n\n /** URL path pattern with optional parameters (`:param` or `{param}`). */\n readonly path: TPath;\n\n /** Request schemas (body, query, params, headers, context). */\n readonly request?: {\n /** Request body schema (or `{ schema, description?, contentType?, required? }`). */\n readonly body?: TBody extends SchemaAdapter ? SchemaFieldInput<TBody> : TBody;\n\n /** Query parameters schema (or `{ schema, description? }`). */\n readonly query?: TQuery extends SchemaAdapter ? SchemaFieldInput<TQuery> : TQuery;\n\n /** Path parameters schema (or `{ schema, description? }`). If omitted, inferred from path template. */\n readonly params?: TParams extends SchemaAdapter ? SchemaFieldInput<TParams> : TParams;\n\n /** Headers schema (or `{ schema, description? }`). */\n readonly headers?: THeaders extends SchemaAdapter ? SchemaFieldInput<THeaders> : THeaders;\n\n /** Context schema (or `{ schema, description? }`). */\n readonly context?: TContext extends SchemaAdapter ? SchemaFieldInput<TContext> : TContext;\n };\n\n /**\n * Per-status response definitions.\n *\n * Each key is an HTTP status code. Each value can have:\n * - `schema` — response body schema (drives type inference for 2xx)\n * - `description` — OpenAPI response description\n * - `contentType` — response content type (default: `application/json`)\n */\n readonly responses?: TResponses;\n\n /** OpenAPI documentation. */\n readonly docs?: {\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly operationId?: string;\n readonly deprecated?: boolean;\n readonly security?: readonly Record<string, readonly string[]>[];\n readonly externalDocs?: {\n readonly url: string;\n readonly description?: string;\n };\n };\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Extracts the SchemaAdapter from a field that may be bare or wrapped in config.\n */\nfunction extractSchema<T extends SchemaAdapter>(\n field: SchemaFieldInput<T> | undefined,\n): T | undefined {\n if (field == null) return undefined;\n if (isSchemaAdapter(field)) return field as T;\n return (field as { schema: T }).schema;\n}\n\n/**\n * Extracts metadata from a field config, if it was passed as an object.\n */\nfunction extractMeta(\n field: SchemaFieldInput | undefined,\n): { description?: string; contentType?: string; required?: boolean } | undefined {\n if (field == null || isSchemaAdapter(field)) return undefined;\n const config = field as { description?: string; contentType?: string; required?: boolean };\n if (config.description == null && config.contentType == null && config.required == null) {\n return undefined;\n }\n return {\n description: config.description,\n contentType: config.contentType,\n required: config.required,\n };\n}\n\n/**\n * Normalizes responses record keys to strings.\n */\nfunction normalizeResponses(\n responses: Record<string | number, ResponseFieldConfig>,\n): Record<string, ResponseFieldConfig> {\n const result: Record<string, ResponseFieldConfig> = {};\n for (const [key, value] of Object.entries(responses)) {\n result[String(key)] = value;\n }\n return result;\n}\n\n// ============================================================================\n// Return type helpers\n// ============================================================================\n\ntype ResolveBody<T> = T extends SchemaAdapter ? InferOutput<T> : undefined;\ntype ResolveQuery<T> = T extends SchemaAdapter ? InferOutput<T> : undefined;\ntype ResolveParams<T, TPath extends string> = T extends SchemaAdapter\n ? InferOutput<T>\n : PathParams<TPath>;\ntype ResolveHeaders<T> = T extends SchemaAdapter ? InferOutput<T> : undefined;\ntype ResolveContext<T> = T extends SchemaAdapter ? InferOutput<T> : undefined;\n\ntype ResolveResponse<T> = T extends ResponsesDefinition\n ? ExtractSuccessSchema<T> extends SchemaAdapter\n ? InferOutput<ExtractSuccessSchema<T>>\n : undefined\n : undefined;\n\n// ============================================================================\n// Factory Function\n// ============================================================================\n\n/**\n * Creates a route definition from the provided configuration.\n *\n * This is the main entry point for defining routes. The resulting definition\n * can be used for type-safe client generation, server-side route registration,\n * and OpenAPI specification generation.\n *\n * @param input - Route configuration with request schemas and responses\n * @returns A frozen RouteDefinition object with full type information\n */\nexport function defineRoute<\n TMethod extends HttpMethod,\n TPath extends string,\n TBody extends SchemaAdapter | undefined = undefined,\n TQuery extends SchemaAdapter | undefined = undefined,\n TParams extends SchemaAdapter | undefined = undefined,\n THeaders extends SchemaAdapter | undefined = undefined,\n TContext extends SchemaAdapter | undefined = undefined,\n TResponses extends ResponsesDefinition | undefined = undefined,\n>(\n input: DefineRouteInput<TMethod, TPath, TBody, TQuery, TParams, THeaders, TContext, TResponses>,\n): RouteDefinition<\n TMethod,\n TPath,\n ResolveBody<TBody>,\n ResolveQuery<TQuery>,\n ResolveParams<TParams, TPath>,\n ResolveHeaders<THeaders>,\n ResolveContext<TContext>,\n ResolveResponse<TResponses>\n> {\n const req = input.request;\n\n // Build _meta from any config-wrapped fields\n const bodyMeta = extractMeta(req?.body as SchemaFieldInput | undefined);\n const queryMeta = extractMeta(req?.query as SchemaFieldInput | undefined);\n const paramsMeta = extractMeta(req?.params as SchemaFieldInput | undefined);\n const headersMeta = extractMeta(req?.headers as SchemaFieldInput | undefined);\n const contextMeta = extractMeta(req?.context as SchemaFieldInput | undefined);\n\n const _meta: RouteFieldMeta = {\n ...(bodyMeta ? { body: bodyMeta } : {}),\n ...(queryMeta ? { query: { description: queryMeta.description } } : {}),\n ...(paramsMeta ? { params: { description: paramsMeta.description } } : {}),\n ...(headersMeta ? { headers: { description: headersMeta.description } } : {}),\n ...(contextMeta ? { context: { description: contextMeta.description } } : {}),\n };\n\n const definition = {\n method: input.method,\n path: input.path,\n request: {\n body: extractSchema(req?.body as SchemaFieldInput | undefined) ?? undefined,\n query: extractSchema(req?.query as SchemaFieldInput | undefined) ?? undefined,\n params: extractSchema(req?.params as SchemaFieldInput | undefined) ?? undefined,\n headers: extractSchema(req?.headers as SchemaFieldInput | undefined) ?? undefined,\n context: extractSchema(req?.context as SchemaFieldInput | undefined) ?? undefined,\n },\n responses: input.responses ? normalizeResponses(input.responses) : undefined,\n docs: {\n summary: input.docs?.summary,\n description: input.docs?.description,\n tags: input.docs?.tags,\n operationId: input.docs?.operationId,\n deprecated: input.docs?.deprecated ?? false,\n security: input.docs?.security,\n externalDocs: input.docs?.externalDocs,\n },\n _meta,\n _types: undefined as unknown,\n };\n\n return Object.freeze(definition) as RouteDefinition<\n TMethod,\n TPath,\n ResolveBody<TBody>,\n ResolveQuery<TQuery>,\n ResolveParams<TParams, TPath>,\n ResolveHeaders<THeaders>,\n ResolveContext<TContext>,\n ResolveResponse<TResponses>\n >;\n}\n","/**\n * @fileoverview Factory function for creating router definitions.\n *\n * The `defineRouter` function groups routes into a hierarchical structure\n * with optional router-level defaults for context and tags.\n *\n * @module unified/route/define-router\n */\n\nimport type {\n RouterConfig,\n RouterDefaults,\n RouterDefinition,\n RouteDefinition,\n DeepMergeTwo,\n DeepMergeAll,\n} from './types';\nimport { isRouteDefinition, isRouterDefinition } from './types';\n\n/**\n * Options for router definition.\n */\nexport interface DefineRouterOptions {\n /**\n * Base path prefix for all routes in this router.\n * Will be prepended to all route paths.\n */\n readonly basePath?: string;\n\n /**\n * Default values applied to all child routes.\n *\n * @example\n * ```typescript\n * defineRouter({\n * list: listUsersRoute,\n * get: getUserRoute,\n * }, {\n * defaults: {\n * context: zodSchema(executionContextSchema),\n * tags: ['Users'],\n * },\n * })\n * ```\n */\n readonly defaults?: RouterDefaults;\n}\n\n/**\n * Creates a router definition from a configuration object.\n *\n * A router is a hierarchical grouping of routes that provides:\n * - Organized API structure with nested namespaces\n * - Typed client method generation\n * - OpenAPI tag grouping\n * - Router-level defaults for context and tags\n *\n * @param routes - Object containing routes and nested routers\n * @param options - Optional router configuration\n * @returns A frozen RouterDefinition object\n *\n * @example Basic router\n * ```typescript\n * const api = defineRouter({\n * users: {\n * list: listUsersRoute,\n * get: getUserRoute,\n * create: createUserRoute,\n * },\n * });\n * ```\n *\n * @example With router-level defaults\n * ```typescript\n * const api = defineRouter({\n * list: listUsersRoute,\n * get: getUserRoute,\n * }, {\n * basePath: '/api/v1',\n * defaults: {\n * context: zodSchema(executionContextSchema),\n * tags: ['Users'],\n * },\n * });\n * // Context is applied to all routes that don't define their own.\n * // Tags are merged with each route's existing tags.\n * ```\n */\nexport function defineRouter<T extends RouterConfig>(\n routes: T,\n options?: DefineRouterOptions,\n): RouterDefinition<T> {\n const defaults = options?.defaults;\n\n // Apply defaults to routes if context or tags are provided\n const processedRoutes =\n defaults?.context || defaults?.tags ? (applyRouterDefaults(routes, defaults) as T) : routes;\n\n const definition: RouterDefinition<T> = {\n routes: processedRoutes,\n basePath: options?.basePath,\n defaults,\n _isRouter: true,\n };\n\n // Deep freeze the router definition\n return deepFreeze(definition);\n}\n\n/**\n * Recursively applies router-level defaults to all routes in the tree.\n */\nfunction applyRouterDefaults(routes: RouterConfig, defaults: RouterDefaults): RouterConfig {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(routes)) {\n if (isRouteDefinition(value)) {\n result[key] = applyDefaultsToRoute(value, defaults);\n } else if (isRouterDefinition(value)) {\n result[key] = {\n ...value,\n routes: applyRouterDefaults(value.routes, defaults),\n };\n } else if (typeof value === 'object' && value !== null) {\n result[key] = applyRouterDefaults(value as RouterConfig, defaults);\n }\n }\n\n return result as RouterConfig;\n}\n\n/**\n * Applies router-level defaults to a single route definition.\n */\nfunction applyDefaultsToRoute(route: RouteDefinition, defaults: RouterDefaults): RouteDefinition {\n const needsContext = defaults.context && !route.request.context;\n const needsTags = defaults.tags && defaults.tags.length > 0;\n\n if (!needsContext && !needsTags) return route;\n\n return Object.freeze({\n ...route,\n request: {\n ...route.request,\n context: route.request.context ?? defaults.context ?? undefined,\n },\n docs: {\n ...route.docs,\n tags: mergeTags(defaults.tags, route.docs.tags),\n },\n }) as RouteDefinition;\n}\n\n/**\n * Merges router-level tags with route-level tags, avoiding duplicates.\n */\nfunction mergeTags(\n routerTags?: readonly string[],\n routeTags?: readonly string[],\n): readonly string[] | undefined {\n if (!routerTags || routerTags.length === 0) return routeTags;\n if (!routeTags || routeTags.length === 0) return routerTags;\n\n // Merge, preserving order: router tags first, then route-specific tags (no duplicates)\n const merged = [...routerTags];\n for (const tag of routeTags) {\n if (!merged.includes(tag)) {\n merged.push(tag);\n }\n }\n return merged;\n}\n\n/**\n * Deep freezes an object and all its nested objects.\n */\nfunction deepFreeze<T extends object>(obj: T): T {\n const propNames = Object.getOwnPropertyNames(obj) as (keyof T)[];\n\n for (const name of propNames) {\n const value = obj[name];\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return Object.freeze(obj);\n}\n\n// ============================================================================\n// mergeRouters — variadic deep merge\n// ============================================================================\n\ntype RouterInput<T extends RouterConfig> = T | RouterDefinition<T>;\n\n/** Extracts the raw RouterConfig from either a plain config or a RouterDefinition. */\nfunction extractRoutes<T extends RouterConfig>(input: RouterInput<T>): T {\n return isRouterDefinition(input) ? input.routes : input;\n}\n\n/** Returns true if `value` is a plain sub-router object (not a RouteDefinition, not a RouterDefinition). */\nfunction isSubRouter(value: unknown): value is RouterConfig {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isRouteDefinition(value) &&\n !isRouterDefinition(value)\n );\n}\n\n/** Recursively deep-merges two router configs. Sub-routers are merged; leaves are overwritten. */\nfunction deepMergeConfigs(a: RouterConfig, b: RouterConfig): RouterConfig {\n const result: Record<string, unknown> = { ...a };\n\n for (const key of Object.keys(b)) {\n const aVal = result[key];\n const bVal = b[key];\n\n if (isSubRouter(aVal) && isSubRouter(bVal)) {\n result[key] = deepMergeConfigs(aVal, bVal);\n } else {\n result[key] = bVal;\n }\n }\n\n return result as RouterConfig;\n}\n\n// Overloads for 2–8 routers (clean IDE experience)\nexport function mergeRouters<T1 extends RouterConfig, T2 extends RouterConfig>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n): RouterDefinition<DeepMergeTwo<T1, T2>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n T6 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n r6: RouterInput<T6>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n T6 extends RouterConfig,\n T7 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n r6: RouterInput<T6>,\n r7: RouterInput<T7>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6, T7]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n T6 extends RouterConfig,\n T7 extends RouterConfig,\n T8 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n r6: RouterInput<T6>,\n r7: RouterInput<T7>,\n r8: RouterInput<T8>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6, T7, T8]>>;\n\n// Variadic fallback for 9+\nexport function mergeRouters(\n ...routers: RouterInput<RouterConfig>[]\n): RouterDefinition<RouterConfig>;\n\n// Implementation\nexport function mergeRouters(\n ...routers: RouterInput<RouterConfig>[]\n): RouterDefinition<RouterConfig> {\n const merged = routers.map(extractRoutes).reduce(deepMergeConfigs);\n return defineRouter(merged);\n}\n"],"mappings":";;;;;;;;;AAgJA,SAAS,cACP,OACe;AACf,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,gBAAgB,KAAK,EAAG,QAAO;AACnC,SAAQ,MAAwB;AAClC;AAKA,SAAS,YACP,OACgF;AAChF,MAAI,SAAS,QAAQ,gBAAgB,KAAK,EAAG,QAAO;AACpD,QAAM,SAAS;AACf,MAAI,OAAO,eAAe,QAA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AE/C,aAAW,OAAO,OAAO,KAAK,CAAC,GAAG;AAChC,UAAM,OAAO,OAAO,GAAG;AACvB,UAAM,OAAO,EAAE,GAAG;AAElB,QAAI,YAAY,IAAI,KAAK,YAAY,IAAI,GAAG;AAC1C,aAAO,GAAG,IAAI,iBAAiB,MAAM,IAAI;AAAA,IAC3C,OAAO;AACL,aAAO,GAAG,IAAI;AAAA,IAChB;AAAA,EACF;AAEA,SAAO;AACT;AAkGO,SAAS,gBACX,SAC6B;AAChC,QAAM,SAAS,QAAQ,IAAI,aAAa,EAAE,OAAO,gBAAgB;AACjE,SAAO,aAAa,MAAM;AAC5B;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=chunk-RVSBIYY4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
collectRoutes,
|
|
3
|
+
generateOperationId,
|
|
3
4
|
getPathParamNames,
|
|
4
5
|
isRouterDefinition
|
|
5
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-XP6PLTV2.js";
|
|
6
7
|
|
|
7
8
|
// src/presentation/http/openapi/generate.ts
|
|
8
9
|
function isValidJsonSchema(value) {
|
|
@@ -17,12 +18,12 @@ function generateOpenAPI(router, config) {
|
|
|
17
18
|
const collectedRoutes = collectRoutes(routes);
|
|
18
19
|
const paths = {};
|
|
19
20
|
const allTags = /* @__PURE__ */ new Set();
|
|
20
|
-
for (const { route } of collectedRoutes) {
|
|
21
|
+
for (const { key, route } of collectedRoutes) {
|
|
21
22
|
const openAPIPath = convertToOpenAPIPath(route.path);
|
|
22
23
|
if (!paths[openAPIPath]) {
|
|
23
24
|
paths[openAPIPath] = {};
|
|
24
25
|
}
|
|
25
|
-
const operation = buildOperation(route);
|
|
26
|
+
const operation = buildOperation(key, route);
|
|
26
27
|
const method = route.method.toLowerCase();
|
|
27
28
|
paths[openAPIPath][method] = operation;
|
|
28
29
|
if (operation.tags) {
|
|
@@ -64,13 +65,12 @@ function generateOpenAPI(router, config) {
|
|
|
64
65
|
function convertToOpenAPIPath(path) {
|
|
65
66
|
return path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, "{$1}");
|
|
66
67
|
}
|
|
67
|
-
function buildOperation(route) {
|
|
68
|
+
function buildOperation(key, route) {
|
|
68
69
|
const operation = {
|
|
69
70
|
responses: buildResponses(route)
|
|
70
71
|
};
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
72
|
+
const operationId = route.docs.operationId ?? generateOperationId(key);
|
|
73
|
+
operation.operationId = operationId;
|
|
74
74
|
if (route.docs.summary) {
|
|
75
75
|
operation.summary = route.docs.summary;
|
|
76
76
|
}
|
|
@@ -108,8 +108,8 @@ function buildParameters(route) {
|
|
|
108
108
|
required: true,
|
|
109
109
|
schema: { type: "string" }
|
|
110
110
|
};
|
|
111
|
-
if (route.request.params
|
|
112
|
-
const jsonSchema = route.request.params.
|
|
111
|
+
if (route.request.params) {
|
|
112
|
+
const jsonSchema = route.request.params.toJsonSchema();
|
|
113
113
|
if (jsonSchema.properties && typeof jsonSchema.properties === "object") {
|
|
114
114
|
const propSchema = jsonSchema.properties[name];
|
|
115
115
|
if (isValidJsonSchema(propSchema)) {
|
|
@@ -119,8 +119,8 @@ function buildParameters(route) {
|
|
|
119
119
|
}
|
|
120
120
|
parameters.push(param);
|
|
121
121
|
}
|
|
122
|
-
if (route.request.query
|
|
123
|
-
const querySchema = route.request.query.
|
|
122
|
+
if (route.request.query) {
|
|
123
|
+
const querySchema = route.request.query.toJsonSchema();
|
|
124
124
|
if (querySchema.properties && typeof querySchema.properties === "object") {
|
|
125
125
|
const requiredFields = new Set(
|
|
126
126
|
Array.isArray(querySchema.required) ? querySchema.required : []
|
|
@@ -144,8 +144,8 @@ function buildParameters(route) {
|
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
|
-
if (route.request.headers
|
|
148
|
-
const headersSchema = route.request.headers.
|
|
147
|
+
if (route.request.headers) {
|
|
148
|
+
const headersSchema = route.request.headers.toJsonSchema();
|
|
149
149
|
if (headersSchema.properties && typeof headersSchema.properties === "object") {
|
|
150
150
|
const requiredFields = new Set(
|
|
151
151
|
Array.isArray(headersSchema.required) ? headersSchema.required : []
|
|
@@ -169,40 +169,42 @@ function buildParameters(route) {
|
|
|
169
169
|
return parameters;
|
|
170
170
|
}
|
|
171
171
|
function buildRequestBody(route) {
|
|
172
|
-
const
|
|
173
|
-
const
|
|
172
|
+
const bodySchema = route.request.body;
|
|
173
|
+
const meta = route._meta?.body;
|
|
174
|
+
const contentType = meta?.contentType ?? "application/json";
|
|
174
175
|
const requestBody = {
|
|
175
|
-
required:
|
|
176
|
+
required: meta?.required !== false,
|
|
176
177
|
content: {
|
|
177
178
|
[contentType]: {
|
|
178
|
-
schema:
|
|
179
|
+
schema: bodySchema.toJsonSchema()
|
|
179
180
|
}
|
|
180
181
|
}
|
|
181
182
|
};
|
|
182
|
-
if (
|
|
183
|
-
requestBody.description =
|
|
183
|
+
if (meta?.description) {
|
|
184
|
+
requestBody.description = meta.description;
|
|
184
185
|
}
|
|
185
186
|
return requestBody;
|
|
186
187
|
}
|
|
187
188
|
function buildResponses(route) {
|
|
188
189
|
const responses = {};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
190
|
+
if (route.responses && Object.keys(route.responses).length > 0) {
|
|
191
|
+
for (const [statusCode, config] of Object.entries(route.responses)) {
|
|
192
|
+
const description = config.description ?? `Response ${statusCode}`;
|
|
193
|
+
if (config.schema) {
|
|
194
|
+
const contentType = config.contentType ?? "application/json";
|
|
195
|
+
responses[statusCode] = {
|
|
196
|
+
description,
|
|
197
|
+
content: {
|
|
198
|
+
[contentType]: {
|
|
199
|
+
schema: config.schema.toJsonSchema()
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
} else {
|
|
204
|
+
responses[statusCode] = { description };
|
|
205
|
+
}
|
|
202
206
|
}
|
|
203
|
-
|
|
204
|
-
}
|
|
205
|
-
if (Object.keys(responses).length === 0) {
|
|
207
|
+
} else {
|
|
206
208
|
responses["200"] = { description: "Successful response" };
|
|
207
209
|
}
|
|
208
210
|
return responses;
|
|
@@ -211,4 +213,4 @@ function buildResponses(route) {
|
|
|
211
213
|
export {
|
|
212
214
|
generateOpenAPI
|
|
213
215
|
};
|
|
214
|
-
//# sourceMappingURL=chunk-
|
|
216
|
+
//# sourceMappingURL=chunk-XIRJ73IO.js.map
|