@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.
Files changed (93) hide show
  1. package/dist/chunk-36IO4BM7.js +113 -0
  2. package/dist/chunk-36IO4BM7.js.map +1 -0
  3. package/dist/chunk-4BVOLXDJ.js +54 -0
  4. package/dist/chunk-4BVOLXDJ.js.map +1 -0
  5. package/dist/{chunk-GGSAAZPM.js → chunk-AUMHMWDD.js} +19 -20
  6. package/dist/chunk-AUMHMWDD.js.map +1 -0
  7. package/dist/chunk-CBTICRSM.js +34 -0
  8. package/dist/chunk-CBTICRSM.js.map +1 -0
  9. package/dist/chunk-H5TNDC5U.js +138 -0
  10. package/dist/chunk-H5TNDC5U.js.map +1 -0
  11. package/dist/chunk-KJ4JGZOE.js +96 -0
  12. package/dist/chunk-KJ4JGZOE.js.map +1 -0
  13. package/dist/chunk-MF2JDREK.js +168 -0
  14. package/dist/chunk-MF2JDREK.js.map +1 -0
  15. package/dist/chunk-RVSBIYY4.js +1 -0
  16. package/dist/chunk-RVSBIYY4.js.map +1 -0
  17. package/dist/{chunk-PUVAB3JX.js → chunk-XIRJ73IO.js} +38 -36
  18. package/dist/chunk-XIRJ73IO.js.map +1 -0
  19. package/dist/{chunk-DS7TE6KZ.js → chunk-XP6PLTV2.js} +11 -3
  20. package/dist/chunk-XP6PLTV2.js.map +1 -0
  21. package/dist/chunk-XWKHOLIP.js +191 -0
  22. package/dist/chunk-XWKHOLIP.js.map +1 -0
  23. package/dist/event-router-definition.type-CP9uTlux.d.cts +150 -0
  24. package/dist/event-router-definition.type-D8CG-kjZ.d.ts +150 -0
  25. package/dist/events/asyncapi/index.cjs +143 -0
  26. package/dist/events/asyncapi/index.cjs.map +1 -0
  27. package/dist/events/asyncapi/index.d.cts +184 -0
  28. package/dist/events/asyncapi/index.d.ts +184 -0
  29. package/dist/events/asyncapi/index.js +8 -0
  30. package/dist/events/asyncapi/index.js.map +1 -0
  31. package/dist/events/handler/index.cjs +171 -0
  32. package/dist/events/handler/index.cjs.map +1 -0
  33. package/dist/events/handler/index.d.cts +153 -0
  34. package/dist/events/handler/index.d.ts +153 -0
  35. package/dist/events/handler/index.js +21 -0
  36. package/dist/events/handler/index.js.map +1 -0
  37. package/dist/events/index.cjs +497 -0
  38. package/dist/events/index.cjs.map +1 -0
  39. package/dist/events/index.d.cts +9 -0
  40. package/dist/events/index.d.ts +9 -0
  41. package/dist/events/index.js +41 -0
  42. package/dist/events/index.js.map +1 -0
  43. package/dist/events/server/index.cjs +291 -0
  44. package/dist/events/server/index.cjs.map +1 -0
  45. package/dist/events/server/index.d.cts +281 -0
  46. package/dist/events/server/index.d.ts +281 -0
  47. package/dist/events/server/index.js +16 -0
  48. package/dist/events/server/index.js.map +1 -0
  49. package/dist/events/shared/index.cjs +85 -0
  50. package/dist/events/shared/index.cjs.map +1 -0
  51. package/dist/events/shared/index.d.cts +35 -0
  52. package/dist/events/shared/index.d.ts +35 -0
  53. package/dist/events/shared/index.js +13 -0
  54. package/dist/events/shared/index.js.map +1 -0
  55. package/dist/global.js +3 -3
  56. package/dist/http/index.cjs +563 -93
  57. package/dist/http/index.cjs.map +1 -1
  58. package/dist/http/index.d.cts +5 -3
  59. package/dist/http/index.d.ts +5 -3
  60. package/dist/http/index.js +30 -12
  61. package/dist/http/openapi/index.cjs +43 -35
  62. package/dist/http/openapi/index.cjs.map +1 -1
  63. package/dist/http/openapi/index.d.cts +8 -34
  64. package/dist/http/openapi/index.d.ts +8 -34
  65. package/dist/http/openapi/index.js +2 -2
  66. package/dist/http/route/index.cjs +106 -9
  67. package/dist/http/route/index.cjs.map +1 -1
  68. package/dist/http/route/index.d.cts +133 -227
  69. package/dist/http/route/index.d.ts +133 -227
  70. package/dist/http/route/index.js +5 -2
  71. package/dist/http/server/index.cjs +24 -19
  72. package/dist/http/server/index.cjs.map +1 -1
  73. package/dist/http/server/index.d.cts +4 -261
  74. package/dist/http/server/index.d.ts +4 -261
  75. package/dist/http/server/index.js +2 -2
  76. package/dist/http/shared/index.cjs.map +1 -1
  77. package/dist/http/shared/index.d.cts +10 -14
  78. package/dist/http/shared/index.d.ts +10 -14
  79. package/dist/http/shared/index.js +11 -127
  80. package/dist/http/shared/index.js.map +1 -1
  81. package/dist/index.js +6 -6
  82. package/dist/{router-definition.type-ynBhT16T.d.cts → router-definition.type-BElX-Pl4.d.cts} +169 -256
  83. package/dist/{router-definition.type-DORVlLNk.d.ts → router-definition.type-DxG8ncJZ.d.ts} +169 -256
  84. package/dist/types-B6Q1iCgf.d.ts +262 -0
  85. package/dist/types-afYpL7Ap.d.cts +262 -0
  86. package/dist/types-cke61juH.d.cts +42 -0
  87. package/dist/types-cke61juH.d.ts +42 -0
  88. package/package.json +35 -2
  89. package/dist/chunk-BZULBF4N.js +0 -82
  90. package/dist/chunk-BZULBF4N.js.map +0 -1
  91. package/dist/chunk-DS7TE6KZ.js.map +0 -1
  92. package/dist/chunk-GGSAAZPM.js.map +0 -1
  93. package/dist/chunk-PUVAB3JX.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/presentation/events/server/index.ts","../../../src/presentation/events/handler/types/event-router-definition.type.ts","../../../src/presentation/events/handler/utils.ts","../../../src/presentation/http/shared/error-mapping.ts","../../../src/presentation/events/shared/error-mapping.ts","../../../src/presentation/events/server/types.ts","../../../src/presentation/events/server/create-event-routes.ts","../../../src/presentation/events/server/event-routes-builder.ts"],"sourcesContent":["export { eventRoutes } from './event-routes-builder';\nexport type {\n EventRoutesBuilder,\n MissingHandlersError,\n BuilderEventHandlerConfig,\n} from './event-routes-builder';\n\nexport type {\n RawEvent,\n EventMetadata,\n ValidatedEvent,\n TypedEventContext,\n EventHandlerConfig,\n SimpleEventHandlerFn,\n SimpleEventHandlerConfig,\n AnyEventHandlerConfig,\n EventMiddlewareFunction,\n EventRoutesConfig,\n CreateEventRoutesOptions,\n UnifiedEventInput,\n UseCasePort,\n} from './types';\n\nexport { isSimpleEventHandlerConfig } from './types';\n","/**\n * @fileoverview Event router definition types for grouping event handlers.\n *\n * Mirrors the HTTP router definition pattern with hierarchical grouping,\n * dotted-key access, and deep merge support.\n *\n * @module events/handler/types/event-router-definition\n */\n\nimport type { EventHandlerDefinition } from './event-handler-definition.type';\nimport type { SchemaAdapter } from '../../../http/schema/types';\n\n// ============================================================================\n// Router Types\n// ============================================================================\n\n/**\n * A router entry can be an event handler definition, a nested config, or a router definition.\n */\nexport type EventRouterEntry =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n EventHandlerDefinition<string, any, any> | EventRouterConfig | EventRouterDefinition;\n\n/**\n * Configuration for an event router (group of event handlers).\n */\nexport interface EventRouterConfig {\n readonly [key: string]: EventRouterEntry;\n}\n\n/**\n * Router-level defaults applied to all child event handlers.\n */\nexport interface EventRouterDefaults {\n /** Default tags for all handlers. Merged with handler-specific tags. */\n readonly tags?: readonly string[];\n\n /** Default context schema. Applied to handlers that don't define their own. */\n readonly context?: SchemaAdapter;\n}\n\n/**\n * A fully defined event router.\n */\nexport interface EventRouterDefinition<T extends EventRouterConfig = EventRouterConfig> {\n /** The handlers and nested routers in this router. */\n readonly handlers: T;\n\n /** Default values applied to all child handlers. */\n readonly defaults?: EventRouterDefaults;\n\n /**\n * Marker to identify this as an event router.\n * @internal\n */\n readonly _isEventRouter: true;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Checks if a value is an EventHandlerDefinition.\n */\nexport function isEventHandlerDefinition(value: unknown): value is EventHandlerDefinition {\n return typeof value === 'object' && value !== null && 'eventType' in value && '_types' in value;\n}\n\n/**\n * Checks if a value is an EventRouterDefinition.\n */\nexport function isEventRouterDefinition(value: unknown): value is EventRouterDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n '_isEventRouter' in value &&\n (value as EventRouterDefinition)._isEventRouter === true\n );\n}\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\n/**\n * Flattens an event router into a map of dotted keys to handler definitions.\n */\nexport type FlattenEventRouter<\n T extends EventRouterConfig,\n Prefix extends string = '',\n> = T extends EventRouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends EventHandlerDefinition<any, any, any>\n ? { [P in `${Prefix}${K & string}`]: T[K] }\n : T[K] extends EventRouterConfig\n ? FlattenEventRouter<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T] extends infer U\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U extends Record<string, EventHandlerDefinition<any, any, any>>\n ? U\n : never\n : never\n : never;\n\n/**\n * Gets all handler keys from an event router.\n */\nexport type EventRouterKeys<\n T extends EventRouterConfig,\n Prefix extends string = '',\n> = T extends EventRouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends EventHandlerDefinition<any, any, any>\n ? `${Prefix}${K & string}`\n : T[K] extends EventRouterConfig\n ? EventRouterKeys<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T]\n : never;\n\n/**\n * Gets an event handler by its dotted key path.\n */\nexport type GetEventHandler<\n T extends EventRouterConfig,\n K extends string,\n> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends EventRouterConfig\n ? GetEventHandler<T[Head], Tail>\n : never\n : never\n : K extends keyof T\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T[K] extends EventHandlerDefinition<any, any, any>\n ? T[K]\n : never\n : never;\n\n// ============================================================================\n// Deep Merge Types\n// ============================================================================\n\n/**\n * Deep-merges two event router configs at the type level.\n */\nexport type DeepMergeTwo<A extends EventRouterConfig, B extends EventRouterConfig> = {\n readonly [K in keyof A | keyof B]: K extends keyof A\n ? K extends keyof B\n ? A[K] extends EventRouterConfig\n ? B[K] extends EventRouterConfig\n ? DeepMergeTwo<A[K], B[K]>\n : B[K]\n : B[K]\n : A[K]\n : K extends keyof B\n ? B[K]\n : never;\n};\n\n/**\n * Recursively deep-merges N event router configs left-to-right.\n */\nexport type DeepMergeAll<T extends readonly EventRouterConfig[]> = T extends readonly [\n infer Only extends EventRouterConfig,\n]\n ? Only\n : T extends readonly [\n infer First extends EventRouterConfig,\n infer Second extends EventRouterConfig,\n ...infer Rest extends readonly EventRouterConfig[],\n ]\n ? DeepMergeAll<[DeepMergeTwo<First, Second>, ...Rest]>\n : EventRouterConfig;\n\n// ============================================================================\n// Runtime Utilities\n// ============================================================================\n\n/**\n * Collects all event handlers from a router into a flat array.\n */\nexport function collectEventHandlers(\n config: EventRouterConfig,\n basePath = '',\n): { key: string; handler: EventHandlerDefinition }[] {\n const handlers: { key: string; handler: EventHandlerDefinition }[] = [];\n\n for (const [key, value] of Object.entries(config)) {\n const fullKey = basePath ? `${basePath}.${key}` : key;\n\n if (isEventHandlerDefinition(value)) {\n handlers.push({ key: fullKey, handler: value });\n } else if (isEventRouterDefinition(value)) {\n handlers.push(...collectEventHandlers(value.handlers, fullKey));\n } else if (typeof value === 'object' && value !== null) {\n handlers.push(...collectEventHandlers(value as EventRouterConfig, fullKey));\n }\n }\n\n return handlers;\n}\n","/**\n * @fileoverview Utility functions for event handler routing.\n *\n * @module events/handler/utils\n */\n\n/**\n * Generates a handler ID from a dotted key path.\n *\n * Converts dot-separated keys to camelCase:\n * - `\"ticket.created\"` → `\"ticketCreated\"`\n * - `\"ecosystem.member.added\"` → `\"ecosystemMemberAdded\"`\n *\n * @param key - The dotted key path\n * @returns A camelCase handler ID\n */\nexport function generateHandlerId(key: string): string {\n return key.replace(/\\.(\\w)/g, (_, char: string) => char.toUpperCase());\n}\n","/**\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","/**\n * @fileoverview Error-to-EventResult mapping for event handlers.\n *\n * Maps caught errors to event processing outcomes (ack/retry/dlq).\n * Uses the same name-based type checking as the HTTP error mapper\n * for compatibility with bundled/minified code.\n *\n * @module events/shared/error-mapping\n */\n\nimport { isErrorType } from '../../http/shared/error-mapping';\nimport type { EventResult } from './types';\n\n// ============================================================================\n// Error Type Classifications\n// ============================================================================\n\n/**\n * Error types that indicate permanent failures (send to DLQ).\n * These errors will not resolve on retry.\n */\nconst DLQ_ERROR_TYPES = [\n 'ObjectValidationError',\n 'InvalidRequestError',\n 'UseCaseError',\n 'DomainError',\n 'UnprocessableError',\n 'AccessDeniedError',\n 'ForbiddenError',\n 'UnauthorizedError',\n 'InvariantViolationError',\n];\n\n/**\n * Error types that indicate transient failures (retry).\n * These errors may resolve on subsequent attempts.\n */\nconst RETRY_ERROR_TYPES = [\n 'NotFoundError',\n 'ConflictError',\n 'InfraError',\n 'DbError',\n 'NetworkError',\n 'TimeoutError',\n 'ExternalServiceError',\n 'PersistenceError',\n];\n\n// ============================================================================\n// Mapping Function\n// ============================================================================\n\n/**\n * Maps a caught error to an EventResult.\n *\n * Default mapping strategy:\n *\n * | Error Type | Outcome | Rationale |\n * |------------------------------------------------|---------|----------------------------------------|\n * | ObjectValidationError, InvalidRequestError | dlq | Bad payload — retrying won't help |\n * | UseCaseError | dlq | Business rule rejection — permanent |\n * | DomainError, InvariantViolationError | dlq | Domain invariant — permanent |\n * | UnprocessableError | dlq | Valid but not processable — permanent |\n * | AccessDeniedError, ForbiddenError, Unauthorized | dlq | Permission — permanent |\n * | NotFoundError | retry | Entity might not exist yet |\n * | ConflictError | retry | Concurrent write — may resolve |\n * | InfraError, DbError, NetworkError, TimeoutError | retry | Infrastructure/transient |\n * | Unknown | retry | Conservative — don't lose messages |\n *\n * @param error - The caught error\n * @returns An EventResult indicating how the message should be handled\n */\nexport function mapErrorToEventResult(error: unknown): EventResult {\n // Check DLQ errors first (permanent failures)\n for (const typeName of DLQ_ERROR_TYPES) {\n if (isErrorType(error, typeName)) {\n return {\n outcome: 'dlq',\n reason: (error as { message: string }).message,\n };\n }\n }\n\n // Check retry errors (transient failures)\n for (const typeName of RETRY_ERROR_TYPES) {\n if (isErrorType(error, typeName)) {\n return {\n outcome: 'retry',\n reason: (error as { message: string }).message,\n };\n }\n }\n\n // Unknown errors — retry conservatively to avoid losing messages\n const message =\n error instanceof Error ? error.message : 'Unknown error occurred during event processing';\n\n return {\n outcome: 'retry',\n reason: message,\n };\n}\n","/**\n * @fileoverview Server types for the event handler system.\n *\n * @module events/server/types\n */\n\nimport type { EventHandlerDefinition, EventRouterConfig, EventRouterKeys } from '../handler/types';\nimport type { EventResult } from '../shared/types';\n\n// Re-export UseCasePort from HTTP — same interface, no duplication\nexport type { UseCasePort } from '../../http/server/types';\n\n// ============================================================================\n// Raw Event (from messaging system)\n// ============================================================================\n\n/**\n * Event metadata provided by the messaging system.\n */\nexport interface EventMetadata {\n /** Unique event identifier for idempotency checks. */\n readonly eventId: string;\n\n /** ISO 8601 timestamp of when the event occurred. */\n readonly timestamp: string;\n\n /** Correlation ID for distributed tracing. */\n readonly correlationId?: string;\n\n /** Source system or bounded context that emitted the event. */\n readonly source?: string;\n\n /** Number of delivery attempts (1-based). */\n readonly attemptCount?: number;\n\n /** Additional metadata from the messaging system. */\n readonly [key: string]: unknown;\n}\n\n/**\n * Raw event from the messaging system.\n * This is the input to event handlers before validation.\n */\nexport interface RawEvent {\n /** Event type string for routing. */\n readonly type: string;\n\n /** Event payload (unvalidated). */\n readonly payload: unknown;\n\n /** Event metadata from the messaging system. */\n readonly metadata: EventMetadata;\n}\n\n// ============================================================================\n// Validated Event\n// ============================================================================\n\n/**\n * A validated event with typed payload.\n * This is what handlers receive after validation passes.\n */\nexport interface ValidatedEvent<THandler extends EventHandlerDefinition> {\n /** Validated event payload. */\n readonly payload: THandler['_types']['payload'];\n\n /** Raw event object for advanced use cases. */\n readonly raw: RawEvent;\n}\n\n/**\n * Typed event context based on handler definition.\n * If the handler defines a context schema, this will be the validated type.\n * Otherwise, it falls back to the generic EventMetadata.\n */\nexport type TypedEventContext<THandler extends EventHandlerDefinition> =\n THandler['_types']['context'] extends undefined ? EventMetadata : THandler['_types']['context'];\n\n// ============================================================================\n// Handler Types\n// ============================================================================\n\n/**\n * Handler configuration using the use case pattern.\n *\n * @typeParam THandler - The event handler definition type\n * @typeParam TInput - Use case input type\n * @typeParam TOutput - Use case output type\n */\nexport interface EventHandlerConfig<\n THandler extends EventHandlerDefinition,\n TInput = void,\n TOutput = void,\n> {\n /**\n * Maps the validated event payload to use case input.\n * Both `event` and `ctx` are fully typed based on handler schemas.\n */\n readonly payloadMapper: (\n event: ValidatedEvent<THandler>,\n ctx: TypedEventContext<THandler>,\n ) => TInput;\n\n /** The use case to execute. */\n readonly useCase: { execute(input?: TInput): Promise<TOutput> };\n\n /**\n * Maps the use case output to an EventResult.\n * If omitted, defaults to `{ outcome: 'ack' }`.\n */\n readonly resultMapper?: (output: TOutput) => EventResult;\n\n /** Middleware to run before the handler. */\n readonly middleware?: readonly EventMiddlewareFunction[];\n}\n\n/**\n * Simple handler function that directly returns an EventResult.\n */\nexport type SimpleEventHandlerFn<THandler extends EventHandlerDefinition> = (\n event: ValidatedEvent<THandler>,\n ctx: TypedEventContext<THandler>,\n) => Promise<EventResult> | EventResult;\n\n/**\n * Configuration for a simple handler (no use case).\n */\nexport interface SimpleEventHandlerConfig<THandler extends EventHandlerDefinition> {\n readonly handler: SimpleEventHandlerFn<THandler>;\n readonly middleware?: readonly EventMiddlewareFunction[];\n}\n\n/**\n * Union of all event handler config types.\n * Used internally to store handlers in the builder.\n */\nexport type AnyEventHandlerConfig<\n THandler extends EventHandlerDefinition,\n TInput = unknown,\n TOutput = unknown,\n> = EventHandlerConfig<THandler, TInput, TOutput> | SimpleEventHandlerConfig<THandler>;\n\n/**\n * Type guard to check if config is a simple event handler.\n */\nexport function isSimpleEventHandlerConfig(\n config: AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>,\n): config is SimpleEventHandlerConfig<EventHandlerDefinition> {\n return 'handler' in config && typeof config.handler === 'function';\n}\n\n/**\n * Event middleware function type.\n */\nexport type EventMiddlewareFunction = (\n event: RawEvent,\n next: () => Promise<EventResult>,\n) => Promise<EventResult>;\n\n// ============================================================================\n// Server Configuration\n// ============================================================================\n\n/**\n * Configuration mapping handler keys to handler configs.\n */\n// TInput/TOutput are user-defined per handler - any is required for heterogeneous configs\nexport type EventRoutesConfig<T extends EventRouterConfig> = Record<\n EventRouterKeys<T>,\n EventHandlerConfig<any, any, any>\n>;\n\n/**\n * Options for creating event routes.\n */\nexport interface CreateEventRoutesOptions {\n /** Global middleware to run before all handlers. */\n readonly middleware?: readonly EventMiddlewareFunction[];\n\n /**\n * Whether to validate incoming event payloads against handler schemas.\n * When enabled, invalid payloads result in a `dlq` outcome.\n * @default true\n */\n readonly validatePayload?: boolean;\n\n /**\n * Custom error mapper to override default error-to-EventResult mapping.\n * If not provided, uses the built-in `mapErrorToEventResult`.\n */\n readonly errorMapper?: (error: unknown) => EventResult;\n\n /**\n * Allow partial handler configuration (not all handlers need to be wired).\n * @default false\n * @internal Used by builder pattern's buildPartial()\n */\n readonly allowPartial?: boolean;\n}\n\n// ============================================================================\n// Unified Event Input (for messaging adapters)\n// ============================================================================\n\n/**\n * Event input compatible with messaging adapters.\n * This is the output of eventRoutes().build().\n */\nexport interface UnifiedEventInput {\n /** Event type string for routing. */\n readonly eventType: string;\n\n /** Handler function. */\n readonly handler: (rawEvent: RawEvent) => Promise<EventResult>;\n\n /** Handler metadata for documentation. */\n readonly metadata: {\n readonly handlerId?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n };\n}\n","/**\n * @fileoverview Internal implementation for creating event routes with auto-validation.\n *\n * Generates event handlers from an event router definition.\n * Each handler automatically validates incoming event payloads and context\n * against the handler's schemas.\n *\n * @module events/server/create-event-routes\n * @internal\n */\n\nimport type { SchemaAdapter, ValidationIssue } from '../../http/schema/types';\nimport type {\n EventRouterConfig,\n EventRouterDefinition,\n EventHandlerDefinition,\n} from '../handler/types';\nimport { isEventRouterDefinition, collectEventHandlers } from '../handler/types';\nimport { generateHandlerId } from '../handler/utils';\nimport { mapErrorToEventResult } from '../shared/error-mapping';\nimport type { EventResult } from '../shared/types';\nimport type {\n AnyEventHandlerConfig,\n CreateEventRoutesOptions,\n EventMetadata,\n RawEvent,\n UnifiedEventInput,\n ValidatedEvent,\n} from './types';\nimport { isSimpleEventHandlerConfig } from './types';\n\n/**\n * Internal implementation for creating event routes.\n * Used by the builder pattern (eventRoutes).\n *\n * @internal\n */\nexport function createEventRoutesInternal<T extends EventRouterConfig>(\n router: T | EventRouterDefinition<T>,\n handlers: Record<string, AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>>,\n options?: CreateEventRoutesOptions,\n): UnifiedEventInput[] {\n const config = isEventRouterDefinition(router) ? router.handlers : router;\n const collectedHandlers = collectEventHandlers(config);\n\n const result: UnifiedEventInput[] = [];\n\n const resolvedOptions: CreateEventRoutesOptions = {\n ...options,\n validatePayload: options?.validatePayload ?? true,\n allowPartial: options?.allowPartial ?? false,\n };\n\n for (const { key, handler: handlerDef } of collectedHandlers) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const handlerConfig = handlers[key] as\n | AnyEventHandlerConfig<EventHandlerDefinition, any, any>\n | undefined;\n\n if (!handlerConfig) {\n if (resolvedOptions.allowPartial) {\n continue;\n }\n throw new Error(\n `Missing handler for event \"${key}\". All event handlers must have a handler configuration.`,\n );\n }\n\n result.push(createEventHandler(key, handlerDef, handlerConfig, resolvedOptions));\n }\n\n return result;\n}\n\n/**\n * Creates a single event handler with validation and error mapping.\n */\nfunction createEventHandler(\n key: string,\n handlerDef: EventHandlerDefinition,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: AnyEventHandlerConfig<EventHandlerDefinition, any, any>,\n options: CreateEventRoutesOptions,\n): UnifiedEventInput {\n const middleware = config.middleware ?? [];\n const globalMiddleware = options?.middleware ?? [];\n const allMiddleware = [...globalMiddleware, ...middleware];\n const shouldValidatePayload = options.validatePayload ?? true;\n const errorMapper = options.errorMapper ?? mapErrorToEventResult;\n\n return {\n eventType: handlerDef.eventType,\n metadata: {\n handlerId: generateHandlerId(key),\n summary: handlerDef.docs.summary,\n description: handlerDef.docs.description,\n tags: handlerDef.docs.tags as string[],\n deprecated: handlerDef.docs.deprecated,\n },\n handler: async (rawEvent: RawEvent): Promise<EventResult> => {\n try {\n // Validate context (if schema defined)\n let validatedContext: unknown = rawEvent.metadata;\n if (handlerDef.context) {\n const contextResult = validateContextData(handlerDef, rawEvent.metadata);\n if (!contextResult.success) {\n const errors = contextResult.errors ?? [];\n return {\n outcome: 'dlq',\n reason: `Context validation failed: ${errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')}`,\n };\n }\n validatedContext = contextResult.data;\n }\n\n // Validate payload (if enabled and schema defined)\n let validatedPayload: unknown = rawEvent.payload;\n if (shouldValidatePayload && handlerDef.payload) {\n const payloadResult = validatePayloadData(handlerDef, rawEvent.payload);\n if (!payloadResult.success) {\n const errors = payloadResult.errors ?? [];\n return {\n outcome: 'dlq',\n reason: `Payload validation failed: ${errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')}`,\n };\n }\n validatedPayload = payloadResult.data;\n }\n\n const validatedEvent: ValidatedEventInternal = {\n payload: validatedPayload,\n raw: rawEvent,\n };\n\n // Execute the pipeline\n const executePipeline = async (): Promise<EventResult> => {\n if (isSimpleEventHandlerConfig(config)) {\n return config.handler(\n validatedEvent as unknown as ValidatedEvent<EventHandlerDefinition>,\n validatedContext as EventMetadata,\n );\n } else {\n const { payloadMapper, useCase, resultMapper } = config;\n\n const input = payloadMapper(\n validatedEvent as unknown as ValidatedEvent<EventHandlerDefinition>,\n validatedContext as EventMetadata,\n );\n\n const output = await useCase.execute(input);\n\n return resultMapper ? resultMapper(output) : { outcome: 'ack' };\n }\n };\n\n if (allMiddleware.length === 0) {\n return await executePipeline();\n }\n\n // Build middleware chain\n let index = 0;\n const next = async (): Promise<EventResult> => {\n if (index >= allMiddleware.length) {\n return executePipeline();\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- index bounds checked above\n const mw = allMiddleware[index++]!;\n return mw(rawEvent, next);\n };\n\n return await next();\n } catch (error) {\n return errorMapper(error);\n }\n },\n };\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\ninterface ValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: unknown;\n}\n\n/**\n * Validates event payload against the handler's payload schema.\n */\nfunction validatePayloadData(\n handler: EventHandlerDefinition,\n payload: unknown,\n): ValidationResultInternal {\n const schema = handler.payload as SchemaAdapter | undefined;\n if (!schema) return { success: true, data: payload };\n\n const result = schema.validate(payload);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['payload', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates event metadata against the handler's context schema.\n */\nfunction validateContextData(\n handler: EventHandlerDefinition,\n metadata: EventMetadata,\n): ValidationResultInternal {\n const schema = handler.context as SchemaAdapter | undefined;\n if (!schema) return { success: true, data: metadata };\n\n const result = schema.validate(metadata);\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['context', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Internal validated event type with unknown fields.\n * Used inside createEventHandler where specific types are erased.\n */\ninterface ValidatedEventInternal {\n readonly payload: unknown;\n readonly raw: RawEvent;\n}\n","/**\n * @fileoverview Builder pattern for creating type-safe event routes.\n *\n * The `eventRoutes` function returns a builder that provides 100% type inference\n * for all handler parameters — no manual type annotations required.\n *\n * @module events/server/event-routes-builder\n */\n\nimport type {\n EventRouterConfig,\n EventRouterDefinition,\n GetEventHandler,\n EventRouterKeys,\n EventHandlerDefinition,\n} from '../handler/types';\nimport type { EventResult } from '../shared/types';\nimport type {\n AnyEventHandlerConfig,\n CreateEventRoutesOptions,\n EventHandlerConfig,\n EventMiddlewareFunction,\n SimpleEventHandlerConfig,\n SimpleEventHandlerFn,\n TypedEventContext,\n UnifiedEventInput,\n ValidatedEvent,\n} from './types';\nimport { createEventRoutesInternal } from './create-event-routes';\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Error type displayed when attempting to build() with missing handlers.\n * The `___missingHandlers` property shows which handlers are missing.\n */\nexport interface MissingHandlersError<TMissing extends string> {\n /**\n * This error indicates that not all event handlers have been wired.\n * Use buildPartial() to build with only the defined handlers,\n * or add handlers for the missing events.\n */\n (options?: never): never;\n /** Event handlers that are missing. */\n readonly ___missingHandlers: TMissing;\n}\n\n/**\n * Handler configuration for the builder pattern.\n */\nexport interface BuilderEventHandlerConfig<\n THandler extends EventHandlerDefinition,\n TInput,\n TOutput,\n> {\n /**\n * Maps the validated event payload to use case input.\n * Both `event` and `ctx` are fully typed based on handler schemas.\n */\n readonly payloadMapper: (\n event: ValidatedEvent<THandler>,\n ctx: TypedEventContext<THandler>,\n ) => TInput;\n\n /** The use case to execute. */\n readonly useCase: { execute(input?: TInput): Promise<TOutput> };\n\n /**\n * Maps the use case output to an EventResult.\n * If omitted, defaults to `{ outcome: 'ack' }`.\n */\n readonly resultMapper?: (output: TOutput) => EventResult;\n\n /** Middleware to run before the handler. */\n readonly middleware?: readonly EventMiddlewareFunction[];\n}\n\n/**\n * Builder interface for creating type-safe event routes.\n *\n * Each `.handle()` call captures the specific handler type and provides\n * full type inference for payloadMapper and useCase.\n *\n * @typeParam T - The event router configuration type\n * @typeParam THandled - Union of handler keys that have been wired (accumulates)\n *\n * @example\n * ```typescript\n * const routes = eventRoutes(ticketEvents)\n * .handleWithUseCase('created', {\n * payloadMapper: (event, ctx) => ({\n * ticketId: event.payload.ticketId, // Fully typed!\n * correlationId: ctx.correlationId, // Fully typed!\n * }),\n * useCase: sendNotificationUseCase,\n * })\n * .handle('assigned', async (event) => {\n * await notifyAssignee(event.payload);\n * return { outcome: 'ack' as const };\n * })\n * .build();\n * ```\n */\nexport interface EventRoutesBuilder<T extends EventRouterConfig, THandled extends string = never> {\n /**\n * Register a simple handler for an event.\n * The handler receives validated event and context, returns EventResult directly.\n */\n handle<K extends Exclude<EventRouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig:\n | SimpleEventHandlerFn<GetEventHandler<T, K>>\n | SimpleEventHandlerConfig<GetEventHandler<T, K>>,\n ): EventRoutesBuilder<T, THandled | K>;\n\n /**\n * Register a handler using the use case pattern.\n * Follows: payloadMapper → useCase.execute() → resultMapper (or ack)\n */\n handleWithUseCase<K extends Exclude<EventRouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderEventHandlerConfig<GetEventHandler<T, K>, TInput, TOutput>,\n ): EventRoutesBuilder<T, THandled | K>;\n\n /**\n * Build the event routes array for messaging adapter registration.\n *\n * This method is only available when ALL handlers have been wired.\n * If some handlers are missing, use `buildPartial()` instead.\n */\n build: [Exclude<EventRouterKeys<T>, THandled>] extends [never]\n ? (options?: CreateEventRoutesOptions) => UnifiedEventInput[]\n : MissingHandlersError<Exclude<EventRouterKeys<T>, THandled>>;\n\n /**\n * Build event routes for only the defined handlers.\n * No compile-time enforcement of completeness.\n */\n buildPartial(options?: CreateEventRoutesOptions): UnifiedEventInput[];\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Internal builder implementation.\n *\n * Uses an immutable pattern where each handle() call returns a new\n * builder instance with the updated handlers map.\n */\nclass EventRoutesBuilderImpl<T extends EventRouterConfig, THandled extends string = never> {\n private readonly router: T | EventRouterDefinition<T>;\n private readonly handlers: Map<\n string,\n AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>\n >;\n\n constructor(\n router: T | EventRouterDefinition<T>,\n handlers?: Map<string, AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>>,\n ) {\n this.router = router;\n this.handlers = handlers ?? new Map();\n }\n\n handle<K extends Exclude<EventRouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig:\n | SimpleEventHandlerFn<GetEventHandler<T, K>>\n | SimpleEventHandlerConfig<GetEventHandler<T, K>>,\n ): EventRoutesBuilder<T, THandled | K> {\n const config: SimpleEventHandlerConfig<EventHandlerDefinition> =\n typeof handlerOrConfig === 'function'\n ? { handler: handlerOrConfig as SimpleEventHandlerFn<EventHandlerDefinition> }\n : (handlerOrConfig as SimpleEventHandlerConfig<EventHandlerDefinition>);\n\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config);\n\n return new EventRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as EventRoutesBuilder<T, THandled | K>;\n }\n\n handleWithUseCase<K extends Exclude<EventRouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderEventHandlerConfig<GetEventHandler<T, K>, TInput, TOutput>,\n ): EventRoutesBuilder<T, THandled | K> {\n const newHandlers = new Map(this.handlers);\n newHandlers.set(\n key as string,\n config as EventHandlerConfig<EventHandlerDefinition, unknown, unknown>,\n );\n\n return new EventRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as EventRoutesBuilder<T, THandled | K>;\n }\n\n build(options?: CreateEventRoutesOptions): UnifiedEventInput[] {\n return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), options);\n }\n\n buildPartial(options?: CreateEventRoutesOptions): UnifiedEventInput[] {\n return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), {\n ...options,\n allowPartial: true,\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Creates a type-safe event routes builder for an event router.\n *\n * The builder pattern provides 100% type inference for all handler parameters:\n * - `event.payload` is typed from the handler's payload schema\n * - `ctx` is typed from the handler's context schema (or EventMetadata)\n * - `output` in resultMapper is typed from the use case\n *\n * @param router - Event router definition or event router config\n * @returns Builder for registering handlers\n *\n * @example Basic usage\n * ```typescript\n * import { eventRoutes } from '@cosmneo/onion-lasagna/events/server';\n * import { ticketEvents } from './router';\n *\n * const routes = eventRoutes(ticketEvents)\n * .handleWithUseCase('created', {\n * payloadMapper: (event, ctx) => ({\n * ticketId: event.payload.ticketId,\n * correlationId: ctx.correlationId,\n * }),\n * useCase: sendNotificationUseCase,\n * })\n * .handle('assigned', async (event) => {\n * await notifyAssignee(event.payload);\n * return { outcome: 'ack' as const };\n * })\n * .build();\n * ```\n */\nexport function eventRoutes<T extends EventRouterConfig>(\n router: T | EventRouterDefinition<T>,\n): EventRoutesBuilder<T, never> {\n return new EventRoutesBuilderImpl(router) as unknown as EventRoutesBuilder<T, never>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiEO,SAAS,yBAAyB,OAAiD;AACxF,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,eAAe,SAAS,YAAY;AAC5F;AAKO,SAAS,wBAAwB,OAAgD;AACtF,SACE,OAAO,UAAU,YACjB,UAAU,QACV,oBAAoB,SACnB,MAAgC,mBAAmB;AAExD;AA2GO,SAAS,qBACd,QACA,WAAW,IACyC;AACpD,QAAM,WAA+D,CAAC;AAEtE,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAM,UAAU,WAAW,GAAG,QAAQ,IAAI,GAAG,KAAK;AAElD,QAAI,yBAAyB,KAAK,GAAG;AACnC,eAAS,KAAK,EAAE,KAAK,SAAS,SAAS,MAAM,CAAC;AAAA,IAChD,WAAW,wBAAwB,KAAK,GAAG;AACzC,eAAS,KAAK,GAAG,qBAAqB,MAAM,UAAU,OAAO,CAAC;AAAA,IAChE,WAAW,OAAO,UAAU,YAAY,UAAU,MAAM;AACtD,eAAS,KAAK,GAAG,qBAAqB,OAA4B,OAAO,CAAC;AAAA,IAC5E;AAAA,EACF;AAEA,SAAO;AACT;;;AC7LO,SAAS,kBAAkB,KAAqB;AACrD,SAAO,IAAI,QAAQ,WAAW,CAAC,GAAG,SAAiB,KAAK,YAAY,CAAC;AACvE;;;AC6EO,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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AY,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC1F;AAAA,EAEA,aAAa,SAAyD;AACpE,WAAO,0BAA0B,KAAK,QAAQ,OAAO,YAAY,KAAK,QAAQ,GAAG;AAAA,MAC/E,GAAG;AAAA,MACH,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAqCO,SAAS,YACd,QAC8B;AAC9B,SAAO,IAAI,uBAAuB,MAAM;AAC1C;","names":[]}
@@ -0,0 +1,281 @@
1
+ import { E as EventHandlerDefinition, c as EventRouterConfig, f as EventRouterKeys, e as EventRouterDefinition, G as GetEventHandler } from '../../event-router-definition.type-CP9uTlux.cjs';
2
+ import { E as EventResult } from '../../types-cke61juH.cjs';
3
+ export { U as UseCasePort } from '../../types-afYpL7Ap.cjs';
4
+ import '../../http/schema/types.cjs';
5
+ import '../../router-definition.type-BElX-Pl4.cjs';
6
+
7
+ /**
8
+ * @fileoverview Server types for the event handler system.
9
+ *
10
+ * @module events/server/types
11
+ */
12
+
13
+ /**
14
+ * Event metadata provided by the messaging system.
15
+ */
16
+ interface EventMetadata {
17
+ /** Unique event identifier for idempotency checks. */
18
+ readonly eventId: string;
19
+ /** ISO 8601 timestamp of when the event occurred. */
20
+ readonly timestamp: string;
21
+ /** Correlation ID for distributed tracing. */
22
+ readonly correlationId?: string;
23
+ /** Source system or bounded context that emitted the event. */
24
+ readonly source?: string;
25
+ /** Number of delivery attempts (1-based). */
26
+ readonly attemptCount?: number;
27
+ /** Additional metadata from the messaging system. */
28
+ readonly [key: string]: unknown;
29
+ }
30
+ /**
31
+ * Raw event from the messaging system.
32
+ * This is the input to event handlers before validation.
33
+ */
34
+ interface RawEvent {
35
+ /** Event type string for routing. */
36
+ readonly type: string;
37
+ /** Event payload (unvalidated). */
38
+ readonly payload: unknown;
39
+ /** Event metadata from the messaging system. */
40
+ readonly metadata: EventMetadata;
41
+ }
42
+ /**
43
+ * A validated event with typed payload.
44
+ * This is what handlers receive after validation passes.
45
+ */
46
+ interface ValidatedEvent<THandler extends EventHandlerDefinition> {
47
+ /** Validated event payload. */
48
+ readonly payload: THandler['_types']['payload'];
49
+ /** Raw event object for advanced use cases. */
50
+ readonly raw: RawEvent;
51
+ }
52
+ /**
53
+ * Typed event context based on handler definition.
54
+ * If the handler defines a context schema, this will be the validated type.
55
+ * Otherwise, it falls back to the generic EventMetadata.
56
+ */
57
+ type TypedEventContext<THandler extends EventHandlerDefinition> = THandler['_types']['context'] extends undefined ? EventMetadata : THandler['_types']['context'];
58
+ /**
59
+ * Handler configuration using the use case pattern.
60
+ *
61
+ * @typeParam THandler - The event handler definition type
62
+ * @typeParam TInput - Use case input type
63
+ * @typeParam TOutput - Use case output type
64
+ */
65
+ interface EventHandlerConfig<THandler extends EventHandlerDefinition, TInput = void, TOutput = void> {
66
+ /**
67
+ * Maps the validated event payload to use case input.
68
+ * Both `event` and `ctx` are fully typed based on handler schemas.
69
+ */
70
+ readonly payloadMapper: (event: ValidatedEvent<THandler>, ctx: TypedEventContext<THandler>) => TInput;
71
+ /** The use case to execute. */
72
+ readonly useCase: {
73
+ execute(input?: TInput): Promise<TOutput>;
74
+ };
75
+ /**
76
+ * Maps the use case output to an EventResult.
77
+ * If omitted, defaults to `{ outcome: 'ack' }`.
78
+ */
79
+ readonly resultMapper?: (output: TOutput) => EventResult;
80
+ /** Middleware to run before the handler. */
81
+ readonly middleware?: readonly EventMiddlewareFunction[];
82
+ }
83
+ /**
84
+ * Simple handler function that directly returns an EventResult.
85
+ */
86
+ type SimpleEventHandlerFn<THandler extends EventHandlerDefinition> = (event: ValidatedEvent<THandler>, ctx: TypedEventContext<THandler>) => Promise<EventResult> | EventResult;
87
+ /**
88
+ * Configuration for a simple handler (no use case).
89
+ */
90
+ interface SimpleEventHandlerConfig<THandler extends EventHandlerDefinition> {
91
+ readonly handler: SimpleEventHandlerFn<THandler>;
92
+ readonly middleware?: readonly EventMiddlewareFunction[];
93
+ }
94
+ /**
95
+ * Union of all event handler config types.
96
+ * Used internally to store handlers in the builder.
97
+ */
98
+ type AnyEventHandlerConfig<THandler extends EventHandlerDefinition, TInput = unknown, TOutput = unknown> = EventHandlerConfig<THandler, TInput, TOutput> | SimpleEventHandlerConfig<THandler>;
99
+ /**
100
+ * Type guard to check if config is a simple event handler.
101
+ */
102
+ declare function isSimpleEventHandlerConfig(config: AnyEventHandlerConfig<EventHandlerDefinition, unknown, unknown>): config is SimpleEventHandlerConfig<EventHandlerDefinition>;
103
+ /**
104
+ * Event middleware function type.
105
+ */
106
+ type EventMiddlewareFunction = (event: RawEvent, next: () => Promise<EventResult>) => Promise<EventResult>;
107
+ /**
108
+ * Configuration mapping handler keys to handler configs.
109
+ */
110
+ type EventRoutesConfig<T extends EventRouterConfig> = Record<EventRouterKeys<T>, EventHandlerConfig<any, any, any>>;
111
+ /**
112
+ * Options for creating event routes.
113
+ */
114
+ interface CreateEventRoutesOptions {
115
+ /** Global middleware to run before all handlers. */
116
+ readonly middleware?: readonly EventMiddlewareFunction[];
117
+ /**
118
+ * Whether to validate incoming event payloads against handler schemas.
119
+ * When enabled, invalid payloads result in a `dlq` outcome.
120
+ * @default true
121
+ */
122
+ readonly validatePayload?: boolean;
123
+ /**
124
+ * Custom error mapper to override default error-to-EventResult mapping.
125
+ * If not provided, uses the built-in `mapErrorToEventResult`.
126
+ */
127
+ readonly errorMapper?: (error: unknown) => EventResult;
128
+ /**
129
+ * Allow partial handler configuration (not all handlers need to be wired).
130
+ * @default false
131
+ * @internal Used by builder pattern's buildPartial()
132
+ */
133
+ readonly allowPartial?: boolean;
134
+ }
135
+ /**
136
+ * Event input compatible with messaging adapters.
137
+ * This is the output of eventRoutes().build().
138
+ */
139
+ interface UnifiedEventInput {
140
+ /** Event type string for routing. */
141
+ readonly eventType: string;
142
+ /** Handler function. */
143
+ readonly handler: (rawEvent: RawEvent) => Promise<EventResult>;
144
+ /** Handler metadata for documentation. */
145
+ readonly metadata: {
146
+ readonly handlerId?: string;
147
+ readonly summary?: string;
148
+ readonly description?: string;
149
+ readonly tags?: readonly string[];
150
+ readonly deprecated?: boolean;
151
+ };
152
+ }
153
+
154
+ /**
155
+ * @fileoverview Builder pattern for creating type-safe event routes.
156
+ *
157
+ * The `eventRoutes` function returns a builder that provides 100% type inference
158
+ * for all handler parameters — no manual type annotations required.
159
+ *
160
+ * @module events/server/event-routes-builder
161
+ */
162
+
163
+ /**
164
+ * Error type displayed when attempting to build() with missing handlers.
165
+ * The `___missingHandlers` property shows which handlers are missing.
166
+ */
167
+ interface MissingHandlersError<TMissing extends string> {
168
+ /**
169
+ * This error indicates that not all event handlers have been wired.
170
+ * Use buildPartial() to build with only the defined handlers,
171
+ * or add handlers for the missing events.
172
+ */
173
+ (options?: never): never;
174
+ /** Event handlers that are missing. */
175
+ readonly ___missingHandlers: TMissing;
176
+ }
177
+ /**
178
+ * Handler configuration for the builder pattern.
179
+ */
180
+ interface BuilderEventHandlerConfig<THandler extends EventHandlerDefinition, TInput, TOutput> {
181
+ /**
182
+ * Maps the validated event payload to use case input.
183
+ * Both `event` and `ctx` are fully typed based on handler schemas.
184
+ */
185
+ readonly payloadMapper: (event: ValidatedEvent<THandler>, ctx: TypedEventContext<THandler>) => TInput;
186
+ /** The use case to execute. */
187
+ readonly useCase: {
188
+ execute(input?: TInput): Promise<TOutput>;
189
+ };
190
+ /**
191
+ * Maps the use case output to an EventResult.
192
+ * If omitted, defaults to `{ outcome: 'ack' }`.
193
+ */
194
+ readonly resultMapper?: (output: TOutput) => EventResult;
195
+ /** Middleware to run before the handler. */
196
+ readonly middleware?: readonly EventMiddlewareFunction[];
197
+ }
198
+ /**
199
+ * Builder interface for creating type-safe event routes.
200
+ *
201
+ * Each `.handle()` call captures the specific handler type and provides
202
+ * full type inference for payloadMapper and useCase.
203
+ *
204
+ * @typeParam T - The event router configuration type
205
+ * @typeParam THandled - Union of handler keys that have been wired (accumulates)
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * const routes = eventRoutes(ticketEvents)
210
+ * .handleWithUseCase('created', {
211
+ * payloadMapper: (event, ctx) => ({
212
+ * ticketId: event.payload.ticketId, // Fully typed!
213
+ * correlationId: ctx.correlationId, // Fully typed!
214
+ * }),
215
+ * useCase: sendNotificationUseCase,
216
+ * })
217
+ * .handle('assigned', async (event) => {
218
+ * await notifyAssignee(event.payload);
219
+ * return { outcome: 'ack' as const };
220
+ * })
221
+ * .build();
222
+ * ```
223
+ */
224
+ interface EventRoutesBuilder<T extends EventRouterConfig, THandled extends string = never> {
225
+ /**
226
+ * Register a simple handler for an event.
227
+ * The handler receives validated event and context, returns EventResult directly.
228
+ */
229
+ handle<K extends Exclude<EventRouterKeys<T>, THandled>>(key: K, handlerOrConfig: SimpleEventHandlerFn<GetEventHandler<T, K>> | SimpleEventHandlerConfig<GetEventHandler<T, K>>): EventRoutesBuilder<T, THandled | K>;
230
+ /**
231
+ * Register a handler using the use case pattern.
232
+ * Follows: payloadMapper → useCase.execute() → resultMapper (or ack)
233
+ */
234
+ handleWithUseCase<K extends Exclude<EventRouterKeys<T>, THandled>, TInput, TOutput>(key: K, config: BuilderEventHandlerConfig<GetEventHandler<T, K>, TInput, TOutput>): EventRoutesBuilder<T, THandled | K>;
235
+ /**
236
+ * Build the event routes array for messaging adapter registration.
237
+ *
238
+ * This method is only available when ALL handlers have been wired.
239
+ * If some handlers are missing, use `buildPartial()` instead.
240
+ */
241
+ build: [Exclude<EventRouterKeys<T>, THandled>] extends [never] ? (options?: CreateEventRoutesOptions) => UnifiedEventInput[] : MissingHandlersError<Exclude<EventRouterKeys<T>, THandled>>;
242
+ /**
243
+ * Build event routes for only the defined handlers.
244
+ * No compile-time enforcement of completeness.
245
+ */
246
+ buildPartial(options?: CreateEventRoutesOptions): UnifiedEventInput[];
247
+ }
248
+ /**
249
+ * Creates a type-safe event routes builder for an event router.
250
+ *
251
+ * The builder pattern provides 100% type inference for all handler parameters:
252
+ * - `event.payload` is typed from the handler's payload schema
253
+ * - `ctx` is typed from the handler's context schema (or EventMetadata)
254
+ * - `output` in resultMapper is typed from the use case
255
+ *
256
+ * @param router - Event router definition or event router config
257
+ * @returns Builder for registering handlers
258
+ *
259
+ * @example Basic usage
260
+ * ```typescript
261
+ * import { eventRoutes } from '@cosmneo/onion-lasagna/events/server';
262
+ * import { ticketEvents } from './router';
263
+ *
264
+ * const routes = eventRoutes(ticketEvents)
265
+ * .handleWithUseCase('created', {
266
+ * payloadMapper: (event, ctx) => ({
267
+ * ticketId: event.payload.ticketId,
268
+ * correlationId: ctx.correlationId,
269
+ * }),
270
+ * useCase: sendNotificationUseCase,
271
+ * })
272
+ * .handle('assigned', async (event) => {
273
+ * await notifyAssignee(event.payload);
274
+ * return { outcome: 'ack' as const };
275
+ * })
276
+ * .build();
277
+ * ```
278
+ */
279
+ declare function eventRoutes<T extends EventRouterConfig>(router: T | EventRouterDefinition<T>): EventRoutesBuilder<T, never>;
280
+
281
+ export { type AnyEventHandlerConfig, type BuilderEventHandlerConfig, type CreateEventRoutesOptions, type EventHandlerConfig, type EventMetadata, type EventMiddlewareFunction, type EventRoutesBuilder, type EventRoutesConfig, type MissingHandlersError, type RawEvent, type SimpleEventHandlerConfig, type SimpleEventHandlerFn, type TypedEventContext, type UnifiedEventInput, type ValidatedEvent, eventRoutes, isSimpleEventHandlerConfig };