@signaltree/events 7.3.1

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,106 @@
1
+ import { BaseEvent, EventActor, EventMetadata, EventPriority, EventVersion } from '../core/types';
2
+ /**
3
+ * Test Event Factories - Create events for testing
4
+ *
5
+ * Provides:
6
+ * - Type-safe event creation
7
+ * - Randomized data generation
8
+ * - Override support
9
+ */
10
+ /**
11
+ * Options for creating test events
12
+ */
13
+ export interface TestEventOptions {
14
+ /** Override event ID */
15
+ id?: string;
16
+ /** Override correlation ID */
17
+ correlationId?: string;
18
+ /** Override causation ID */
19
+ causationId?: string;
20
+ /** Override timestamp */
21
+ timestamp?: string;
22
+ /** Override actor */
23
+ actor?: Partial<EventActor>;
24
+ /** Override metadata */
25
+ metadata?: Partial<EventMetadata>;
26
+ /** Override priority */
27
+ priority?: EventPriority;
28
+ /** Override version */
29
+ version?: EventVersion;
30
+ /** Override aggregate */
31
+ aggregate?: {
32
+ type: string;
33
+ id: string;
34
+ };
35
+ }
36
+ /**
37
+ * Test event factory interface
38
+ */
39
+ export interface TestEventFactory<TEvents extends BaseEvent = BaseEvent> {
40
+ /**
41
+ * Create a test event
42
+ */
43
+ create<T extends TEvents>(type: T['type'], data: T['data'], options?: TestEventOptions): T;
44
+ /**
45
+ * Create multiple test events
46
+ */
47
+ createMany<T extends TEvents>(type: T['type'], dataArray: T['data'][], options?: TestEventOptions): T[];
48
+ /**
49
+ * Create a test event with random data
50
+ * Override this in your app's test utilities
51
+ */
52
+ createRandom<T extends TEvents>(type: T['type'], overrides?: Partial<T['data']>, options?: TestEventOptions): T;
53
+ }
54
+ /**
55
+ * Create a test event
56
+ *
57
+ * @example
58
+ * ```typescript
59
+ * const event = createTestEvent('TradeProposalCreated', {
60
+ * tradeId: '123',
61
+ * initiatorId: 'user-1',
62
+ * recipientId: 'user-2',
63
+ * });
64
+ * ```
65
+ */
66
+ export declare function createTestEvent<TType extends string, TData>(type: TType, data: TData, options?: TestEventOptions): BaseEvent<TType, TData>;
67
+ /**
68
+ * Create a test event factory
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * const factory = createTestEventFactory({
73
+ * defaultActor: { id: 'test-user', type: 'user' },
74
+ * defaultMetadata: { source: 'test-service' },
75
+ * });
76
+ *
77
+ * const event = factory.create('TradeProposalCreated', {
78
+ * tradeId: '123',
79
+ * });
80
+ * ```
81
+ */
82
+ export declare function createTestEventFactory(config?: {
83
+ defaultActor?: Partial<EventActor>;
84
+ defaultMetadata?: Partial<EventMetadata>;
85
+ randomGenerators?: Record<string, () => unknown>;
86
+ }): TestEventFactory;
87
+ /**
88
+ * Generate a random UUID for testing
89
+ */
90
+ export declare function randomUuid(): string;
91
+ /**
92
+ * Generate a random string for testing
93
+ */
94
+ export declare function randomString(length?: number): string;
95
+ /**
96
+ * Generate a random number for testing
97
+ */
98
+ export declare function randomNumber(min?: number, max?: number): number;
99
+ /**
100
+ * Generate a random date for testing
101
+ */
102
+ export declare function randomDate(start?: Date, end?: Date): Date;
103
+ /**
104
+ * Generate a random element from array
105
+ */
106
+ export declare function randomFrom<T>(array: T[]): T;
@@ -0,0 +1,104 @@
1
+ import { ClassificationResult, ErrorClassification, RetryConfig } from '../core/error-classification';
2
+ import { IdempotencyStore, ProcessedEventRecord } from '../core/idempotency';
3
+ import { BaseEvent } from '../core/types';
4
+ import { MockEventBus } from './mock-event-bus';
5
+ /**
6
+ * Test Helpers - Utility functions for testing
7
+ *
8
+ * Provides:
9
+ * - Event waiting utilities
10
+ * - Mock implementations
11
+ * - Test fixtures
12
+ */
13
+ /**
14
+ * Wait for an event to be published
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * const eventPromise = waitForEvent(eventBus, 'TradeCreated');
19
+ * await performAction();
20
+ * const event = await eventPromise;
21
+ * expect(event.data.tradeId).toBe('123');
22
+ * ```
23
+ */
24
+ export declare function waitForEvent<T extends BaseEvent>(eventBus: MockEventBus, eventType: T['type'], timeoutMs?: number): Promise<T>;
25
+ /**
26
+ * Wait for multiple events to be published
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const eventsPromise = waitForEvents(eventBus, ['TradeCreated', 'NotificationSent']);
31
+ * await performAction();
32
+ * const events = await eventsPromise;
33
+ * ```
34
+ */
35
+ export declare function waitForEvents(eventBus: MockEventBus, eventTypes: string[], timeoutMs?: number): Promise<BaseEvent[]>;
36
+ /**
37
+ * Collect events during an action
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const events = await collectEvents(eventBus, async () => {
42
+ * await createTrade();
43
+ * await acceptTrade();
44
+ * });
45
+ * expect(events).toHaveLength(2);
46
+ * ```
47
+ */
48
+ export declare function collectEvents(eventBus: MockEventBus, action: () => Promise<void>, eventTypes?: string[]): Promise<BaseEvent[]>;
49
+ /**
50
+ * Create a mock idempotency store
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const store = mockIdempotencyStore({
55
+ * duplicateIds: ['event-1', 'event-2'],
56
+ * });
57
+ *
58
+ * const result = await store.check({ id: 'event-1' }, 'consumer');
59
+ * expect(result.isDuplicate).toBe(true);
60
+ * ```
61
+ */
62
+ export declare function mockIdempotencyStore(options?: {
63
+ duplicateIds?: string[];
64
+ shouldAcquireLock?: boolean;
65
+ processedRecords?: Map<string, ProcessedEventRecord>;
66
+ }): IdempotencyStore;
67
+ /**
68
+ * Create a mock error classifier
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * const classifier = mockErrorClassifier({
73
+ * defaultClassification: 'transient',
74
+ * customClassifications: {
75
+ * 'ValidationError': 'permanent',
76
+ * 'NetworkError': 'transient',
77
+ * },
78
+ * });
79
+ * ```
80
+ */
81
+ export declare function mockErrorClassifier(options?: {
82
+ defaultClassification?: ErrorClassification;
83
+ customClassifications?: Record<string, ErrorClassification>;
84
+ retryConfig?: Partial<RetryConfig>;
85
+ }): {
86
+ classify: (error: unknown) => ClassificationResult;
87
+ isRetryable: (error: unknown) => boolean;
88
+ };
89
+ /**
90
+ * Create a test delay helper
91
+ */
92
+ export declare function delay(ms: number): Promise<void>;
93
+ /**
94
+ * Create a deferred promise for testing async flows
95
+ */
96
+ export declare function createDeferred<T>(): {
97
+ promise: Promise<T>;
98
+ resolve: (value: T) => void;
99
+ reject: (error: Error) => void;
100
+ };
101
+ /**
102
+ * Flush pending promises (useful for testing)
103
+ */
104
+ export declare function flushPromises(): Promise<void>;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @signaltree/events/testing
3
+ *
4
+ * Testing utilities for event-driven applications.
5
+ * Provides mocks, factories, and helpers for unit testing.
6
+ */
7
+ export { MockEventBus, createMockEventBus } from './mock-event-bus';
8
+ export type { MockEventBusOptions, PublishedEvent } from './mock-event-bus';
9
+ export { createTestEvent, createTestEventFactory } from './factories';
10
+ export type { TestEventFactory, TestEventOptions } from './factories';
11
+ export { EventAssertions, createEventAssertions } from './assertions';
12
+ export type { AssertionResult } from './assertions';
13
+ export { waitForEvent, waitForEvents, collectEvents, mockIdempotencyStore, mockErrorClassifier, } from './helpers';
@@ -0,0 +1,144 @@
1
+ import { BaseEvent } from '../core/types';
2
+ /**
3
+ * Mock Event Bus - In-memory event bus for testing
4
+ *
5
+ * Provides:
6
+ * - Synchronous publish/subscribe
7
+ * - Event history tracking
8
+ * - Assertions and expectations
9
+ */
10
+ /**
11
+ * Published event with metadata
12
+ */
13
+ export interface PublishedEvent<T extends BaseEvent = BaseEvent> {
14
+ event: T;
15
+ queue: string;
16
+ publishedAt: Date;
17
+ delay?: number;
18
+ }
19
+ /**
20
+ * Subscription handler
21
+ */
22
+ type SubscriptionHandler<T extends BaseEvent = BaseEvent> = (event: T) => void | Promise<void>;
23
+ /**
24
+ * Mock EventBus options
25
+ */
26
+ export interface MockEventBusOptions {
27
+ /** Simulate async behavior with delays */
28
+ simulateAsync?: boolean;
29
+ /** Delay for simulated async (ms) */
30
+ asyncDelayMs?: number;
31
+ /** Auto-generate missing event IDs */
32
+ autoGenerateIds?: boolean;
33
+ /** Throw on publish errors */
34
+ throwOnError?: boolean;
35
+ }
36
+ /**
37
+ * Mock Event Bus for testing
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const eventBus = createMockEventBus();
42
+ *
43
+ * // Subscribe to events
44
+ * eventBus.subscribe('TradeProposalCreated', (event) => {
45
+ * expect(event.data.tradeId).toBe('123');
46
+ * });
47
+ *
48
+ * // Publish an event
49
+ * await eventBus.publish({
50
+ * type: 'TradeProposalCreated',
51
+ * data: { tradeId: '123' },
52
+ * });
53
+ *
54
+ * // Assert published events
55
+ * expect(eventBus.getPublishedEvents()).toHaveLength(1);
56
+ * expect(eventBus.wasPublished('TradeProposalCreated')).toBe(true);
57
+ * ```
58
+ */
59
+ export declare class MockEventBus {
60
+ private readonly options;
61
+ private publishedEvents;
62
+ private subscriptions;
63
+ private allSubscriptions;
64
+ constructor(options?: MockEventBusOptions);
65
+ /**
66
+ * Publish an event
67
+ */
68
+ publish<T extends BaseEvent>(event: Omit<T, 'id' | 'timestamp'> & Partial<Pick<T, 'id' | 'timestamp'>>, options?: {
69
+ queue?: string;
70
+ delay?: number;
71
+ }): Promise<{
72
+ eventId: string;
73
+ queue: string;
74
+ }>;
75
+ /**
76
+ * Publish multiple events
77
+ */
78
+ publishBatch<T extends BaseEvent>(events: Array<Omit<T, 'id' | 'timestamp'> & Partial<Pick<T, 'id' | 'timestamp'>>>, options?: {
79
+ queue?: string;
80
+ }): Promise<Array<{
81
+ eventId: string;
82
+ queue: string;
83
+ }>>;
84
+ /**
85
+ * Subscribe to a specific event type
86
+ */
87
+ subscribe<T extends BaseEvent>(eventType: T['type'], handler: SubscriptionHandler<T>): () => void;
88
+ /**
89
+ * Subscribe to all events
90
+ */
91
+ subscribeAll(handler: SubscriptionHandler): () => void;
92
+ /**
93
+ * Get all published events
94
+ */
95
+ getPublishedEvents(): PublishedEvent[];
96
+ /**
97
+ * Get published events by type
98
+ */
99
+ getPublishedEventsByType<T extends BaseEvent>(type: T['type']): PublishedEvent<T>[];
100
+ /**
101
+ * Get the last published event
102
+ */
103
+ getLastPublishedEvent(): PublishedEvent | undefined;
104
+ /**
105
+ * Get the last published event of a specific type
106
+ */
107
+ getLastPublishedEventByType<T extends BaseEvent>(type: T['type']): PublishedEvent<T> | undefined;
108
+ /**
109
+ * Check if an event type was published
110
+ */
111
+ wasPublished(eventType: string): boolean;
112
+ /**
113
+ * Check if an event with specific data was published
114
+ */
115
+ wasPublishedWith<T extends BaseEvent>(eventType: T['type'], predicate: (event: T) => boolean): boolean;
116
+ /**
117
+ * Get count of published events
118
+ */
119
+ getPublishedCount(eventType?: string): number;
120
+ /**
121
+ * Clear all published events (for test cleanup)
122
+ */
123
+ clearHistory(): void;
124
+ /**
125
+ * Clear all subscriptions
126
+ */
127
+ clearSubscriptions(): void;
128
+ /**
129
+ * Reset the mock (clear history and subscriptions)
130
+ */
131
+ reset(): void;
132
+ /**
133
+ * Simulate an incoming event (as if received from server)
134
+ */
135
+ simulateIncomingEvent<T extends BaseEvent>(event: T): Promise<void>;
136
+ private notifySubscribers;
137
+ private getQueueForPriority;
138
+ private delay;
139
+ }
140
+ /**
141
+ * Create a mock event bus for testing
142
+ */
143
+ export declare function createMockEventBus(options?: MockEventBusOptions): MockEventBus;
144
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @signaltree/events/testing
3
+ *
4
+ * Re-export barrel for testing utilities.
5
+ * This file exists for build tooling - import from '@signaltree/events/testing'
6
+ */
7
+ export * from './testing/index';
package/testing.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./src/testing";