@exium/core 1.0.0-rc.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/application/application.module.ts","../src/application/cqrs/command/command-registry.ts","../src/application/exceptions/handler-not-found.exception.ts","../src/application/exceptions/duplicate-handler.exception.ts","../src/application/cqrs/command/command-executor.ts","../src/application/cqrs/query/query-registry.ts","../src/application/cqrs/query/query-executor.ts","../src/application/cqrs/event/event-registry.ts","../src/application/cqrs/event/event-bus.ts","../src/application/application-discovery.service.ts","../src/application/decorators/handle-command.decorator.ts","../src/application/decorators/handle-query.decorator.ts","../src/application/decorators/handle-event.decorator.ts","../src/application/decorators/middleware.decorator.ts","../src/application/eventing/integration-event-registry.ts","../src/application/decorators/integration-event-mapper.decorator.ts","../src/application/context/exium-context.service.ts","../src/application/middlewares/middleware-priority.ts","../src/application/middlewares/context-command.middleware.ts","../src/application/middlewares/context-query.middleware.ts","../src/application/middlewares/logging-command.middleware.ts","../src/application/middlewares/logging-query.middleware.ts","../src/application/middlewares/validation-command.middleware.ts","../src/foundation/result/result.ts","../src/foundation/result/failure.ts","../src/application/decorators/validation.decorator.ts","../src/application/middlewares/validation.utils.ts","../src/application/middlewares/validation-query.middleware.ts","../src/application/middlewares/authorization-command.middleware.ts","../src/application/decorators/authorization.decorator.ts","../src/application/authorization/permission-checker.ts","../src/application/middlewares/authorization-query.middleware.ts","../src/application/middlewares/cache-query.middleware.ts","../src/application/decorators/cache-query.decorator.ts","../src/application/cache/cache-store.ts","../src/application/cache/noop-cache-store.ts","../src/application/cache/cache-key-factory.ts","../src/application/cache/cache-version.service.ts","../src/application/middlewares/cache-invalidation-command.middleware.ts","../src/application/decorators/invalidate-cache.decorator.ts","../src/application/middlewares/idempotency-command.middleware.ts","../src/application/decorators/idempotent.decorator.ts","../src/application/idempotency/idempotency-store.ts","../src/application/idempotency/noop-idempotency-store.ts","../src/application/exceptions/idempotency.exception.ts","../src/application/idempotency/idempotency-key-resolver.ts","../src/application/idempotency/idempotency-fingerprint-factory.ts","../src/application/middlewares/audit-command.middleware.ts","../src/application/decorators/auditable.decorator.ts","../src/application/audit/audit-writer.ts","../src/application/audit/noop-audit-writer.ts","../src/application/middlewares/audit.utils.ts","../src/application/middlewares/audit-query.middleware.ts","../src/application/authorization/context-permission-checker.ts","../src/application/eventing/noop-outbox-writer.ts","../src/application/eventing/outbox-writer.ts","../src/application/unit-of-work.ts","../src/application/cqrs/command/command.ts","../src/application/cqrs/command/command-handler.ts","../src/application/cqrs/query/query.ts","../src/application/cqrs/query/query-result.ts","../src/application/cqrs/query/query-handler.ts","../src/application/cqrs/event/event-handler.ts","../src/application/decorators/transactional.decorator.ts","../src/application/exceptions/authorization.exception.ts","../src/application/eventing/integration-event.ts","../src/application/eventing/integration-event-mapper.ts","../src/application/read/read.exceptions.ts","../src/application/read/criteria/criteria.ts","../src/application/read/sort/sort.ts","../src/application/read/pagination/pagination.ts","../src/application/read/source/read-source.ts","../src/domain/entity.ts","../src/common/auditable-entity.ts","../src/domain/aggregate-root.ts","../src/common/auditable-aggregate-root.ts","../src/domain/value-object.ts","../src/common/primitive-value-object.ts","../src/config/exium-config.module.ts","../src/config/exium-config.schema.ts","../src/config/exium-config.service.ts","../src/runtime/exium-module.ts","../src/logger/exium-logger.module.ts","../src/http/responses/api.response.ts","../src/http/responses/success.response.ts","../src/http/responses/error.response.ts","../src/http/contracts/http-api-contract.ts","../src/http/decorators/external-api.decorator.ts","../src/http/decorators/internal-api.decorator.ts","../src/http/http-options.ts","../src/http/http.module.ts","../src/http/internal/internal-api-handler.ts","../src/http/internal/internal-api-registry.ts","../src/http/internal/internal-api-discovery.service.ts","../src/http/internal/internal-api-endpoint-resolver.ts","../src/http/internal/internal-api-client.ts","../src/http/interceptors/exium-http-context.interceptor.ts","../src/http/interceptors/exium-response.interceptor.ts","../src/http/filters/exium-exception.filter.ts","../src/infrastructure/infrastructure.module.ts","../src/infrastructure/cache/cache-infrastructure.module.ts","../src/infrastructure/cache/redis-cache-store.ts","../src/infrastructure/redis/redis.module.ts","../src/infrastructure/redis/redis-client.provider.ts","../src/infrastructure/redis/redis-options.ts","../src/infrastructure/cache/redis-cache-version.service.ts","../src/infrastructure/idempotency/idempotency-infrastructure.module.ts","../src/infrastructure/idempotency/redis-idempotency-store.ts","../src/infrastructure/messaging/integration-message-publisher.ts","../src/infrastructure/messaging/noop-integration-message-publisher.ts","../src/infrastructure/messaging/messaging.module.ts","../src/infrastructure/messaging/rabbitmq/rabbitmq-options.ts","../src/infrastructure/messaging/rabbitmq/rabbitmq-integration-message-publisher.ts","../src/infrastructure/persistence/exium-persistence.module.ts","../src/infrastructure/persistence/mikro-orm.unit-of-work.ts","../src/infrastructure/persistence/transaction/transaction.context.ts","../src/infrastructure/persistence/transaction/transaction-command.middleware.ts","../src/infrastructure/persistence/outbox/outbox-message.entity.ts","../src/infrastructure/persistence/outbox/outbox-message-status.ts","../src/infrastructure/persistence/outbox/mikro-orm-outbox-writer.ts","../src/infrastructure/persistence/exceptions/persistence-transaction-not-active.exception.ts","../src/infrastructure/persistence/outbox/outbox-publisher.ts","../src/infrastructure/persistence/outbox/outbox-publisher-options.ts","../src/infrastructure/persistence/mikro-orm/mikro-orm.repository.ts","../src/infrastructure/persistence/mikro-orm/mikro-orm.aggregate.repository.ts","../src/infrastructure/read/kysely/kysely-read-engine.ts","../src/runtime/create-exium-app.ts","../src/domain/id.ts","../src/domain/domain-event.ts","../src/domain/domain-service.ts","../src/domain/specification.ts","../src/domain/auditable.ts","../src/domain/versionable.ts"],"sourcesContent":["export {\n Auditable,\n NonAuditable,\n AUDITABLE_METADATA,\n type AuditableMetadata,\n type AuditableOptions,\n} from './application/index';\n\nexport * from './foundation/index';\nexport type { Auditable as DomainAuditable } from './domain/index';\nexport * from './common/index';\nexport * from './config/index';\nexport * from './runtime/index';\nexport * from './domain/index';\nexport * from './application/index';\nexport * from './http/index';\nexport * from './infrastructure/index';\nexport * from './logger/index';\n","import { DynamicModule, Global, Module, type Provider } from '@nestjs/common';\nimport { DiscoveryModule } from '@nestjs/core';\n\nimport { CommandRegistry } from './cqrs/command/command-registry';\nimport { CommandExecutor } from './cqrs/command/command-executor';\n\nimport { QueryRegistry } from './cqrs/query/query-registry';\nimport { QueryExecutor } from './cqrs/query/query-executor';\n\nimport { EventRegistry } from './cqrs/event/event-registry';\nimport { EventBus } from './cqrs/event/event-bus';\n\nimport { ExiumApplicationDiscoveryService } from './application-discovery.service';\nimport { ExiumContextService } from './context/exium-context.service';\n\nimport {\n AuditCommandMiddleware,\n AuditQueryMiddleware,\n AuthorizationCommandMiddleware,\n AuthorizationQueryMiddleware,\n CacheInvalidationCommandMiddleware,\n CacheQueryMiddleware,\n ContextCommandMiddleware,\n ContextQueryMiddleware,\n IdempotencyCommandMiddleware,\n LoggingCommandMiddleware,\n LoggingQueryMiddleware,\n ValidationCommandMiddleware,\n ValidationQueryMiddleware,\n} from './middlewares';\n\nimport { ContextPermissionChecker, PermissionChecker } from './authorization';\n\nimport { IntegrationEventRegistry } from './eventing/integration-event-registry';\nimport { NoopOutboxWriter } from './eventing/noop-outbox-writer';\nimport { OutboxWriter } from './eventing/outbox-writer';\n\nimport {\n CacheKeyFactory,\n CacheStore,\n CacheVersionService,\n DefaultCacheKeyFactory,\n InMemoryCacheVersionService,\n NoopCacheStore,\n} from './cache';\n\nimport {\n DefaultIdempotencyFingerprintFactory,\n DefaultIdempotencyKeyResolver,\n IdempotencyFingerprintFactory,\n IdempotencyKeyResolver,\n IdempotencyStore,\n NoopIdempotencyStore,\n} from './idempotency';\n\nimport { AuditWriter, NoopAuditWriter } from './audit';\n\nexport interface ExiumApplicationModuleOptions {\n readonly defaults?: {\n readonly cacheStore?: boolean;\n readonly cacheVersionService?: boolean;\n readonly idempotencyStore?: boolean;\n readonly auditWriter?: boolean;\n };\n}\n\n@Global()\n@Module({})\nexport class ExiumApplicationModule {\n static forRoot(options: ExiumApplicationModuleOptions = {}): DynamicModule {\n const defaultCacheStoreEnabled = options.defaults?.cacheStore ?? true;\n const defaultCacheVersionServiceEnabled = options.defaults?.cacheVersionService ?? true;\n const defaultIdempotencyStoreEnabled = options.defaults?.idempotencyStore ?? true;\n const defaultAuditWriterEnabled = options.defaults?.auditWriter ?? true;\n\n const providers: Provider[] = [\n ExiumApplicationDiscoveryService,\n\n ExiumContextService,\n\n CommandRegistry,\n CommandExecutor,\n\n QueryRegistry,\n QueryExecutor,\n\n EventRegistry,\n EventBus,\n\n ContextCommandMiddleware,\n ContextQueryMiddleware,\n\n LoggingCommandMiddleware,\n LoggingQueryMiddleware,\n\n ValidationCommandMiddleware,\n ValidationQueryMiddleware,\n\n AuthorizationCommandMiddleware,\n AuthorizationQueryMiddleware,\n\n CacheQueryMiddleware,\n CacheInvalidationCommandMiddleware,\n\n {\n provide: PermissionChecker,\n useClass: ContextPermissionChecker,\n },\n\n IntegrationEventRegistry,\n\n {\n provide: OutboxWriter,\n useClass: NoopOutboxWriter,\n },\n\n {\n provide: CacheKeyFactory,\n useClass: DefaultCacheKeyFactory,\n },\n\n IdempotencyCommandMiddleware,\n\n {\n provide: IdempotencyKeyResolver,\n useClass: DefaultIdempotencyKeyResolver,\n },\n {\n provide: IdempotencyFingerprintFactory,\n useClass: DefaultIdempotencyFingerprintFactory,\n },\n\n AuditCommandMiddleware,\n AuditQueryMiddleware,\n ];\n\n if (defaultAuditWriterEnabled) {\n providers.push({\n provide: AuditWriter,\n useClass: NoopAuditWriter,\n });\n }\n\n if (defaultCacheStoreEnabled) {\n providers.push({\n provide: CacheStore,\n useClass: NoopCacheStore,\n });\n }\n\n if (defaultCacheVersionServiceEnabled) {\n providers.push({\n provide: CacheVersionService,\n useClass: InMemoryCacheVersionService,\n });\n }\n\n if (defaultIdempotencyStoreEnabled) {\n providers.push({\n provide: IdempotencyStore,\n useClass: NoopIdempotencyStore,\n });\n }\n\n const moduleExports: NonNullable<DynamicModule['exports']> = [\n ExiumContextService,\n\n CommandExecutor,\n QueryExecutor,\n\n EventBus,\n\n PermissionChecker,\n\n IntegrationEventRegistry,\n OutboxWriter,\n\n CacheKeyFactory,\n\n IdempotencyKeyResolver,\n IdempotencyFingerprintFactory,\n ];\n\n if (defaultCacheStoreEnabled) {\n moduleExports.push(CacheStore);\n }\n\n if (defaultIdempotencyStoreEnabled) {\n moduleExports.push(IdempotencyStore);\n }\n\n if (defaultCacheVersionServiceEnabled) {\n moduleExports.push(CacheVersionService);\n }\n\n if (defaultAuditWriterEnabled) {\n moduleExports.push(AuditWriter);\n }\n\n return {\n module: ExiumApplicationModule,\n global: true,\n imports: [DiscoveryModule],\n providers,\n exports: moduleExports,\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { Command } from './command';\nimport type { CommandHandler } from './command-handler';\nimport type { CommandMiddleware } from './command-middleware';\nimport { HandlerNotFoundException } from '../../exceptions/handler-not-found.exception';\nimport { DuplicateHandlerException } from '../../exceptions/duplicate-handler.exception';\n\ntype CommandConstructor<TCommand extends Command<any>> = new (...args: any[]) => TCommand;\n\n@Injectable()\nexport class CommandRegistry {\n private readonly handlers = new Map<Function, CommandHandler<any>>();\n\n private readonly middlewares: Array<{\n instance: CommandMiddleware;\n priority: number;\n }> = [];\n\n register<TCommand extends Command<any>>(\n commandType: CommandConstructor<TCommand>,\n handler: CommandHandler<TCommand>,\n ): void {\n if (this.handlers.has(commandType)) {\n throw new DuplicateHandlerException('command', commandType.name);\n }\n\n this.handlers.set(commandType, handler);\n }\n\n registerMiddleware(middleware: CommandMiddleware, priority = 0): void {\n const alreadyRegistered = this.middlewares.some(\n (registeredMiddleware) =>\n registeredMiddleware.instance.constructor === middleware.constructor,\n );\n\n if (alreadyRegistered) {\n return;\n }\n\n this.middlewares.push({ instance: middleware, priority });\n this.middlewares.sort((a, b) => b.priority - a.priority);\n }\n\n resolve<TCommand extends Command<any>>(command: TCommand): CommandHandler<TCommand> {\n const handler = this.handlers.get(command.constructor);\n\n if (!handler) {\n throw new HandlerNotFoundException(command.constructor.name);\n }\n\n return handler as CommandHandler<TCommand>;\n }\n\n getMiddlewares(): CommandMiddleware[] {\n return this.middlewares.map((middleware) => middleware.instance);\n }\n}\n","export class HandlerNotFoundException extends Error {\n constructor(name: string) {\n super(\n `No handler found for \"${name}\". ` +\n `Make sure it is decorated with @HandleCommand, @HandleQuery, or @HandleEvent and registered as a provider.`,\n );\n this.name = 'HandlerNotFoundException';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","export class DuplicateHandlerException extends Error {\n constructor(type: 'command' | 'query', name: string) {\n super(\n `Duplicate ${type} handler found for \"${name}\". ` +\n `Each command/query must have exactly one handler.`,\n );\n\n this.name = 'DuplicateHandlerException';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { Command, CommandResultOf } from './command';\nimport { CommandRegistry } from './command-registry';\nimport type { ResultType } from '../../../foundation';\n\n@Injectable()\nexport class CommandExecutor {\n constructor(private readonly registry: CommandRegistry) {}\n\n async execute<TCommand extends Command<any>>(\n command: TCommand,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const handler = this.registry.resolve(command);\n const middlewares = this.registry.getMiddlewares();\n\n const executeHandler = () => handler.handle(command);\n\n const pipeline = middlewares.reduceRight<() => Promise<ResultType<CommandResultOf<TCommand>>>>(\n (next, middleware) => () => middleware.use(command, next),\n executeHandler,\n );\n\n return pipeline();\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { Query } from './query';\nimport type { QueryHandler } from './query-handler';\nimport type { QueryMiddleware } from './query-middleware';\nimport { HandlerNotFoundException } from '../../exceptions/handler-not-found.exception';\nimport { DuplicateHandlerException } from '../../exceptions/duplicate-handler.exception';\n\ntype QueryConstructor<TQuery extends Query<any>> = new (...args: any[]) => TQuery;\n\n@Injectable()\nexport class QueryRegistry {\n private readonly handlers = new Map<Function, QueryHandler<any>>();\n\n private readonly middlewares: Array<{\n instance: QueryMiddleware;\n priority: number;\n }> = [];\n\n register<TQuery extends Query<any>>(\n queryType: QueryConstructor<TQuery>,\n handler: QueryHandler<TQuery>,\n ): void {\n if (this.handlers.has(queryType)) {\n throw new DuplicateHandlerException('query', queryType.name);\n }\n\n this.handlers.set(queryType, handler);\n }\n\n registerMiddleware(middleware: QueryMiddleware, priority = 0): void {\n const alreadyRegistered = this.middlewares.some(\n (registeredMiddleware) =>\n registeredMiddleware.instance.constructor === middleware.constructor,\n );\n\n if (alreadyRegistered) {\n return;\n }\n\n this.middlewares.push({ instance: middleware, priority });\n this.middlewares.sort((a, b) => b.priority - a.priority);\n }\n\n resolve<TQuery extends Query<any>>(query: TQuery): QueryHandler<TQuery> {\n const handler = this.handlers.get(query.constructor);\n\n if (!handler) {\n throw new HandlerNotFoundException(query.constructor.name);\n }\n\n return handler as QueryHandler<TQuery>;\n }\n\n getMiddlewares(): QueryMiddleware[] {\n return this.middlewares.map((middleware) => middleware.instance);\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { Query, QueryResultOf } from './query';\nimport { QueryRegistry } from './query-registry';\nimport type { ResultType } from '../../../foundation';\n\n@Injectable()\nexport class QueryExecutor {\n constructor(private readonly registry: QueryRegistry) {}\n\n async execute<TQuery extends Query<any>>(\n query: TQuery,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const handler = this.registry.resolve(query);\n const middlewares = this.registry.getMiddlewares();\n\n const executeHandler = () => handler.handle(query);\n\n const pipeline = middlewares.reduceRight<() => Promise<ResultType<QueryResultOf<TQuery>>>>(\n (next, middleware) => () => middleware.use(query, next),\n executeHandler,\n );\n\n return pipeline();\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { DomainEvent } from '../../../domain/domain-event';\nimport type { EventHandler } from './event-handler';\n\ntype EventConstructor<TEvent extends DomainEvent> = new (...args: any[]) => TEvent;\n\n@Injectable()\nexport class EventRegistry {\n private readonly handlers = new Map<Function, EventHandler<any>[]>();\n\n register<TEvent extends DomainEvent>(\n eventType: EventConstructor<TEvent>,\n handler: EventHandler<TEvent>,\n ): void {\n const existingHandlers = this.handlers.get(eventType) ?? [];\n\n const alreadyRegistered = existingHandlers.some(\n (registeredHandler) => registeredHandler.constructor === handler.constructor,\n );\n\n if (alreadyRegistered) {\n return;\n }\n\n existingHandlers.push(handler);\n this.handlers.set(eventType, existingHandlers);\n }\n\n resolve<TEvent extends DomainEvent>(event: TEvent): EventHandler<TEvent>[] {\n return (this.handlers.get(event.constructor) ?? []) as EventHandler<TEvent>[];\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { DomainEvent } from '../../../domain/domain-event';\nimport { EventRegistry } from './event-registry';\n\n@Injectable()\nexport class EventBus {\n constructor(private readonly registry: EventRegistry) {}\n\n async publish<TEvent extends DomainEvent>(event: TEvent): Promise<void> {\n const handlers = this.registry.resolve(event);\n\n for (const handler of handlers) {\n await handler.handle(event);\n }\n }\n}\n","import { Injectable, OnApplicationBootstrap } from '@nestjs/common';\nimport { DiscoveryService } from '@nestjs/core';\nimport 'reflect-metadata';\n\nimport { CommandRegistry } from './cqrs/command/command-registry';\nimport { QueryRegistry } from './cqrs/query/query-registry';\nimport { EventRegistry } from './cqrs/event/event-registry';\n\nimport { COMMAND_HANDLER_METADATA } from './decorators/handle-command.decorator';\nimport { QUERY_HANDLER_METADATA } from './decorators/handle-query.decorator';\nimport { EVENT_HANDLER_METADATA } from './decorators/handle-event.decorator';\n\nimport {\n COMMAND_MIDDLEWARE_METADATA,\n QUERY_MIDDLEWARE_METADATA,\n type MiddlewareOptions,\n} from './decorators/middleware.decorator';\n\nimport { IntegrationEventRegistry } from './eventing/integration-event-registry';\nimport { INTEGRATION_EVENT_MAPPER_METADATA } from './decorators/integration-event-mapper.decorator';\n\ntype DiscoveredProviderWrapper = {\n instance?: unknown;\n metatype?: Function | null;\n};\n\nfunction hasMethod(\n instance: unknown,\n methodName: string,\n): instance is Record<string, (...args: any[]) => any> {\n return (\n typeof instance === 'object' &&\n instance !== null &&\n typeof (instance as Record<string, unknown>)[methodName] === 'function'\n );\n}\n\nfunction getProviderTarget(wrapper: DiscoveredProviderWrapper): Function | null {\n if (wrapper.metatype) {\n return wrapper.metatype;\n }\n\n if (wrapper.instance && typeof wrapper.instance === 'object') {\n return wrapper.instance.constructor;\n }\n\n return null;\n}\n\n@Injectable()\nexport class ExiumApplicationDiscoveryService implements OnApplicationBootstrap {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly commandRegistry: CommandRegistry,\n private readonly queryRegistry: QueryRegistry,\n private readonly eventRegistry: EventRegistry,\n private readonly integrationEventRegistry: IntegrationEventRegistry,\n ) {}\n\n onApplicationBootstrap(): void {\n const providers = this.discovery.getProviders() as DiscoveredProviderWrapper[];\n\n for (const wrapper of providers) {\n const { instance } = wrapper;\n\n if (!instance || typeof instance !== 'object') {\n continue;\n }\n\n const target = getProviderTarget(wrapper);\n\n if (!target) {\n continue;\n }\n\n this.registerCommandHandler(target, instance);\n this.registerQueryHandler(target, instance);\n this.registerEventHandler(target, instance);\n this.registerCommandMiddleware(target, instance);\n this.registerQueryMiddleware(target, instance);\n this.registerIntegrationEventMapper(target, instance);\n }\n }\n\n private registerCommandHandler(target: Function, instance: object): void {\n const commandType = Reflect.getMetadata(COMMAND_HANDLER_METADATA, target);\n\n if (!commandType) {\n return;\n }\n\n if (!hasMethod(instance, 'handle')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as a command handler ` +\n `but does not implement handle(command).`,\n );\n }\n\n this.commandRegistry.register(commandType, instance as any);\n }\n\n private registerQueryHandler(target: Function, instance: object): void {\n const queryType = Reflect.getMetadata(QUERY_HANDLER_METADATA, target);\n\n if (!queryType) {\n return;\n }\n\n if (!hasMethod(instance, 'handle')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as a query handler ` +\n `but does not implement handle(query).`,\n );\n }\n\n this.queryRegistry.register(queryType, instance as any);\n }\n\n private registerEventHandler(target: Function, instance: object): void {\n const eventType = Reflect.getMetadata(EVENT_HANDLER_METADATA, target);\n\n if (!eventType) {\n return;\n }\n\n if (!hasMethod(instance, 'handle')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as an event handler ` +\n `but does not implement handle(event).`,\n );\n }\n\n this.eventRegistry.register(eventType, instance as any);\n }\n\n private registerCommandMiddleware(target: Function, instance: object): void {\n const options = Reflect.getMetadata(COMMAND_MIDDLEWARE_METADATA, target) as\n | MiddlewareOptions\n | undefined;\n\n if (!options) {\n return;\n }\n\n if (!hasMethod(instance, 'use')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as a command middleware ` +\n `but does not implement use(command, next).`,\n );\n }\n\n this.commandRegistry.registerMiddleware(instance as any, options.priority ?? 0);\n }\n\n private registerQueryMiddleware(target: Function, instance: object): void {\n const options = Reflect.getMetadata(QUERY_MIDDLEWARE_METADATA, target) as\n | MiddlewareOptions\n | undefined;\n\n if (!options) {\n return;\n }\n\n if (!hasMethod(instance, 'use')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as a query middleware ` +\n `but does not implement use(query, next).`,\n );\n }\n\n this.queryRegistry.registerMiddleware(instance as any, options.priority ?? 0);\n }\n\n private registerIntegrationEventMapper(target: Function, instance: object): void {\n const isIntegrationEventMapper = Reflect.getMetadata(\n INTEGRATION_EVENT_MAPPER_METADATA,\n target,\n ) as boolean | undefined;\n\n if (!isIntegrationEventMapper) {\n return;\n }\n\n if (!hasMethod(instance, 'supports')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as an integration event mapper ` +\n `but does not implement supports(domainEvent).`,\n );\n }\n\n if (!hasMethod(instance, 'map')) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as an integration event mapper ` +\n `but does not implement map(domainEvent).`,\n );\n }\n\n this.integrationEventRegistry.register(instance as any);\n }\n}\n","import 'reflect-metadata';\nimport type { Command } from '../cqrs/command/command';\n\nexport const COMMAND_HANDLER_METADATA = Symbol('exium:command-handler');\n\nexport function HandleCommand<TCommand extends Command<any>>(\n commandType: new (...args: any[]) => TCommand,\n): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(COMMAND_HANDLER_METADATA, commandType, target);\n };\n}\n","import 'reflect-metadata';\nimport type { Query } from '../cqrs/query/query';\n\nexport const QUERY_HANDLER_METADATA = Symbol('exium:query-handler');\n\nexport function HandleQuery<TQuery extends Query<any>>(\n queryType: new (...args: any[]) => TQuery,\n): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(QUERY_HANDLER_METADATA, queryType, target);\n };\n}\n","import 'reflect-metadata';\nimport type { DomainEvent } from '../../domain/domain-event';\n\nexport const EVENT_HANDLER_METADATA = Symbol('exium:event-handler');\n\nexport function HandleEvent<TEvent extends DomainEvent>(\n eventType: new (...args: any[]) => TEvent,\n): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(EVENT_HANDLER_METADATA, eventType, target);\n };\n}\n","import 'reflect-metadata';\n\nexport const COMMAND_MIDDLEWARE_METADATA = Symbol('exium:command-middleware');\nexport const QUERY_MIDDLEWARE_METADATA = Symbol('exium:query-middleware');\n\nexport interface MiddlewareOptions {\n priority?: number;\n}\n\nexport function RegisterCommandMiddleware(options: MiddlewareOptions = {}): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(COMMAND_MIDDLEWARE_METADATA, options, target);\n };\n}\n\nexport function RegisterQueryMiddleware(options: MiddlewareOptions = {}): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(QUERY_MIDDLEWARE_METADATA, options, target);\n };\n}\n","import { Injectable } from '@nestjs/common';\nimport type { DomainEvent } from '../../domain/domain-event';\nimport type { IntegrationEvent } from './integration-event';\nimport { IntegrationEventMapper } from './integration-event-mapper';\n\n@Injectable()\nexport class IntegrationEventRegistry {\n private readonly mappers: IntegrationEventMapper[] = [];\n\n register(mapper: IntegrationEventMapper): void {\n const alreadyRegistered = this.mappers.some((item) => item.constructor === mapper.constructor);\n\n if (!alreadyRegistered) {\n this.mappers.push(mapper);\n }\n }\n\n map(domainEvents: readonly DomainEvent[]): IntegrationEvent[] {\n const integrationEvents: IntegrationEvent[] = [];\n\n for (const domainEvent of domainEvents) {\n for (const mapper of this.mappers) {\n if (!mapper.supports(domainEvent)) {\n continue;\n }\n\n const mapped = mapper.map(domainEvent);\n\n if (!mapped) {\n continue;\n }\n\n if (Array.isArray(mapped)) {\n integrationEvents.push(...mapped);\n } else {\n integrationEvents.push(mapped);\n }\n }\n }\n\n return integrationEvents;\n }\n}\n","import 'reflect-metadata';\n\nexport const INTEGRATION_EVENT_MAPPER_METADATA = Symbol('exium:integration_event_mapper');\n\nexport function RegisterIntegrationEventMapper(): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(INTEGRATION_EVENT_MAPPER_METADATA, true, target);\n };\n}\n","import { Injectable } from '@nestjs/common';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\nimport type { ExiumExecutionContext, ExiumOperationType } from './exium-context';\n\n@Injectable()\nexport class ExiumContextService {\n private readonly storage = new AsyncLocalStorage<ExiumExecutionContext>();\n\n run<T>(context: Partial<ExiumExecutionContext>, callback: () => Promise<T> | T): Promise<T> | T {\n const parent = this.getOrUndefined();\n\n const nextContext: ExiumExecutionContext = {\n correlationId: context.correlationId ?? parent?.correlationId ?? randomUUID(),\n\n causationId: context.causationId ?? parent?.causationId,\n\n requestId: context.requestId ?? parent?.requestId,\n\n tenantId: context.tenantId ?? parent?.tenantId,\n\n userId: context.userId ?? parent?.userId,\n\n roles: context.roles ?? parent?.roles,\n\n permissions: context.permissions ?? parent?.permissions,\n\n locale: context.locale ?? parent?.locale,\n\n source: context.source ?? parent?.source,\n\n operationType: context.operationType ?? parent?.operationType ?? 'unknown',\n\n operationName: context.operationName ?? parent?.operationName,\n\n startedAt: context.startedAt ?? parent?.startedAt ?? new Date(),\n };\n\n return this.storage.run(nextContext, callback);\n }\n\n get(): ExiumExecutionContext {\n const context = this.storage.getStore();\n\n if (!context) {\n throw new Error(\n '[ExiumFramework] Execution context is not available. ' +\n 'Make sure ExiumContextService.run() is used before accessing context.',\n );\n }\n\n return context;\n }\n\n getOrUndefined(): ExiumExecutionContext | undefined {\n return this.storage.getStore();\n }\n\n getCorrelationId(): string | undefined {\n return this.getOrUndefined()?.correlationId;\n }\n\n getTenantId(): string | undefined {\n return this.getOrUndefined()?.tenantId;\n }\n\n getUserId(): string | undefined {\n return this.getOrUndefined()?.userId;\n }\n\n withOperation<T>(\n operationType: ExiumOperationType,\n operationName: string,\n callback: () => Promise<T> | T,\n ): Promise<T> | T {\n return this.run(\n {\n operationType,\n operationName,\n },\n callback,\n );\n }\n}\n","export const ApplicationMiddlewarePriority = {\n Context: 1000,\n Logging: 900,\n Validation: 800,\n Authorization: 700,\n Idempotency: 600,\n\n /**\n * Runs outside/around transaction middleware.\n * Its \"after next()\" section executes after transactional command has committed.\n */\n CacheInvalidation: 550,\n\n Audit: 525,\n\n Transaction: 500,\n Cache: 400,\n Metrics: 100,\n} as const;\n","import { Injectable } from '@nestjs/common';\nimport type { ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Context,\n})\nexport class ContextCommandMiddleware implements CommandMiddleware {\n constructor(private readonly contextService: ExiumContextService) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const commandName = command.constructor.name;\n\n return this.contextService.withOperation('command', commandName, next) as Promise<\n ResultType<CommandResultOf<TCommand>>\n >;\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { ResultType } from '../../foundation';\nimport type { Query, QueryResultOf } from '../cqrs/query/query';\nimport type { QueryMiddleware } from '../cqrs/query/query-middleware';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport { RegisterQueryMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\n@Injectable()\n@RegisterQueryMiddleware({\n priority: ApplicationMiddlewarePriority.Context,\n})\nexport class ContextQueryMiddleware implements QueryMiddleware {\n constructor(private readonly contextService: ExiumContextService) {}\n\n async use<TQuery extends Query<any>>(\n query: TQuery,\n next: () => Promise<ResultType<QueryResultOf<TQuery>>>,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const queryName = query.constructor.name;\n\n return this.contextService.withOperation('query', queryName, next) as Promise<\n ResultType<QueryResultOf<TQuery>>\n >;\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { Logger } from 'nestjs-pino';\nimport type { ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Logging,\n})\nexport class LoggingCommandMiddleware implements CommandMiddleware {\n constructor(\n private readonly logger: Logger,\n private readonly contextService: ExiumContextService,\n ) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const commandName = command.constructor.name;\n const context = this.contextService.getOrUndefined();\n const startTime = Date.now();\n\n this.logger.log(\n {\n command: commandName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n },\n `Executing command: ${commandName}`,\n );\n\n try {\n const result = await next();\n const duration = Date.now() - startTime;\n\n if (result.isFailure()) {\n this.logger.warn(\n {\n command: commandName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n durationMs: duration,\n failureKind: result.error.kind,\n failureCode: result.error.code,\n },\n `Command returned expected failure: ${commandName}`,\n );\n\n return result;\n }\n\n this.logger.log(\n {\n command: commandName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n durationMs: duration,\n },\n `Successfully executed command: ${commandName}`,\n );\n\n return result;\n } catch (error: unknown) {\n const duration = Date.now() - startTime;\n\n this.logger.error(\n {\n command: commandName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n durationMs: duration,\n err: error,\n },\n `Failed to execute command: ${commandName}`,\n );\n\n throw error;\n }\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { Logger } from 'nestjs-pino';\nimport type { ResultType } from '../../foundation';\nimport type { Query, QueryResultOf } from '../cqrs/query/query';\nimport type { QueryMiddleware } from '../cqrs/query/query-middleware';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport { RegisterQueryMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\n@Injectable()\n@RegisterQueryMiddleware({\n priority: ApplicationMiddlewarePriority.Logging,\n})\nexport class LoggingQueryMiddleware implements QueryMiddleware {\n constructor(\n private readonly logger: Logger,\n private readonly contextService: ExiumContextService,\n ) {}\n\n async use<TQuery extends Query<any>>(\n query: TQuery,\n next: () => Promise<ResultType<QueryResultOf<TQuery>>>,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const queryName = query.constructor.name;\n const context = this.contextService.getOrUndefined();\n const startTime = Date.now();\n\n this.logger.log(\n {\n query: queryName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n },\n `Executing query: ${queryName}`,\n );\n\n try {\n const result = await next();\n const duration = Date.now() - startTime;\n\n if (result.isFailure()) {\n this.logger.warn(\n {\n query: queryName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n durationMs: duration,\n failureKind: result.error.kind,\n failureCode: result.error.code,\n },\n `Query returned expected failure: ${queryName}`,\n );\n\n return result;\n }\n\n this.logger.log(\n {\n query: queryName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n durationMs: duration,\n },\n `Successfully executed query: ${queryName}`,\n );\n\n return result;\n } catch (error: unknown) {\n const duration = Date.now() - startTime;\n\n this.logger.error(\n {\n query: queryName,\n correlationId: context?.correlationId,\n tenantId: context?.tenantId,\n userId: context?.userId,\n durationMs: duration,\n err: error,\n },\n `Failed to execute query: ${queryName}`,\n );\n\n throw error;\n }\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { validate } from 'class-validator';\nimport 'reflect-metadata';\n\nimport { Failure, Result, type ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { SKIP_VALIDATION_METADATA } from '../decorators/validation.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\nimport { mapValidationErrors } from './validation.utils';\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Validation,\n})\nexport class ValidationCommandMiddleware implements CommandMiddleware {\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const skipValidation = Reflect.getMetadata(SKIP_VALIDATION_METADATA, command.constructor) as\n | boolean\n | undefined;\n\n if (skipValidation) {\n return next();\n }\n\n const errors = await validate(command as object, {\n whitelist: false,\n forbidUnknownValues: false,\n validationError: {\n target: false,\n value: false,\n },\n });\n\n if (errors.length > 0) {\n return Result.fail(\n Failure.validation(\n 'APPLICATION_VALIDATION_FAILED',\n `Validation failed for \"${command.constructor.name}\".`,\n {\n metadata: {\n target: command.constructor.name,\n errors: mapValidationErrors(errors),\n },\n },\n ),\n );\n }\n\n return next();\n }\n}\n","import type { Failure } from './failure';\n\nexport type Result<T, E = Failure> = SuccessResult<T, E> | FailureResult<T, E>;\n\nexport interface SuccessResult<T, E = Failure> {\n readonly type: 'success';\n readonly value: T;\n\n isSuccess(): this is SuccessResult<T, E>;\n isFailure(): this is FailureResult<T, E>;\n\n map<U>(mapper: (value: T) => U): Result<U, E>;\n\n flatMap<U, E2 = E>(mapper: (value: T) => Result<U, E2>): Result<U, E | E2>;\n\n mapFailure<E2>(mapper: (error: E) => E2): Result<T, E2>;\n\n match<U>(handlers: { success: (value: T) => U; failure: (error: E) => U }): U;\n}\n\nexport interface FailureResult<T = never, E = Failure> {\n readonly type: 'failure';\n readonly error: E;\n\n isSuccess(): this is SuccessResult<T, E>;\n isFailure(): this is FailureResult<T, E>;\n\n map<U>(mapper: (value: T) => U): Result<U, E>;\n\n flatMap<U, E2 = E>(mapper: (value: T) => Result<U, E2>): Result<U, E | E2>;\n\n mapFailure<E2>(mapper: (error: E) => E2): Result<T, E2>;\n\n match<U>(handlers: { success: (value: T) => U; failure: (error: E) => U }): U;\n}\n\nclass OkResult<T, E = never> implements SuccessResult<T, E> {\n readonly type = 'success' as const;\n\n private constructor(readonly value: T) {}\n\n static create<T>(value: T): Result<T, never> {\n return new OkResult<T, never>(value);\n }\n\n isSuccess(): this is SuccessResult<T, E> {\n return true;\n }\n\n isFailure(): this is FailureResult<T, E> {\n return false;\n }\n\n map<U>(mapper: (value: T) => U): Result<U, E> {\n return Result.ok(mapper(this.value));\n }\n\n flatMap<U, E2 = E>(mapper: (value: T) => Result<U, E2>): Result<U, E | E2> {\n return mapper(this.value);\n }\n\n mapFailure<E2>(_mapper: (error: E) => E2): Result<T, E2> {\n return Result.ok(this.value);\n }\n\n match<U>(handlers: { success: (value: T) => U; failure: (error: E) => U }): U {\n return handlers.success(this.value);\n }\n}\n\nclass ErrResult<T = never, E = Failure> implements FailureResult<T, E> {\n readonly type = 'failure' as const;\n\n private constructor(readonly error: E) {}\n\n static create<E>(error: E): Result<never, E> {\n return new ErrResult<never, E>(error);\n }\n\n isSuccess(): this is SuccessResult<T, E> {\n return false;\n }\n\n isFailure(): this is FailureResult<T, E> {\n return true;\n }\n\n map<U>(_mapper: (value: T) => U): Result<U, E> {\n return Result.fail(this.error);\n }\n\n flatMap<U, E2 = E>(_mapper: (value: T) => Result<U, E2>): Result<U, E | E2> {\n return Result.fail(this.error);\n }\n\n mapFailure<E2>(mapper: (error: E) => E2): Result<T, E2> {\n return Result.fail(mapper(this.error));\n }\n\n match<U>(handlers: { success: (value: T) => U; failure: (error: E) => U }): U {\n return handlers.failure(this.error);\n }\n}\n\ntype ResultValue<R> = R extends Result<infer T, any> ? T : never;\ntype ResultError<R> = R extends Result<any, infer E> ? E : never;\n\ntype ResultRecord = Record<string, Result<any, any>>;\n\ntype CompileValues<T extends ResultRecord> = {\n [K in keyof T]: ResultValue<T[K]>;\n};\n\ntype CompileErrors<T extends ResultRecord> = Array<ResultError<T[keyof T]>>;\n\nexport const Result = {\n ok<T>(value: T): Result<T, never> {\n return OkResult.create(value);\n },\n\n fail<E = Failure>(error: E): Result<never, E> {\n return ErrResult.create(error);\n },\n\n combine<T, E = Failure>(results: readonly Result<T, E>[]): Result<T[], E[]> {\n const values: T[] = [];\n const errors: E[] = [];\n\n for (const result of results) {\n if (result.isSuccess()) {\n values.push(result.value);\n } else {\n errors.push(result.error);\n }\n }\n\n if (errors.length > 0) {\n return Result.fail(errors);\n }\n\n return Result.ok(values);\n },\n\n compile<T extends ResultRecord>(results: T): Result<CompileValues<T>, CompileErrors<T>> {\n const values: Record<string, unknown> = {};\n const errors: unknown[] = [];\n\n for (const [key, result] of Object.entries(results)) {\n if (result.isSuccess()) {\n values[key] = result.value;\n } else {\n errors.push(result.error);\n }\n }\n\n if (errors.length > 0) {\n return Result.fail(errors as CompileErrors<T>);\n }\n\n return Result.ok(values as CompileValues<T>);\n },\n};\n","export type FailureKind =\n | 'validation'\n | 'not_found'\n | 'business_rule'\n | 'authentication'\n | 'authorization'\n | 'conflict'\n | 'idempotency'\n | 'internal';\n\nexport interface Failure {\n readonly kind: FailureKind;\n readonly code: string;\n readonly message: string;\n readonly field?: string;\n readonly metadata?: Record<string, unknown>;\n readonly internal?: Record<string, unknown>;\n}\n\nexport const Failure = {\n validation(\n code: string,\n message: string,\n options: {\n field?: string;\n metadata?: Record<string, unknown>;\n internal?: Record<string, unknown>;\n } = {},\n ): Failure {\n return {\n kind: 'validation',\n code,\n message,\n field: options.field,\n metadata: options.metadata,\n internal: options.internal,\n };\n },\n\n notFound(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'not_found',\n code,\n message,\n metadata,\n };\n },\n\n businessRule(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'business_rule',\n code,\n message,\n metadata,\n };\n },\n\n authentication(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'authentication',\n code,\n message,\n metadata,\n };\n },\n\n authorization(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'authorization',\n code,\n message,\n metadata,\n };\n },\n\n conflict(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'conflict',\n code,\n message,\n metadata,\n };\n },\n\n idempotency(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'idempotency',\n code,\n message,\n metadata,\n };\n },\n\n internal(code: string, message: string, metadata?: Record<string, unknown>): Failure {\n return {\n kind: 'internal',\n code,\n message,\n metadata,\n };\n },\n};\n","import 'reflect-metadata';\n\nexport const SKIP_VALIDATION_METADATA = Symbol('exium:skip-validation');\n\nexport function SkipValidation(): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(SKIP_VALIDATION_METADATA, true, target);\n };\n}\n","import type { ValidationError } from 'class-validator';\n\nexport interface ApplicationValidationErrorItem {\n readonly property: string;\n readonly constraints: Record<string, string>;\n readonly children?: ApplicationValidationErrorItem[];\n}\n\nexport function mapValidationErrors(errors: ValidationError[]): ApplicationValidationErrorItem[] {\n return errors.map((error) => ({\n property: error.property,\n constraints: error.constraints ?? {},\n children: error.children?.length ? mapValidationErrors(error.children) : undefined,\n }));\n}\n","import { Injectable } from '@nestjs/common';\nimport { validate } from 'class-validator';\nimport 'reflect-metadata';\n\nimport { Failure, Result, type ResultType } from '../../foundation';\nimport type { Query, QueryResultOf } from '../cqrs/query/query';\nimport type { QueryMiddleware } from '../cqrs/query/query-middleware';\nimport { RegisterQueryMiddleware } from '../decorators/middleware.decorator';\nimport { SKIP_VALIDATION_METADATA } from '../decorators/validation.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\nimport { mapValidationErrors } from './validation.utils';\n\n@Injectable()\n@RegisterQueryMiddleware({\n priority: ApplicationMiddlewarePriority.Validation,\n})\nexport class ValidationQueryMiddleware implements QueryMiddleware {\n async use<TQuery extends Query<any>>(\n query: TQuery,\n next: () => Promise<ResultType<QueryResultOf<TQuery>>>,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const skipValidation = Reflect.getMetadata(SKIP_VALIDATION_METADATA, query.constructor) as\n | boolean\n | undefined;\n\n if (skipValidation) {\n return next();\n }\n\n const errors = await validate(query as object, {\n whitelist: false,\n forbidUnknownValues: false,\n validationError: {\n target: false,\n value: false,\n },\n });\n\n if (errors.length > 0) {\n return Result.fail(\n Failure.validation(\n 'APPLICATION_VALIDATION_FAILED',\n `Validation failed for \"${query.constructor.name}\".`,\n {\n metadata: {\n target: query.constructor.name,\n errors: mapValidationErrors(errors),\n },\n },\n ),\n );\n }\n\n return next();\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport { Failure, Result, type ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport {\n AUTHORIZATION_METADATA,\n type AuthorizationMetadata,\n} from '../decorators/authorization.decorator';\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { PermissionChecker } from '../authorization/permission-checker';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Authorization,\n})\nexport class AuthorizationCommandMiddleware implements CommandMiddleware {\n constructor(\n private readonly contextService: ExiumContextService,\n private readonly permissionChecker: PermissionChecker,\n ) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const operationName = command.constructor.name;\n\n const metadata = Reflect.getMetadata(AUTHORIZATION_METADATA, command.constructor) as\n | AuthorizationMetadata\n | undefined;\n\n if (!metadata) {\n return next();\n }\n\n if (metadata.allowAnonymous) {\n return next();\n }\n\n const context = this.contextService.getOrUndefined();\n\n if (!context) {\n return Result.fail(\n Failure.authentication(\n 'AUTHENTICATION_REQUIRED',\n `Authentication is required for \"${operationName}\".`,\n {\n operationName,\n reason: 'missing_context',\n },\n ),\n );\n }\n\n if (!context.userId) {\n return Result.fail(\n Failure.authentication(\n 'AUTHENTICATION_REQUIRED',\n `Authentication is required for \"${operationName}\".`,\n {\n operationName,\n reason: 'missing_user',\n },\n ),\n );\n }\n\n const result = await this.permissionChecker.check({\n context,\n operationName,\n permissions: metadata.permissions,\n permissionMode: metadata.permissionMode,\n roles: metadata.roles,\n roleMode: metadata.roleMode,\n });\n\n if (!result.allowed) {\n const reason = result.reason === 'missing_role' ? 'missing_role' : 'missing_permission';\n const required = [...(metadata.permissions ?? []), ...(metadata.roles ?? [])];\n\n return Result.fail(\n Failure.authorization(\n 'AUTHORIZATION_DENIED',\n `Authorization failed for \"${operationName}\".`,\n {\n operationName,\n reason,\n required,\n },\n ),\n );\n }\n\n return next();\n }\n}\n","import 'reflect-metadata';\n\nexport const AUTHORIZATION_METADATA = Symbol('exium:authorization');\n\nexport type AuthorizationRequirementMode = 'all' | 'any';\n\nexport interface AuthorizationMetadata {\n readonly allowAnonymous?: boolean;\n\n readonly permissions?: readonly string[];\n readonly permissionMode?: AuthorizationRequirementMode;\n\n readonly roles?: readonly string[];\n readonly roleMode?: AuthorizationRequirementMode;\n}\n\nfunction mergeAuthorizationMetadata(target: object, next: AuthorizationMetadata): void {\n const existing = Reflect.getMetadata(AUTHORIZATION_METADATA, target) as\n | AuthorizationMetadata\n | undefined;\n\n Reflect.defineMetadata(\n AUTHORIZATION_METADATA,\n {\n ...existing,\n ...next,\n permissions: [...(existing?.permissions ?? []), ...(next.permissions ?? [])],\n roles: [...(existing?.roles ?? []), ...(next.roles ?? [])],\n },\n target,\n );\n}\n\nexport function AllowAnonymous(): ClassDecorator {\n return (target: object) => {\n mergeAuthorizationMetadata(target, {\n allowAnonymous: true,\n });\n };\n}\n\nexport function RequirePermission(...permissions: string[]): ClassDecorator {\n return (target: object) => {\n mergeAuthorizationMetadata(target, {\n permissions,\n permissionMode: 'all',\n allowAnonymous: false,\n });\n };\n}\n\nexport function RequireAnyPermission(...permissions: string[]): ClassDecorator {\n return (target: object) => {\n mergeAuthorizationMetadata(target, {\n permissions,\n permissionMode: 'any',\n allowAnonymous: false,\n });\n };\n}\n\nexport function RequireRole(...roles: string[]): ClassDecorator {\n return (target: object) => {\n mergeAuthorizationMetadata(target, {\n roles,\n roleMode: 'all',\n allowAnonymous: false,\n });\n };\n}\n\nexport function RequireAnyRole(...roles: string[]): ClassDecorator {\n return (target: object) => {\n mergeAuthorizationMetadata(target, {\n roles,\n roleMode: 'any',\n allowAnonymous: false,\n });\n };\n}\n","import type { ExiumExecutionContext } from '../context/exium-context';\n\nexport interface PermissionCheckInput {\n readonly context: ExiumExecutionContext;\n readonly operationName: string;\n\n readonly permissions?: readonly string[];\n readonly permissionMode?: 'all' | 'any';\n\n readonly roles?: readonly string[];\n readonly roleMode?: 'all' | 'any';\n}\n\nexport interface PermissionCheckResult {\n readonly allowed: boolean;\n readonly reason?: string;\n}\n\nexport abstract class PermissionChecker {\n abstract check(input: PermissionCheckInput): Promise<PermissionCheckResult>;\n}\n","import { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport { Failure, Result, type ResultType } from '../../foundation';\nimport type { Query, QueryResultOf } from '../cqrs/query/query';\nimport type { QueryMiddleware } from '../cqrs/query/query-middleware';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport {\n AUTHORIZATION_METADATA,\n type AuthorizationMetadata,\n} from '../decorators/authorization.decorator';\nimport { RegisterQueryMiddleware } from '../decorators/middleware.decorator';\nimport { PermissionChecker } from '../authorization/permission-checker';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\n@Injectable()\n@RegisterQueryMiddleware({\n priority: ApplicationMiddlewarePriority.Authorization,\n})\nexport class AuthorizationQueryMiddleware implements QueryMiddleware {\n constructor(\n private readonly contextService: ExiumContextService,\n private readonly permissionChecker: PermissionChecker,\n ) {}\n\n async use<TQuery extends Query<any>>(\n query: TQuery,\n next: () => Promise<ResultType<QueryResultOf<TQuery>>>,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const operationName = query.constructor.name;\n\n const metadata = Reflect.getMetadata(AUTHORIZATION_METADATA, query.constructor) as\n | AuthorizationMetadata\n | undefined;\n\n if (!metadata) {\n return next();\n }\n\n if (metadata.allowAnonymous) {\n return next();\n }\n\n const context = this.contextService.getOrUndefined();\n\n if (!context) {\n return Result.fail(\n Failure.authentication(\n 'AUTHENTICATION_REQUIRED',\n `Authentication is required for \"${operationName}\".`,\n {\n operationName,\n reason: 'missing_context',\n },\n ),\n );\n }\n\n if (!context.userId) {\n return Result.fail(\n Failure.authentication(\n 'AUTHENTICATION_REQUIRED',\n `Authentication is required for \"${operationName}\".`,\n {\n operationName,\n reason: 'missing_user',\n },\n ),\n );\n }\n\n const result = await this.permissionChecker.check({\n context,\n operationName,\n permissions: metadata.permissions,\n permissionMode: metadata.permissionMode,\n roles: metadata.roles,\n roleMode: metadata.roleMode,\n });\n\n if (!result.allowed) {\n const reason = result.reason === 'missing_role' ? 'missing_role' : 'missing_permission';\n const required = [...(metadata.permissions ?? []), ...(metadata.roles ?? [])];\n\n return Result.fail(\n Failure.authorization(\n 'AUTHORIZATION_DENIED',\n `Authorization failed for \"${operationName}\".`,\n {\n operationName,\n reason,\n required,\n },\n ),\n );\n }\n\n return next();\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport { Result, type ResultType } from '../../foundation';\nimport type { Query, QueryResultOf } from '../cqrs/query/query';\nimport type { QueryMiddleware } from '../cqrs/query/query-middleware';\n\nimport { CACHE_QUERY_METADATA, type CacheQueryMetadata } from '../decorators/cache-query.decorator';\n\nimport { RegisterQueryMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\nimport { CacheKeyFactory, CacheStore, CacheVersionService } from '../cache';\n\n@Injectable()\n@RegisterQueryMiddleware({\n priority: ApplicationMiddlewarePriority.Cache,\n})\nexport class CacheQueryMiddleware implements QueryMiddleware {\n constructor(\n private readonly cacheStore: CacheStore,\n private readonly cacheKeyFactory: CacheKeyFactory,\n private readonly cacheVersionService: CacheVersionService,\n ) {}\n\n async use<TQuery extends Query<any>>(\n query: TQuery,\n next: () => Promise<ResultType<QueryResultOf<TQuery>>>,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const metadata = Reflect.getMetadata(CACHE_QUERY_METADATA, query.constructor) as\n | CacheQueryMetadata\n | undefined;\n\n if (!metadata?.enabled) {\n return next();\n }\n\n const queryName = query.constructor.name;\n const namespace = metadata.namespace ?? queryName;\n\n const version = metadata.versioned\n ? await this.cacheVersionService.getVersion(namespace)\n : 'static';\n\n const cacheKey = this.cacheKeyFactory.create({\n namespace,\n queryName,\n version,\n payload: query,\n });\n\n const cached = await this.cacheStore.get<QueryResultOf<TQuery>>(cacheKey);\n\n if (cached.hit) {\n return Result.ok(cached.value as QueryResultOf<TQuery>);\n }\n\n const result = await next();\n\n if (result.isSuccess()) {\n await this.cacheStore.set(cacheKey, result.value, {\n ttlSeconds: metadata.ttlSeconds,\n });\n }\n\n return result;\n }\n}\n","import 'reflect-metadata';\n\nexport const CACHE_QUERY_METADATA = Symbol('exium:cache-query');\n\nexport interface CacheQueryOptions {\n readonly namespace?: string;\n readonly ttlSeconds?: number;\n readonly versioned?: boolean;\n}\n\nexport interface CacheQueryMetadata {\n readonly enabled: boolean;\n readonly namespace?: string;\n readonly ttlSeconds?: number;\n readonly versioned: boolean;\n}\n\nexport function CacheQuery(options: CacheQueryOptions = {}): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n CACHE_QUERY_METADATA,\n {\n enabled: true,\n namespace: options.namespace,\n ttlSeconds: options.ttlSeconds,\n versioned: options.versioned ?? true,\n } satisfies CacheQueryMetadata,\n target,\n );\n };\n}\n\nexport function NonCacheable(): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n CACHE_QUERY_METADATA,\n {\n enabled: false,\n versioned: false,\n } satisfies CacheQueryMetadata,\n target,\n );\n };\n}\n","export interface CacheGetResult<T> {\n readonly hit: boolean;\n readonly value?: T;\n}\n\nexport interface CacheSetOptions {\n readonly ttlSeconds?: number;\n}\n\nexport abstract class CacheStore {\n abstract get<T>(key: string): Promise<CacheGetResult<T>>;\n\n abstract set<T>(key: string, value: T, options?: CacheSetOptions): Promise<void>;\n\n abstract delete(key: string): Promise<void>;\n\n abstract deleteByPrefix(prefix: string): Promise<void>;\n}\n","import { Injectable } from '@nestjs/common';\nimport { CacheStore, type CacheGetResult, type CacheSetOptions } from './cache-store';\n\n@Injectable()\nexport class NoopCacheStore extends CacheStore {\n async get<T>(_key: string): Promise<CacheGetResult<T>> {\n return {\n hit: false,\n };\n }\n\n async set<T>(_key: string, _value: T, _options?: CacheSetOptions): Promise<void> {\n // Intentionally empty.\n }\n\n async delete(_key: string): Promise<void> {\n // Intentionally empty.\n }\n\n async deleteByPrefix(_prefix: string): Promise<void> {\n // Intentionally empty.\n }\n}\n","import { createHash } from 'node:crypto';\nimport { Injectable } from '@nestjs/common';\n\nexport interface CacheKeyFactoryInput {\n readonly namespace: string;\n readonly queryName: string;\n readonly version: string | number;\n readonly payload: unknown;\n}\n\nexport interface CacheKeyPrefixInput {\n readonly namespace: string;\n readonly version?: string | number;\n readonly queryName?: string;\n}\n\nexport abstract class CacheKeyFactory {\n abstract create(input: CacheKeyFactoryInput): string;\n\n abstract createPrefix(input: CacheKeyPrefixInput): string;\n}\n\n@Injectable()\nexport class DefaultCacheKeyFactory extends CacheKeyFactory {\n create(input: CacheKeyFactoryInput): string {\n const payloadHash = createHash('sha256').update(stableStringify(input.payload)).digest('hex');\n\n return [\n 'exium',\n 'query',\n input.namespace,\n `v${input.version}`,\n input.queryName,\n payloadHash,\n ].join(':');\n }\n\n createPrefix(input: CacheKeyPrefixInput): string {\n const parts = ['exium', 'query', input.namespace];\n\n if (input.version !== undefined) {\n parts.push(`v${input.version}`);\n }\n\n if (input.queryName) {\n parts.push(input.queryName);\n }\n\n return `${parts.join(':')}:`;\n }\n}\n\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(sortRecursively(value));\n}\n\nfunction sortRecursively(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortRecursively);\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = sortRecursively((value as Record<string, unknown>)[key]);\n\n return acc;\n }, {});\n }\n\n return value;\n}\n","import { Injectable } from '@nestjs/common';\n\nexport abstract class CacheVersionService {\n abstract getVersion(namespace: string): Promise<string | number>;\n\n abstract bumpVersion(namespace: string): Promise<string | number>;\n}\n\n@Injectable()\nexport class InMemoryCacheVersionService extends CacheVersionService {\n private readonly versions = new Map<string, number>();\n\n async getVersion(namespace: string): Promise<number> {\n return this.versions.get(namespace) ?? 1;\n }\n\n async bumpVersion(namespace: string): Promise<number> {\n const nextVersion = (this.versions.get(namespace) ?? 1) + 1;\n this.versions.set(namespace, nextVersion);\n return nextVersion;\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport { Logger } from 'nestjs-pino';\nimport 'reflect-metadata';\n\nimport type { ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\n\nimport {\n INVALIDATE_CACHE_METADATA,\n type InvalidateCacheMetadata,\n} from '../decorators/invalidate-cache.decorator';\n\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\nimport { CacheKeyFactory, CacheStore, CacheVersionService } from '../cache';\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.CacheInvalidation,\n})\nexport class CacheInvalidationCommandMiddleware implements CommandMiddleware {\n constructor(\n private readonly cacheStore: CacheStore,\n private readonly cacheKeyFactory: CacheKeyFactory,\n private readonly cacheVersionService: CacheVersionService,\n private readonly logger: Logger,\n ) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const metadata = Reflect.getMetadata(INVALIDATE_CACHE_METADATA, command.constructor) as\n | InvalidateCacheMetadata\n | undefined;\n\n if (!metadata?.enabled) {\n return next();\n }\n\n const result = await next();\n\n if (result.isFailure()) {\n return result;\n }\n\n try {\n await this.invalidate(metadata);\n } catch (error: unknown) {\n this.logger.error(\n {\n command: command.constructor.name,\n namespaces: metadata.namespaces,\n mode: metadata.mode,\n err: error,\n },\n `Cache invalidation failed for command: ${command.constructor.name}`,\n );\n\n if (metadata.failOnError) {\n throw error;\n }\n }\n\n return result;\n }\n\n private async invalidate(metadata: InvalidateCacheMetadata): Promise<void> {\n for (const namespace of metadata.namespaces) {\n if (metadata.mode === 'version-bump' || metadata.mode === 'both') {\n await this.cacheVersionService.bumpVersion(namespace);\n }\n\n if (metadata.mode === 'delete-prefix' || metadata.mode === 'both') {\n const prefix = this.cacheKeyFactory.createPrefix({\n namespace,\n });\n\n await this.cacheStore.deleteByPrefix(prefix);\n }\n }\n }\n}\n","import 'reflect-metadata';\n\nexport const INVALIDATE_CACHE_METADATA = Symbol('exium:invalidate-cache');\n\nexport type CacheInvalidationMode = 'version-bump' | 'delete-prefix' | 'both';\n\nexport interface InvalidateCacheOptions {\n readonly namespaces: readonly string[];\n readonly mode?: CacheInvalidationMode;\n\n /**\n * Default false.\n *\n * Cache invalidation happens after the command succeeds.\n * If invalidation fails after DB commit, failing the command response may be misleading.\n */\n readonly failOnError?: boolean;\n}\n\nexport interface InvalidateCacheMetadata {\n readonly enabled: boolean;\n readonly namespaces: readonly string[];\n readonly mode: CacheInvalidationMode;\n readonly failOnError: boolean;\n}\n\nexport function InvalidateCache(namespace: string, ...namespaces: string[]): ClassDecorator;\n\nexport function InvalidateCache(options: InvalidateCacheOptions): ClassDecorator;\n\nexport function InvalidateCache(\n first: string | InvalidateCacheOptions,\n ...rest: string[]\n): ClassDecorator {\n return (target: object) => {\n const options = normalizeInvalidateCacheOptions(first, rest);\n\n Reflect.defineMetadata(\n INVALIDATE_CACHE_METADATA,\n {\n enabled: true,\n namespaces: options.namespaces,\n mode: options.mode ?? 'version-bump',\n failOnError: options.failOnError ?? false,\n } satisfies InvalidateCacheMetadata,\n target,\n );\n };\n}\n\nfunction normalizeInvalidateCacheOptions(\n first: string | InvalidateCacheOptions,\n rest: string[],\n): InvalidateCacheOptions {\n const namespaces = typeof first === 'string' ? [first, ...rest] : [...first.namespaces];\n\n const uniqueNamespaces = [\n ...new Set(namespaces.map((namespace) => namespace.trim()).filter(Boolean)),\n ];\n\n if (uniqueNamespaces.length === 0) {\n throw new Error('[ExiumFramework] @InvalidateCache requires at least one namespace.');\n }\n\n if (typeof first === 'string') {\n return {\n namespaces: uniqueNamespaces,\n };\n }\n\n return {\n ...first,\n namespaces: uniqueNamespaces,\n };\n}\n","import { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport { Failure, Result, type FailureType, type ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\n\nimport { IDEMPOTENT_METADATA, type IdempotentMetadata } from '../decorators/idempotent.decorator';\n\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\n\nimport {\n IdempotencyFingerprintFactory,\n IdempotencyKeyResolver,\n IdempotencyStore,\n} from '../idempotency';\n\ninterface StoredCommandResult<TResult> {\n readonly __type: 'exium.result';\n readonly result:\n | {\n readonly type: 'success';\n readonly value: TResult;\n }\n | {\n readonly type: 'failure';\n readonly error: FailureType;\n };\n}\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Idempotency,\n})\nexport class IdempotencyCommandMiddleware implements CommandMiddleware {\n constructor(\n private readonly store: IdempotencyStore,\n private readonly keyResolver: IdempotencyKeyResolver,\n private readonly fingerprintFactory: IdempotencyFingerprintFactory,\n ) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const operationName = command.constructor.name;\n\n const metadata = Reflect.getMetadata(IDEMPOTENT_METADATA, command.constructor) as\n | IdempotentMetadata\n | undefined;\n\n if (!metadata?.enabled) {\n return next();\n }\n\n const scope = metadata.scope ?? operationName;\n\n const key = await this.keyResolver.resolve({\n command,\n operationName,\n keyProperty: metadata.keyProperty,\n });\n\n if (!key) {\n return Result.fail(\n Failure.validation(\n 'IDEMPOTENCY_KEY_MISSING',\n `Idempotency key is required for \"${operationName}\".`,\n {\n metadata: {\n operationName,\n reason: 'missing_key',\n scope,\n },\n },\n ),\n );\n }\n\n const fingerprint = metadata.fingerprintPayload\n ? this.fingerprintFactory.create({\n operationName,\n payload: command,\n excludeProperties: [metadata.keyProperty],\n })\n : 'none';\n\n const beginResult = await this.store.begin<\n StoredCommandResult<CommandResultOf<TCommand>> | CommandResultOf<TCommand>\n >({\n scope,\n key,\n fingerprint,\n ttlSeconds: metadata.ttlSeconds,\n operationName,\n startedAt: new Date(),\n });\n\n if (beginResult.status === 'completed') {\n return restoreStoredResult(beginResult.result);\n }\n\n if (beginResult.status === 'in_progress') {\n return Result.fail(\n Failure.idempotency(\n 'IDEMPOTENCY_IN_PROGRESS',\n `Idempotent command \"${operationName}\" is already in progress.`,\n {\n operationName,\n reason: 'in_progress',\n scope,\n key,\n },\n ),\n );\n }\n\n if (beginResult.status === 'conflict') {\n return Result.fail(\n Failure.conflict(\n 'IDEMPOTENCY_CONFLICT',\n `Idempotency fingerprint conflict for \"${operationName}\".`,\n {\n operationName,\n reason: 'conflict',\n scope,\n key,\n existingFingerprint: beginResult.existingFingerprint,\n incomingFingerprint: beginResult.incomingFingerprint,\n },\n ),\n );\n }\n\n try {\n const result = await next();\n\n await this.store.complete<StoredCommandResult<CommandResultOf<TCommand>>>({\n scope,\n key,\n result: toStoredResult(result),\n completedAt: new Date(),\n });\n\n return result;\n } catch (error: unknown) {\n await this.store.fail({\n scope,\n key,\n failedAt: new Date(),\n error,\n });\n\n throw error;\n }\n }\n}\n\nfunction toStoredResult<TResult>(result: ResultType<TResult>): StoredCommandResult<TResult> {\n if (result.isSuccess()) {\n return {\n __type: 'exium.result',\n result: {\n type: 'success',\n value: result.value,\n },\n };\n }\n\n return {\n __type: 'exium.result',\n result: {\n type: 'failure',\n error: result.error,\n },\n };\n}\n\nfunction restoreStoredResult<TResult>(\n stored: StoredCommandResult<TResult> | TResult,\n): ResultType<TResult> {\n if (isStoredCommandResult<TResult>(stored)) {\n if (stored.result.type === 'success') {\n return Result.ok(stored.result.value);\n }\n\n return Result.fail(stored.result.error);\n }\n\n return Result.ok(stored);\n}\n\nfunction isStoredCommandResult<TResult>(\n value: StoredCommandResult<TResult> | TResult,\n): value is StoredCommandResult<TResult> {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const candidate = value as Partial<StoredCommandResult<TResult>>;\n\n return candidate.__type === 'exium.result' && !!candidate.result;\n}\n","import 'reflect-metadata';\n\nexport const IDEMPOTENT_METADATA = Symbol('exium:idempotent');\n\nexport interface IdempotentOptions {\n /**\n * The command property that contains the idempotency key.\n *\n * Default: \"idempotencyKey\"\n */\n readonly keyProperty?: string;\n\n /**\n * Logical idempotency scope.\n *\n * Default: command class name.\n */\n readonly scope?: string;\n\n /**\n * How long the idempotency record should live.\n *\n * Default: 24 hours.\n */\n readonly ttlSeconds?: number;\n\n /**\n * Protects against reusing the same idempotency key with a different payload.\n *\n * Default: true.\n */\n readonly fingerprintPayload?: boolean;\n}\n\nexport interface IdempotentMetadata {\n readonly enabled: boolean;\n readonly keyProperty: string;\n readonly scope?: string;\n readonly ttlSeconds: number;\n readonly fingerprintPayload: boolean;\n}\n\nexport function Idempotent(options: IdempotentOptions = {}): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n IDEMPOTENT_METADATA,\n {\n enabled: true,\n keyProperty: options.keyProperty ?? 'idempotencyKey',\n scope: options.scope,\n ttlSeconds: options.ttlSeconds ?? 86_400,\n fingerprintPayload: options.fingerprintPayload ?? true,\n } satisfies IdempotentMetadata,\n target,\n );\n };\n}\n\nexport function NonIdempotent(): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n IDEMPOTENT_METADATA,\n {\n enabled: false,\n keyProperty: 'idempotencyKey',\n ttlSeconds: 0,\n fingerprintPayload: false,\n } satisfies IdempotentMetadata,\n target,\n );\n };\n}\n","export type IdempotencyBeginStatus = 'started' | 'completed' | 'in_progress' | 'conflict';\n\nexport interface IdempotencyBeginInput {\n readonly scope: string;\n readonly key: string;\n readonly fingerprint: string;\n readonly ttlSeconds: number;\n readonly operationName: string;\n readonly startedAt: Date;\n}\n\nexport type IdempotencyBeginResult<TResult = unknown> =\n | {\n readonly status: 'started';\n }\n | {\n readonly status: 'completed';\n readonly result: TResult;\n }\n | {\n readonly status: 'in_progress';\n }\n | {\n readonly status: 'conflict';\n readonly existingFingerprint?: string;\n readonly incomingFingerprint: string;\n };\n\nexport interface IdempotencyCompleteInput<TResult = unknown> {\n readonly scope: string;\n readonly key: string;\n readonly result: TResult;\n readonly completedAt: Date;\n}\n\nexport interface IdempotencyFailInput {\n readonly scope: string;\n readonly key: string;\n readonly failedAt: Date;\n readonly error: unknown;\n}\n\nexport abstract class IdempotencyStore {\n abstract begin<TResult = unknown>(\n input: IdempotencyBeginInput,\n ): Promise<IdempotencyBeginResult<TResult>>;\n\n abstract complete<TResult = unknown>(input: IdempotencyCompleteInput<TResult>): Promise<void>;\n\n abstract fail(input: IdempotencyFailInput): Promise<void>;\n}\n","import { Injectable } from '@nestjs/common';\n\nimport {\n IdempotencyStore,\n type IdempotencyBeginInput,\n type IdempotencyBeginResult,\n type IdempotencyCompleteInput,\n type IdempotencyFailInput,\n} from './idempotency-store';\n\nimport { IdempotencyException } from '../exceptions/idempotency.exception';\n\n@Injectable()\nexport class NoopIdempotencyStore extends IdempotencyStore {\n async begin<TResult = unknown>(\n input: IdempotencyBeginInput,\n ): Promise<IdempotencyBeginResult<TResult>> {\n throw new IdempotencyException(input.operationName, 'store_not_configured', {\n scope: input.scope,\n key: input.key,\n });\n }\n\n async complete<TResult = unknown>(_input: IdempotencyCompleteInput<TResult>): Promise<void> {\n // Intentionally empty.\n }\n\n async fail(_input: IdempotencyFailInput): Promise<void> {\n // Intentionally empty.\n }\n}\n","export type IdempotencyFailureReason =\n | 'missing_key'\n | 'in_progress'\n | 'conflict'\n | 'store_not_configured';\n\nexport interface IdempotencyExceptionDetails {\n readonly scope?: string;\n readonly key?: string;\n readonly existingFingerprint?: string;\n readonly incomingFingerprint?: string;\n}\n\nexport class IdempotencyException extends Error {\n constructor(\n public readonly operationName: string,\n public readonly reason: IdempotencyFailureReason,\n public readonly details: IdempotencyExceptionDetails = {},\n ) {\n super(`Idempotency failed for \"${operationName}\". ` + `Reason: ${reason}.`);\n\n this.name = 'IdempotencyException';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nexport interface IdempotencyKeyResolverInput {\n readonly command: object;\n readonly operationName: string;\n readonly keyProperty: string;\n}\n\nexport abstract class IdempotencyKeyResolver {\n abstract resolve(input: IdempotencyKeyResolverInput): Promise<string | undefined>;\n}\n\n@Injectable()\nexport class DefaultIdempotencyKeyResolver extends IdempotencyKeyResolver {\n async resolve(input: IdempotencyKeyResolverInput): Promise<string | undefined> {\n const value = getValueByPath(input.command, input.keyProperty);\n\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const key = value.trim();\n\n return key.length > 0 ? key : undefined;\n }\n}\n\nfunction getValueByPath(source: object, path: string): unknown {\n return path\n .split('.')\n .filter(Boolean)\n .reduce<unknown>((current, key) => {\n if (!current || typeof current !== 'object') {\n return undefined;\n }\n\n return (current as Record<string, unknown>)[key];\n }, source);\n}\n","import { createHash } from 'node:crypto';\nimport { Injectable } from '@nestjs/common';\n\nexport interface IdempotencyFingerprintFactoryInput {\n readonly operationName: string;\n readonly payload: unknown;\n readonly excludeProperties?: readonly string[];\n}\n\nexport abstract class IdempotencyFingerprintFactory {\n abstract create(input: IdempotencyFingerprintFactoryInput): string;\n}\n\n@Injectable()\nexport class DefaultIdempotencyFingerprintFactory extends IdempotencyFingerprintFactory {\n create(input: IdempotencyFingerprintFactoryInput): string {\n const normalizedPayload = removePropertiesByPath(input.payload, input.excludeProperties ?? []);\n\n return createHash('sha256')\n .update(\n stableStringify({\n operationName: input.operationName,\n payload: normalizedPayload,\n }),\n )\n .digest('hex');\n }\n}\n\nfunction stableStringify(value: unknown): string {\n return JSON.stringify(sortRecursively(value));\n}\n\nfunction sortRecursively(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortRecursively);\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = sortRecursively((value as Record<string, unknown>)[key]);\n\n return acc;\n }, {});\n }\n\n return value;\n}\n\nfunction removePropertiesByPath(value: unknown, paths: readonly string[]): unknown {\n const cloned = clonePlain(value);\n\n for (const path of paths) {\n removePath(cloned, path);\n }\n\n return cloned;\n}\n\nfunction clonePlain(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(clonePlain);\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>).reduce<Record<string, unknown>>(\n (acc, key) => {\n acc[key] = clonePlain((value as Record<string, unknown>)[key]);\n\n return acc;\n },\n {},\n );\n }\n\n return value;\n}\n\nfunction removePath(source: unknown, path: string): void {\n if (!source || typeof source !== 'object') {\n return;\n }\n\n const parts = path.split('.').filter(Boolean);\n\n if (parts.length === 0) {\n return;\n }\n\n let current = source as Record<string, unknown>;\n\n for (const part of parts.slice(0, -1)) {\n const next = current[part];\n\n if (!next || typeof next !== 'object') {\n return;\n }\n\n current = next as Record<string, unknown>;\n }\n\n delete current[parts[parts.length - 1]];\n}\n","import { Injectable } from '@nestjs/common';\nimport { Logger } from 'nestjs-pino';\nimport 'reflect-metadata';\n\nimport type { ResultType } from '../../foundation';\nimport type { Command, CommandResultOf } from '../cqrs/command/command';\nimport type { CommandMiddleware } from '../cqrs/command/command-middleware';\n\nimport { AUDITABLE_METADATA, type AuditableMetadata } from '../decorators/auditable.decorator';\n\nimport { RegisterCommandMiddleware } from '../decorators/middleware.decorator';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\nimport { AuditWriter } from '../audit';\nimport { createAuditEvent } from './audit.utils';\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Audit,\n})\nexport class AuditCommandMiddleware implements CommandMiddleware {\n constructor(\n private readonly auditWriter: AuditWriter,\n private readonly contextService: ExiumContextService,\n private readonly logger: Logger,\n ) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const metadata = Reflect.getMetadata(AUDITABLE_METADATA, command.constructor) as\n | AuditableMetadata\n | undefined;\n\n if (!metadata?.enabled) {\n return next();\n }\n\n const operationName = command.constructor.name;\n const startedAt = Date.now();\n\n try {\n const result = await next();\n\n if (result.isFailure()) {\n await this.writeAuditSafely(\n metadata,\n createAuditEvent({\n metadata,\n operationType: 'command',\n operationName,\n payload: command,\n context: this.contextService.getOrUndefined(),\n outcome: 'failure',\n durationMs: Date.now() - startedAt,\n occurredAt: new Date(),\n failure: result.error,\n }),\n );\n\n return result;\n }\n\n await this.writeAuditSafely(\n metadata,\n createAuditEvent({\n metadata,\n operationType: 'command',\n operationName,\n payload: command,\n context: this.contextService.getOrUndefined(),\n outcome: 'success',\n durationMs: Date.now() - startedAt,\n occurredAt: new Date(),\n }),\n );\n\n return result;\n } catch (error: unknown) {\n await this.writeAuditSafely(\n metadata,\n createAuditEvent({\n metadata,\n operationType: 'command',\n operationName,\n payload: command,\n context: this.contextService.getOrUndefined(),\n outcome: 'failure',\n durationMs: Date.now() - startedAt,\n occurredAt: new Date(),\n error,\n }),\n );\n\n throw error;\n }\n }\n\n private async writeAuditSafely(\n metadata: AuditableMetadata,\n event: Parameters<AuditWriter['write']>[0],\n ): Promise<void> {\n try {\n await this.auditWriter.write(event);\n } catch (error: unknown) {\n this.logger.error(\n {\n action: metadata.action,\n resource: metadata.resource,\n err: error,\n },\n 'Audit write failed.',\n );\n\n if (metadata.failOnError) {\n throw error;\n }\n }\n }\n}\n","import 'reflect-metadata';\n\nexport const AUDITABLE_METADATA = Symbol('exium:auditable');\n\nexport interface AuditableOptions {\n readonly action: string;\n readonly resource?: string;\n\n /**\n * Optional static resource id.\n *\n * Dynamic resource id extraction can be added later with resourceIdProperty.\n */\n readonly resourceId?: string;\n\n /**\n * Optional command/query property path for resource id extraction.\n *\n * Example:\n * resourceIdProperty: \"userId\"\n * resourceIdProperty: \"payload.customerId\"\n */\n readonly resourceIdProperty?: string;\n\n /**\n * Extra static metadata written to audit event.\n */\n readonly metadata?: Record<string, unknown>;\n\n /**\n * Default false.\n *\n * If audit write fails, command/query result should usually not fail.\n */\n readonly failOnError?: boolean;\n}\n\nexport interface AuditableMetadata {\n readonly enabled: boolean;\n readonly action: string;\n readonly resource?: string;\n readonly resourceId?: string;\n readonly resourceIdProperty?: string;\n readonly metadata?: Record<string, unknown>;\n readonly failOnError: boolean;\n}\n\nexport function Auditable(options: AuditableOptions): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n AUDITABLE_METADATA,\n {\n enabled: true,\n action: options.action,\n resource: options.resource,\n resourceId: options.resourceId,\n resourceIdProperty: options.resourceIdProperty,\n metadata: options.metadata,\n failOnError: options.failOnError ?? false,\n } satisfies AuditableMetadata,\n target,\n );\n };\n}\n\nexport function NonAuditable(): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n AUDITABLE_METADATA,\n {\n enabled: false,\n action: '',\n failOnError: false,\n } satisfies AuditableMetadata,\n target,\n );\n };\n}\n","import type { AuditEvent } from './audit-event';\n\nexport abstract class AuditWriter {\n abstract write(event: AuditEvent): Promise<void>;\n}\n","import { Injectable } from '@nestjs/common';\nimport type { AuditEvent } from './audit-event';\nimport { AuditWriter } from './audit-writer';\n\n@Injectable()\nexport class NoopAuditWriter extends AuditWriter {\n async write(_event: AuditEvent): Promise<void> {\n // Intentionally empty.\n }\n}\n","import type { ExiumExecutionContext } from '../context/exium-context';\nimport type { AuditableMetadata } from '../decorators/auditable.decorator';\nimport type { AuditEvent, AuditOperationType } from '../audit';\nimport type { FailureType } from '../../foundation';\n\nexport interface CreateAuditEventInput {\n readonly metadata: AuditableMetadata;\n readonly operationType: AuditOperationType;\n readonly operationName: string;\n readonly payload: object;\n readonly context?: ExiumExecutionContext;\n readonly outcome: 'success' | 'failure';\n readonly durationMs: number;\n readonly occurredAt: Date;\n readonly failure?: FailureType;\n readonly error?: unknown;\n}\n\nexport function createAuditEvent(input: CreateAuditEventInput): AuditEvent {\n const error = normalizeError(input.error);\n\n return {\n action: input.metadata.action,\n resource: input.metadata.resource,\n resourceId:\n input.metadata.resourceId ??\n resolveResourceId(input.payload, input.metadata.resourceIdProperty),\n\n operationType: input.operationType,\n operationName: input.operationName,\n\n outcome: input.outcome,\n errorName: input.failure?.kind ?? error?.name,\n errorMessage: input.failure?.message ?? error?.message,\n failureKind: input.failure?.kind,\n failureCode: input.failure?.code,\n failureMessage: input.failure?.message,\n\n correlationId: input.context?.correlationId,\n causationId: input.context?.causationId,\n requestId: input.context?.requestId,\n\n tenantId: input.context?.tenantId,\n userId: input.context?.userId,\n\n source: input.context?.source,\n locale: input.context?.locale,\n\n durationMs: input.durationMs,\n occurredAt: input.occurredAt,\n\n metadata: input.metadata.metadata,\n };\n}\n\nfunction resolveResourceId(payload: object, path: string | undefined): string | undefined {\n if (!path) {\n return undefined;\n }\n\n const value = path\n .split('.')\n .filter(Boolean)\n .reduce<unknown>((current, key) => {\n if (!current || typeof current !== 'object') {\n return undefined;\n }\n\n return (current as Record<string, unknown>)[key];\n }, payload);\n\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n return undefined;\n}\n\nfunction normalizeError(error: unknown): { name: string; message: string } | undefined {\n if (!error) {\n return undefined;\n }\n\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n };\n }\n\n return {\n name: 'UnknownError',\n message: String(error),\n };\n}\n","import { Injectable } from '@nestjs/common';\nimport { Logger } from 'nestjs-pino';\nimport 'reflect-metadata';\n\nimport type { ResultType } from '../../foundation';\nimport type { Query, QueryResultOf } from '../cqrs/query/query';\nimport type { QueryMiddleware } from '../cqrs/query/query-middleware';\n\nimport { AUDITABLE_METADATA, type AuditableMetadata } from '../decorators/auditable.decorator';\n\nimport { RegisterQueryMiddleware } from '../decorators/middleware.decorator';\nimport { ExiumContextService } from '../context/exium-context.service';\nimport { ApplicationMiddlewarePriority } from './middleware-priority';\nimport { AuditWriter } from '../audit';\nimport { createAuditEvent } from './audit.utils';\n\n@Injectable()\n@RegisterQueryMiddleware({\n priority: ApplicationMiddlewarePriority.Audit,\n})\nexport class AuditQueryMiddleware implements QueryMiddleware {\n constructor(\n private readonly auditWriter: AuditWriter,\n private readonly contextService: ExiumContextService,\n private readonly logger: Logger,\n ) {}\n\n async use<TQuery extends Query<any>>(\n query: TQuery,\n next: () => Promise<ResultType<QueryResultOf<TQuery>>>,\n ): Promise<ResultType<QueryResultOf<TQuery>>> {\n const metadata = Reflect.getMetadata(AUDITABLE_METADATA, query.constructor) as\n | AuditableMetadata\n | undefined;\n\n if (!metadata?.enabled) {\n return next();\n }\n\n const operationName = query.constructor.name;\n const startedAt = Date.now();\n\n try {\n const result = await next();\n\n if (result.isFailure()) {\n await this.writeAuditSafely(\n metadata,\n createAuditEvent({\n metadata,\n operationType: 'query',\n operationName,\n payload: query,\n context: this.contextService.getOrUndefined(),\n outcome: 'failure',\n durationMs: Date.now() - startedAt,\n occurredAt: new Date(),\n failure: result.error,\n }),\n );\n\n return result;\n }\n\n await this.writeAuditSafely(\n metadata,\n createAuditEvent({\n metadata,\n operationType: 'query',\n operationName,\n payload: query,\n context: this.contextService.getOrUndefined(),\n outcome: 'success',\n durationMs: Date.now() - startedAt,\n occurredAt: new Date(),\n }),\n );\n\n return result;\n } catch (error: unknown) {\n await this.writeAuditSafely(\n metadata,\n createAuditEvent({\n metadata,\n operationType: 'query',\n operationName,\n payload: query,\n context: this.contextService.getOrUndefined(),\n outcome: 'failure',\n durationMs: Date.now() - startedAt,\n occurredAt: new Date(),\n error,\n }),\n );\n\n throw error;\n }\n }\n\n private async writeAuditSafely(\n metadata: AuditableMetadata,\n event: Parameters<AuditWriter['write']>[0],\n ): Promise<void> {\n try {\n await this.auditWriter.write(event);\n } catch (error: unknown) {\n this.logger.error(\n {\n action: metadata.action,\n resource: metadata.resource,\n err: error,\n },\n 'Audit write failed.',\n );\n\n if (metadata.failOnError) {\n throw error;\n }\n }\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport {\n PermissionChecker,\n type PermissionCheckInput,\n type PermissionCheckResult,\n} from './permission-checker';\n\nfunction hasAll(\n actual: readonly string[] | undefined,\n required: readonly string[] | undefined,\n): boolean {\n if (!required || required.length === 0) {\n return true;\n }\n\n if (!actual || actual.length === 0) {\n return false;\n }\n\n return required.every((item) => actual.includes(item));\n}\n\nfunction hasAny(\n actual: readonly string[] | undefined,\n required: readonly string[] | undefined,\n): boolean {\n if (!required || required.length === 0) {\n return true;\n }\n\n if (!actual || actual.length === 0) {\n return false;\n }\n\n return required.some((item) => actual.includes(item));\n}\n\n@Injectable()\nexport class ContextPermissionChecker extends PermissionChecker {\n async check(input: PermissionCheckInput): Promise<PermissionCheckResult> {\n const permissionMode = input.permissionMode ?? 'all';\n const roleMode = input.roleMode ?? 'all';\n\n const permissionAllowed =\n permissionMode === 'all'\n ? hasAll(input.context.permissions, input.permissions)\n : hasAny(input.context.permissions, input.permissions);\n\n if (!permissionAllowed) {\n return {\n allowed: false,\n reason: 'missing_permission',\n };\n }\n\n const roleAllowed =\n roleMode === 'all'\n ? hasAll(input.context.roles, input.roles)\n : hasAny(input.context.roles, input.roles);\n\n if (!roleAllowed) {\n return {\n allowed: false,\n reason: 'missing_role',\n };\n }\n\n return {\n allowed: true,\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\nimport type { IntegrationEvent } from './integration-event';\nimport { OutboxWriter } from './outbox-writer';\n\n@Injectable()\nexport class NoopOutboxWriter extends OutboxWriter {\n async write(_events: readonly IntegrationEvent[]): Promise<void> {\n // Intentionally empty.\n }\n}\n","import type { IntegrationEvent } from './integration-event';\n\nexport abstract class OutboxWriter {\n abstract write(events: readonly IntegrationEvent[]): Promise<void>;\n}\n","import { AggregateRoot } from '../domain';\n\nexport abstract class UnitOfWork {\n abstract execute<T>(work: () => Promise<T>): Promise<T>;\n abstract registerAggregate(aggregate: AggregateRoot<any>): void;\n}\n","export abstract class Command<TResult = void> {\n declare readonly __resultType?: TResult;\n}\n\nexport type CommandResultOf<TCommand extends Command<any>> =\n TCommand extends Command<infer TResult> ? TResult : never;\n","import type { Command, CommandResultOf } from './command';\nimport type { ResultType } from '../../../foundation';\n\nexport abstract class CommandHandler<TCommand extends Command<any>> {\n abstract handle(command: TCommand): Promise<ResultType<CommandResultOf<TCommand>>>;\n}\n","export abstract class Query<TResult = unknown> {\n declare readonly __resultType?: TResult;\n}\n\nexport type QueryResultOf<TQuery extends Query<any>> =\n TQuery extends Query<infer TResult> ? TResult : never;\n","export abstract class QueryResult {}\n","import type { Query, QueryResultOf } from './query';\nimport type { ResultType } from '../../../foundation';\n\nexport abstract class QueryHandler<TQuery extends Query<any>> {\n abstract handle(query: TQuery): Promise<ResultType<QueryResultOf<TQuery>>>;\n}\n","import type { DomainEvent } from '../../../domain/domain-event';\n\nexport abstract class EventHandler<TEvent extends DomainEvent> {\n abstract handle(event: TEvent): Promise<void>;\n}\n","import 'reflect-metadata';\n\nexport const TRANSACTIONAL_METADATA = Symbol('exium:transactional');\n\nexport interface TransactionalOptions {\n readonly enabled?: boolean;\n}\n\nexport function Transactional(options: TransactionalOptions = {}): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n TRANSACTIONAL_METADATA,\n {\n enabled: options.enabled ?? true,\n },\n target,\n );\n };\n}\n\nexport function NonTransactional(): ClassDecorator {\n return (target: object) => {\n Reflect.defineMetadata(\n TRANSACTIONAL_METADATA,\n {\n enabled: false,\n },\n target,\n );\n };\n}\n","export type AuthorizationFailureReason =\n | 'missing_context'\n | 'missing_user'\n | 'missing_permission'\n | 'missing_role'\n | 'custom_denied';\n\nexport class AuthorizationException extends Error {\n constructor(\n public readonly operationName: string,\n public readonly reason: AuthorizationFailureReason,\n public readonly required?: readonly string[],\n ) {\n super(`Authorization failed for \"${operationName}\". ` + `Reason: ${reason}.`);\n\n this.name = 'AuthorizationException';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","export abstract class IntegrationEvent {\n readonly id: string;\n readonly name: string;\n readonly version: number;\n readonly occurredAt: Date;\n\n protected constructor(params: { id: string; name: string; version: number; occurredAt?: Date }) {\n this.id = params.id;\n this.name = params.name;\n this.version = params.version;\n this.occurredAt = params.occurredAt ?? new Date();\n }\n}\n","import type { DomainEvent } from '../../domain/domain-event';\nimport type { IntegrationEvent } from './integration-event';\n\nexport abstract class IntegrationEventMapper<TDomainEvent extends DomainEvent = DomainEvent> {\n abstract supports(event: DomainEvent): event is TDomainEvent;\n\n abstract map(event: TDomainEvent): IntegrationEvent | IntegrationEvent[] | null;\n}\n","export class ReadQueryException extends Error {\n constructor(message: string) {\n super(`[ExiumFramework] ${message}`);\n this.name = new.target.name;\n }\n}\n\nexport class ReadFieldNotFoundException extends ReadQueryException {\n constructor(sourceName: string, field: string) {\n super(`ReadSource \"${sourceName}\" does not define read field \"${field}\".`);\n }\n}\n\nexport class ReadOperationNotSupportedException extends ReadQueryException {\n constructor(operation: string, reason?: string) {\n super(`${operation} is not supported.${reason ? ` ${reason}` : ''}`);\n }\n}\n","import { ReadQueryException } from '../read.exceptions';\n\nexport type CriteriaOperator =\n | 'eq'\n | 'ne'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'in'\n | 'notIn'\n | 'contains'\n | 'startsWith'\n | 'endsWith'\n | 'isNull'\n | 'isNotNull'\n | 'between';\n\nexport interface ComparisonCriteriaNode {\n readonly type: 'comparison';\n readonly field: string;\n readonly operator: Exclude<\n CriteriaOperator,\n 'in' | 'notIn' | 'isNull' | 'isNotNull' | 'between'\n >;\n readonly value: unknown;\n}\n\nexport interface InCriteriaNode {\n readonly type: 'in';\n readonly field: string;\n readonly operator: 'in' | 'notIn';\n readonly values: readonly unknown[];\n}\n\nexport interface IsNullCriteriaNode {\n readonly type: 'isNull';\n readonly field: string;\n}\n\nexport interface IsNotNullCriteriaNode {\n readonly type: 'isNotNull';\n readonly field: string;\n}\n\nexport interface BetweenCriteriaNode {\n readonly type: 'between';\n readonly field: string;\n readonly lower: unknown;\n readonly upper: unknown;\n}\n\nexport interface AndCriteriaNode {\n readonly type: 'and';\n readonly nodes: readonly CriteriaNode[];\n}\n\nexport interface OrCriteriaNode {\n readonly type: 'or';\n readonly nodes: readonly CriteriaNode[];\n}\n\nexport interface NotCriteriaNode {\n readonly type: 'not';\n readonly node: CriteriaNode;\n}\n\nexport type CriteriaNode =\n | ComparisonCriteriaNode\n | InCriteriaNode\n | IsNullCriteriaNode\n | IsNotNullCriteriaNode\n | BetweenCriteriaNode\n | AndCriteriaNode\n | OrCriteriaNode\n | NotCriteriaNode;\n\ntype CriteriaConnector = 'and' | 'or';\n\nexport class Criteria {\n private constructor(readonly node: CriteriaNode | null) {}\n\n static empty(): Criteria {\n return new Criteria(null);\n }\n\n static where(field: string): CriteriaFieldBuilder {\n return Criteria.empty().where(field);\n }\n\n where(field: string): CriteriaFieldBuilder {\n return this.and(field);\n }\n\n and(field: string): CriteriaFieldBuilder {\n return new CriteriaFieldBuilder(this, 'and', normalizeField(field));\n }\n\n or(field: string): CriteriaFieldBuilder {\n return new CriteriaFieldBuilder(this, 'or', normalizeField(field));\n }\n\n andGroup(factory: (group: Criteria) => Criteria): Criteria {\n return this.append('and', requireNode(factory(Criteria.empty())));\n }\n\n orGroup(factory: (group: Criteria) => Criteria): Criteria {\n return this.append('or', requireNode(factory(Criteria.empty())));\n }\n\n not(): Criteria {\n return new Criteria(freezeNode({ type: 'not', node: requireNode(this) }));\n }\n\n isEmpty(): boolean {\n return this.node === null;\n }\n\n private append(connector: CriteriaConnector, nextNode: CriteriaNode): Criteria {\n if (!this.node) {\n return new Criteria(nextNode);\n }\n\n if (this.node.type === connector) {\n return new Criteria(\n freezeNode({\n type: connector,\n nodes: freezeNodes([...this.node.nodes, nextNode]),\n }),\n );\n }\n\n return new Criteria(\n freezeNode({\n type: connector,\n nodes: freezeNodes([this.node, nextNode]),\n }),\n );\n }\n}\n\nexport class CriteriaFieldBuilder {\n constructor(\n private readonly criteria: Criteria,\n private readonly connector: CriteriaConnector,\n private readonly field: string,\n ) {}\n\n eq(value: unknown): Criteria {\n return this.comparison('eq', value);\n }\n\n ne(value: unknown): Criteria {\n return this.comparison('ne', value);\n }\n\n gt(value: unknown): Criteria {\n return this.comparison('gt', value);\n }\n\n gte(value: unknown): Criteria {\n return this.comparison('gte', value);\n }\n\n lt(value: unknown): Criteria {\n return this.comparison('lt', value);\n }\n\n lte(value: unknown): Criteria {\n return this.comparison('lte', value);\n }\n\n in(values: readonly unknown[]): Criteria {\n return this.inclusion('in', values);\n }\n\n notIn(values: readonly unknown[]): Criteria {\n return this.inclusion('notIn', values);\n }\n\n contains(value: string): Criteria {\n return this.comparison('contains', value);\n }\n\n startsWith(value: string): Criteria {\n return this.comparison('startsWith', value);\n }\n\n endsWith(value: string): Criteria {\n return this.comparison('endsWith', value);\n }\n\n isNull(): Criteria {\n return this.addNode({ type: 'isNull', field: this.field });\n }\n\n isNotNull(): Criteria {\n return this.addNode({ type: 'isNotNull', field: this.field });\n }\n\n between(lower: unknown, upper: unknown): Criteria {\n return this.addNode({\n type: 'between',\n field: this.field,\n lower,\n upper,\n });\n }\n\n private comparison(operator: ComparisonCriteriaNode['operator'], value: unknown): Criteria {\n return this.addNode({\n type: 'comparison',\n field: this.field,\n operator,\n value,\n });\n }\n\n private inclusion(operator: 'in' | 'notIn', values: readonly unknown[]): Criteria {\n if (!Array.isArray(values) || values.length === 0) {\n throw new ReadQueryException(`Criteria.${operator} requires at least one value.`);\n }\n\n return this.addNode({\n type: 'in',\n field: this.field,\n operator,\n values: Object.freeze([...values]),\n });\n }\n\n private addNode(node: CriteriaNode): Criteria {\n return (this.criteria as any).append(this.connector, freezeNode(node));\n }\n}\n\nfunction normalizeField(field: string): string {\n const normalized = field.trim();\n\n if (!normalized) {\n throw new ReadQueryException('Criteria field name must not be empty.');\n }\n\n return normalized;\n}\n\nfunction requireNode(criteria: Criteria): CriteriaNode {\n if (!criteria.node) {\n throw new ReadQueryException('Criteria group must contain at least one condition.');\n }\n\n return criteria.node;\n}\n\nfunction freezeNodes(nodes: readonly CriteriaNode[]): readonly CriteriaNode[] {\n return Object.freeze([...nodes]);\n}\n\nfunction freezeNode<TNode extends CriteriaNode>(node: TNode): TNode {\n if (node.type === 'and' || node.type === 'or') {\n return Object.freeze({\n ...node,\n nodes: freezeNodes(node.nodes),\n }) as unknown as TNode;\n }\n\n if (node.type === 'in') {\n return Object.freeze({\n ...node,\n values: Object.freeze([...node.values]),\n }) as unknown as TNode;\n }\n\n return Object.freeze(node);\n}\n","import { ReadQueryException } from '../read.exceptions';\n\nexport type SortDirection = 'asc' | 'desc';\n\nexport type SortNulls = 'first' | 'last';\n\nexport interface SortField {\n readonly field: string;\n readonly direction: SortDirection;\n readonly nulls?: SortNulls;\n}\n\nexport class Sort {\n private constructor(readonly fields: readonly SortField[]) {}\n\n static none(): Sort {\n return new Sort(Object.freeze([]));\n }\n\n static by(field: string): SortDirectionBuilder {\n return new SortDirectionBuilder([], normalizeField(field));\n }\n\n thenBy(field: string): SortDirectionBuilder {\n return new SortDirectionBuilder(this.fields, normalizeField(field));\n }\n\n isEmpty(): boolean {\n return this.fields.length === 0;\n }\n\n static fromFields(fields: readonly SortField[]): Sort {\n return new Sort(freezeFields(fields.map(normalizeSortField)));\n }\n}\n\nexport class SortDirectionBuilder {\n constructor(\n private readonly previousFields: readonly SortField[],\n private readonly field: string,\n ) {}\n\n asc(options: { readonly nulls?: SortNulls } = {}): Sort {\n return this.build('asc', options.nulls);\n }\n\n desc(options: { readonly nulls?: SortNulls } = {}): Sort {\n return this.build('desc', options.nulls);\n }\n\n private build(direction: SortDirection, nulls?: SortNulls): Sort {\n return Sort.fromFields([\n ...this.previousFields,\n {\n field: this.field,\n direction,\n nulls,\n },\n ]);\n }\n}\n\nfunction normalizeSortField(field: SortField): SortField {\n return Object.freeze({\n field: normalizeField(field.field),\n direction: field.direction,\n nulls: field.nulls,\n });\n}\n\nfunction freezeFields(fields: readonly SortField[]): readonly SortField[] {\n return Object.freeze([...fields]);\n}\n\nfunction normalizeField(field: string): string {\n const normalized = field.trim();\n\n if (!normalized) {\n throw new ReadQueryException('Sort field name must not be empty.');\n }\n\n return normalized;\n}\n","import { Failure, Result, type ResultType } from '../../../foundation';\n\nconst DEFAULT_MAX_PAGE_SIZE = 100;\n\nexport interface PageRequestOptions {\n readonly maxSize?: number;\n}\n\nexport class PageRequest {\n private constructor(\n readonly page: number,\n readonly size: number,\n ) {}\n\n static of(\n page: number,\n size: number,\n options: PageRequestOptions = {},\n ): ResultType<PageRequest> {\n const maxSize = options.maxSize ?? DEFAULT_MAX_PAGE_SIZE;\n\n if (!Number.isInteger(page) || page < 1) {\n return Result.fail(\n Failure.validation('READ_PAGE_INVALID_PAGE', 'Page number must be greater than or equal to 1.', {\n field: 'page',\n metadata: { page },\n }),\n );\n }\n\n if (!Number.isInteger(size) || size < 1) {\n return Result.fail(\n Failure.validation('READ_PAGE_INVALID_SIZE', 'Page size must be greater than or equal to 1.', {\n field: 'size',\n metadata: { size },\n }),\n );\n }\n\n if (size > maxSize) {\n return Result.fail(\n Failure.validation('READ_PAGE_SIZE_TOO_LARGE', `Page size must be less than or equal to ${maxSize}.`, {\n field: 'size',\n metadata: { size, maxSize },\n }),\n );\n }\n\n return Result.ok(new PageRequest(page, size));\n }\n\n get offset(): number {\n return (this.page - 1) * this.size;\n }\n}\n\nexport class Page<T> {\n private constructor(\n readonly items: readonly T[],\n readonly page: number,\n readonly size: number,\n readonly totalItems: number,\n readonly totalPages: number,\n ) {}\n\n static of<T>(items: readonly T[], request: PageRequest, totalItems: number): Page<T> {\n return new Page<T>(\n Object.freeze([...items]),\n request.page,\n request.size,\n totalItems,\n Math.ceil(totalItems / request.size),\n );\n }\n}\n\nexport class CursorRequest {\n private constructor(\n readonly after: string | null,\n readonly before: string | null,\n readonly limit: number,\n ) {}\n\n static first(limit: number, options: PageRequestOptions = {}): ResultType<CursorRequest> {\n return CursorRequest.create(null, null, limit, options);\n }\n\n static after(\n cursor: string,\n limit: number,\n options: PageRequestOptions = {},\n ): ResultType<CursorRequest> {\n const normalized = normalizeCursor(cursor, 'after');\n\n if (normalized.isFailure()) {\n return Result.fail(normalized.error);\n }\n\n return CursorRequest.create(normalized.value, null, limit, options);\n }\n\n static before(\n cursor: string,\n limit: number,\n options: PageRequestOptions = {},\n ): ResultType<CursorRequest> {\n const normalized = normalizeCursor(cursor, 'before');\n\n if (normalized.isFailure()) {\n return Result.fail(normalized.error);\n }\n\n return CursorRequest.create(null, normalized.value, limit, options);\n }\n\n private static create(\n after: string | null,\n before: string | null,\n limit: number,\n options: PageRequestOptions,\n ): ResultType<CursorRequest> {\n const maxSize = options.maxSize ?? DEFAULT_MAX_PAGE_SIZE;\n\n if (!Number.isInteger(limit) || limit < 1) {\n return Result.fail(\n Failure.validation('READ_CURSOR_INVALID_LIMIT', 'Cursor limit must be greater than or equal to 1.', {\n field: 'limit',\n metadata: { limit },\n }),\n );\n }\n\n if (limit > maxSize) {\n return Result.fail(\n Failure.validation('READ_CURSOR_LIMIT_TOO_LARGE', `Cursor limit must be less than or equal to ${maxSize}.`, {\n field: 'limit',\n metadata: { limit, maxSize },\n }),\n );\n }\n\n return Result.ok(new CursorRequest(after, before, limit));\n }\n}\n\nexport class CursorPage<T> {\n constructor(\n readonly items: readonly T[],\n readonly hasNext: boolean,\n readonly hasPrevious: boolean,\n readonly nextCursor?: string,\n readonly previousCursor?: string,\n ) {\n this.items = Object.freeze([...items]);\n }\n}\n\nfunction normalizeCursor(cursor: string, field: 'after' | 'before'): ResultType<string> {\n const normalized = cursor.trim();\n\n if (!normalized) {\n return Result.fail(\n Failure.validation('READ_CURSOR_INVALID_VALUE', 'Cursor must not be empty.', {\n field,\n }),\n );\n }\n\n return Result.ok(normalized);\n}\n","import type { Sort } from '../sort';\nimport { ReadFieldNotFoundException, ReadQueryException } from '../read.exceptions';\n\nexport interface ReadSource {\n readonly name: string;\n}\n\nexport type SqlJoinType = 'left' | 'inner';\n\nexport type SqlJoinOperator = '=' | '!=' | '<' | '<=' | '>' | '>=';\n\nexport interface SqlJoinOnRef {\n readonly left: string;\n readonly operator: SqlJoinOperator;\n readonly right: string;\n}\n\nexport interface SqlJoin {\n readonly type: SqlJoinType;\n readonly table: string;\n readonly alias: string;\n readonly on: SqlJoinOnRef;\n}\n\nexport interface SqlReadSourceDefinition {\n readonly name: string;\n readonly table: string;\n readonly alias?: string;\n readonly fields: Record<string, string>;\n readonly joins?: readonly SqlJoin[];\n readonly defaultSort?: Sort;\n readonly defaultSelectedFields?: readonly string[];\n}\n\nexport class SqlReadSource implements ReadSource {\n private constructor(\n readonly name: string,\n readonly table: string,\n readonly alias: string | undefined,\n readonly fields: Readonly<Record<string, string>>,\n readonly joins: readonly SqlJoin[],\n readonly defaultSort: Sort | undefined,\n readonly defaultSelectedFields: readonly string[] | undefined,\n ) {}\n\n static define(definition: SqlReadSourceDefinition): SqlReadSource {\n const name = normalizeIdentifier(definition.name, 'ReadSource name');\n const table = normalizeIdentifier(definition.table, 'ReadSource table');\n const alias = definition.alias\n ? normalizeIdentifier(definition.alias, 'ReadSource alias')\n : undefined;\n const fields = normalizeFields(definition.fields);\n const defaultSelectedFields = definition.defaultSelectedFields\n ? Object.freeze([...definition.defaultSelectedFields])\n : undefined;\n\n return new SqlReadSource(\n name,\n table,\n alias,\n fields,\n Object.freeze([...(definition.joins ?? [])]),\n definition.defaultSort,\n defaultSelectedFields,\n );\n }\n\n static is(source: ReadSource): source is SqlReadSource {\n return source instanceof SqlReadSource;\n }\n\n resolveField(field: string): string {\n const resolved = this.fields[field];\n\n if (!resolved) {\n throw new ReadFieldNotFoundException(this.name, field);\n }\n\n return resolved;\n }\n\n getSelectFields(): readonly string[] {\n const fieldNames = this.defaultSelectedFields ?? Object.keys(this.fields);\n\n return Object.freeze(fieldNames.map((fieldName) => `${this.resolveField(fieldName)} as ${fieldName}`));\n }\n\n getFromExpression(): string {\n return this.alias ? `${this.table} as ${this.alias}` : this.table;\n }\n}\n\nexport class Join {\n static left(table: string, alias: string): JoinBuilder {\n return new JoinBuilder('left', table, alias);\n }\n\n static inner(table: string, alias: string): JoinBuilder {\n return new JoinBuilder('inner', table, alias);\n }\n}\n\nexport class JoinBuilder {\n constructor(\n private readonly type: SqlJoinType,\n private readonly table: string,\n private readonly alias: string,\n ) {}\n\n onRef(left: string, operator: SqlJoinOperator, right: string): SqlJoin {\n return Object.freeze({\n type: this.type,\n table: normalizeIdentifier(this.table, 'Join table'),\n alias: normalizeIdentifier(this.alias, 'Join alias'),\n on: Object.freeze({\n left: normalizeIdentifier(left, 'Join left reference'),\n operator,\n right: normalizeIdentifier(right, 'Join right reference'),\n }),\n });\n }\n}\n\nfunction normalizeFields(fields: Record<string, string>): Readonly<Record<string, string>> {\n const entries = Object.entries(fields);\n\n if (entries.length === 0) {\n throw new ReadQueryException('ReadSource must define at least one field.');\n }\n\n return Object.freeze(\n Object.fromEntries(\n entries.map(([logical, physical]) => [\n normalizeIdentifier(logical, 'ReadSource logical field'),\n normalizeIdentifier(physical, 'ReadSource physical field'),\n ]),\n ),\n );\n}\n\nfunction normalizeIdentifier(value: string, label: string): string {\n const normalized = value.trim();\n\n if (!normalized) {\n throw new ReadQueryException(`${label} must not be empty.`);\n }\n\n return normalized;\n}\n","import type { Id } from './id';\n\nexport abstract class Entity<TId extends Id> {\n protected constructor(readonly id: TId) {}\n\n equals(other?: Entity<Id> | null): boolean {\n if (other == null) {\n return false;\n }\n\n if (other.constructor !== this.constructor) {\n return false;\n }\n\n return this.id.equals(other.id);\n }\n\n toString(): string {\n return `${this.constructor.name}(${this.id.toString()})`;\n }\n}\n","import type { Id } from '../domain/id';\nimport { Entity } from '../domain/entity';\n\nexport abstract class AuditableEntity<TId extends Id> extends Entity<TId> {\n readonly createdAt: Date;\n updatedAt: Date;\n\n constructor(id: TId, createdAt = new Date(), updatedAt = new Date()) {\n super(id);\n this.createdAt = createdAt;\n this.updatedAt = updatedAt;\n }\n\n protected touch(): void {\n this.updatedAt = new Date();\n }\n}\n","import { Entity } from './entity';\nimport type { Id } from './id';\nimport type { DomainEvent } from './domain-event';\n\nexport abstract class AggregateRoot<TId extends Id> extends Entity<TId> {\n private domainEvents: DomainEvent[] = [];\n\n protected raise(event: DomainEvent): void {\n this.domainEvents.push(event);\n }\n\n pullDomainEvents(): DomainEvent[] {\n const events = [...this.domainEvents];\n this.domainEvents = [];\n return events;\n }\n}\n","import type { Id } from '../domain/id';\nimport { AggregateRoot } from '../domain/aggregate-root';\nimport type { Auditable } from '../domain/auditable';\nimport type { Versionable } from '../domain/versionable';\n\nexport abstract class AuditableAggregateRoot<TId extends Id>\n extends AggregateRoot<TId>\n implements Auditable, Versionable\n{\n readonly createdAt: Date;\n updatedAt: Date;\n version: number;\n\n constructor(id: TId, createdAt = new Date(), updatedAt = new Date(), version = 1) {\n super(id);\n this.createdAt = createdAt;\n this.updatedAt = updatedAt;\n this.version = version;\n }\n\n protected touch(): void {\n this.updatedAt = new Date();\n this.version++;\n }\n}\n","export type ReadonlyDate = Omit<\n Date,\n | 'setTime'\n | 'setMilliseconds'\n | 'setUTCMilliseconds'\n | 'setSeconds'\n | 'setUTCSeconds'\n | 'setMinutes'\n | 'setUTCMinutes'\n | 'setHours'\n | 'setUTCHours'\n | 'setDate'\n | 'setUTCDate'\n | 'setMonth'\n | 'setUTCMonth'\n | 'setFullYear'\n | 'setUTCFullYear'\n>;\n\ntype DeepReadonly<T> = T extends Date\n ? ReadonlyDate\n : T extends readonly (infer Item)[]\n ? ReadonlyArray<DeepReadonly<Item>>\n : T extends object\n ? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }\n : T;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction cloneAndFreeze<T>(value: T): DeepReadonly<T> {\n if (value instanceof Date) {\n return new Date(value.getTime()) as DeepReadonly<T>;\n }\n\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => cloneAndFreeze(item))) as DeepReadonly<T>;\n }\n\n if (isPlainObject(value)) {\n const cloned = Object.keys(value).reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = cloneAndFreeze(value[key]);\n return acc;\n }, {});\n\n return Object.freeze(cloned) as DeepReadonly<T>;\n }\n\n return value as DeepReadonly<T>;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n\n if (a instanceof Date || b instanceof Date) {\n return a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime());\n }\n\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n\n if (a.length !== b.length) {\n return false;\n }\n\n return a.every((item, index) => deepEqual(item, b[index]));\n }\n\n if (!isPlainObject(a) || !isPlainObject(b)) {\n return false;\n }\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n return keysA.every((key) => {\n if (!Object.prototype.hasOwnProperty.call(b, key)) {\n return false;\n }\n\n return deepEqual(a[key], b[key]);\n });\n}\n\nexport abstract class ValueObject<TProps extends Record<string, unknown>> {\n protected readonly props: DeepReadonly<TProps>;\n\n protected constructor(props: TProps) {\n this.props = cloneAndFreeze(props);\n }\n\n equals(other?: ValueObject<TProps>): boolean {\n if (other == null) {\n return false;\n }\n\n if (!(other instanceof this.constructor)) {\n return false;\n }\n\n return deepEqual(this.props, other.props);\n }\n}\n","import { ValueObject } from '../domain/value-object';\n\nexport abstract class PrimitiveValueObject<T> extends ValueObject<{\n value: T;\n}> {\n get value(): T {\n return this.props.value as T;\n }\n\n protected constructor(value: T) {\n super({ value });\n }\n}\n","import { Global, Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { plainToInstance } from 'class-transformer';\nimport { validateSync } from 'class-validator';\nimport { ExiumEnvironment } from './exium-config.schema';\nimport { ExiumConfigService } from './exium-config.service';\n\nfunction validate(config: Record<string, unknown>) {\n const validatedConfig = plainToInstance(ExiumEnvironment, config, {\n enableImplicitConversion: true,\n });\n\n const errors = validateSync(validatedConfig, { skipMissingProperties: false });\n\n if (errors.length > 0) {\n throw new Error(\n `[ExiumFramework] Config Validation Failed! Lutfen .env dosyanizi kontrol edin:\\n${errors\n .map((e) => Object.values(e.constraints || {}).join(', '))\n .join('\\n')}`,\n );\n }\n return validatedConfig;\n}\n\n@Global()\n@Module({\n imports: [\n ConfigModule.forRoot({\n validate,\n isGlobal: true, // Her yerde ExiumConfigService'i inject edilebilir kılar\n }),\n ],\n providers: [ExiumConfigService],\n exports: [ExiumConfigService],\n})\nexport class ExiumConfigModule {}\n","import { Transform } from 'class-transformer';\nimport { IsBoolean, IsOptional, IsString } from 'class-validator';\n\nexport class ExiumEnvironment {\n @IsString()\n @IsOptional()\n EXIUM_DB_URL?: string;\n\n @IsString()\n @IsOptional()\n EXIUM_RABBITMQ_URL?: string;\n\n @IsString()\n @IsOptional()\n EXIUM_REDIS_URL?: string;\n\n @IsString()\n @IsOptional()\n EXIUM_LOG_LEVEL?: string;\n\n @Transform(({ obj }) => obj.EXIUM_LOG_PRETTY === 'true' || obj.EXIUM_LOG_PRETTY === true)\n @IsBoolean()\n @IsOptional()\n EXIUM_LOG_PRETTY?: boolean;\n}\n","import { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { ExiumEnvironment } from './exium-config.schema';\n\n@Injectable()\nexport class ExiumConfigService {\n constructor(private readonly configService: ConfigService<ExiumEnvironment, true>) {}\n\n get isProduction(): boolean {\n return process.env.NODE_ENV === 'production';\n }\n\n get databaseUrl(): string | undefined {\n return this.configService.get('EXIUM_DB_URL', { infer: true });\n }\n\n getRequiredDatabaseUrl(): string {\n const value = this.databaseUrl;\n\n if (!value) {\n throw new Error(\n '[ExiumFramework] EXIUM_DB_URL is required when persistence infrastructure is enabled.',\n );\n }\n\n return value;\n }\n\n get rabbitMqUrl(): string | undefined {\n return this.configService.get('EXIUM_RABBITMQ_URL', { infer: true });\n }\n\n get redisUrl(): string | undefined {\n return this.configService.get('EXIUM_REDIS_URL', { infer: true });\n }\n\n get logLevel(): string | undefined {\n return this.configService.get('EXIUM_LOG_LEVEL', { infer: true });\n }\n\n get logPretty(): boolean | undefined {\n return this.configService.get('EXIUM_LOG_PRETTY', { infer: true });\n }\n}\n","import { DynamicModule, Global, Module, type ModuleMetadata } from '@nestjs/common';\n\nimport { ExiumLoggerModule } from '../logger';\nimport { ExiumConfigModule } from '../config/exium-config.module';\nimport { ExiumApplicationModule } from '../application';\nimport { ExiumHttpModule, type ExiumHttpOptions } from '../http';\nimport { ExiumInfrastructureModule, type ExiumInfrastructureOptions } from '../infrastructure';\n\nexport interface ExiumModuleOptions {\n readonly serviceName: string;\n readonly http?: ExiumHttpOptions;\n readonly infrastructure?: ExiumInfrastructureOptions;\n}\n\n@Global()\n@Module({})\nexport class ExiumModule {\n static forRoot(options: ExiumModuleOptions): DynamicModule {\n const redisCacheEnabled = options.infrastructure?.cache?.driver === 'redis';\n const redisIdempotencyEnabled = options.infrastructure?.idempotency?.driver === 'redis';\n\n const applicationModule = ExiumApplicationModule.forRoot({\n defaults: {\n cacheStore: !redisCacheEnabled,\n cacheVersionService: !redisCacheEnabled,\n idempotencyStore: !redisIdempotencyEnabled,\n },\n });\n\n const imports: NonNullable<ModuleMetadata['imports']> = [ExiumConfigModule, ExiumLoggerModule];\n\n if (options.infrastructure) {\n imports.push(ExiumInfrastructureModule.forRoot(options.infrastructure));\n }\n\n const httpModule = ExiumHttpModule.forRoot(options.http);\n\n imports.push(applicationModule, httpModule);\n\n const exports: NonNullable<DynamicModule['exports']> = [\n 'EXIUM_SERVICE_NAME',\n ExiumConfigModule,\n ExiumLoggerModule,\n applicationModule,\n httpModule,\n ];\n\n if (options.infrastructure) {\n exports.push(ExiumInfrastructureModule);\n }\n\n return {\n module: ExiumModule,\n global: true,\n imports,\n providers: [\n {\n provide: 'EXIUM_SERVICE_NAME',\n useValue: options.serviceName,\n },\n ],\n exports,\n };\n }\n}\n","import { Global, Module } from '@nestjs/common';\nimport { LoggerModule } from 'nestjs-pino';\nimport { IncomingMessage } from 'node:http';\n\nimport { ExiumConfigModule, ExiumConfigService } from '../config';\n\n@Global()\n@Module({\n imports: [\n ExiumConfigModule,\n LoggerModule.forRootAsync({\n imports: [ExiumConfigModule],\n inject: [ExiumConfigService],\n useFactory: (config: ExiumConfigService) => {\n const isProduction = config.isProduction;\n const level = config.logLevel || (isProduction ? 'info' : 'debug');\n const pretty = config.logPretty !== undefined ? config.logPretty : !isProduction;\n\n return {\n pinoHttp: {\n level,\n transport: pretty\n ? {\n target: 'pino-pretty',\n }\n : undefined,\n\n /**\n * HTTP auto logging is disabled.\n * Framework-level interceptors/filters and CQRS logging middlewares\n * are responsible for structured logs.\n */\n autoLogging: false,\n\n serializers: {\n req: (req: IncomingMessage) => ({\n method: req.method,\n url: req.url,\n }),\n },\n },\n };\n },\n }),\n ],\n exports: [LoggerModule],\n})\nexport class ExiumLoggerModule {}\n","export abstract class ApiResponse {\n public success!: boolean;\n public message?: string;\n public timestamp!: string;\n\n constructor(message?: string) {\n this.message = message;\n this.timestamp = new Date().toISOString();\n }\n}\n","import { ApiResponse } from './api.response';\n\nexport class SuccessResult extends ApiResponse {\n constructor(message = 'Operation successful') {\n super(message);\n this.success = true;\n }\n}\n\nexport class SuccessDataResult<T> extends SuccessResult {\n public data: T;\n\n constructor(data: T, message = 'Operation successful') {\n super(message);\n this.data = data;\n }\n}\n\nexport class SuccessListResult<T> extends SuccessResult {\n public data: T[];\n\n constructor(data: T[], message = 'Operation successful') {\n super(message);\n this.data = data;\n }\n}\n\nexport class SuccessPageResult<T> extends SuccessResult {\n public data: T[];\n public meta: {\n total: number;\n page: number;\n size: number;\n totalPages?: number;\n };\n\n constructor(\n data: T[],\n meta: { total: number; page: number; size: number; totalPages?: number },\n message = 'Operation successful',\n ) {\n super(message);\n this.data = data;\n this.meta = meta;\n }\n}\n\nexport class SuccessCursorResult<T> extends SuccessResult {\n public data: T[];\n public meta: {\n nextCursor?: string;\n previousCursor?: string;\n hasNext: boolean;\n hasPrevious: boolean;\n };\n\n constructor(\n data: T[],\n meta: {\n nextCursor?: string;\n previousCursor?: string;\n hasNext: boolean;\n hasPrevious: boolean;\n },\n message = 'Operation successful',\n ) {\n super(message);\n this.data = data;\n this.meta = meta;\n }\n}\n","import { ApiResponse } from './api.response';\nimport type { FailureKind } from '../../foundation';\n\nexport class ErrorResult extends ApiResponse {\n public error: {\n code: string;\n kind?: FailureKind;\n details?: unknown;\n };\n\n constructor(code: string, message: string, details?: unknown, kind?: FailureKind) {\n super(message);\n this.success = false;\n this.error = {\n code,\n details,\n };\n\n if (kind) {\n this.error.kind = kind;\n }\n }\n}\n","import 'reflect-metadata';\n\nexport type HttpApiExposure = 'external' | 'internal';\n\nexport type InternalApiMode = 'auto' | 'local' | 'remote';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\nexport interface HttpApiMetadata {\n readonly exposure: HttpApiExposure;\n readonly name?: string;\n readonly version?: string;\n readonly owner?: string;\n readonly audience?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly internalMode?: InternalApiMode;\n}\n\nexport const EXIUM_HTTP_API_METADATA = Symbol('exium:http-api');\n\nexport function defineHttpApiMetadata(\n metadata: HttpApiMetadata,\n target: object,\n propertyKey?: string | symbol,\n): void {\n if (propertyKey === undefined) {\n Reflect.defineMetadata(EXIUM_HTTP_API_METADATA, metadata, target);\n return;\n }\n\n Reflect.defineMetadata(EXIUM_HTTP_API_METADATA, metadata, target, propertyKey);\n}\n\nexport function getHttpApiMetadata(\n target: object,\n propertyKey?: string | symbol,\n): HttpApiMetadata | undefined {\n if (propertyKey === undefined) {\n return Reflect.getMetadata(EXIUM_HTTP_API_METADATA, target) as HttpApiMetadata | undefined;\n }\n\n return Reflect.getMetadata(EXIUM_HTTP_API_METADATA, target, propertyKey) as\n | HttpApiMetadata\n | undefined;\n}\n","import type { HttpApiMetadata } from '../contracts/http-api-contract';\nimport { defineHttpApiMetadata } from '../contracts/http-api-contract';\n\nexport type ExternalApiOptions = Omit<HttpApiMetadata, 'exposure' | 'internalMode'>;\n\nexport function ExternalApi(options: ExternalApiOptions = {}): ClassDecorator & MethodDecorator {\n return ((target: object, propertyKey?: string | symbol) => {\n defineHttpApiMetadata(\n {\n ...options,\n exposure: 'external',\n },\n target,\n propertyKey,\n );\n }) as ClassDecorator & MethodDecorator;\n}\n","import type { HttpApiMetadata, InternalApiMode } from '../contracts/http-api-contract';\nimport { defineHttpApiMetadata } from '../contracts/http-api-contract';\n\nexport interface InternalApiOptions extends Omit<HttpApiMetadata, 'exposure' | 'internalMode'> {\n readonly mode?: InternalApiMode;\n}\n\nexport function InternalApi(options: InternalApiOptions = {}): ClassDecorator & MethodDecorator {\n return ((target: object, propertyKey?: string | symbol) => {\n defineHttpApiMetadata(\n {\n ...options,\n exposure: 'internal',\n internalMode: options.mode ?? 'auto',\n },\n target,\n propertyKey,\n );\n }) as ClassDecorator & MethodDecorator;\n}\n","import type { InternalApiMode } from './contracts/http-api-contract';\n\nexport const EXIUM_HTTP_OPTIONS = Symbol('exium:http-options');\n\nexport type ExiumHttpAdapter = 'express';\n\nexport interface ExiumHttpHeaderNames {\n readonly requestId: string;\n readonly correlationId: string;\n readonly causationId: string;\n readonly tenantId: string;\n readonly userId: string;\n readonly roles: string;\n readonly permissions: string;\n readonly source: string;\n readonly locale: string;\n}\n\nexport interface ExiumHttpOptions {\n readonly adapter?: ExiumHttpAdapter;\n readonly context?: {\n readonly headerNames?: Partial<ExiumHttpHeaderNames>;\n };\n readonly internalApis?: {\n readonly defaultMode?: InternalApiMode;\n readonly remoteServices?: Record<string, string>;\n };\n}\n\nexport interface ResolvedExiumHttpOptions {\n readonly adapter: ExiumHttpAdapter;\n readonly context: {\n readonly headerNames: ExiumHttpHeaderNames;\n };\n readonly internalApis: {\n readonly defaultMode: InternalApiMode;\n readonly remoteServices: Record<string, string>;\n };\n}\n\nexport const DEFAULT_EXIUM_HTTP_HEADER_NAMES: ExiumHttpHeaderNames = {\n requestId: 'x-request-id',\n correlationId: 'x-correlation-id',\n causationId: 'x-causation-id',\n tenantId: 'x-tenant-id',\n userId: 'x-user-id',\n roles: 'x-user-roles',\n permissions: 'x-user-permissions',\n source: 'x-source',\n locale: 'accept-language',\n};\n\nexport function resolveExiumHttpOptions(options: ExiumHttpOptions = {}): ResolvedExiumHttpOptions {\n return {\n adapter: options.adapter ?? 'express',\n context: {\n headerNames: {\n ...DEFAULT_EXIUM_HTTP_HEADER_NAMES,\n ...(options.context?.headerNames ?? {}),\n },\n },\n internalApis: {\n defaultMode: options.internalApis?.defaultMode ?? 'auto',\n remoteServices: {\n ...(options.internalApis?.remoteServices ?? {}),\n },\n },\n };\n}\n","import { DynamicModule, Global, Module, type Provider } from '@nestjs/common';\nimport { DiscoveryModule } from '@nestjs/core';\n\nimport { EXIUM_HTTP_OPTIONS, resolveExiumHttpOptions, type ExiumHttpOptions } from './http-options';\nimport {\n ConfiguredInternalApiEndpointResolver,\n ExiumHttpDiscoveryService,\n ExiumInternalApiClient,\n ExiumInternalApiEndpointResolver,\n ExiumInternalApiRegistry,\n} from './internal';\n\n@Global()\n@Module({})\nexport class ExiumHttpModule {\n static forRoot(options: ExiumHttpOptions = {}): DynamicModule {\n const resolvedOptions = resolveExiumHttpOptions(options);\n\n const providers: Provider[] = [\n {\n provide: EXIUM_HTTP_OPTIONS,\n useValue: resolvedOptions,\n },\n ExiumInternalApiRegistry,\n ExiumHttpDiscoveryService,\n {\n provide: ExiumInternalApiEndpointResolver,\n useClass: ConfiguredInternalApiEndpointResolver,\n },\n ExiumInternalApiClient,\n ];\n\n return {\n module: ExiumHttpModule,\n global: true,\n imports: [DiscoveryModule],\n providers,\n exports: [\n EXIUM_HTTP_OPTIONS,\n ExiumInternalApiRegistry,\n ExiumInternalApiEndpointResolver,\n ExiumInternalApiClient,\n ],\n };\n }\n}\n","import 'reflect-metadata';\nimport type { ResultType } from '../../foundation';\nimport type { HttpMethod, InternalApiMode } from '../contracts';\n\nexport interface InternalApiHandlerContext {\n readonly sourceServiceName: string;\n readonly targetServiceName: string;\n readonly operation: string;\n readonly mode: Exclude<InternalApiMode, 'auto'>;\n readonly method?: HttpMethod;\n readonly path?: string;\n}\n\nexport interface InternalApiHandler<TRequest = unknown, TResponse = unknown> {\n handle(\n request: TRequest,\n context: InternalApiHandlerContext,\n ): Promise<ResultType<TResponse> | TResponse> | ResultType<TResponse> | TResponse;\n}\n\nexport interface InternalApiHandlerMetadata {\n readonly operation: string;\n readonly serviceName?: string;\n readonly description?: string;\n}\n\nexport const INTERNAL_API_HANDLER_METADATA = Symbol('exium:internal-api-handler');\n\nexport function HandleInternalApi(options: InternalApiHandlerMetadata): ClassDecorator {\n return (target: object) => {\n const operation = options.operation.trim();\n\n if (!operation) {\n throw new Error('[ExiumFramework] Internal API handler operation is required.');\n }\n\n Reflect.defineMetadata(\n INTERNAL_API_HANDLER_METADATA,\n {\n ...options,\n operation,\n serviceName: options.serviceName?.trim() || undefined,\n },\n target,\n );\n };\n}\n\nexport function getInternalApiHandlerMetadata(\n target: object,\n): InternalApiHandlerMetadata | undefined {\n return Reflect.getMetadata(INTERNAL_API_HANDLER_METADATA, target) as\n | InternalApiHandlerMetadata\n | undefined;\n}\n","import { Injectable } from '@nestjs/common';\nimport type { InternalApiHandler, InternalApiHandlerMetadata } from './internal-api-handler';\n\nexport interface RegisteredInternalApiHandler {\n readonly metadata: InternalApiHandlerMetadata;\n readonly handler: InternalApiHandler<any, any>;\n}\n\n@Injectable()\nexport class ExiumInternalApiRegistry {\n private readonly handlers = new Map<string, RegisteredInternalApiHandler>();\n\n register(metadata: InternalApiHandlerMetadata, handler: InternalApiHandler<any, any>): void {\n const key = composeHandlerKey(metadata.serviceName, metadata.operation);\n const existing = this.handlers.get(key);\n\n if (existing?.handler.constructor === handler.constructor) {\n return;\n }\n\n if (existing) {\n throw new Error(\n `[ExiumFramework] Duplicate internal API handler found for \"${metadata.operation}\".`,\n );\n }\n\n this.handlers.set(key, {\n metadata,\n handler,\n });\n }\n\n resolve(serviceName: string, operation: string): RegisteredInternalApiHandler | undefined {\n return (\n this.handlers.get(composeHandlerKey(serviceName, operation)) ??\n this.handlers.get(composeHandlerKey(undefined, operation))\n );\n }\n\n has(serviceName: string, operation: string): boolean {\n return this.resolve(serviceName, operation) !== undefined;\n }\n\n list(): RegisteredInternalApiHandler[] {\n return [...this.handlers.values()];\n }\n}\n\nfunction composeHandlerKey(serviceName: string | undefined, operation: string): string {\n const service = serviceName?.trim() || '*';\n return `${service}:${operation.trim()}`;\n}\n","import { Injectable, OnApplicationBootstrap } from '@nestjs/common';\nimport { DiscoveryService } from '@nestjs/core';\n\nimport { ExiumInternalApiRegistry } from './internal-api-registry';\nimport { getInternalApiHandlerMetadata } from './internal-api-handler';\n\ntype DiscoveredProviderWrapper = {\n instance?: unknown;\n metatype?: Function | null;\n};\n\nfunction hasHandleMethod(instance: unknown): instance is { handle: (...args: any[]) => any } {\n return (\n typeof instance === 'object' &&\n instance !== null &&\n typeof (instance as Record<string, unknown>)['handle'] === 'function'\n );\n}\n\nfunction getProviderTarget(wrapper: DiscoveredProviderWrapper): Function | null {\n if (wrapper.metatype) {\n return wrapper.metatype;\n }\n\n if (wrapper.instance && typeof wrapper.instance === 'object') {\n return wrapper.instance.constructor;\n }\n\n return null;\n}\n\n@Injectable()\nexport class ExiumHttpDiscoveryService implements OnApplicationBootstrap {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly internalApiRegistry: ExiumInternalApiRegistry,\n ) {}\n\n onApplicationBootstrap(): void {\n const providers = this.discovery.getProviders() as DiscoveredProviderWrapper[];\n\n for (const wrapper of providers) {\n const { instance } = wrapper;\n\n if (!instance || typeof instance !== 'object') {\n continue;\n }\n\n const target = getProviderTarget(wrapper);\n\n if (!target) {\n continue;\n }\n\n const metadata = getInternalApiHandlerMetadata(target);\n\n if (!metadata) {\n continue;\n }\n\n if (!hasHandleMethod(instance)) {\n throw new Error(\n `[ExiumFramework] ${target.name} is decorated as an internal API handler ` +\n `but does not implement handle(request, context).`,\n );\n }\n\n this.internalApiRegistry.register(metadata, instance);\n }\n }\n}\n","import { Inject, Injectable } from '@nestjs/common';\n\nimport { EXIUM_HTTP_OPTIONS, type ResolvedExiumHttpOptions } from '../http-options';\n\nexport abstract class ExiumInternalApiEndpointResolver {\n abstract resolve(serviceName: string): Promise<string | undefined> | string | undefined;\n}\n\n@Injectable()\nexport class ConfiguredInternalApiEndpointResolver extends ExiumInternalApiEndpointResolver {\n constructor(\n @Inject(EXIUM_HTTP_OPTIONS)\n private readonly options: ResolvedExiumHttpOptions,\n ) {\n super();\n }\n\n resolve(serviceName: string): string | undefined {\n return this.options.internalApis.remoteServices[serviceName];\n }\n}\n","import { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { ExiumContextService } from '../../application/context';\nimport {\n Failure,\n Result,\n type FailureKind,\n type FailureType,\n type ResultType,\n} from '../../foundation';\nimport type { HttpMethod, InternalApiMode } from '../contracts';\nimport {\n EXIUM_HTTP_OPTIONS,\n resolveExiumHttpOptions,\n type ResolvedExiumHttpOptions,\n} from '../http-options';\nimport { ExiumInternalApiEndpointResolver } from './internal-api-endpoint-resolver';\nimport { ExiumInternalApiRegistry } from './internal-api-registry';\n\nexport type InternalApiQueryScalar = string | number | boolean | null | undefined;\n\nexport type InternalApiQueryValue = InternalApiQueryScalar | readonly InternalApiQueryScalar[];\n\nexport interface InternalApiCall<TRequest = unknown> {\n readonly serviceName: string;\n readonly operation: string;\n readonly mode?: InternalApiMode;\n readonly method?: HttpMethod;\n readonly path?: string;\n readonly query?: Record<string, InternalApiQueryValue>;\n readonly body?: TRequest;\n readonly headers?: Record<string, string>;\n readonly timeoutMs?: number;\n}\n\ninterface ApiErrorEnvelope {\n readonly success: false;\n readonly message?: string;\n readonly error?: {\n readonly kind?: FailureKind;\n readonly code?: string;\n readonly details?: unknown;\n };\n}\n\ninterface ApiSuccessEnvelope<TResult> {\n readonly success: true;\n readonly data?: TResult;\n}\n\ntype ApiEnvelope<TResult> = ApiSuccessEnvelope<TResult> | ApiErrorEnvelope;\n\n@Injectable()\nexport class ExiumInternalApiClient {\n private readonly options: ResolvedExiumHttpOptions;\n\n constructor(\n private readonly registry: ExiumInternalApiRegistry,\n private readonly endpointResolver: ExiumInternalApiEndpointResolver,\n private readonly contextService: ExiumContextService,\n @Optional()\n @Inject('EXIUM_SERVICE_NAME')\n private readonly sourceServiceName = 'unknown-service',\n @Optional()\n @Inject(EXIUM_HTTP_OPTIONS)\n options?: ResolvedExiumHttpOptions,\n ) {\n this.options = options ?? resolveExiumHttpOptions();\n }\n\n async call<TResult, TRequest = unknown>(\n call: InternalApiCall<TRequest>,\n ): Promise<ResultType<TResult>> {\n const mode = call.mode ?? this.options.internalApis.defaultMode;\n\n if (mode === 'local') {\n return this.callLocal<TResult, TRequest>(call);\n }\n\n if (mode === 'remote') {\n return this.callRemote<TResult, TRequest>(call);\n }\n\n if (this.registry.has(call.serviceName, call.operation)) {\n return this.callLocal<TResult, TRequest>(call);\n }\n\n return this.callRemote<TResult, TRequest>(call);\n }\n\n private async callLocal<TResult, TRequest>(\n call: InternalApiCall<TRequest>,\n ): Promise<ResultType<TResult>> {\n const registered = this.registry.resolve(call.serviceName, call.operation);\n\n if (!registered) {\n return Result.fail(\n Failure.notFound(\n 'INTERNAL_API_LOCAL_HANDLER_NOT_FOUND',\n `Local internal API handler was not found for \"${call.operation}\".`,\n {\n serviceName: call.serviceName,\n operation: call.operation,\n },\n ),\n );\n }\n\n const result = await this.contextService.run(\n {\n operationType: 'http',\n operationName: `internal:${call.serviceName}.${call.operation}`,\n source: `internal:${this.sourceServiceName}`,\n },\n async () =>\n registered.handler.handle(call.body, {\n sourceServiceName: this.sourceServiceName,\n targetServiceName: call.serviceName,\n operation: call.operation,\n mode: 'local',\n method: call.method,\n path: call.path,\n }),\n );\n\n if (isResultLike<TResult>(result)) {\n return result;\n }\n\n return Result.ok(result as TResult);\n }\n\n private async callRemote<TResult, TRequest>(\n call: InternalApiCall<TRequest>,\n ): Promise<ResultType<TResult>> {\n const baseUrl = await this.endpointResolver.resolve(call.serviceName);\n\n if (!baseUrl) {\n return Result.fail(\n Failure.notFound(\n 'INTERNAL_API_REMOTE_SERVICE_NOT_CONFIGURED',\n `Remote internal API endpoint was not configured for \"${call.serviceName}\".`,\n {\n serviceName: call.serviceName,\n operation: call.operation,\n },\n ),\n );\n }\n\n if (!call.path?.trim()) {\n return Result.fail(\n Failure.validation(\n 'INTERNAL_API_REMOTE_PATH_REQUIRED',\n `Remote internal API path is required for \"${call.operation}\".`,\n {\n metadata: {\n serviceName: call.serviceName,\n operation: call.operation,\n },\n },\n ),\n );\n }\n\n const method = call.method ?? 'POST';\n const url = buildUrl(baseUrl, call.path, call.query);\n const controller = call.timeoutMs ? new AbortController() : undefined;\n const timeout = controller ? setTimeout(() => controller.abort(), call.timeoutMs) : undefined;\n\n try {\n const response = await fetch(url, {\n method,\n headers: this.createRemoteHeaders(call.headers),\n body: method === 'GET' || call.body === undefined ? undefined : JSON.stringify(call.body),\n signal: controller?.signal,\n });\n\n const responseBody = await readResponseBody<TResult>(response);\n\n if (isApiEnvelope<TResult>(responseBody)) {\n if (responseBody.success) {\n return Result.ok(responseBody.data as TResult);\n }\n\n return Result.fail(toFailureFromEnvelope(response.status, call, responseBody));\n }\n\n if (response.ok) {\n return Result.ok(responseBody as TResult);\n }\n\n return Result.fail(\n toTransportFailure(response.status, call, {\n response: responseBody,\n }),\n );\n } catch (error: unknown) {\n return Result.fail(\n toTransportFailure(503, call, {\n reason: error instanceof Error ? error.message : String(error),\n }),\n );\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n }\n\n private createRemoteHeaders(headers: Record<string, string> = {}): Record<string, string> {\n const context = this.contextService.getOrUndefined();\n const headerNames = this.options.context.headerNames;\n const propagated: Record<string, string> = {\n accept: 'application/json',\n 'content-type': 'application/json',\n [headerNames.source]: this.sourceServiceName,\n };\n\n if (context?.requestId) {\n propagated[headerNames.requestId] = context.requestId;\n }\n\n if (context?.correlationId) {\n propagated[headerNames.correlationId] = context.correlationId;\n }\n\n if (context?.causationId) {\n propagated[headerNames.causationId] = context.causationId;\n }\n\n if (context?.tenantId) {\n propagated[headerNames.tenantId] = context.tenantId;\n }\n\n if (context?.userId) {\n propagated[headerNames.userId] = context.userId;\n }\n\n if (context?.roles?.length) {\n propagated[headerNames.roles] = context.roles.join(',');\n }\n\n if (context?.permissions?.length) {\n propagated[headerNames.permissions] = context.permissions.join(',');\n }\n\n if (context?.locale) {\n propagated[headerNames.locale] = context.locale;\n }\n\n return {\n ...propagated,\n ...headers,\n };\n }\n}\n\nfunction buildUrl(\n baseUrl: string,\n path: string,\n query: Record<string, InternalApiQueryValue> = {},\n): string {\n const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;\n const normalizedPath = path.replace(/^\\/+/, '');\n const url = new URL(normalizedPath, normalizedBaseUrl);\n\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n appendQueryValue(url, key, item);\n }\n continue;\n }\n\n appendQueryValue(url, key, value as InternalApiQueryScalar);\n }\n\n return url.toString();\n}\n\nfunction appendQueryValue(url: URL, key: string, value: InternalApiQueryScalar): void {\n if (value === undefined || value === null) {\n return;\n }\n\n url.searchParams.append(key, String(value));\n}\n\nasync function readResponseBody<TResult>(\n response: Response,\n): Promise<ApiEnvelope<TResult> | unknown> {\n const text = await response.text();\n\n if (!text.trim()) {\n return undefined;\n }\n\n try {\n return JSON.parse(text) as ApiEnvelope<TResult> | unknown;\n } catch {\n return text;\n }\n}\n\nfunction isApiEnvelope<TResult>(value: unknown): value is ApiEnvelope<TResult> {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const candidate = value as Partial<ApiEnvelope<TResult>>;\n\n return candidate.success === true || candidate.success === false;\n}\n\nfunction isResultLike<TResult>(value: unknown): value is ResultType<TResult> {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const candidate = value as {\n type?: unknown;\n isSuccess?: unknown;\n isFailure?: unknown;\n };\n\n return (\n (candidate.type === 'success' || candidate.type === 'failure') &&\n typeof candidate.isSuccess === 'function' &&\n typeof candidate.isFailure === 'function'\n );\n}\n\nfunction toFailureFromEnvelope<TRequest>(\n status: number,\n call: InternalApiCall<TRequest>,\n envelope: ApiErrorEnvelope,\n): FailureType {\n const code = envelope.error?.code ?? 'INTERNAL_API_ERROR';\n const message =\n envelope.message ?? `Internal API \"${call.operation}\" returned an error response.`;\n const kind = envelope.error?.kind ?? statusToFailureKind(status);\n\n return {\n kind,\n code,\n message,\n metadata: toFailureMetadata(envelope.error?.details),\n };\n}\n\nfunction toFailureMetadata(details: unknown): Record<string, unknown> | undefined {\n if (details === undefined) {\n return undefined;\n }\n\n if (details && typeof details === 'object' && !Array.isArray(details)) {\n return details as Record<string, unknown>;\n }\n\n return {\n details,\n };\n}\n\nfunction toTransportFailure<TRequest>(\n status: number,\n call: InternalApiCall<TRequest>,\n metadata: Record<string, unknown>,\n): FailureType {\n return {\n kind: statusToFailureKind(status),\n code: 'INTERNAL_API_REMOTE_CALL_FAILED',\n message: `Remote internal API call failed for \"${call.operation}\".`,\n metadata: {\n serviceName: call.serviceName,\n operation: call.operation,\n status,\n ...metadata,\n },\n };\n}\n\nfunction statusToFailureKind(status: number): FailureKind {\n if (status === 400) {\n return 'validation';\n }\n\n if (status === 401) {\n return 'authentication';\n }\n\n if (status === 403) {\n return 'authorization';\n }\n\n if (status === 404) {\n return 'not_found';\n }\n\n if (status === 409) {\n return 'conflict';\n }\n\n return 'business_rule';\n}\n","import {\n CallHandler,\n ExecutionContext,\n Inject,\n Injectable,\n NestInterceptor,\n Optional,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\nimport { ExiumContextService } from '../../application/context';\nimport {\n EXIUM_HTTP_OPTIONS,\n resolveExiumHttpOptions,\n type ResolvedExiumHttpOptions,\n} from '../http-options';\n\ninterface HttpRequestLike {\n readonly headers?: Record<string, string | string[] | undefined>;\n readonly method?: string;\n readonly path?: string;\n readonly url?: string;\n readonly route?: {\n readonly path?: string;\n };\n}\n\n@Injectable()\nexport class ExiumHttpContextInterceptor implements NestInterceptor {\n private readonly options: ResolvedExiumHttpOptions;\n\n constructor(\n private readonly contextService: ExiumContextService,\n @Optional()\n @Inject(EXIUM_HTTP_OPTIONS)\n options?: ResolvedExiumHttpOptions,\n ) {\n this.options = options ?? resolveExiumHttpOptions();\n }\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n if (context.getType() !== 'http') {\n return next.handle();\n }\n\n const request = context.switchToHttp().getRequest<HttpRequestLike>();\n const executionContext = this.createExecutionContext(request);\n\n return new Observable((subscriber) => {\n const subscription = this.contextService.run(executionContext, () =>\n next.handle().subscribe({\n next: (value) => subscriber.next(value),\n error: (error) => subscriber.error(error),\n complete: () => subscriber.complete(),\n }),\n ) as { unsubscribe(): void };\n\n return () => {\n subscription.unsubscribe();\n };\n });\n }\n\n private createExecutionContext(request: HttpRequestLike) {\n const headers = request.headers ?? {};\n const headerNames = this.options.context.headerNames;\n const method = request.method ?? 'HTTP';\n const route = request.route?.path ?? request.path ?? request.url ?? 'unknown';\n\n return {\n requestId: readHeader(headers, headerNames.requestId),\n correlationId: readHeader(headers, headerNames.correlationId),\n causationId: readHeader(headers, headerNames.causationId),\n tenantId: readHeader(headers, headerNames.tenantId),\n userId: readHeader(headers, headerNames.userId),\n roles: splitHeaderList(readHeader(headers, headerNames.roles)),\n permissions: splitHeaderList(readHeader(headers, headerNames.permissions)),\n locale: readHeader(headers, headerNames.locale),\n source: readHeader(headers, headerNames.source) ?? 'http',\n operationType: 'http' as const,\n operationName: `${method.toUpperCase()} ${route}`,\n startedAt: new Date(),\n };\n }\n}\n\nfunction readHeader(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const value =\n headers[name] ??\n headers[name.toLowerCase()] ??\n Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];\n\n if (Array.isArray(value)) {\n return value[0];\n }\n\n return value;\n}\n\nfunction splitHeaderList(value: string | undefined): readonly string[] | undefined {\n if (!value) {\n return undefined;\n }\n\n const values = value\n .split(',')\n .map((item) => item.trim())\n .filter(Boolean);\n\n return values.length > 0 ? values : undefined;\n}\n","import {\n CallHandler,\n ExecutionContext,\n HttpStatus,\n Injectable,\n NestInterceptor,\n} from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { ApiResponse } from '../responses/api.response';\nimport { ErrorResult } from '../responses/error.response';\nimport {\n SuccessResult,\n SuccessDataResult,\n SuccessListResult,\n SuccessPageResult,\n SuccessCursorResult,\n} from '../responses/success.response';\nimport { Page, CursorPage } from '../../application/read';\nimport type { FailureType } from '../../foundation';\n\ntype ResultLike =\n | {\n readonly type: 'success';\n readonly value: unknown;\n isSuccess(): boolean;\n isFailure(): boolean;\n }\n | {\n readonly type: 'failure';\n readonly error: FailureType;\n isSuccess(): boolean;\n isFailure(): boolean;\n };\n\n@Injectable()\nexport class ExiumResponseInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n return next.handle().pipe(\n map((data) => {\n if (isResultLike(data)) {\n if (data.type === 'failure') {\n const response = context.switchToHttp().getResponse<any>();\n\n if (typeof response.status === 'function') {\n response.status(toHttpStatus(data.error));\n }\n\n return new ErrorResult(\n data.error.code,\n data.error.message,\n toFailureDetails(data.error),\n data.error.kind,\n );\n }\n\n return this.wrapSuccess(data.value);\n }\n\n return this.wrapSuccess(data);\n }),\n );\n }\n\n private wrapSuccess(data: unknown): ApiResponse {\n // If the controller manually returns a standard envelope (e.g. SuccessPageResult), return as is.\n if (data instanceof ApiResponse) {\n return data;\n }\n\n // If the endpoint is void/empty\n if (data === undefined || data === null) {\n return new SuccessResult();\n }\n\n // Auto-wrap read-side Page\n if (data instanceof Page) {\n return new SuccessPageResult([...data.items], {\n total: data.totalItems,\n page: data.page,\n size: data.size,\n totalPages: data.totalPages,\n });\n }\n\n // Auto-wrap read-side CursorPage\n if (data instanceof CursorPage) {\n return new SuccessCursorResult([...data.items], {\n nextCursor: data.nextCursor,\n previousCursor: data.previousCursor,\n hasNext: data.hasNext,\n hasPrevious: data.hasPrevious,\n });\n }\n\n // Auto-wrap pure Arrays\n if (Array.isArray(data)) {\n return new SuccessListResult(data);\n }\n\n // Automatically wrap pure DTOs/primitives\n return new SuccessDataResult(data);\n }\n}\n\nfunction isResultLike(value: unknown): value is ResultLike {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const candidate = value as Partial<ResultLike>;\n\n return (\n (candidate.type === 'success' || candidate.type === 'failure') &&\n typeof candidate.isSuccess === 'function' &&\n typeof candidate.isFailure === 'function'\n );\n}\n\nfunction toHttpStatus(failure: FailureType): number {\n switch (failure.kind) {\n case 'validation':\n return HttpStatus.BAD_REQUEST;\n case 'authentication':\n return HttpStatus.UNAUTHORIZED;\n case 'authorization':\n return HttpStatus.FORBIDDEN;\n case 'not_found':\n return HttpStatus.NOT_FOUND;\n case 'conflict':\n case 'idempotency':\n return HttpStatus.CONFLICT;\n case 'business_rule':\n return HttpStatus.UNPROCESSABLE_ENTITY;\n case 'internal':\n return HttpStatus.INTERNAL_SERVER_ERROR;\n }\n}\n\nfunction toFailureDetails(failure: FailureType): Record<string, unknown> | undefined {\n if (failure.field) {\n return {\n ...(failure.metadata ?? {}),\n field: failure.field,\n };\n }\n\n return failure.metadata;\n}\n","import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';\nimport { Logger } from 'nestjs-pino';\nimport { ErrorResult } from '../responses/error.response';\nimport type { FailureKind } from '../../foundation';\n\n/**\n * Exception policy:\n *\n * - Thrown exceptions represent unexpected failures (programmer errors,\n * infrastructure faults). They are logged and surfaced as HTTP 500 with a\n * generic message — internal details never leak to clients.\n * - Expected business failures must be returned as `Result.fail(Failure...)`,\n * which the response interceptor maps to the appropriate 4xx status.\n *\n * `HttpException` is the only exception with a meaningful HTTP status — it is\n * preserved for compatibility with NestJS pipes (e.g. ValidationPipe) and any\n * controller-level redirect/throw semantics.\n */\n@Catch()\nexport class ExiumExceptionFilter implements ExceptionFilter {\n constructor(private readonly logger?: Logger) {}\n\n catch(exception: unknown, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<any>();\n\n if (exception instanceof HttpException) {\n const status = exception.getStatus();\n const body = exception.getResponse();\n const message = typeof body === 'string' ? body : (body as any)?.message ?? exception.message;\n const details = typeof body === 'string' ? undefined : (body as any)?.error;\n\n const errorResponse = new ErrorResult(\n 'HTTP_ERROR',\n Array.isArray(message) ? message.join(', ') : String(message),\n details,\n toFailureKind(status),\n );\n\n if (typeof response.status === 'function') {\n response.status(status).json(errorResponse);\n }\n return;\n }\n\n if (this.logger) {\n this.logger.error(\n exception instanceof Error ? exception : { exception },\n exception instanceof Error\n ? `Unhandled exception: ${exception.message}`\n : `Unknown exception thrown: ${String(exception)}`,\n );\n } else {\n console.error(exception);\n }\n\n const errorResponse = new ErrorResult(\n 'INTERNAL_ERROR',\n 'Internal server error.',\n undefined,\n 'internal',\n );\n\n if (typeof response.status === 'function') {\n response.status(HttpStatus.INTERNAL_SERVER_ERROR).json(errorResponse);\n }\n }\n}\n\nfunction toFailureKind(status: number): FailureKind {\n if (status >= 500) {\n return 'internal';\n }\n\n switch (status) {\n case HttpStatus.BAD_REQUEST:\n return 'validation';\n case HttpStatus.UNAUTHORIZED:\n return 'authentication';\n case HttpStatus.FORBIDDEN:\n return 'authorization';\n case HttpStatus.NOT_FOUND:\n return 'not_found';\n case HttpStatus.CONFLICT:\n return 'conflict';\n default:\n return 'business_rule';\n }\n}\n","import { DynamicModule, Module } from '@nestjs/common';\n\nimport { ExiumCacheInfrastructureModule, type ExiumCacheInfrastructureOptions } from './cache';\n\nimport {\n ExiumIdempotencyInfrastructureModule,\n type ExiumIdempotencyInfrastructureOptions,\n} from './idempotency';\n\nimport { ExiumMessagingModule, type ExiumMessagingOptions } from './messaging';\nimport { ExiumPersistenceModule, type ExiumPersistenceOptions } from './persistence';\nimport { ExiumRedisModule, type ExiumRedisOptionsInput } from './redis';\n\nexport interface ExiumInfrastructureOptions {\n readonly messaging?: ExiumMessagingOptions;\n readonly persistence?: ExiumPersistenceOptions;\n readonly redis?: ExiumRedisOptionsInput;\n readonly cache?: ExiumCacheInfrastructureOptions;\n readonly idempotency?: ExiumIdempotencyInfrastructureOptions;\n}\n\n@Module({})\nexport class ExiumInfrastructureModule {\n static forRoot(options: ExiumInfrastructureOptions = {}): DynamicModule {\n const imports: DynamicModule[] = [];\n\n const persistenceOutboxEnabled = options.persistence\n ? (options.persistence.outbox?.enabled ?? true)\n : false;\n\n const redisRequired =\n options.redis !== undefined ||\n options.cache?.driver === 'redis' ||\n options.idempotency?.driver === 'redis';\n\n /**\n * Redis is a shared infrastructure dependency.\n *\n * Cache and idempotency adapters reuse this module instead of creating\n * their own Redis clients.\n */\n if (redisRequired) {\n imports.push(ExiumRedisModule.forRoot(options.redis ?? {}));\n }\n\n if (options.cache) {\n imports.push(ExiumCacheInfrastructureModule.forRoot(options.cache));\n }\n\n if (options.idempotency) {\n imports.push(ExiumIdempotencyInfrastructureModule.forRoot(options.idempotency));\n }\n\n /**\n * Messaging must be imported before persistence when outbox is enabled.\n *\n * OutboxPublisher depends on IntegrationMessagePublisher.\n * If no messaging options are provided, noop messaging is registered.\n */\n if (options.messaging || persistenceOutboxEnabled) {\n imports.push(ExiumMessagingModule.forRoot(options.messaging ?? {}));\n }\n\n if (options.persistence) {\n imports.push(ExiumPersistenceModule.forRoot(options.persistence));\n }\n\n return {\n module: ExiumInfrastructureModule,\n imports,\n exports: imports,\n };\n }\n}\n","import { DynamicModule, Global, Module, type Provider } from '@nestjs/common';\n\nimport { CacheStore, CacheVersionService } from '../../application/cache';\n\nimport { RedisCacheStore } from './redis-cache-store';\nimport { RedisCacheVersionService } from './redis-cache-version.service';\n\nexport type ExiumCacheInfrastructureDriver = 'redis';\n\nexport interface ExiumCacheInfrastructureOptions {\n readonly driver?: ExiumCacheInfrastructureDriver;\n}\n\n@Global()\n@Module({})\nexport class ExiumCacheInfrastructureModule {\n static forRoot(options: ExiumCacheInfrastructureOptions = {}): DynamicModule {\n const driver = options.driver ?? 'redis';\n\n if (driver !== 'redis') {\n throw new Error(`[ExiumFramework] Unsupported cache infrastructure driver: ${driver}`);\n }\n\n const providers: Provider[] = [\n RedisCacheStore,\n RedisCacheVersionService,\n\n {\n provide: CacheStore,\n useExisting: RedisCacheStore,\n },\n {\n provide: CacheVersionService,\n useExisting: RedisCacheVersionService,\n },\n ];\n\n return {\n module: ExiumCacheInfrastructureModule,\n global: true,\n providers,\n exports: [CacheStore, CacheVersionService, RedisCacheStore, RedisCacheVersionService],\n };\n }\n}\n","import { Inject, Injectable } from '@nestjs/common';\nimport type Redis from 'ioredis';\n\nimport { CacheStore, type CacheGetResult, type CacheSetOptions } from '../../application/cache';\n\nimport { EXIUM_REDIS_CLIENT, EXIUM_REDIS_OPTIONS, type ExiumRedisOptions } from '../redis';\n\ninterface RedisCacheEnvelope<T> {\n readonly value: T;\n}\n\n@Injectable()\nexport class RedisCacheStore extends CacheStore {\n constructor(\n @Inject(EXIUM_REDIS_CLIENT)\n private readonly redis: Redis,\n\n @Inject(EXIUM_REDIS_OPTIONS)\n private readonly options: ExiumRedisOptions,\n ) {\n super();\n }\n\n async get<T>(key: string): Promise<CacheGetResult<T>> {\n const raw = await this.redis.get(this.toPhysicalKey(key));\n\n if (raw === null) {\n return {\n hit: false,\n };\n }\n\n try {\n const envelope = JSON.parse(raw) as RedisCacheEnvelope<T>;\n\n return {\n hit: true,\n value: envelope.value,\n };\n } catch {\n await this.delete(key);\n\n return {\n hit: false,\n };\n }\n }\n\n async set<T>(key: string, value: T, options?: CacheSetOptions): Promise<void> {\n const physicalKey = this.toPhysicalKey(key);\n const payload = JSON.stringify({\n value,\n } satisfies RedisCacheEnvelope<T>);\n\n const ttlSeconds = options?.ttlSeconds;\n\n if (ttlSeconds !== undefined && ttlSeconds > 0) {\n await this.redis.set(physicalKey, payload, 'EX', ttlSeconds);\n return;\n }\n\n await this.redis.set(physicalKey, payload);\n }\n\n async delete(key: string): Promise<void> {\n await this.redis.del(this.toPhysicalKey(key));\n }\n\n async deleteByPrefix(prefix: string): Promise<void> {\n const physicalPrefix = this.toPhysicalKey(prefix);\n const pattern = `${physicalPrefix}*`;\n\n let cursor = '0';\n\n do {\n const [nextCursor, keys] = await this.redis.scan(cursor, 'MATCH', pattern, 'COUNT', 500);\n\n cursor = nextCursor;\n\n if (keys.length > 0) {\n await this.redis.del(...keys);\n }\n } while (cursor !== '0');\n }\n\n private toPhysicalKey(key: string): string {\n return `${this.options.keyPrefix ?? ''}${key}`;\n }\n}\n","import { DynamicModule, Global, Module, type Provider } from '@nestjs/common';\n\nimport { ExiumConfigModule } from '../../config/exium-config.module';\nimport { ExiumConfigService } from '../../config/exium-config.service';\n\nimport { ExiumRedisClient } from './redis-client.provider';\nimport {\n EXIUM_REDIS_CLIENT,\n EXIUM_REDIS_OPTIONS,\n normalizeExiumRedisOptions,\n type ExiumRedisOptionsInput,\n} from './redis-options';\n\n@Global()\n@Module({})\nexport class ExiumRedisModule {\n static forRoot(options: ExiumRedisOptionsInput = {}): DynamicModule {\n const providers: Provider[] = [\n {\n provide: EXIUM_REDIS_OPTIONS,\n inject: [ExiumConfigService],\n useFactory: (config: ExiumConfigService) =>\n normalizeExiumRedisOptions({\n ...options,\n url: options.url ?? config.redisUrl,\n }),\n },\n\n ExiumRedisClient,\n\n {\n provide: EXIUM_REDIS_CLIENT,\n inject: [ExiumRedisClient],\n useFactory: (client: ExiumRedisClient) => client.native,\n },\n ];\n\n return {\n module: ExiumRedisModule,\n global: true,\n imports: [ExiumConfigModule],\n providers,\n exports: [EXIUM_REDIS_OPTIONS, EXIUM_REDIS_CLIENT, ExiumRedisClient],\n };\n }\n}\n","import { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport Redis from 'ioredis';\n\nimport { EXIUM_REDIS_OPTIONS, type ExiumRedisOptions } from './redis-options';\n\n@Injectable()\nexport class ExiumRedisClient implements OnApplicationShutdown {\n private client?: Redis;\n\n constructor(\n @Inject(EXIUM_REDIS_OPTIONS)\n private readonly options: ExiumRedisOptions,\n ) {}\n\n get native(): Redis {\n if (!this.client) {\n this.client = new Redis(this.options.url, {\n connectTimeout: this.options.connectTimeoutMs,\n lazyConnect: this.options.lazyConnect,\n maxRetriesPerRequest: this.options.maxRetriesPerRequest,\n enableOfflineQueue: this.options.enableOfflineQueue,\n });\n }\n\n return this.client;\n }\n\n async ping(): Promise<string> {\n return this.native.ping();\n }\n\n async onApplicationShutdown(): Promise<void> {\n const client = this.client;\n\n if (!client) {\n return;\n }\n\n this.client = undefined;\n\n try {\n await client.quit();\n } catch {\n client.disconnect();\n }\n }\n}\n","export const EXIUM_REDIS_OPTIONS = Symbol('exium:redis-options');\nexport const EXIUM_REDIS_CLIENT = Symbol('exium:redis-client');\n\nexport interface ExiumRedisOptions {\n readonly url: string;\n\n /**\n * Application-level Redis key prefix.\n *\n * This is intentionally not passed to ioredis as native keyPrefix.\n * Framework adapters apply it manually so scan/delete-by-prefix behavior\n * stays deterministic.\n */\n readonly keyPrefix?: string;\n\n readonly connectTimeoutMs: number;\n readonly lazyConnect: boolean;\n readonly maxRetriesPerRequest: number;\n readonly enableOfflineQueue: boolean;\n}\n\nexport type ExiumRedisOptionsInput = Partial<ExiumRedisOptions>;\n\nexport const DEFAULT_EXIUM_REDIS_OPTIONS: Omit<ExiumRedisOptions, 'url'> = {\n connectTimeoutMs: 10_000,\n lazyConnect: true,\n maxRetriesPerRequest: 3,\n enableOfflineQueue: true,\n};\n\nexport function normalizeExiumRedisOptions(input: ExiumRedisOptionsInput = {}): ExiumRedisOptions {\n const url = input.url?.trim();\n\n if (!url) {\n throw new Error(\n '[ExiumFramework] Redis url is required when Redis infrastructure is enabled. ' +\n 'Provide infrastructure.redis.url or EXIUM_REDIS_URL.',\n );\n }\n\n const keyPrefix = normalizeKeyPrefix(input.keyPrefix);\n\n const options: ExiumRedisOptions = {\n url,\n keyPrefix,\n connectTimeoutMs: input.connectTimeoutMs ?? DEFAULT_EXIUM_REDIS_OPTIONS.connectTimeoutMs,\n lazyConnect: input.lazyConnect ?? DEFAULT_EXIUM_REDIS_OPTIONS.lazyConnect,\n maxRetriesPerRequest:\n input.maxRetriesPerRequest ?? DEFAULT_EXIUM_REDIS_OPTIONS.maxRetriesPerRequest,\n enableOfflineQueue: input.enableOfflineQueue ?? DEFAULT_EXIUM_REDIS_OPTIONS.enableOfflineQueue,\n };\n\n assertPositiveInteger(options.connectTimeoutMs, 'connectTimeoutMs');\n assertPositiveInteger(options.maxRetriesPerRequest, 'maxRetriesPerRequest');\n\n return options;\n}\n\nfunction normalizeKeyPrefix(value: string | undefined): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const trimmed = value.trim();\n\n if (!trimmed) {\n throw new Error('[ExiumFramework] Redis keyPrefix must not be empty.');\n }\n\n return trimmed;\n}\n\nfunction assertPositiveInteger(value: number, propertyName: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(`[ExiumFramework] Redis ${propertyName} must be a positive integer.`);\n }\n}\n","import { Inject, Injectable } from '@nestjs/common';\nimport type Redis from 'ioredis';\n\nimport { CacheVersionService } from '../../application/cache';\n\nimport { EXIUM_REDIS_CLIENT, EXIUM_REDIS_OPTIONS, type ExiumRedisOptions } from '../redis';\n\n@Injectable()\nexport class RedisCacheVersionService extends CacheVersionService {\n constructor(\n @Inject(EXIUM_REDIS_CLIENT)\n private readonly redis: Redis,\n\n @Inject(EXIUM_REDIS_OPTIONS)\n private readonly options: ExiumRedisOptions,\n ) {\n super();\n }\n\n async getVersion(namespace: string): Promise<number> {\n const value = await this.redis.get(this.createVersionKey(namespace));\n\n if (value === null) {\n return 1;\n }\n\n const parsed = Number(value);\n\n if (!Number.isInteger(parsed) || parsed <= 0) {\n return 1;\n }\n\n return parsed;\n }\n\n async bumpVersion(namespace: string): Promise<number> {\n const key = this.createVersionKey(namespace);\n\n const result = await this.redis.eval(\n `\n local current = redis.call(\"GET\", KEYS[1])\n\n if not current then\n redis.call(\"SET\", KEYS[1], \"2\")\n return 2\n end\n\n return redis.call(\"INCR\", KEYS[1])\n `,\n 1,\n key,\n );\n\n return Number(result);\n }\n\n private createVersionKey(namespace: string): string {\n return this.toPhysicalKey(`exium:cache-version:${namespace}`);\n }\n\n private toPhysicalKey(key: string): string {\n return `${this.options.keyPrefix ?? ''}${key}`;\n }\n}\n","import { DynamicModule, Global, Module, type Provider } from '@nestjs/common';\n\nimport { IdempotencyStore } from '../../application/idempotency';\n\nimport { RedisIdempotencyStore } from './redis-idempotency-store';\n\nexport type ExiumIdempotencyInfrastructureDriver = 'redis';\n\nexport interface ExiumIdempotencyInfrastructureOptions {\n readonly driver?: ExiumIdempotencyInfrastructureDriver;\n}\n\n@Global()\n@Module({})\nexport class ExiumIdempotencyInfrastructureModule {\n static forRoot(options: ExiumIdempotencyInfrastructureOptions = {}): DynamicModule {\n const driver = options.driver ?? 'redis';\n\n if (driver !== 'redis') {\n throw new Error(`[ExiumFramework] Unsupported idempotency infrastructure driver: ${driver}`);\n }\n\n const providers: Provider[] = [\n RedisIdempotencyStore,\n\n {\n provide: IdempotencyStore,\n useExisting: RedisIdempotencyStore,\n },\n ];\n\n return {\n module: ExiumIdempotencyInfrastructureModule,\n global: true,\n providers,\n exports: [IdempotencyStore, RedisIdempotencyStore],\n };\n }\n}\n","import { Inject, Injectable } from '@nestjs/common';\nimport type Redis from 'ioredis';\n\nimport {\n IdempotencyStore,\n type IdempotencyBeginInput,\n type IdempotencyBeginResult,\n type IdempotencyCompleteInput,\n type IdempotencyFailInput,\n} from '../../application/idempotency';\n\nimport { EXIUM_REDIS_CLIENT, EXIUM_REDIS_OPTIONS, type ExiumRedisOptions } from '../redis';\n\ntype RedisIdempotencyStatus = 'started' | 'completed' | 'failed';\n\ninterface RedisIdempotencyRecord<TResult = unknown> {\n readonly status: RedisIdempotencyStatus;\n readonly scope: string;\n readonly key: string;\n readonly fingerprint: string;\n readonly operationName: string;\n readonly startedAt: string;\n readonly completedAt?: string;\n readonly failedAt?: string;\n readonly result?: TResult;\n readonly error?: string;\n}\n\n@Injectable()\nexport class RedisIdempotencyStore extends IdempotencyStore {\n constructor(\n @Inject(EXIUM_REDIS_CLIENT)\n private readonly redis: Redis,\n\n @Inject(EXIUM_REDIS_OPTIONS)\n private readonly options: ExiumRedisOptions,\n ) {\n super();\n }\n\n async begin<TResult = unknown>(\n input: IdempotencyBeginInput,\n ): Promise<IdempotencyBeginResult<TResult>> {\n const physicalKey = this.createPhysicalKey(input.scope, input.key);\n\n const record: RedisIdempotencyRecord = {\n status: 'started',\n scope: input.scope,\n key: input.key,\n fingerprint: input.fingerprint,\n operationName: input.operationName,\n startedAt: input.startedAt.toISOString(),\n };\n\n const created = await this.redis.set(\n physicalKey,\n JSON.stringify(record),\n 'EX',\n input.ttlSeconds,\n 'NX',\n );\n\n if (created === 'OK') {\n return {\n status: 'started',\n };\n }\n\n const existing = await this.readRecord<TResult>(physicalKey);\n\n if (!existing) {\n /**\n * Rare race: key existed during SET NX but expired before GET.\n * Retrying once keeps behavior deterministic enough without looping.\n */\n const retryCreated = await this.redis.set(\n physicalKey,\n JSON.stringify(record),\n 'EX',\n input.ttlSeconds,\n 'NX',\n );\n\n if (retryCreated === 'OK') {\n return {\n status: 'started',\n };\n }\n\n return {\n status: 'in_progress',\n };\n }\n\n if (existing.fingerprint !== input.fingerprint) {\n return {\n status: 'conflict',\n existingFingerprint: existing.fingerprint,\n incomingFingerprint: input.fingerprint,\n };\n }\n\n if (existing.status === 'completed') {\n return {\n status: 'completed',\n result: existing.result as TResult,\n };\n }\n\n return {\n status: 'in_progress',\n };\n }\n\n async complete<TResult = unknown>(input: IdempotencyCompleteInput<TResult>): Promise<void> {\n const physicalKey = this.createPhysicalKey(input.scope, input.key);\n const existing = await this.readRecord<TResult>(physicalKey);\n\n if (!existing) {\n return;\n }\n\n const ttlSeconds = await this.redis.ttl(physicalKey);\n\n const completed: RedisIdempotencyRecord<TResult> = {\n ...existing,\n status: 'completed',\n completedAt: input.completedAt.toISOString(),\n result: input.result,\n };\n\n await this.writePreservingTtl(physicalKey, completed, ttlSeconds);\n }\n\n async fail(input: IdempotencyFailInput): Promise<void> {\n const physicalKey = this.createPhysicalKey(input.scope, input.key);\n const existing = await this.readRecord(physicalKey);\n\n if (!existing) {\n return;\n }\n\n const ttlSeconds = await this.redis.ttl(physicalKey);\n\n const failed: RedisIdempotencyRecord = {\n ...existing,\n status: 'failed',\n failedAt: input.failedAt.toISOString(),\n error: normalizeError(input.error),\n };\n\n await this.writePreservingTtl(physicalKey, failed, ttlSeconds);\n }\n\n private async readRecord<TResult = unknown>(\n physicalKey: string,\n ): Promise<RedisIdempotencyRecord<TResult> | null> {\n const raw = await this.redis.get(physicalKey);\n\n if (raw === null) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as RedisIdempotencyRecord<TResult>;\n\n if (!isValidRecord(parsed)) {\n await this.redis.del(physicalKey);\n return null;\n }\n\n return parsed;\n } catch {\n await this.redis.del(physicalKey);\n return null;\n }\n }\n\n private async writePreservingTtl(\n physicalKey: string,\n record: RedisIdempotencyRecord,\n ttlSeconds: number,\n ): Promise<void> {\n const payload = JSON.stringify(record);\n\n if (ttlSeconds > 0) {\n await this.redis.set(physicalKey, payload, 'EX', ttlSeconds);\n return;\n }\n\n /**\n * ttl === -1 means key exists without expiry.\n * ttl === -2 means key no longer exists.\n *\n * For -2 we intentionally do nothing to avoid resurrecting expired records.\n */\n if (ttlSeconds === -1) {\n await this.redis.set(physicalKey, payload);\n }\n }\n\n private createPhysicalKey(scope: string, key: string): string {\n return this.toPhysicalKey(`exium:idempotency:${safeKeyPart(scope)}:${safeKeyPart(key)}`);\n }\n\n private toPhysicalKey(key: string): string {\n return `${this.options.keyPrefix ?? ''}${key}`;\n }\n}\n\nfunction isValidRecord(value: unknown): value is RedisIdempotencyRecord {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const record = value as Partial<RedisIdempotencyRecord>;\n\n return (\n (record.status === 'started' || record.status === 'completed' || record.status === 'failed') &&\n typeof record.scope === 'string' &&\n typeof record.key === 'string' &&\n typeof record.fingerprint === 'string' &&\n typeof record.operationName === 'string' &&\n typeof record.startedAt === 'string'\n );\n}\n\nfunction safeKeyPart(value: string): string {\n return encodeURIComponent(value);\n}\n\nfunction normalizeError(error: unknown): string {\n if (error instanceof Error) {\n return `${error.name}: ${error.message}`;\n }\n\n return String(error);\n}\n","export interface IntegrationMessageEnvelope {\n readonly id: string;\n readonly name: string;\n readonly version: number;\n readonly occurredAt: Date;\n readonly payload: Record<string, unknown>;\n}\n\nexport abstract class IntegrationMessagePublisher {\n abstract publish(message: IntegrationMessageEnvelope): Promise<void>;\n}\n","import { Injectable } from '@nestjs/common';\n\nimport {\n IntegrationMessagePublisher,\n type IntegrationMessageEnvelope,\n} from './integration-message-publisher';\n\n@Injectable()\nexport class NoopIntegrationMessagePublisher extends IntegrationMessagePublisher {\n async publish(message: IntegrationMessageEnvelope): Promise<void> {\n throw new Error(\n `[ExiumFramework] Cannot publish integration message \"${message.name}\" ` +\n `because no IntegrationMessagePublisher is configured.`,\n );\n }\n}\n","import { DynamicModule, Global, Module, type Provider } from '@nestjs/common';\n\nimport { ExiumConfigModule } from '../../config/exium-config.module';\nimport { ExiumConfigService } from '../../config/exium-config.service';\n\nimport { IntegrationMessagePublisher } from './integration-message-publisher';\nimport { NoopIntegrationMessagePublisher } from './noop-integration-message-publisher';\n\nimport {\n RABBITMQ_OPTIONS,\n normalizeRabbitMqOptions,\n type RabbitMqOptionsInput,\n} from './rabbitmq/rabbitmq-options';\n\nimport { RabbitMqIntegrationMessagePublisher } from './rabbitmq/rabbitmq-integration-message-publisher';\n\nexport type ExiumMessagingDriver = 'noop' | 'rabbitmq';\n\nexport interface ExiumMessagingOptions {\n readonly driver?: ExiumMessagingDriver;\n readonly rabbitmq?: RabbitMqOptionsInput;\n}\n\n@Global()\n@Module({})\nexport class ExiumMessagingModule {\n static forRoot(options: ExiumMessagingOptions = {}): DynamicModule {\n const driver = options.driver ?? 'noop';\n\n const providers: Provider[] = [];\n\n if (driver === 'noop') {\n providers.push({\n provide: IntegrationMessagePublisher,\n useClass: NoopIntegrationMessagePublisher,\n });\n } else if (driver === 'rabbitmq') {\n providers.push(\n {\n provide: RABBITMQ_OPTIONS,\n inject: [ExiumConfigService],\n useFactory: (config: ExiumConfigService) =>\n normalizeRabbitMqOptions({\n ...options.rabbitmq,\n url: options.rabbitmq?.url ?? config.rabbitMqUrl,\n }),\n },\n RabbitMqIntegrationMessagePublisher,\n {\n provide: IntegrationMessagePublisher,\n useExisting: RabbitMqIntegrationMessagePublisher,\n },\n );\n } else {\n throw new Error(`[ExiumFramework] Unsupported messaging driver: ${driver}`);\n }\n\n return {\n module: ExiumMessagingModule,\n global: true,\n imports: [ExiumConfigModule],\n providers,\n exports: [\n IntegrationMessagePublisher,\n ...(driver === 'rabbitmq' ? [RABBITMQ_OPTIONS, RabbitMqIntegrationMessagePublisher] : []),\n ],\n };\n }\n}\n","export const RABBITMQ_OPTIONS = Symbol('exium:rabbitmq-options');\n\nexport type RabbitMqExchangeType = 'topic' | 'direct' | 'fanout';\n\nexport interface RabbitMqOptions {\n readonly url: string;\n readonly exchange: string;\n readonly exchangeType: RabbitMqExchangeType;\n readonly routingKey?: string;\n readonly durable: boolean;\n readonly persistent: boolean;\n}\n\nexport type RabbitMqOptionsInput = Partial<RabbitMqOptions>;\n\nexport const DEFAULT_RABBITMQ_OPTIONS: Omit<RabbitMqOptions, 'url'> = {\n exchange: 'exium.integration-events',\n exchangeType: 'topic',\n durable: true,\n persistent: true,\n};\n\nexport function normalizeRabbitMqOptions(input: RabbitMqOptionsInput): RabbitMqOptions {\n const url = input.url?.trim();\n\n if (!url) {\n throw new Error(\n '[ExiumFramework] RabbitMQ url is required when messaging.driver is \"rabbitmq\". ' +\n 'Provide options.messaging.rabbitmq.url or EXIUM_RABBITMQ_URL.',\n );\n }\n\n const exchange = input.exchange?.trim() || DEFAULT_RABBITMQ_OPTIONS.exchange;\n\n const exchangeType = input.exchangeType ?? DEFAULT_RABBITMQ_OPTIONS.exchangeType;\n\n if (!['topic', 'direct', 'fanout'].includes(exchangeType)) {\n throw new Error(`[ExiumFramework] Unsupported RabbitMQ exchangeType: ${exchangeType}`);\n }\n\n const routingKey = input.routingKey?.trim();\n\n return {\n url,\n exchange,\n exchangeType,\n routingKey,\n durable: input.durable ?? DEFAULT_RABBITMQ_OPTIONS.durable,\n persistent: input.persistent ?? DEFAULT_RABBITMQ_OPTIONS.persistent,\n };\n}\n","import { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { connect, type ChannelModel, type ConfirmChannel, type Options } from 'amqplib';\n\nimport {\n IntegrationMessagePublisher,\n type IntegrationMessageEnvelope,\n} from '../integration-message-publisher';\n\nimport { RABBITMQ_OPTIONS, type RabbitMqOptions } from './rabbitmq-options';\n\n@Injectable()\nexport class RabbitMqIntegrationMessagePublisher\n extends IntegrationMessagePublisher\n implements OnApplicationShutdown\n{\n private connection?: ChannelModel;\n private channel?: ConfirmChannel;\n private initializing?: Promise<void>;\n\n constructor(\n @Inject(RABBITMQ_OPTIONS)\n private readonly options: RabbitMqOptions,\n ) {\n super();\n }\n\n async publish(message: IntegrationMessageEnvelope): Promise<void> {\n await this.ensureChannel();\n\n const channel = this.channel;\n\n if (!channel) {\n throw new Error('[ExiumFramework] RabbitMQ channel could not be initialized.');\n }\n\n const routingKey = this.options.routingKey ?? message.name;\n\n const payload = Buffer.from(JSON.stringify(message));\n\n const publishOptions: Options.Publish = {\n persistent: this.options.persistent,\n contentType: 'application/json',\n messageId: message.id,\n type: message.name,\n timestamp: Math.floor(message.occurredAt.getTime() / 1000),\n headers: {\n 'x-event-id': message.id,\n 'x-event-name': message.name,\n 'x-event-version': message.version,\n 'x-occurred-at': message.occurredAt.toISOString(),\n },\n };\n\n channel.publish(this.options.exchange, routingKey, payload, publishOptions);\n\n await channel.waitForConfirms();\n }\n\n async onApplicationShutdown(): Promise<void> {\n await this.closeSafely();\n }\n\n private async ensureChannel(): Promise<void> {\n if (this.channel) {\n return;\n }\n\n if (this.initializing) {\n await this.initializing;\n return;\n }\n\n this.initializing = this.initialize();\n\n try {\n await this.initializing;\n } finally {\n this.initializing = undefined;\n }\n }\n\n private async initialize(): Promise<void> {\n this.connection = await connect(this.options.url);\n this.channel = await this.connection.createConfirmChannel();\n\n await this.channel.assertExchange(this.options.exchange, this.options.exchangeType, {\n durable: this.options.durable,\n });\n }\n\n private async closeSafely(): Promise<void> {\n const channel = this.channel;\n const connection = this.connection;\n\n this.channel = undefined;\n this.connection = undefined;\n\n if (channel) {\n try {\n await channel.close();\n } catch {\n // Ignore shutdown errors.\n }\n }\n\n if (connection) {\n try {\n await connection.close();\n } catch {\n // Ignore shutdown errors.\n }\n }\n }\n}\n","import { DynamicModule, Module, type ModuleMetadata, type Provider } from '@nestjs/common';\nimport { MikroOrmModule } from '@mikro-orm/nestjs';\nimport type { AnyEntity, EntityClass, EntitySchema } from '@mikro-orm/core';\nimport { MongoDriver } from '@mikro-orm/mongodb';\nimport { PostgreSqlDriver } from '@mikro-orm/postgresql';\n\nimport { OutboxWriter } from '../../application/eventing/outbox-writer';\n\nimport { ExiumConfigModule } from '../../config/exium-config.module';\nimport { ExiumConfigService } from '../../config/exium-config.service';\n\nimport { UnitOfWork } from '../../application/unit-of-work';\n\nimport { MikroOrmUnitOfWork } from './mikro-orm.unit-of-work';\nimport { TransactionCommandMiddleware } from './transaction/transaction-command.middleware';\n\nimport { OutboxMessageEntity } from './outbox/outbox-message.entity';\nimport { MikroOrmOutboxWriter } from './outbox/mikro-orm-outbox-writer';\n\nimport {\n OutboxPublisher,\n OUTBOX_PUBLISHER_OPTIONS,\n normalizeOutboxPublisherOptions,\n type OutboxPublisherOptionsInput,\n} from './outbox';\n\nexport interface ExiumPersistenceOutboxOptions {\n readonly enabled?: boolean;\n readonly publisher?: OutboxPublisherOptionsInput;\n}\n\nexport type ExiumPersistenceDriver = 'postgres' | 'mongo';\ntype ExiumPersistenceDriverClass = typeof PostgreSqlDriver | typeof MongoDriver;\ntype ExiumPersistenceEntity = string | EntityClass<AnyEntity> | EntitySchema;\n\nexport interface ExiumPersistenceOptions {\n readonly driver: ExiumPersistenceDriver;\n readonly entities: ExiumPersistenceEntity[];\n readonly outbox?: ExiumPersistenceOutboxOptions;\n}\n\ntype ModuleImport = NonNullable<ModuleMetadata['imports']>[number];\n\n@Module({})\nexport class ExiumPersistenceModule {\n static forRoot(options: ExiumPersistenceOptions): DynamicModule {\n const outboxEnabled = options.outbox?.enabled ?? true;\n\n const entities = outboxEnabled\n ? uniqueEntities([...options.entities, OutboxMessageEntity])\n : options.entities;\n\n const providers: Provider[] = [\n MikroOrmUnitOfWork,\n TransactionCommandMiddleware,\n\n {\n provide: UnitOfWork,\n useExisting: MikroOrmUnitOfWork,\n },\n ];\n\n if (outboxEnabled) {\n providers.push(\n MikroOrmOutboxWriter,\n OutboxPublisher,\n\n {\n provide: OutboxWriter,\n useExisting: MikroOrmOutboxWriter,\n },\n\n {\n provide: OUTBOX_PUBLISHER_OPTIONS,\n useValue: normalizeOutboxPublisherOptions(options.outbox?.publisher),\n },\n );\n }\n\n return {\n module: ExiumPersistenceModule,\n imports: [ExiumConfigModule, createMikroOrmModule(options.driver, entities)],\n providers,\n exports: [\n UnitOfWork,\n MikroOrmUnitOfWork,\n\n ...(outboxEnabled\n ? [OutboxWriter, MikroOrmOutboxWriter, OutboxPublisher, OUTBOX_PUBLISHER_OPTIONS]\n : []),\n ],\n };\n }\n}\n\nfunction createMikroOrmModule(\n driver: ExiumPersistenceOptions['driver'],\n entities: ExiumPersistenceEntity[],\n): ModuleImport {\n switch (driver) {\n case 'postgres':\n return createDriverSpecificMikroOrmModule(PostgreSqlDriver, entities);\n case 'mongo':\n return createDriverSpecificMikroOrmModule(MongoDriver, entities);\n default:\n return assertNever(driver);\n }\n}\n\nfunction createDriverSpecificMikroOrmModule(\n driver: ExiumPersistenceDriverClass,\n entities: ExiumPersistenceEntity[],\n): ModuleImport {\n return MikroOrmModule.forRootAsync({\n driver,\n imports: [ExiumConfigModule],\n inject: [ExiumConfigService],\n useFactory: (config: ExiumConfigService) => ({\n driver,\n ...createBaseMikroOrmOptions(config, entities),\n }),\n });\n}\n\nfunction createBaseMikroOrmOptions(config: ExiumConfigService, entities: ExiumPersistenceEntity[]) {\n return {\n clientUrl: config.getRequiredDatabaseUrl(),\n entities,\n\n /**\n * UnitOfWork explicitly controls transaction boundaries.\n */\n implicitTransactions: false,\n\n /**\n * Temporary compatibility.\n * Later we should replace this with strict request/transaction context usage.\n */\n allowGlobalContext: true,\n };\n}\n\nfunction uniqueEntities(entities: ExiumPersistenceEntity[]): ExiumPersistenceEntity[] {\n return [...new Set(entities)];\n}\n\nfunction assertNever(value: never): never {\n throw new Error(`[ExiumFramework] Unsupported DB driver: ${value}`);\n}\n","import { Inject, Injectable } from '@nestjs/common';\nimport { EntityManager } from '@mikro-orm/core';\nimport { Logger } from 'nestjs-pino';\n\nimport type { AggregateRoot } from '../../domain/aggregate-root';\nimport type { DomainEvent } from '../../domain/domain-event';\nimport { UnitOfWork } from '../../application/unit-of-work';\n\nimport { EventBus } from '../../application/cqrs/event/event-bus';\nimport { IntegrationEventRegistry } from '../../application/eventing/integration-event-registry';\nimport { OutboxWriter } from '../../application/eventing/outbox-writer';\n\nimport {\n TransactionContext,\n getTransactionContext,\n getTransactionAggregates,\n} from './transaction/transaction.context';\n\n@Injectable()\nexport class MikroOrmUnitOfWork extends UnitOfWork {\n constructor(\n @Inject(EntityManager)\n private readonly rootEntityManager: EntityManager,\n private readonly eventBus: EventBus,\n private readonly integrationEventRegistry: IntegrationEventRegistry,\n private readonly outboxWriter: OutboxWriter,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n async execute<T>(work: () => Promise<T>): Promise<T> {\n const existingContext = getTransactionContext();\n\n /**\n * Nested UnitOfWork protection.\n *\n * If a transaction is already active, we do not start another transaction.\n * The inner operation will reuse the existing transaction context and the\n * existing aggregate collection.\n */\n if (existingContext) {\n return work();\n }\n\n const aggregates = new Set<AggregateRoot<any>>();\n let result!: T;\n let domainEvents: DomainEvent[] = [];\n\n try {\n await this.rootEntityManager.transactional(async (txEm) => {\n result = await TransactionContext.run(\n {\n em: txEm,\n aggregates,\n },\n async () => {\n const workResult = await work();\n\n if (isFailureResult(workResult)) {\n throw new ResultFailureRollback(workResult);\n }\n\n /**\n * Domain events are pulled before commit.\n *\n * We need them before commit because IntegrationEvents must be written\n * to the outbox in the same database transaction.\n */\n domainEvents = [...aggregates].flatMap((aggregate) => aggregate.pullDomainEvents());\n\n /**\n * DomainEvent -> IntegrationEvent mapping.\n *\n * Aggregate only produces DomainEvents.\n * IntegrationEvents are application-level public contracts.\n */\n const integrationEvents = this.integrationEventRegistry.map(domainEvents);\n\n /**\n * Outbox write must happen inside the same transaction.\n *\n * The concrete OutboxWriter should use the current transaction context,\n * so the outbox rows are committed atomically with aggregate changes.\n */\n if (integrationEvents.length > 0) {\n await this.outboxWriter.write(integrationEvents);\n }\n\n /**\n * Keep flush explicit.\n *\n * MikroORM transactional can flush automatically depending on config,\n * but framework-level behavior should be deterministic.\n */\n await txEm.flush();\n\n return workResult;\n },\n );\n });\n } catch (error: unknown) {\n if (error instanceof ResultFailureRollback) {\n return error.result as T;\n }\n\n throw error;\n }\n\n /**\n * Domain events are published only after successful commit.\n *\n * These handlers are in-process handlers within the same bounded context.\n * Cross-service publishing must go through IntegrationEvent + Outbox.\n */\n for (const domainEvent of domainEvents) {\n try {\n await this.eventBus.publish(domainEvent);\n } catch (error: unknown) {\n this.logger.error(\n {\n err: error,\n eventId: domainEvent.eventId,\n eventName: domainEvent.name,\n },\n 'Post-commit domain event handler failed. This error is isolated and does not fail the transaction.',\n );\n }\n }\n\n return result;\n }\n\n registerAggregate(aggregate: AggregateRoot<any>): void {\n const aggregates = getTransactionAggregates();\n\n if (!aggregates) {\n throw new Error(\n '[ExiumFramework] registerAggregate() called outside UnitOfWork.execute(). ' +\n 'Make sure the command is decorated with @Transactional().',\n );\n }\n\n aggregates.add(aggregate);\n }\n}\n\nclass ResultFailureRollback extends Error {\n constructor(readonly result: unknown) {\n super('[ExiumFramework] Transaction rolled back because use case returned Result.fail(...).');\n this.name = 'ResultFailureRollback';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nfunction isFailureResult(value: unknown): boolean {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const candidate = value as {\n readonly type?: unknown;\n isFailure?: unknown;\n };\n\n return (\n candidate.type === 'failure' &&\n typeof candidate.isFailure === 'function' &&\n candidate.isFailure() === true\n );\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { EntityManager } from '@mikro-orm/core';\nimport type { AggregateRoot } from '../../../domain/aggregate-root';\n\nexport interface PersistenceTransactionContext {\n readonly em: EntityManager;\n readonly aggregates: Set<AggregateRoot<any>>;\n}\n\nexport const TransactionContext = new AsyncLocalStorage<PersistenceTransactionContext>();\n\nexport function getTransactionContext(): PersistenceTransactionContext | undefined {\n return TransactionContext.getStore();\n}\n\nexport function getTransactionEntityManager(): EntityManager | undefined {\n return TransactionContext.getStore()?.em;\n}\n\nexport function getTransactionAggregates(): Set<AggregateRoot<any>> | undefined {\n return TransactionContext.getStore()?.aggregates;\n}\n","import { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nimport {\n RegisterCommandMiddleware,\n TRANSACTIONAL_METADATA,\n type Command,\n type CommandResultOf,\n type CommandMiddleware,\n} from '../../../application';\nimport type { ResultType } from '../../../foundation';\n\nimport { UnitOfWork } from '../../../application/unit-of-work';\nimport { ApplicationMiddlewarePriority } from '../../../application';\n\ninterface TransactionalMetadata {\n readonly enabled: boolean;\n}\n\n@Injectable()\n@RegisterCommandMiddleware({\n priority: ApplicationMiddlewarePriority.Transaction,\n})\nexport class TransactionCommandMiddleware implements CommandMiddleware {\n constructor(private readonly unitOfWork: UnitOfWork) {}\n\n async use<TCommand extends Command<any>>(\n command: TCommand,\n next: () => Promise<ResultType<CommandResultOf<TCommand>>>,\n ): Promise<ResultType<CommandResultOf<TCommand>>> {\n const metadata = Reflect.getMetadata(TRANSACTIONAL_METADATA, command.constructor) as\n | TransactionalMetadata\n | undefined;\n\n if (!metadata?.enabled) {\n return next();\n }\n\n return this.unitOfWork.execute(next);\n }\n}\n","import { defineEntity, p } from '@mikro-orm/core';\nimport { v7 as uuidv7 } from 'uuid';\n\nimport { OutboxMessageStatus } from './outbox-message-status';\n\nconst OutboxMessageSchema = defineEntity({\n name: 'OutboxMessageEntity',\n tableName: 'exium_outbox_messages',\n properties: {\n id: p.string().primary(),\n\n eventId: p.string().unique(),\n eventName: p.string(),\n eventVersion: p.integer(),\n\n payload: p.json<Record<string, unknown>>(),\n\n occurredAt: p.datetime(),\n\n /**\n * Keep status as string instead of enum metadata here.\n * This keeps the schema simple and portable across SQL/Mongo drivers.\n */\n status: p.string(),\n\n retryCount: p.integer(),\n\n nextAttemptAt: p.datetime().nullable(),\n publishedAt: p.datetime().nullable(),\n lockedAt: p.datetime().nullable(),\n lockedBy: p.string().nullable(),\n\n lastError: p.string().nullable(),\n\n createdAt: p.datetime().onCreate(() => new Date()),\n updatedAt: p\n .datetime()\n .onCreate(() => new Date())\n .onUpdate(() => new Date()),\n },\n});\n\nexport class OutboxMessageEntity extends OutboxMessageSchema.class {\n static create(params: {\n eventId: string;\n eventName: string;\n eventVersion: number;\n payload: Record<string, unknown>;\n occurredAt: Date;\n }): OutboxMessageEntity {\n const entity = new OutboxMessageEntity();\n\n entity.id = uuidv7();\n entity.eventId = params.eventId;\n entity.eventName = params.eventName;\n entity.eventVersion = params.eventVersion;\n entity.payload = params.payload;\n entity.occurredAt = params.occurredAt;\n entity.status = OutboxMessageStatus.Pending;\n entity.retryCount = 0;\n entity.nextAttemptAt = new Date();\n\n return entity;\n }\n}\n\nOutboxMessageSchema.setClass(OutboxMessageEntity);\n","export enum OutboxMessageStatus {\n Pending = 'pending',\n Published = 'published',\n Failed = 'failed',\n}\n","import { Injectable } from '@nestjs/common';\n\nimport type { IntegrationEvent } from '../../../application/eventing/integration-event';\nimport { OutboxWriter } from '../../../application/eventing/outbox-writer';\n\nimport { getTransactionEntityManager } from '../transaction/transaction.context';\nimport { PersistenceTransactionNotActiveException } from '../exceptions/persistence-transaction-not-active.exception';\nimport { OutboxMessageEntity } from './outbox-message.entity';\n\n@Injectable()\nexport class MikroOrmOutboxWriter extends OutboxWriter {\n async write(events: readonly IntegrationEvent[]): Promise<void> {\n if (events.length === 0) {\n return;\n }\n\n const em = getTransactionEntityManager();\n\n if (!em) {\n throw new PersistenceTransactionNotActiveException('outbox.write');\n }\n\n for (const event of events) {\n const message = OutboxMessageEntity.create({\n eventId: event.id,\n eventName: event.name,\n eventVersion: event.version,\n occurredAt: event.occurredAt,\n payload: toPlainRecord(event),\n });\n\n em.persist(message);\n }\n }\n}\n\nfunction toPlainRecord(source: unknown): Record<string, unknown> {\n const normalized = normalize(source);\n\n if (!normalized || typeof normalized !== 'object' || Array.isArray(normalized)) {\n return {};\n }\n\n return normalized as Record<string, unknown>;\n}\n\nfunction normalize(value: unknown): unknown {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (Array.isArray(value)) {\n return value.map(normalize);\n }\n\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n\n for (const [key, item] of Object.entries(value)) {\n if (item === undefined) {\n continue;\n }\n\n if (typeof item === 'function') {\n continue;\n }\n\n result[key] = normalize(item);\n }\n\n return result;\n }\n\n return value;\n}\n","export class PersistenceTransactionNotActiveException extends Error {\n constructor(operation: string) {\n super(\n `[ExiumFramework] Cannot execute persistence write operation \"${operation}\" ` +\n `outside an active transaction. ` +\n `Make sure the command is decorated with @Transactional().`,\n );\n\n this.name = 'PersistenceTransactionNotActiveException';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { Inject, Injectable } from '@nestjs/common';\nimport { EntityManager } from '@mikro-orm/core';\nimport { Logger } from 'nestjs-pino';\n\nimport { IntegrationMessagePublisher, type IntegrationMessageEnvelope } from '../../messaging';\n\nimport { OutboxMessageEntity } from './outbox-message.entity';\nimport { OutboxMessageStatus } from './outbox-message-status';\nimport { OUTBOX_PUBLISHER_OPTIONS, type OutboxPublisherOptions } from './outbox-publisher-options';\n\n@Injectable()\nexport class OutboxPublisher {\n constructor(\n private readonly em: EntityManager,\n private readonly messagePublisher: IntegrationMessagePublisher,\n private readonly logger: Logger,\n @Inject(OUTBOX_PUBLISHER_OPTIONS)\n private readonly options: OutboxPublisherOptions,\n ) {}\n\n async publishPending(): Promise<number> {\n const messages = await this.findPublishableMessages();\n\n let publishedCount = 0;\n\n for (const message of messages) {\n const claimed = await this.claim(message);\n\n if (!claimed) {\n continue;\n }\n\n try {\n await this.messagePublisher.publish(this.toEnvelope(message));\n\n message.status = OutboxMessageStatus.Published;\n message.publishedAt = new Date();\n message.lockedAt = undefined;\n message.lockedBy = undefined;\n message.lastError = undefined;\n\n await this.em.flush();\n\n publishedCount += 1;\n } catch (error: unknown) {\n message.retryCount += 1;\n message.lockedAt = undefined;\n message.lockedBy = undefined;\n message.lastError = normalizeError(error);\n\n if (message.retryCount >= this.options.maxRetryCount) {\n message.status = OutboxMessageStatus.Failed;\n message.nextAttemptAt = undefined;\n } else {\n message.status = OutboxMessageStatus.Pending;\n message.nextAttemptAt = new Date(Date.now() + this.options.retryDelayMs);\n }\n\n await this.em.flush();\n\n this.logger.error(\n {\n outboxMessageId: message.id,\n eventId: message.eventId,\n eventName: message.eventName,\n retryCount: message.retryCount,\n status: message.status,\n err: error,\n },\n 'Outbox message publish failed.',\n );\n }\n }\n\n return publishedCount;\n }\n\n private async findPublishableMessages(): Promise<OutboxMessageEntity[]> {\n const now = new Date();\n const lockExpiredBefore = new Date(Date.now() - this.options.lockTimeoutMs);\n\n return this.em.find(\n OutboxMessageEntity,\n {\n status: OutboxMessageStatus.Pending,\n $and: [\n {\n $or: [{ nextAttemptAt: null }, { nextAttemptAt: { $lte: now } }],\n },\n {\n $or: [{ lockedAt: null }, { lockedAt: { $lte: lockExpiredBefore } }],\n },\n ],\n } as any,\n {\n limit: this.options.batchSize,\n orderBy: {\n occurredAt: 'asc',\n } as any,\n },\n );\n }\n\n private async claim(message: OutboxMessageEntity): Promise<boolean> {\n if (message.lockedAt && Date.now() - message.lockedAt.getTime() < this.options.lockTimeoutMs) {\n return false;\n }\n\n const oldLockedAt = message.lockedAt;\n const now = new Date();\n const lockExpiredBefore = new Date(Date.now() - this.options.lockTimeoutMs);\n\n const updatedCount = await this.em.nativeUpdate(\n OutboxMessageEntity,\n {\n id: message.id,\n status: OutboxMessageStatus.Pending,\n $and: [\n {\n $or: [{ nextAttemptAt: null }, { nextAttemptAt: { $lte: now } }],\n },\n {\n $or: [\n { lockedAt: oldLockedAt || null },\n { lockedAt: null },\n { lockedAt: { $lte: lockExpiredBefore } },\n ],\n },\n ],\n } as any,\n {\n lockedAt: now,\n lockedBy: this.options.publisherId,\n },\n );\n\n if (updatedCount > 0) {\n message.lockedAt = now;\n message.lockedBy = this.options.publisherId;\n return true;\n }\n\n return false;\n }\n\n private toEnvelope(message: OutboxMessageEntity): IntegrationMessageEnvelope {\n return {\n id: message.eventId,\n name: message.eventName,\n version: message.eventVersion,\n occurredAt: message.occurredAt,\n payload: message.payload,\n };\n }\n}\n\nfunction normalizeError(error: unknown): string {\n if (error instanceof Error) {\n return `${error.name}: ${error.message}`;\n }\n\n return String(error);\n}\n","export const OUTBOX_PUBLISHER_OPTIONS = Symbol('exium:outbox-publisher-options');\n\nexport interface OutboxPublisherOptions {\n readonly batchSize: number;\n readonly maxRetryCount: number;\n readonly retryDelayMs: number;\n readonly lockTimeoutMs: number;\n readonly publisherId: string;\n}\n\nexport type OutboxPublisherOptionsInput = Partial<OutboxPublisherOptions>;\n\nexport const DEFAULT_OUTBOX_PUBLISHER_OPTIONS: OutboxPublisherOptions = {\n batchSize: 50,\n maxRetryCount: 5,\n retryDelayMs: 30_000,\n lockTimeoutMs: 60_000,\n publisherId: 'exium-outbox-publisher',\n};\n\nexport function normalizeOutboxPublisherOptions(\n input: OutboxPublisherOptionsInput = {},\n): OutboxPublisherOptions {\n const options: OutboxPublisherOptions = {\n ...DEFAULT_OUTBOX_PUBLISHER_OPTIONS,\n ...input,\n };\n\n assertPositiveInteger(options.batchSize, 'batchSize');\n assertPositiveInteger(options.maxRetryCount, 'maxRetryCount');\n assertPositiveInteger(options.retryDelayMs, 'retryDelayMs');\n assertPositiveInteger(options.lockTimeoutMs, 'lockTimeoutMs');\n\n if (!options.publisherId.trim()) {\n throw new Error('[ExiumFramework] Outbox publisherId must not be empty.');\n }\n\n return options;\n}\n\nfunction assertPositiveInteger(value: number, propertyName: string): void {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(`[ExiumFramework] Outbox ${propertyName} must be a positive integer.`);\n }\n}\n","import type { FilterQuery } from '@mikro-orm/core';\n\nimport { getTransactionEntityManager } from '../transaction/transaction.context';\nimport { PersistenceTransactionNotActiveException } from '../exceptions/persistence-transaction-not-active.exception';\n\nexport interface MikroOrmRepositoryOptions<TPersistenceEntity extends object> {\n /**\n * Persistence entity id field.\n *\n * Default: \"id\"\n *\n * Examples:\n * - Postgres entity: \"id\"\n * - Mongo entity: \"_id\"\n * - Legacy entity: \"uuid\"\n */\n readonly idField?: keyof TPersistenceEntity & string;\n}\n\nexport interface EntityManagerLike {\n getContext(): EntityManagerLike;\n\n findOne(entityName: unknown, where: FilterQuery<any>): Promise<any>;\n\n find(entityName: unknown, where: FilterQuery<any>): Promise<any[]>;\n\n count(entityName: unknown, where: FilterQuery<any>): Promise<number>;\n\n persist(entity: object): void;\n\n remove(entity: object): void;\n}\n\nexport abstract class MikroOrmRepository<TPersistenceEntity extends object, TPrimitiveId> {\n private readonly idField: keyof TPersistenceEntity & string;\n\n protected constructor(\n private readonly entityName: unknown,\n private readonly rootEntityManager: EntityManagerLike,\n options: MikroOrmRepositoryOptions<TPersistenceEntity> = {},\n ) {\n this.idField = options.idField ?? ('id' as keyof TPersistenceEntity & string);\n }\n\n /**\n * Read operations may run outside explicit transaction.\n * If a transaction exists, reads use the transaction EntityManager.\n */\n protected get em(): EntityManagerLike {\n const txEm = getTransactionEntityManager();\n\n if (txEm) {\n return txEm;\n }\n\n return this.rootEntityManager.getContext();\n }\n\n /**\n * Write operations must be executed inside UnitOfWork transaction.\n */\n protected get transactionalEm(): EntityManagerLike {\n const txEm = getTransactionEntityManager();\n\n if (!txEm) {\n throw new PersistenceTransactionNotActiveException(String(this.entityName));\n }\n\n return txEm;\n }\n\n protected getIdField(): keyof TPersistenceEntity & string {\n return this.idField;\n }\n\n protected createIdFilter(id: TPrimitiveId): FilterQuery<TPersistenceEntity> {\n return {\n [this.idField]: id,\n } as FilterQuery<TPersistenceEntity>;\n }\n\n protected createIdsFilter(ids: readonly TPrimitiveId[]): FilterQuery<TPersistenceEntity> {\n return {\n [this.idField]: {\n $in: ids,\n },\n } as FilterQuery<TPersistenceEntity>;\n }\n\n protected async findOrmById(id: TPrimitiveId): Promise<TPersistenceEntity | null> {\n return this.em.findOne(this.entityName, this.createIdFilter(id) as any);\n }\n\n protected async findOrmByIds(ids: readonly TPrimitiveId[]): Promise<TPersistenceEntity[]> {\n if (ids.length === 0) {\n return [];\n }\n\n return this.em.find(this.entityName, this.createIdsFilter(ids) as any);\n }\n\n protected persistOrm(entity: TPersistenceEntity): void {\n this.transactionalEm.persist(entity);\n }\n\n protected removeOrm(entity: TPersistenceEntity): void {\n this.transactionalEm.remove(entity);\n }\n\n protected async deleteOrmById(id: TPrimitiveId): Promise<void> {\n const em = this.transactionalEm;\n\n const entity = await em.findOne(this.entityName, this.createIdFilter(id) as any);\n\n if (!entity) {\n return;\n }\n\n em.remove(entity);\n }\n\n protected async existsOrm(id: TPrimitiveId): Promise<boolean> {\n const count = await this.em.count(this.entityName, this.createIdFilter(id) as any);\n\n return count > 0;\n }\n}\n","import type { Id } from '../../../domain/id';\nimport type { AggregateRoot } from '../../../domain/aggregate-root';\nimport type { Repository } from '../../../domain/repository';\nimport { UnitOfWork } from '../../../application/unit-of-work';\n\nimport {\n MikroOrmRepository,\n type EntityManagerLike,\n type MikroOrmRepositoryOptions,\n} from './mikro-orm.repository';\n\nimport type { PersistenceMapper } from '../mapper';\n\nexport abstract class MikroOrmAggregateRepository<\n TAggregate extends AggregateRoot<TId>,\n TId extends Id,\n TPersistenceEntity extends object,\n TPrimitiveId,\n>\n extends MikroOrmRepository<TPersistenceEntity, TPrimitiveId>\n implements Repository<TAggregate, TId>\n{\n protected constructor(\n entityName: unknown,\n rootEntityManager: EntityManagerLike,\n private readonly mapper: PersistenceMapper<TAggregate, TId, TPersistenceEntity, TPrimitiveId>,\n private readonly unitOfWork: UnitOfWork,\n options: MikroOrmRepositoryOptions<TPersistenceEntity> = {},\n ) {\n super(entityName, rootEntityManager, options);\n }\n\n async findById(id: TId): Promise<TAggregate | null> {\n const primitiveId = this.mapper.toPersistenceId(id);\n const entity = await this.findOrmById(primitiveId);\n\n if (!entity) {\n return null;\n }\n\n return this.mapper.toDomain(entity);\n }\n\n async findByIds(ids: readonly TId[]): Promise<TAggregate[]> {\n if (ids.length === 0) {\n return [];\n }\n\n const primitiveIds = ids.map((id) => this.mapper.toPersistenceId(id));\n\n const entities = await this.findOrmByIds(primitiveIds);\n\n return entities.map((entity) => this.mapper.toDomain(entity));\n }\n\n async save(aggregate: TAggregate): Promise<void> {\n const primitiveId = this.mapper.getPersistenceId(aggregate);\n const entity = this.mapper.toPersistence(aggregate);\n const existing = await this.findOrmById(primitiveId);\n\n if (existing) {\n // Keep the managed instance attached to the current UnitOfWork.\n Object.assign(existing, entity);\n this.unitOfWork.registerAggregate(aggregate);\n return;\n }\n\n this.persistOrm(entity);\n this.unitOfWork.registerAggregate(aggregate);\n }\n\n async delete(id: TId): Promise<void> {\n const primitiveId = this.mapper.toPersistenceId(id);\n\n await this.deleteOrmById(primitiveId);\n }\n\n async exists(id: TId): Promise<boolean> {\n const primitiveId = this.mapper.toPersistenceId(id);\n\n return this.existsOrm(primitiveId);\n }\n}\n","import {\n type Expression,\n type ExpressionBuilder,\n type Kysely,\n type SelectQueryBuilder,\n sql,\n} from 'kysely';\n\nimport {\n Criteria,\n CursorPage,\n Page,\n ReadQueryException,\n ReadOperationNotSupportedException,\n SqlReadSource,\n type CountQuery,\n type CriteriaNode,\n type ExistsQuery,\n type FindCursorQuery,\n type FindManyQuery,\n type FindOneQuery,\n type FindPageQuery,\n type ReadEngine,\n type ReadSource,\n type RowMapper,\n Sort,\n} from '../../../application/read';\n\ntype AnyDatabase = Record<string, any>;\ntype AnyRow = Record<string, any>;\ntype AnySelectQuery = SelectQueryBuilder<any, any, any>;\n\nexport class KyselyReadEngine<TDatabase extends AnyDatabase = AnyDatabase>\n implements ReadEngine\n{\n constructor(private readonly db: Kysely<TDatabase>) {}\n\n async findOne<TView>(query: FindOneQuery<TView>): Promise<TView | null> {\n const rows = await this.findMany({\n ...query,\n limit: 1,\n });\n\n return rows[0] ?? null;\n }\n\n async findMany<TView>(query: FindManyQuery<TView>): Promise<readonly TView[]> {\n const source = requireSqlSource(query.from);\n let builder = this.createSelect(source);\n\n builder = this.applyCriteria(builder, source, query.criteria);\n builder = this.applySort(builder, source, query.sort ?? source.defaultSort);\n\n if (query.limit !== undefined) {\n builder = builder.limit(query.limit);\n }\n\n const rows = await builder.execute();\n\n return rows.map((row) => mapRow(row, query.map));\n }\n\n async findPage<TView>(query: FindPageQuery<TView>): Promise<Page<TView>> {\n const source = requireSqlSource(query.from);\n let builder = this.createSelect(source);\n\n builder = this.applyCriteria(builder, source, query.criteria);\n builder = this.applySort(builder, source, query.sort ?? source.defaultSort);\n builder = builder.limit(query.page.size).offset(query.page.offset);\n\n const [items, totalItems] = await Promise.all([\n builder.execute().then((rows) => rows.map((row) => mapRow(row, query.map))),\n this.count({\n from: query.from,\n criteria: query.criteria,\n }),\n ]);\n\n return Page.of(items, query.page, totalItems);\n }\n\n async findCursor<TView>(query: FindCursorQuery<TView>): Promise<CursorPage<TView>> {\n const source = requireSqlSource(query.from);\n const sort = query.sort ?? source.defaultSort;\n\n assertCursorSort(sort);\n\n let builder = this.createSelect(source);\n\n builder = this.applyCriteria(builder, source, query.criteria);\n\n if (query.cursor.after) {\n builder = this.applyCursorPredicate(builder, source, sort, query.cursor.after, 'after');\n }\n\n if (query.cursor.before) {\n builder = this.applyCursorPredicate(builder, source, sort, query.cursor.before, 'before');\n }\n\n const executionSort = query.cursor.before ? reverseSort(sort) : sort;\n builder = this.applySort(builder, source, executionSort);\n\n const limit = query.cursor.limit;\n builder = builder.limit(limit + 1);\n\n const rows = await builder.execute() as AnyRow[];\n const hasExtraItem = rows.length > limit;\n const selectedRows = hasExtraItem ? rows.slice(0, limit) : rows;\n const pageRows = query.cursor.before ? [...selectedRows].reverse() : selectedRows;\n const items = pageRows.map((row) => mapRow(row, query.map));\n\n const hasPrevious = query.cursor.before ? hasExtraItem : Boolean(query.cursor.after);\n const hasNext = query.cursor.before ? true : hasExtraItem;\n const previousCursor =\n hasPrevious && pageRows.length > 0\n ? encodeCursor(pageRows[0], sort)\n : undefined;\n const nextCursor =\n hasNext && pageRows.length > 0\n ? encodeCursor(pageRows[pageRows.length - 1], sort)\n : undefined;\n\n return new CursorPage<TView>(\n items,\n hasNext,\n hasPrevious,\n nextCursor,\n previousCursor,\n );\n }\n\n async exists(query: ExistsQuery): Promise<boolean> {\n const source = requireSqlSource(query.from);\n let builder = this.createBaseQuery(source).select(sql<number>`1`.as('exists')).limit(1);\n\n builder = this.applyCriteria(builder, source, query.criteria);\n\n const row = await builder.executeTakeFirst();\n\n return row !== undefined;\n }\n\n async count(query: CountQuery): Promise<number> {\n const source = requireSqlSource(query.from);\n let builder = this.createBaseQuery(source).select(sql<number>`count(*)`.as('count'));\n\n builder = this.applyCriteria(builder, source, query.criteria);\n\n const row = (await builder.executeTakeFirst()) as { count?: number | string | bigint } | undefined;\n\n return Number(row?.count ?? 0);\n }\n\n private createSelect(source: SqlReadSource): AnySelectQuery {\n return this.createBaseQuery(source).select(source.getSelectFields() as any);\n }\n\n private createBaseQuery(source: SqlReadSource): AnySelectQuery {\n let builder = this.db.selectFrom(source.getFromExpression() as any) as AnySelectQuery;\n\n for (const join of source.joins) {\n const joinSource = `${join.table} as ${join.alias}`;\n\n if (join.type === 'left') {\n builder = builder.leftJoin(\n joinSource as any,\n (joinBuilder: any) =>\n joinBuilder.onRef(join.on.left as any, join.on.operator as any, join.on.right as any),\n );\n } else {\n builder = builder.innerJoin(\n joinSource as any,\n (joinBuilder: any) =>\n joinBuilder.onRef(join.on.left as any, join.on.operator as any, join.on.right as any),\n );\n }\n }\n\n return builder;\n }\n\n private applyCriteria(\n builder: AnySelectQuery,\n source: SqlReadSource,\n criteria: Criteria | undefined,\n ): AnySelectQuery {\n if (!criteria?.node) {\n return builder;\n }\n\n return builder.where((eb: ExpressionBuilder<any, any>) =>\n this.toKyselyExpression(eb, source, criteria.node as CriteriaNode),\n );\n }\n\n private applySort(\n builder: AnySelectQuery,\n source: SqlReadSource,\n sort: Sort | undefined,\n ): AnySelectQuery {\n if (!sort || sort.isEmpty()) {\n return builder;\n }\n\n let sorted = builder;\n\n for (const field of sort.fields) {\n const resolved = source.resolveField(field.field);\n\n if (field.nulls) {\n sorted = sorted.orderBy(\n sql`${sql.ref(resolved)} ${sql.raw(field.direction)} nulls ${sql.raw(field.nulls)}`,\n );\n } else {\n sorted = sorted.orderBy(resolved as any, field.direction);\n }\n }\n\n return sorted;\n }\n\n private applyCursorPredicate(\n builder: AnySelectQuery,\n source: SqlReadSource,\n sort: Sort,\n cursor: string,\n direction: 'after' | 'before',\n ): AnySelectQuery {\n const payload = decodeCursor(cursor);\n\n return builder.where((eb: ExpressionBuilder<any, any>) => {\n const branches = sort.fields.map((field, index) => {\n const equalPredicates = sort.fields.slice(0, index).map((previousField) =>\n eb(\n source.resolveField(previousField.field) as any,\n '=',\n getCursorValue(payload, previousField.field),\n ) as Expression<boolean>,\n );\n\n const operator =\n direction === 'after'\n ? (field.direction === 'asc' ? '>' : '<')\n : (field.direction === 'asc' ? '<' : '>');\n\n const seekPredicate = eb(\n source.resolveField(field.field) as any,\n operator,\n getCursorValue(payload, field.field),\n ) as Expression<boolean>;\n\n const predicates = [...equalPredicates, seekPredicate];\n\n if (predicates.length === 1) {\n return seekPredicate;\n }\n\n return eb.and(predicates) as Expression<boolean>;\n });\n\n return eb.or(branches) as Expression<boolean>;\n });\n }\n\n private toKyselyExpression(\n eb: ExpressionBuilder<any, any>,\n source: SqlReadSource,\n node: CriteriaNode,\n ): Expression<boolean> {\n switch (node.type) {\n case 'comparison':\n return this.toComparisonExpression(eb, source, node);\n case 'in':\n return eb(\n source.resolveField(node.field) as any,\n node.operator === 'in' ? 'in' : 'not in',\n [...node.values],\n ) as Expression<boolean>;\n case 'isNull':\n return eb(source.resolveField(node.field) as any, 'is', null) as Expression<boolean>;\n case 'isNotNull':\n return eb(source.resolveField(node.field) as any, 'is not', null) as Expression<boolean>;\n case 'between':\n return eb.and([\n eb(source.resolveField(node.field) as any, '>=', node.lower),\n eb(source.resolveField(node.field) as any, '<=', node.upper),\n ]) as Expression<boolean>;\n case 'and':\n return eb.and(\n node.nodes.map((child) => this.toKyselyExpression(eb, source, child)),\n ) as Expression<boolean>;\n case 'or':\n return eb.or(\n node.nodes.map((child) => this.toKyselyExpression(eb, source, child)),\n ) as Expression<boolean>;\n case 'not':\n return eb.not(this.toKyselyExpression(eb, source, node.node)) as Expression<boolean>;\n }\n }\n\n private toComparisonExpression(\n eb: ExpressionBuilder<any, any>,\n source: SqlReadSource,\n node: Extract<CriteriaNode, { readonly type: 'comparison' }>,\n ): Expression<boolean> {\n const field = source.resolveField(node.field) as any;\n\n switch (node.operator) {\n case 'eq':\n return eb(field, '=', node.value) as Expression<boolean>;\n case 'ne':\n return eb(field, '!=', node.value) as Expression<boolean>;\n case 'gt':\n return eb(field, '>', node.value) as Expression<boolean>;\n case 'gte':\n return eb(field, '>=', node.value) as Expression<boolean>;\n case 'lt':\n return eb(field, '<', node.value) as Expression<boolean>;\n case 'lte':\n return eb(field, '<=', node.value) as Expression<boolean>;\n case 'contains':\n return eb(field, 'like', `%${String(node.value)}%`) as Expression<boolean>;\n case 'startsWith':\n return eb(field, 'like', `${String(node.value)}%`) as Expression<boolean>;\n case 'endsWith':\n return eb(field, 'like', `%${String(node.value)}`) as Expression<boolean>;\n }\n }\n}\n\nfunction requireSqlSource(source: ReadSource): SqlReadSource {\n if (!SqlReadSource.is(source)) {\n throw new ReadOperationNotSupportedException(\n 'KyselyReadEngine',\n `ReadSource \"${source.name}\" is not a SqlReadSource.`,\n );\n }\n\n return source;\n}\n\nfunction assertCursorSort(sort: Sort | undefined): asserts sort is Sort {\n if (!sort || sort.isEmpty()) {\n throw new ReadOperationNotSupportedException(\n 'KyselyReadEngine.findCursor',\n 'Cursor pagination requires an explicit non-empty sort.',\n );\n }\n\n const unsupportedNullSort = sort.fields.find((field) => field.nulls !== undefined);\n\n if (unsupportedNullSort) {\n throw new ReadOperationNotSupportedException(\n 'KyselyReadEngine.findCursor',\n `Cursor sort field \"${unsupportedNullSort.field}\" uses explicit null ordering, which is not supported in v1.`,\n );\n }\n\n const tieBreaker = sort.fields[sort.fields.length - 1];\n\n if (tieBreaker?.field !== 'id') {\n throw new ReadOperationNotSupportedException(\n 'KyselyReadEngine.findCursor',\n 'Cursor sort must include \"id\" as the final tie-breaker field.',\n );\n }\n}\n\nfunction reverseSort(sort: Sort): Sort {\n return Sort.fromFields(\n sort.fields.map((field) => ({\n field: field.field,\n direction: field.direction === 'asc' ? 'desc' : 'asc',\n })),\n );\n}\n\nfunction decodeCursor(cursor: string): AnyRow {\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64').toString('utf8'));\n\n if (!isRecord(parsed)) {\n throw new Error('Cursor payload must be an object.');\n }\n\n return parsed;\n } catch (error: unknown) {\n throw new ReadQueryException('Cursor value is not a valid Exium cursor.');\n }\n}\n\nfunction encodeCursor(row: AnyRow, sort: Sort): string {\n const payload: AnyRow = {};\n\n for (const field of sort.fields) {\n payload[field.field] = getCursorValue(row, field.field);\n }\n\n return Buffer.from(JSON.stringify(payload)).toString('base64');\n}\n\nfunction getCursorValue(record: AnyRow, field: string): unknown {\n if (!Object.prototype.hasOwnProperty.call(record, field)) {\n throw new ReadQueryException(`Cursor field \"${field}\" is missing from the selected row.`);\n }\n\n const value = record[field];\n\n if (value === null || value === undefined) {\n throw new ReadOperationNotSupportedException(\n 'KyselyReadEngine.findCursor',\n `Cursor field \"${field}\" must be non-null.`,\n );\n }\n\n return value;\n}\n\nfunction isRecord(value: unknown): value is AnyRow {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction mapRow<TView>(row: unknown, mapper: RowMapper<TView> | undefined): TView {\n if (mapper) {\n return mapper(row);\n }\n\n return row as TView;\n}\n","import 'reflect-metadata';\nimport {\n DynamicModule,\n INestApplication,\n INestApplicationContext,\n Module,\n ValidationPipe,\n} from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Logger } from 'nestjs-pino';\nimport { ExiumModule } from './exium-module';\nimport type { ExiumApp } from './types/exium-app';\nimport type { ExiumOptions } from './types/exium-options';\nimport { ExiumContextService } from '../application';\nimport { EXIUM_HTTP_OPTIONS } from '../http/http-options';\nimport { ExiumHttpContextInterceptor } from '../http/interceptors/exium-http-context.interceptor';\nimport { ExiumResponseInterceptor } from '../http/interceptors/exium-response.interceptor';\nimport { ExiumExceptionFilter } from '../http/filters/exium-exception.filter';\n\n@Module({})\nclass ExiumRootModule {}\n\nfunction validateOptions(options: ExiumOptions): void {\n if (!options.serviceName?.trim()) {\n throw new Error('ExiumOptions.serviceName is required.');\n }\n\n if (!options.module) {\n throw new Error('ExiumOptions.module is required.');\n }\n}\n\nexport async function createExiumApp(options: ExiumOptions): Promise<ExiumApp> {\n validateOptions(options);\n\n const mode = options.mode ?? 'http';\n\n const rootModule: DynamicModule = {\n module: ExiumRootModule,\n imports: [\n ExiumModule.forRoot({\n serviceName: options.serviceName,\n http: options.http,\n infrastructure: options.infrastructure,\n }),\n options.module,\n ],\n };\n\n const nestApp: INestApplicationContext | INestApplication =\n mode === 'http'\n ? await NestFactory.create(rootModule, {\n bufferLogs: true,\n })\n : await NestFactory.createApplicationContext(rootModule, {\n bufferLogs: true,\n });\n\n const pinoLogger = nestApp.get(Logger);\n nestApp.useLogger(pinoLogger);\n\n if (options.shutdownHooks ?? true) {\n nestApp.enableShutdownHooks();\n }\n\n if (mode === 'http') {\n const httpApp = nestApp as INestApplication;\n\n httpApp.useGlobalPipes(\n new ValidationPipe({\n whitelist: true,\n transform: true,\n }),\n );\n\n httpApp.useGlobalInterceptors(\n new ExiumHttpContextInterceptor(\n httpApp.get(ExiumContextService),\n httpApp.get(EXIUM_HTTP_OPTIONS),\n ),\n new ExiumResponseInterceptor(),\n );\n\n httpApp.useGlobalFilters(new ExiumExceptionFilter(pinoLogger));\n }\n\n return {\n async start(): Promise<void> {\n const service = String(nestApp.get('EXIUM_SERVICE_NAME'));\n const port = options.port ?? 3000;\n\n if (mode === 'http') {\n await (nestApp as INestApplication).listen(port);\n pinoLogger.log(`[${service}] started in HTTP mode on port ${port}.`);\n return;\n }\n\n if (options.port !== undefined) {\n pinoLogger.warn(`[${service}] 'port' is ignored in context mode.`);\n }\n\n pinoLogger.log(`[${service}] started in context mode.`);\n },\n\n async stop(): Promise<void> {\n await nestApp.close();\n },\n\n getNestApp() {\n return nestApp;\n },\n };\n}\n","import { v7 as uuidv7, validate, version } from 'uuid';\nimport { Failure, Result, type ResultType } from '../foundation';\nimport { ValueObject } from './value-object';\n\ntype IdStatic<TId extends Id> = {\n readonly prototype: TId;\n readonly name: string;\n};\n\ntype IdConstructor<TId extends Id> = new (value: string) => TId;\n\nexport abstract class Id extends ValueObject<{ value: string }> {\n protected constructor(value: string) {\n if (!Id.isUuidV7(value)) {\n // Programmer error: callers should use Id.parse() for untrusted input.\n throw new Error(`[Exium] Id must be a valid UUID v7, got: \"${value}\"`);\n }\n\n super({ value });\n }\n\n protected static newUuid(): string {\n return uuidv7();\n }\n\n static generate<TId extends Id>(this: IdStatic<TId>): TId {\n return Id.create(this, Id.newUuid());\n }\n\n static of<TId extends Id>(this: IdStatic<TId>, value: string): TId {\n return Id.create(this, value);\n }\n\n static parse<TId extends Id>(\n this: IdStatic<TId>,\n value: string,\n options: {\n field?: string;\n } = {},\n ): ResultType<TId> {\n return Id.parseUuid(value, {\n idType: this.name,\n field: options.field,\n }).map((normalized) => Id.create(this, normalized));\n }\n\n protected static parseUuid(\n value: string,\n options: {\n idType: string;\n field?: string;\n },\n ): ResultType<string> {\n const normalized = value.trim();\n\n if (!Id.isUuidV7(normalized)) {\n return Result.fail(\n Failure.validation('INVALID_ID', `${options.idType} must be a valid UUID v7.`, {\n field: options.field,\n metadata: {\n idType: options.idType,\n expected: 'uuid-v7',\n },\n internal: {\n value,\n },\n }),\n );\n }\n\n return Result.ok(normalized);\n }\n\n private static create<TId extends Id>(idType: IdStatic<TId>, value: string): TId {\n const constructor = idType as unknown as IdConstructor<TId>;\n\n return new constructor(value);\n }\n\n private static isUuidV7(value: string): boolean {\n return validate(value) && version(value) === 7;\n }\n\n get value(): string {\n return this.props.value;\n }\n\n override toString(): string {\n return this.value;\n }\n\n toJSON(): string {\n return this.value;\n }\n}\n","import { v7 as uuidv7 } from 'uuid';\n\nexport abstract class DomainEvent {\n readonly eventId: string;\n readonly occurredAt: Date;\n\n abstract readonly name: string;\n\n protected constructor(readonly aggregateId: string) {\n this.eventId = uuidv7();\n this.occurredAt = new Date();\n }\n}\n","/**\n * Marker base class for domain services.\n *\n * Domain services contain business logic that does not naturally belong\n * to a single entity or aggregate — typically operations that coordinate\n * between multiple domain objects.\n *\n * Rules:\n * - Stateless: no mutable instance state\n * - Pure: no infrastructure dependencies, no I/O\n * - No framework imports: do not use @Injectable() or any NestJS decorator\n *\n * Registration:\n * Domain services are registered as plain providers in NestJS modules.\n * Since they have no injected dependencies, @Injectable() is not needed.\n *\n * @Module({ providers: [MoneyTransferService] })\n */\nexport abstract class DomainService {}\n","export abstract class Specification<T> {\n abstract isSatisfiedBy(candidate: T): boolean;\n\n and(other: Specification<T>): Specification<T> {\n return new AndSpecification(this, other);\n }\n\n or(other: Specification<T>): Specification<T> {\n return new OrSpecification(this, other);\n }\n\n not(): Specification<T> {\n return new NotSpecification(this);\n }\n}\n\nclass AndSpecification<T> extends Specification<T> {\n constructor(\n private readonly left: Specification<T>,\n private readonly right: Specification<T>,\n ) {\n super();\n }\n\n isSatisfiedBy(candidate: T): boolean {\n return this.left.isSatisfiedBy(candidate) && this.right.isSatisfiedBy(candidate);\n }\n}\n\nclass OrSpecification<T> extends Specification<T> {\n constructor(\n private readonly left: Specification<T>,\n private readonly right: Specification<T>,\n ) {\n super();\n }\n\n isSatisfiedBy(candidate: T): boolean {\n return this.left.isSatisfiedBy(candidate) || this.right.isSatisfiedBy(candidate);\n }\n}\n\nclass NotSpecification<T> extends Specification<T> {\n constructor(private readonly spec: Specification<T>) {\n super();\n }\n\n isSatisfiedBy(candidate: T): boolean {\n return !this.spec.isSatisfiedBy(candidate);\n }\n}\n","export interface Auditable {\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function isAuditable(obj: any): obj is Auditable {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n obj.createdAt instanceof Date &&\n obj.updatedAt instanceof Date\n );\n}\n","export interface Versionable {\n version: number;\n}\n\nexport function isVersionable(obj: any): obj is Versionable {\n return obj !== null && typeof obj === 'object' && typeof obj.version === 'number';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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mBAAN,MAAMA,0BAA4BP,cAAAA;EA1ClC,OA0CkCA;;;;EAChC,YAA6BY,MAAwB;AACnD,UAAK,GAAA,KADsBA,OAAAA;EAE7B;EAEAF,cAAcC,WAAuB;AACnC,WAAO,CAAC,KAAKC,KAAKF,cAAcC,SAAAA;EAClC;AACF;;;AC7CO,SAASE,YAAYC,KAAQ;AAClC,SACEA,QAAQ,QACR,OAAOA,QAAQ,YACfA,IAAIC,qBAAqBC,QACzBF,IAAIG,qBAAqBD;AAE7B;AAPgBH;;;ACDT,SAASK,cAAcC,KAAQ;AACpC,SAAOA,QAAQ,QAAQ,OAAOA,QAAQ,YAAY,OAAOA,IAAIC,YAAY;AAC3E;AAFgBF;","names":["import_common","import_core","HandlerNotFoundException","Error","name","Object","setPrototypeOf","prototype","DuplicateHandlerException","Error","type","name","Object","setPrototypeOf","prototype","CommandRegistry","handlers","Map","middlewares","register","commandType","handler","has","DuplicateHandlerException","name","set","registerMiddleware","middleware","priority","alreadyRegistered","some","registeredMiddleware","instance","push","sort","a","b","resolve","command","get","HandlerNotFoundException","getMiddlewares","map","import_common","CommandExecutor","registry","execute","command","handler","resolve","middlewares","getMiddlewares","executeHandler","handle","pipeline","reduceRight","next","middleware","use","import_common","QueryRegistry","handlers","Map","middlewares","register","queryType","handler","has","DuplicateHandlerException","name","set","registerMiddleware","middleware","priority","alreadyRegistered","some","registeredMiddleware","instance","push","sort","a","b","resolve","query","get","HandlerNotFoundException","getMiddlewares","map","import_common","QueryExecutor","registry","execute","query","handler","resolve","middlewares","getMiddlewares","executeHandler","handle","pipeline","reduceRight","next","middleware","use","import_common","EventRegistry","handlers","Map","register","eventType","handler","existingHandlers","get","alreadyRegistered","some","registeredHandler","push","set","resolve","event","import_common","EventBus","registry","publish","event","handlers","resolve","handler","handle","import_common","import_reflect_metadata","COMMAND_HANDLER_METADATA","Symbol","HandleCommand","commandType","target","Reflect","defineMetadata","import_reflect_metadata","QUERY_HANDLER_METADATA","Symbol","HandleQuery","queryType","target","Reflect","defineMetadata","import_reflect_metadata","EVENT_HANDLER_METADATA","Symbol","HandleEvent","eventType","target","Reflect","defineMetadata","import_reflect_metadata","COMMAND_MIDDLEWARE_METADATA","Symbol","QUERY_MIDDLEWARE_METADATA","RegisterCommandMiddleware","options","target","Reflect","defineMetadata","RegisterQueryMiddleware","import_common","IntegrationEventRegistry","mappers","register","mapper","alreadyRegistered","some","item","push","map","domainEvents","integrationEvents","domainEvent","supports","mapped","Array","isArray","import_reflect_metadata","INTEGRATION_EVENT_MAPPER_METADATA","Symbol","RegisterIntegrationEventMapper","target","Reflect","defineMetadata","hasMethod","instance","methodName","getProviderTarget","wrapper","metatype","ExiumApplicationDiscoveryService","discovery","commandRegistry","queryRegistry","eventRegistry","integrationEventRegistry","onApplicationBootstrap","providers","getProviders","target","registerCommandHandler","registerQueryHandler","registerEventHandler","registerCommandMiddleware","registerQueryMiddleware","registerIntegrationEventMapper","commandType","Reflect","getMetadata","COMMAND_HANDLER_METADATA","Error","name","register","queryType","QUERY_HANDLER_METADATA","eventType","EVENT_HANDLER_METADATA","options","COMMAND_MIDDLEWARE_METADATA","registerMiddleware","priority","QUERY_MIDDLEWARE_METADATA","isIntegrationEventMapper","INTEGRATION_EVENT_MAPPER_METADATA","import_common","ExiumContextService","storage","AsyncLocalStorage","run","context","callback","parent","getOrUndefined","nextContext","correlationId","randomUUID","causationId","requestId","tenantId","userId","roles","permissions","locale","source","operationType","operationName","startedAt","Date","get","getStore","Error","getCorrelationId","getTenantId","getUserId","withOperation","ApplicationMiddlewarePriority","Context","Logging","Validation","Authorization","Idempotency","CacheInvalidation","Audit","Transaction","Cache","Metrics","import_common","ContextCommandMiddleware","contextService","use","command","next","commandName","name","withOperation","priority","ApplicationMiddlewarePriority","Context","import_common","ContextQueryMiddleware","contextService","use","query","next","queryName","name","withOperation","priority","ApplicationMiddlewarePriority","Context","import_common","LoggingCommandMiddleware","logger","contextService","use","command","next","commandName","name","context","getOrUndefined","startTime","Date","now","log","correlationId","tenantId","userId","result","duration","isFailure","warn","durationMs","failureKind","error","kind","failureCode","code","err","priority","ApplicationMiddlewarePriority","Logging","import_common","import_nestjs_pino","LoggingQueryMiddleware","logger","contextService","use","query","next","queryName","name","context","getOrUndefined","startTime","Date","now","log","correlationId","tenantId","userId","result","duration","isFailure","warn","durationMs","failureKind","error","kind","failureCode","code","err","priority","ApplicationMiddlewarePriority","Logging","import_common","import_reflect_metadata","OkResult","type","value","create","isSuccess","isFailure","map","mapper","Result","ok","flatMap","mapFailure","_mapper","match","handlers","success","ErrResult","error","fail","failure","combine","results","values","errors","result","push","length","compile","key","Object","entries","Failure","validation","code","message","options","kind","field","metadata","internal","notFound","businessRule","authentication","authorization","conflict","idempotency","import_reflect_metadata","SKIP_VALIDATION_METADATA","Symbol","SkipValidation","target","Reflect","defineMetadata","mapValidationErrors","errors","map","error","property","constraints","children","length","undefined","ValidationCommandMiddleware","use","command","next","skipValidation","Reflect","getMetadata","SKIP_VALIDATION_METADATA","errors","validate","whitelist","forbidUnknownValues","validationError","target","value","length","Result","fail","Failure","validation","name","metadata","mapValidationErrors","priority","ApplicationMiddlewarePriority","Validation","import_common","import_class_validator","import_reflect_metadata","ValidationQueryMiddleware","use","query","next","skipValidation","Reflect","getMetadata","SKIP_VALIDATION_METADATA","errors","validate","whitelist","forbidUnknownValues","validationError","target","value","length","Result","fail","Failure","validation","name","metadata","mapValidationErrors","priority","ApplicationMiddlewarePriority","Validation","import_common","import_reflect_metadata","import_reflect_metadata","AUTHORIZATION_METADATA","Symbol","mergeAuthorizationMetadata","target","next","existing","Reflect","getMetadata","defineMetadata","permissions","roles","AllowAnonymous","allowAnonymous","RequirePermission","permissionMode","RequireAnyPermission","RequireRole","roleMode","RequireAnyRole","PermissionChecker","AuthorizationCommandMiddleware","contextService","permissionChecker","use","command","next","operationName","name","metadata","Reflect","getMetadata","AUTHORIZATION_METADATA","allowAnonymous","context","getOrUndefined","Result","fail","Failure","authentication","reason","userId","result","check","permissions","permissionMode","roles","roleMode","allowed","required","authorization","priority","ApplicationMiddlewarePriority","Authorization","import_common","import_reflect_metadata","AuthorizationQueryMiddleware","contextService","permissionChecker","use","query","next","operationName","name","metadata","Reflect","getMetadata","AUTHORIZATION_METADATA","allowAnonymous","context","getOrUndefined","Result","fail","Failure","authentication","reason","userId","result","check","permissions","permissionMode","roles","roleMode","allowed","required","authorization","priority","ApplicationMiddlewarePriority","Authorization","import_common","import_reflect_metadata","import_reflect_metadata","CACHE_QUERY_METADATA","Symbol","CacheQuery","options","target","Reflect","defineMetadata","enabled","namespace","ttlSeconds","versioned","NonCacheable","CacheStore","import_common","NoopCacheStore","CacheStore","get","_key","hit","set","_value","_options","delete","deleteByPrefix","_prefix","import_node_crypto","import_common","CacheKeyFactory","DefaultCacheKeyFactory","create","input","payloadHash","createHash","update","stableStringify","payload","digest","namespace","version","queryName","join","createPrefix","parts","undefined","push","value","JSON","stringify","sortRecursively","Array","isArray","map","Date","toISOString","Object","keys","sort","reduce","acc","key","import_common","CacheVersionService","InMemoryCacheVersionService","versions","Map","getVersion","namespace","get","bumpVersion","nextVersion","set","CacheQueryMiddleware","cacheStore","cacheKeyFactory","cacheVersionService","use","query","next","metadata","Reflect","getMetadata","CACHE_QUERY_METADATA","enabled","queryName","name","namespace","version","versioned","getVersion","cacheKey","create","payload","cached","get","hit","Result","ok","value","result","isSuccess","set","ttlSeconds","priority","ApplicationMiddlewarePriority","Cache","import_common","import_nestjs_pino","import_reflect_metadata","import_reflect_metadata","INVALIDATE_CACHE_METADATA","Symbol","InvalidateCache","first","rest","target","options","normalizeInvalidateCacheOptions","Reflect","defineMetadata","enabled","namespaces","mode","failOnError","uniqueNamespaces","Set","map","namespace","trim","filter","Boolean","length","Error","CacheInvalidationCommandMiddleware","cacheStore","cacheKeyFactory","cacheVersionService","logger","use","command","next","metadata","Reflect","getMetadata","INVALIDATE_CACHE_METADATA","enabled","result","isFailure","invalidate","error","name","namespaces","mode","err","failOnError","namespace","bumpVersion","prefix","createPrefix","deleteByPrefix","priority","ApplicationMiddlewarePriority","CacheInvalidation","import_common","import_reflect_metadata","import_reflect_metadata","IDEMPOTENT_METADATA","Symbol","Idempotent","options","target","Reflect","defineMetadata","enabled","keyProperty","scope","ttlSeconds","fingerprintPayload","NonIdempotent","IdempotencyStore","import_common","IdempotencyException","Error","operationName","reason","details","name","Object","setPrototypeOf","prototype","NoopIdempotencyStore","IdempotencyStore","begin","input","IdempotencyException","operationName","scope","key","complete","_input","fail","import_common","IdempotencyKeyResolver","DefaultIdempotencyKeyResolver","resolve","input","value","getValueByPath","command","keyProperty","undefined","key","trim","length","source","path","split","filter","Boolean","reduce","current","import_node_crypto","import_common","IdempotencyFingerprintFactory","DefaultIdempotencyFingerprintFactory","create","input","normalizedPayload","removePropertiesByPath","payload","excludeProperties","createHash","update","stableStringify","operationName","digest","value","JSON","stringify","sortRecursively","Array","isArray","map","Date","toISOString","Object","keys","sort","reduce","acc","key","paths","cloned","clonePlain","path","removePath","source","parts","split","filter","Boolean","length","current","part","slice","next","IdempotencyCommandMiddleware","store","keyResolver","fingerprintFactory","use","command","next","operationName","name","metadata","Reflect","getMetadata","IDEMPOTENT_METADATA","enabled","scope","key","resolve","keyProperty","Result","fail","Failure","validation","reason","fingerprint","fingerprintPayload","create","payload","excludeProperties","beginResult","begin","ttlSeconds","startedAt","Date","status","restoreStoredResult","result","idempotency","conflict","existingFingerprint","incomingFingerprint","complete","toStoredResult","completedAt","error","failedAt","priority","ApplicationMiddlewarePriority","Idempotency","isSuccess","__type","type","value","stored","isStoredCommandResult","ok","candidate","import_common","import_nestjs_pino","import_reflect_metadata","import_reflect_metadata","AUDITABLE_METADATA","Symbol","Auditable","options","target","Reflect","defineMetadata","enabled","action","resource","resourceId","resourceIdProperty","metadata","failOnError","NonAuditable","AuditWriter","import_common","NoopAuditWriter","AuditWriter","write","_event","createAuditEvent","input","error","normalizeError","action","metadata","resource","resourceId","resolveResourceId","payload","resourceIdProperty","operationType","operationName","outcome","errorName","failure","kind","name","errorMessage","message","failureKind","failureCode","code","failureMessage","correlationId","context","causationId","requestId","tenantId","userId","source","locale","durationMs","occurredAt","path","undefined","value","split","filter","Boolean","reduce","current","key","String","Error","AuditCommandMiddleware","auditWriter","contextService","logger","use","command","next","metadata","Reflect","getMetadata","AUDITABLE_METADATA","enabled","operationName","name","startedAt","Date","now","result","isFailure","writeAuditSafely","createAuditEvent","operationType","payload","context","getOrUndefined","outcome","durationMs","occurredAt","failure","error","event","write","action","resource","err","failOnError","priority","ApplicationMiddlewarePriority","Audit","import_common","import_nestjs_pino","import_reflect_metadata","AuditQueryMiddleware","auditWriter","contextService","logger","use","query","next","metadata","Reflect","getMetadata","AUDITABLE_METADATA","enabled","operationName","name","startedAt","Date","now","result","isFailure","writeAuditSafely","createAuditEvent","operationType","payload","context","getOrUndefined","outcome","durationMs","occurredAt","failure","error","event","write","action","resource","err","failOnError","priority","ApplicationMiddlewarePriority","Audit","import_common","hasAll","actual","required","length","every","item","includes","hasAny","some","ContextPermissionChecker","PermissionChecker","check","input","permissionMode","roleMode","permissionAllowed","context","permissions","allowed","reason","roleAllowed","roles","import_common","OutboxWriter","NoopOutboxWriter","OutboxWriter","write","_events","ExiumApplicationModule","forRoot","options","defaultCacheStoreEnabled","defaults","cacheStore","defaultCacheVersionServiceEnabled","cacheVersionService","defaultIdempotencyStoreEnabled","idempotencyStore","defaultAuditWriterEnabled","auditWriter","providers","ExiumApplicationDiscoveryService","ExiumContextService","CommandRegistry","CommandExecutor","QueryRegistry","QueryExecutor","EventRegistry","EventBus","ContextCommandMiddleware","ContextQueryMiddleware","LoggingCommandMiddleware","LoggingQueryMiddleware","ValidationCommandMiddleware","ValidationQueryMiddleware","AuthorizationCommandMiddleware","AuthorizationQueryMiddleware","CacheQueryMiddleware","CacheInvalidationCommandMiddleware","provide","PermissionChecker","useClass","ContextPermissionChecker","IntegrationEventRegistry","OutboxWriter","NoopOutboxWriter","CacheKeyFactory","DefaultCacheKeyFactory","IdempotencyCommandMiddleware","IdempotencyKeyResolver","DefaultIdempotencyKeyResolver","IdempotencyFingerprintFactory","DefaultIdempotencyFingerprintFactory","AuditCommandMiddleware","AuditQueryMiddleware","push","AuditWriter","NoopAuditWriter","CacheStore","NoopCacheStore","CacheVersionService","InMemoryCacheVersionService","IdempotencyStore","NoopIdempotencyStore","moduleExports","module","global","imports","DiscoveryModule","exports","UnitOfWork","Command","CommandHandler","Query","QueryResult","QueryHandler","EventHandler","import_reflect_metadata","TRANSACTIONAL_METADATA","Symbol","Transactional","options","target","Reflect","defineMetadata","enabled","NonTransactional","AuthorizationException","Error","operationName","reason","required","name","Object","setPrototypeOf","prototype","IntegrationEvent","id","name","version","occurredAt","params","Date","IntegrationEventMapper","ReadQueryException","Error","message","name","ReadFieldNotFoundException","sourceName","field","ReadOperationNotSupportedException","operation","reason","Criteria","node","empty","where","field","and","CriteriaFieldBuilder","normalizeField","or","andGroup","factory","append","requireNode","orGroup","not","freezeNode","type","isEmpty","connector","nextNode","nodes","freezeNodes","criteria","eq","value","comparison","ne","gt","gte","lt","lte","in","values","inclusion","notIn","contains","startsWith","endsWith","isNull","addNode","isNotNull","between","lower","upper","operator","Array","isArray","length","ReadQueryException","Object","freeze","normalized","trim","Sort","fields","none","Object","freeze","by","field","SortDirectionBuilder","normalizeField","thenBy","isEmpty","length","fromFields","freezeFields","map","normalizeSortField","previousFields","asc","options","build","nulls","desc","direction","normalized","trim","ReadQueryException","DEFAULT_MAX_PAGE_SIZE","PageRequest","page","size","of","options","maxSize","Number","isInteger","Result","fail","Failure","validation","field","metadata","ok","offset","Page","items","totalItems","totalPages","request","Object","freeze","Math","ceil","CursorRequest","after","before","limit","first","create","cursor","normalized","normalizeCursor","isFailure","error","value","CursorPage","hasNext","hasPrevious","nextCursor","previousCursor","trim","SqlReadSource","name","table","alias","fields","joins","defaultSort","defaultSelectedFields","define","definition","normalizeIdentifier","undefined","normalizeFields","Object","freeze","is","source","resolveField","field","resolved","ReadFieldNotFoundException","getSelectFields","fieldNames","keys","map","fieldName","getFromExpression","Join","left","JoinBuilder","inner","type","onRef","operator","right","on","entries","length","ReadQueryException","fromEntries","logical","physical","value","label","normalized","trim","Entity","id","equals","other","toString","name","AuditableEntity","Entity","createdAt","updatedAt","id","Date","touch","AggregateRoot","Entity","domainEvents","raise","event","push","pullDomainEvents","events","AuditableAggregateRoot","AggregateRoot","createdAt","updatedAt","version","id","Date","touch","isPlainObject","value","prototype","Object","getPrototypeOf","cloneAndFreeze","Date","getTime","Array","isArray","freeze","map","item","cloned","keys","reduce","acc","key","deepEqual","a","b","is","length","every","index","keysA","keysB","hasOwnProperty","call","ValueObject","props","equals","other","PrimitiveValueObject","ValueObject","value","props","import_common","import_config","import_class_transformer","import_class_validator","import_class_validator","ExiumEnvironment","EXIUM_DB_URL","EXIUM_RABBITMQ_URL","EXIUM_REDIS_URL","EXIUM_LOG_LEVEL","EXIUM_LOG_PRETTY","obj","import_common","ExiumConfigService","configService","isProduction","process","env","NODE_ENV","databaseUrl","get","infer","getRequiredDatabaseUrl","value","Error","rabbitMqUrl","redisUrl","logLevel","logPretty","validate","config","validatedConfig","plainToInstance","ExiumEnvironment","enableImplicitConversion","errors","validateSync","skipMissingProperties","length","Error","map","e","Object","values","constraints","join","ExiumConfigModule","imports","ConfigModule","forRoot","isGlobal","providers","ExiumConfigService","exports","import_common","import_common","import_nestjs_pino","ExiumLoggerModule","imports","ExiumConfigModule","LoggerModule","forRootAsync","inject","ExiumConfigService","useFactory","config","isProduction","level","logLevel","pretty","logPretty","undefined","pinoHttp","transport","target","autoLogging","serializers","req","method","url","exports","ApiResponse","success","message","timestamp","Date","toISOString","SuccessResult","ApiResponse","message","success","SuccessDataResult","data","SuccessListResult","SuccessPageResult","meta","SuccessCursorResult","ErrorResult","ApiResponse","error","code","message","details","kind","success","import_reflect_metadata","EXIUM_HTTP_API_METADATA","Symbol","defineHttpApiMetadata","metadata","target","propertyKey","undefined","Reflect","defineMetadata","getHttpApiMetadata","getMetadata","ExternalApi","options","target","propertyKey","defineHttpApiMetadata","exposure","InternalApi","options","target","propertyKey","defineHttpApiMetadata","exposure","internalMode","mode","EXIUM_HTTP_OPTIONS","Symbol","DEFAULT_EXIUM_HTTP_HEADER_NAMES","requestId","correlationId","causationId","tenantId","userId","roles","permissions","source","locale","resolveExiumHttpOptions","options","adapter","context","headerNames","internalApis","defaultMode","remoteServices","import_common","import_core","import_reflect_metadata","INTERNAL_API_HANDLER_METADATA","Symbol","HandleInternalApi","options","target","operation","trim","Error","Reflect","defineMetadata","serviceName","undefined","getInternalApiHandlerMetadata","getMetadata","import_common","ExiumInternalApiRegistry","handlers","Map","register","metadata","handler","key","composeHandlerKey","serviceName","operation","existing","get","Error","set","resolve","undefined","has","list","values","service","trim","import_common","import_core","hasHandleMethod","instance","getProviderTarget","wrapper","metatype","ExiumHttpDiscoveryService","discovery","internalApiRegistry","onApplicationBootstrap","providers","getProviders","target","metadata","getInternalApiHandlerMetadata","Error","name","register","import_common","ExiumInternalApiEndpointResolver","ConfiguredInternalApiEndpointResolver","options","resolve","serviceName","internalApis","remoteServices","import_common","ExiumInternalApiClient","options","registry","endpointResolver","contextService","sourceServiceName","resolveExiumHttpOptions","call","mode","internalApis","defaultMode","callLocal","callRemote","has","serviceName","operation","registered","resolve","Result","fail","Failure","notFound","result","run","operationType","operationName","source","handler","handle","body","targetServiceName","method","path","isResultLike","ok","baseUrl","trim","validation","metadata","url","buildUrl","query","controller","timeoutMs","AbortController","undefined","timeout","setTimeout","abort","response","fetch","headers","createRemoteHeaders","JSON","stringify","signal","responseBody","readResponseBody","isApiEnvelope","success","data","toFailureFromEnvelope","status","toTransportFailure","error","reason","Error","message","String","clearTimeout","context","getOrUndefined","headerNames","propagated","accept","requestId","correlationId","causationId","tenantId","userId","roles","length","join","permissions","locale","normalizedBaseUrl","endsWith","normalizedPath","replace","URL","key","value","Object","entries","Array","isArray","item","appendQueryValue","toString","searchParams","append","text","parse","candidate","type","isSuccess","isFailure","envelope","code","kind","statusToFailureKind","toFailureMetadata","details","ExiumHttpModule","forRoot","options","resolvedOptions","resolveExiumHttpOptions","providers","provide","EXIUM_HTTP_OPTIONS","useValue","ExiumInternalApiRegistry","ExiumHttpDiscoveryService","ExiumInternalApiEndpointResolver","useClass","ConfiguredInternalApiEndpointResolver","ExiumInternalApiClient","module","global","imports","DiscoveryModule","exports","import_common","ExiumHttpContextInterceptor","options","contextService","resolveExiumHttpOptions","intercept","context","next","getType","handle","request","switchToHttp","getRequest","executionContext","createExecutionContext","Observable","subscriber","subscription","run","subscribe","value","error","complete","unsubscribe","headers","headerNames","method","route","path","url","requestId","readHeader","correlationId","causationId","tenantId","userId","roles","splitHeaderList","permissions","locale","source","operationType","operationName","toUpperCase","startedAt","Date","name","toLowerCase","Object","entries","find","key","Array","isArray","undefined","values","split","map","item","trim","filter","Boolean","length","import_common","ExiumResponseInterceptor","intercept","context","next","handle","pipe","map","data","isResultLike","type","response","switchToHttp","getResponse","status","toHttpStatus","error","ErrorResult","code","message","toFailureDetails","kind","wrapSuccess","value","ApiResponse","undefined","SuccessResult","Page","SuccessPageResult","items","total","totalItems","page","size","totalPages","CursorPage","SuccessCursorResult","nextCursor","previousCursor","hasNext","hasPrevious","Array","isArray","SuccessListResult","SuccessDataResult","candidate","isSuccess","isFailure","failure","HttpStatus","BAD_REQUEST","UNAUTHORIZED","FORBIDDEN","NOT_FOUND","CONFLICT","UNPROCESSABLE_ENTITY","INTERNAL_SERVER_ERROR","field","metadata","import_common","import_nestjs_pino","ExiumExceptionFilter","logger","catch","exception","host","ctx","switchToHttp","response","getResponse","HttpException","status","getStatus","body","message","details","undefined","error","errorResponse","ErrorResult","Array","isArray","join","String","toFailureKind","json","Error","console","HttpStatus","INTERNAL_SERVER_ERROR","BAD_REQUEST","UNAUTHORIZED","FORBIDDEN","NOT_FOUND","CONFLICT","import_common","import_common","import_common","import_common","import_common","EXIUM_REDIS_OPTIONS","Symbol","EXIUM_REDIS_CLIENT","DEFAULT_EXIUM_REDIS_OPTIONS","connectTimeoutMs","lazyConnect","maxRetriesPerRequest","enableOfflineQueue","normalizeExiumRedisOptions","input","url","trim","Error","keyPrefix","normalizeKeyPrefix","options","assertPositiveInteger","value","undefined","trimmed","propertyName","Number","isInteger","ExiumRedisClient","client","options","native","Redis","url","connectTimeout","connectTimeoutMs","lazyConnect","maxRetriesPerRequest","enableOfflineQueue","ping","onApplicationShutdown","undefined","quit","disconnect","ExiumRedisModule","forRoot","options","providers","provide","EXIUM_REDIS_OPTIONS","inject","ExiumConfigService","useFactory","config","normalizeExiumRedisOptions","url","redisUrl","ExiumRedisClient","EXIUM_REDIS_CLIENT","client","native","module","global","imports","ExiumConfigModule","exports","RedisCacheStore","CacheStore","redis","options","get","key","raw","toPhysicalKey","hit","envelope","JSON","parse","value","delete","set","physicalKey","payload","stringify","ttlSeconds","undefined","del","deleteByPrefix","prefix","physicalPrefix","pattern","cursor","nextCursor","keys","scan","length","keyPrefix","import_common","RedisCacheVersionService","CacheVersionService","redis","options","getVersion","namespace","value","get","createVersionKey","parsed","Number","isInteger","bumpVersion","key","result","eval","toPhysicalKey","keyPrefix","ExiumCacheInfrastructureModule","forRoot","options","driver","Error","providers","RedisCacheStore","RedisCacheVersionService","provide","CacheStore","useExisting","CacheVersionService","module","global","exports","import_common","import_common","RedisIdempotencyStore","IdempotencyStore","redis","options","begin","input","physicalKey","createPhysicalKey","scope","key","record","status","fingerprint","operationName","startedAt","toISOString","created","set","JSON","stringify","ttlSeconds","existing","readRecord","retryCreated","existingFingerprint","incomingFingerprint","result","complete","ttl","completed","completedAt","writePreservingTtl","fail","failed","failedAt","error","normalizeError","raw","get","parsed","parse","isValidRecord","del","payload","toPhysicalKey","safeKeyPart","keyPrefix","value","encodeURIComponent","Error","name","message","String","ExiumIdempotencyInfrastructureModule","forRoot","options","driver","Error","providers","RedisIdempotencyStore","provide","IdempotencyStore","useExisting","module","global","exports","IntegrationMessagePublisher","import_common","NoopIntegrationMessagePublisher","IntegrationMessagePublisher","publish","message","Error","name","import_common","RABBITMQ_OPTIONS","Symbol","DEFAULT_RABBITMQ_OPTIONS","exchange","exchangeType","durable","persistent","normalizeRabbitMqOptions","input","url","trim","Error","includes","routingKey","import_common","RabbitMqIntegrationMessagePublisher","IntegrationMessagePublisher","connection","channel","initializing","options","publish","message","ensureChannel","Error","routingKey","name","payload","Buffer","from","JSON","stringify","publishOptions","persistent","contentType","messageId","id","type","timestamp","Math","floor","occurredAt","getTime","headers","version","toISOString","exchange","waitForConfirms","onApplicationShutdown","closeSafely","initialize","undefined","connect","url","createConfirmChannel","assertExchange","exchangeType","durable","close","ExiumMessagingModule","forRoot","options","driver","providers","push","provide","IntegrationMessagePublisher","useClass","NoopIntegrationMessagePublisher","RABBITMQ_OPTIONS","inject","ExiumConfigService","useFactory","config","normalizeRabbitMqOptions","rabbitmq","url","rabbitMqUrl","RabbitMqIntegrationMessagePublisher","useExisting","Error","module","global","imports","ExiumConfigModule","exports","import_common","import_common","import_core","import_nestjs_pino","import_node_async_hooks","TransactionContext","AsyncLocalStorage","getTransactionContext","getStore","getTransactionEntityManager","em","getTransactionAggregates","aggregates","MikroOrmUnitOfWork","UnitOfWork","rootEntityManager","eventBus","integrationEventRegistry","outboxWriter","logger","execute","work","existingContext","getTransactionContext","aggregates","Set","result","domainEvents","transactional","txEm","TransactionContext","run","em","workResult","isFailureResult","ResultFailureRollback","flatMap","aggregate","pullDomainEvents","integrationEvents","map","length","write","flush","error","domainEvent","publish","err","eventId","eventName","name","registerAggregate","getTransactionAggregates","Error","add","Object","setPrototypeOf","prototype","value","candidate","type","isFailure","import_common","import_reflect_metadata","TransactionCommandMiddleware","unitOfWork","use","command","next","metadata","Reflect","getMetadata","TRANSACTIONAL_METADATA","enabled","execute","priority","ApplicationMiddlewarePriority","Transaction","import_core","OutboxMessageStatus","OutboxMessageSchema","defineEntity","name","tableName","properties","id","p","string","primary","eventId","unique","eventName","eventVersion","integer","payload","json","occurredAt","datetime","status","retryCount","nextAttemptAt","nullable","publishedAt","lockedAt","lockedBy","lastError","createdAt","onCreate","Date","updatedAt","onUpdate","OutboxMessageEntity","class","create","params","entity","uuidv7","OutboxMessageStatus","Pending","setClass","import_common","PersistenceTransactionNotActiveException","Error","operation","name","Object","setPrototypeOf","prototype","MikroOrmOutboxWriter","OutboxWriter","write","events","length","em","getTransactionEntityManager","PersistenceTransactionNotActiveException","event","message","OutboxMessageEntity","create","eventId","id","eventName","name","eventVersion","version","occurredAt","payload","toPlainRecord","persist","source","normalized","normalize","Array","isArray","value","Date","toISOString","map","result","key","item","Object","entries","undefined","import_common","import_core","import_nestjs_pino","OUTBOX_PUBLISHER_OPTIONS","Symbol","DEFAULT_OUTBOX_PUBLISHER_OPTIONS","batchSize","maxRetryCount","retryDelayMs","lockTimeoutMs","publisherId","normalizeOutboxPublisherOptions","input","options","assertPositiveInteger","trim","Error","value","propertyName","Number","isInteger","OutboxPublisher","em","messagePublisher","logger","options","publishPending","messages","findPublishableMessages","publishedCount","message","claimed","claim","publish","toEnvelope","status","OutboxMessageStatus","Published","publishedAt","Date","lockedAt","undefined","lockedBy","lastError","flush","error","retryCount","normalizeError","maxRetryCount","Failed","nextAttemptAt","Pending","now","retryDelayMs","outboxMessageId","id","eventId","eventName","err","lockExpiredBefore","lockTimeoutMs","find","OutboxMessageEntity","$and","$or","$lte","limit","batchSize","orderBy","occurredAt","getTime","oldLockedAt","updatedCount","nativeUpdate","publisherId","name","version","eventVersion","payload","Error","String","ExiumPersistenceModule","forRoot","options","outboxEnabled","outbox","enabled","entities","uniqueEntities","OutboxMessageEntity","providers","MikroOrmUnitOfWork","TransactionCommandMiddleware","provide","UnitOfWork","useExisting","push","MikroOrmOutboxWriter","OutboxPublisher","OutboxWriter","OUTBOX_PUBLISHER_OPTIONS","useValue","normalizeOutboxPublisherOptions","publisher","module","imports","ExiumConfigModule","createMikroOrmModule","driver","exports","createDriverSpecificMikroOrmModule","PostgreSqlDriver","MongoDriver","assertNever","MikroOrmModule","forRootAsync","inject","ExiumConfigService","useFactory","config","createBaseMikroOrmOptions","clientUrl","getRequiredDatabaseUrl","implicitTransactions","allowGlobalContext","Set","value","Error","MikroOrmRepository","idField","entityName","rootEntityManager","options","em","txEm","getTransactionEntityManager","getContext","transactionalEm","PersistenceTransactionNotActiveException","String","getIdField","createIdFilter","id","createIdsFilter","ids","$in","findOrmById","findOne","findOrmByIds","length","find","persistOrm","entity","persist","removeOrm","remove","deleteOrmById","existsOrm","count","MikroOrmAggregateRepository","MikroOrmRepository","entityName","rootEntityManager","mapper","unitOfWork","options","findById","id","primitiveId","toPersistenceId","entity","findOrmById","toDomain","findByIds","ids","length","primitiveIds","map","entities","findOrmByIds","save","aggregate","getPersistenceId","toPersistence","existing","Object","assign","registerAggregate","persistOrm","delete","deleteOrmById","exists","existsOrm","ExiumInfrastructureModule","forRoot","options","imports","persistenceOutboxEnabled","persistence","outbox","enabled","redisRequired","redis","undefined","cache","driver","idempotency","push","ExiumRedisModule","ExiumCacheInfrastructureModule","ExiumIdempotencyInfrastructureModule","messaging","ExiumMessagingModule","ExiumPersistenceModule","module","exports","KyselyReadEngine","db","findOne","query","rows","findMany","limit","source","requireSqlSource","from","builder","createSelect","applyCriteria","criteria","applySort","sort","defaultSort","undefined","execute","map","row","mapRow","findPage","page","size","offset","items","totalItems","Promise","all","then","count","Page","of","findCursor","assertCursorSort","cursor","after","applyCursorPredicate","before","executionSort","reverseSort","hasExtraItem","length","selectedRows","slice","pageRows","reverse","hasPrevious","Boolean","hasNext","previousCursor","encodeCursor","nextCursor","CursorPage","exists","createBaseQuery","select","sql","as","executeTakeFirst","Number","getSelectFields","selectFrom","getFromExpression","join","joins","joinSource","table","alias","type","leftJoin","joinBuilder","onRef","on","left","operator","right","innerJoin","node","where","eb","toKyselyExpression","isEmpty","sorted","field","fields","resolved","resolveField","nulls","orderBy","ref","raw","direction","payload","decodeCursor","branches","index","equalPredicates","previousField","getCursorValue","seekPredicate","predicates","and","or","toComparisonExpression","values","lower","upper","nodes","child","not","value","String","SqlReadSource","is","ReadOperationNotSupportedException","name","unsupportedNullSort","find","tieBreaker","Sort","fromFields","parsed","JSON","parse","Buffer","toString","isRecord","Error","error","ReadQueryException","stringify","record","Object","prototype","hasOwnProperty","call","Array","isArray","mapper","ExiumModule","forRoot","options","redisCacheEnabled","infrastructure","cache","driver","redisIdempotencyEnabled","idempotency","applicationModule","ExiumApplicationModule","defaults","cacheStore","cacheVersionService","idempotencyStore","imports","ExiumConfigModule","ExiumLoggerModule","push","ExiumInfrastructureModule","httpModule","ExiumHttpModule","http","exports","module","global","providers","provide","useValue","serviceName","import_reflect_metadata","import_common","import_core","import_nestjs_pino","ExiumRootModule","validateOptions","options","serviceName","trim","Error","module","createExiumApp","mode","rootModule","imports","ExiumModule","forRoot","http","infrastructure","nestApp","NestFactory","create","bufferLogs","createApplicationContext","pinoLogger","get","Logger","useLogger","shutdownHooks","enableShutdownHooks","httpApp","useGlobalPipes","ValidationPipe","whitelist","transform","useGlobalInterceptors","ExiumHttpContextInterceptor","ExiumContextService","EXIUM_HTTP_OPTIONS","ExiumResponseInterceptor","useGlobalFilters","ExiumExceptionFilter","start","service","String","port","listen","log","undefined","warn","stop","close","getNestApp","import_uuid","Id","ValueObject","value","isUuidV7","Error","newUuid","uuidv7","generate","create","of","parse","options","parseUuid","idType","name","field","map","normalized","trim","Result","fail","Failure","validation","metadata","expected","internal","ok","constructor","validate","version","props","toString","toJSON","import_uuid","DomainEvent","eventId","occurredAt","aggregateId","uuidv7","Date","DomainService","Specification","and","other","AndSpecification","or","OrSpecification","not","NotSpecification","left","right","isSatisfiedBy","candidate","spec","isAuditable","obj","createdAt","Date","updatedAt","isVersionable","obj","version"]}