import { BaseEventBus } from './base-event-bus'; import { IEventBus, BaseEventBusOptions, IDomainEvent } from '@vytches/ddd-contracts'; /** * Constructor type for class references */ type Constructor = new (...args: any[]) => T; /** * Base event type for internal use * Since both IAuditEvent and IIntegrationEvent extend IDomainEvent, * we can use IDomainEvent as the base type */ type BaseEvent = IDomainEvent; /** * @public * @stable * @since 0.22.0 */ export type UnifiedEventHandler = (event: T) => Promise | void; /** * Production event bus for systems that mix domain, integration, and audit * events under one publishing surface. Extends {@link BaseEventBus} with: * * - **Bounded context filtering** — register handlers scoped to one or * more `contextId`s; events from other contexts are ignored. Lets a * single shared bus carry traffic from many contexts without each * handler defensively checking origin. * - **Decorator auto-discovery** — on construction, scans the global * `VytchesDDD` registry for `@EventHandler`-decorated classes and wires * them in. Plays nicely with `@vytches/ddd-di` and `EventDiscoveryPlugin`. * - **Heterogeneous event types** — handles `IDomainEvent`, `IAuditEvent`, * and `IIntegrationEvent` through a common `BaseEvent` discriminator. * * Use this when you want one bus for the whole app. For tighter isolation * (per-context bus), construct multiple `BaseEventBus` instances instead. * * @example Basic usage with logging * ```typescript * import { UnifiedEventBus } from '@vytches/ddd-events'; * * const bus = new UnifiedEventBus({ enableLogging: true }); * bus.subscribe('OrderCreated', async event => { * await analytics.track('order_created', event.payload); * }); * await bus.publish({ * eventName: 'OrderCreated', * payload: { id: 'o-1' }, * metadata: { contextId: 'sales' }, * }); * ``` * * @example NestJS provider * ```typescript * @Module({ * providers: [ * { * provide: IEventBus, * useFactory: () => new UnifiedEventBus({ enableLogging: true }), * }, * ], * exports: [IEventBus], * }) * class EventsModule {} * ``` * * @public * @stable * @since 0.22.0 */ export declare class UnifiedEventBus extends BaseEventBus implements IEventBus { private readonly handlerRegistry; /** * Identity mapping for class-based handlers (UX-C8): original handler * object → (event name → wrapper function). Lets `unsubscribe` remove * exactly the requested handler instead of matching wrappers textually. */ private readonly classHandlerWrappers; constructor(options?: BaseEventBusOptions); /** * Auto-register handlers discovered through decorators */ private autoRegisterHandlers; /** * Register a handler discovered through DI system */ private registerDiscoveredHandler; /** * Publish an event with automatic routing to appropriate handlers */ publish(event: BaseEvent): Promise; /** * Convenience method to publish all events from an aggregate and clear them * Simplifies the common pattern of dispatching aggregate events */ publishEventsForAggregate(aggregate: { getDomainEvents(): IDomainEvent[]; commit(): void; }): Promise; /** * Subscribe to events with flexible context filtering * * @param eventName - Event constructor or string * @param handlerOrContext - Handler function, context string, or context array * @param handler - Handler function (when second param is context) */ subscribe(eventName: string | Constructor, handlerOrContext?: UnifiedEventHandler | string | string[], handler?: UnifiedEventHandler): void; /** * Register a class-based handler */ registerHandler(eventName: string | Constructor, handler: { handle(event: T): Promise | void; }): void; /** * Unsubscribe from events. Class-based handlers are removed by identity — * the exact wrapper created for this handler at registration time is * looked up in an identity map, so two textually identical class handlers * on the same event never collide (UX-C8). */ unsubscribe(eventName: string | Constructor, handler: UnifiedEventHandler | { handle(event: BaseEvent): Promise | void; }): void; /** * Get handlers for a specific event with context filtering */ protected getHandlersForEvent(event: BaseEvent): UnifiedEventHandler[]; /** * Register handler with context filtering. Single funnel for all * registration paths (`subscribe`, * `registerHandler`, decorator auto-discovery) — enforces * `MAX_HANDLERS_PER_EVENT` here so no path can bypass the cap (UX-C9). */ private registerHandlerWithContext; /** * Order-independent equality for the `contexts` filter of two handler * registrations. Used only for the duplicate-registration warning in * {@link registerHandlerWithContext}. */ private static contextsAreEqual; /** * Gets the registered handlers for a specific event type. Operates on * this bus's own registry (not the inherited `BaseEventBus` store, which * `UnifiedEventBus` does not use). Returns a snapshot `Set` of the * registered handler functions; class-based handlers appear as their * wrapper functions. Useful for testing and debugging. * * Note: because the return type is a `Set`, it collapses entries that * share the same handler function reference. If the same handler was * registered multiple times with the same `contexts` (which now logs a * warning at registration — see `registerHandlerWithContext`), the * `Set`'s size will be *smaller* than the number of times that handler * actually runs per matching event at dispatch time. Use this method for * introspecting which unique handler functions are wired up, not for * counting invocations. */ getHandlers(eventName: string | Constructor): Set> | undefined; /** * Gets all event types with at least one registered handler. Operates on * this bus's own registry. */ getRegisteredEventTypes(): string[]; /** * Clears all registered handlers (including context-scoped ones and the * class-handler identity map). Useful for testing. */ clearHandlers(): void; /** * Check if handler should receive event based on context filtering */ private shouldHandleEvent; /** * Execute handlers for an event (overrides base class). * * Shares the unified run-all error semantics with {@link BaseEventBus} * (UX-C2): every handler runs to completion, failures are collected, and * only after the full fan-out are they surfaced via * {@link BaseEventBus.handleErrors} — routed to `options.onError` when * configured (publish resolves), otherwise thrown as a single * {@link AggregatedEventHandlerError}. */ protected executeHandlers(event: BaseEvent, handlers: UnifiedEventHandler[]): Promise; /** * Build middleware pipeline for handler execution */ private buildMiddlewarePipeline; } export {};